blob: 3209bb343b05537a75ef3d18bcf65c4f33990491 [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>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Chris Lattner87eae5e2008-07-11 22:52:41 +000054/// EvalInfo - This is a private struct used by the evaluator to capture
55/// information about a subexpression as it is folded. It retains information
56/// about the AST context, but also maintains information about the folded
57/// expression.
58///
59/// If an expression could be evaluated, it is still possible it is not a C
60/// "integer constant expression" or constant expression. If not, this struct
61/// captures information about how and why not.
62///
63/// One bit of information passed *into* the request for constant folding
64/// indicates whether the subexpression is "evaluated" or not according to C
65/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
66/// evaluate the expression regardless of what the RHS is, but C only allows
67/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000068namespace {
Richard Smith180f4792011-11-10 06:34:14 +000069 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000070 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000071 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000072
Richard Smith1bf9a9e2011-11-12 22:28:03 +000073 QualType getType(APValue::LValueBase B) {
74 if (!B) return QualType();
75 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
76 return D->getType();
77 return B.get<const Expr*>()->getType();
78 }
79
Richard Smith180f4792011-11-10 06:34:14 +000080 /// Get an LValue path entry, which is known to not be an array index, as a
81 /// field declaration.
82 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
83 APValue::BaseOrMemberType Value;
84 Value.setFromOpaqueValue(E.BaseOrMember);
85 return dyn_cast<FieldDecl>(Value.getPointer());
86 }
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// base class declaration.
89 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
90 APValue::BaseOrMemberType Value;
91 Value.setFromOpaqueValue(E.BaseOrMember);
92 return dyn_cast<CXXRecordDecl>(Value.getPointer());
93 }
94 /// Determine whether this LValue path entry for a base class names a virtual
95 /// base class.
96 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
97 APValue::BaseOrMemberType Value;
98 Value.setFromOpaqueValue(E.BaseOrMember);
99 return Value.getInt();
100 }
101
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 /// Find the path length and type of the most-derived subobject in the given
103 /// path, and find the size of the containing array, if any.
104 static
105 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
106 ArrayRef<APValue::LValuePathEntry> Path,
107 uint64_t &ArraySize, QualType &Type) {
108 unsigned MostDerivedLength = 0;
109 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000110 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000111 if (Type->isArrayType()) {
112 const ConstantArrayType *CAT =
113 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
114 Type = CAT->getElementType();
115 ArraySize = CAT->getSize().getZExtValue();
116 MostDerivedLength = I + 1;
117 } else if (const FieldDecl *FD = getAsField(Path[I])) {
118 Type = FD->getType();
119 ArraySize = 0;
120 MostDerivedLength = I + 1;
121 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000122 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 ArraySize = 0;
124 }
Richard Smith9a17a682011-11-07 05:07:52 +0000125 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000127 }
128
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 // The order of this enum is important for diagnostics.
130 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000131 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
132 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000133 };
134
Richard Smith0a3bdb62011-11-04 02:25:55 +0000135 /// A path from a glvalue to a subobject of that glvalue.
136 struct SubobjectDesignator {
137 /// True if the subobject was named in a manner not supported by C++11. Such
138 /// lvalues can still be folded, but they are not core constant expressions
139 /// and we cannot perform lvalue-to-rvalue conversions on them.
140 bool Invalid : 1;
141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// Is this a pointer one past the end of an object?
143 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000144
Richard Smithb4e85ed2012-01-06 16:39:00 +0000145 /// The length of the path to the most-derived object of which this is a
146 /// subobject.
147 unsigned MostDerivedPathLength : 30;
148
149 /// The size of the array of which the most-derived object is an element, or
150 /// 0 if the most-derived object is not an array element.
151 uint64_t MostDerivedArraySize;
152
153 /// The type of the most derived object referred to by this address.
154 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155
Richard Smith9a17a682011-11-07 05:07:52 +0000156 typedef APValue::LValuePathEntry PathEntry;
157
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158 /// The entries on the path from the glvalue to the designated subobject.
159 SmallVector<PathEntry, 8> Entries;
160
Richard Smithb4e85ed2012-01-06 16:39:00 +0000161 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000162
Richard Smithb4e85ed2012-01-06 16:39:00 +0000163 explicit SubobjectDesignator(QualType T)
164 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
165 MostDerivedArraySize(0), MostDerivedType(T) {}
166
167 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
168 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
169 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000170 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000172 ArrayRef<PathEntry> VEntries = V.getLValuePath();
173 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
174 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000175 MostDerivedPathLength =
176 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
177 V.getLValuePath(), MostDerivedArraySize,
178 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000179 }
180 }
181
Richard Smith0a3bdb62011-11-04 02:25:55 +0000182 void setInvalid() {
183 Invalid = true;
184 Entries.clear();
185 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000186
187 /// Determine whether this is a one-past-the-end pointer.
188 bool isOnePastTheEnd() const {
189 if (IsOnePastTheEnd)
190 return true;
191 if (MostDerivedArraySize &&
192 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
193 return true;
194 return false;
195 }
196
197 /// Check that this refers to a valid subobject.
198 bool isValidSubobject() const {
199 if (Invalid)
200 return false;
201 return !isOnePastTheEnd();
202 }
203 /// Check that this refers to a valid subobject, and if not, produce a
204 /// relevant diagnostic and set the designator as invalid.
205 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
206
207 /// Update this designator to refer to the first element within this array.
208 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000209 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000210 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000211 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000212
213 // This is a most-derived object.
214 MostDerivedType = CAT->getElementType();
215 MostDerivedArraySize = CAT->getSize().getZExtValue();
216 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 }
218 /// Update this designator to refer to the given base or member of this
219 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000220 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000222 APValue::BaseOrMemberType Value(D, Virtual);
223 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000224 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000225
226 // If this isn't a base class, it's a new most-derived object.
227 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
228 MostDerivedType = FD->getType();
229 MostDerivedArraySize = 0;
230 MostDerivedPathLength = Entries.size();
231 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000233 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000236 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000237 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000238 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000239 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
240 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
241 setInvalid();
242 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 return;
244 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 // [expr.add]p4: For the purposes of these operators, a pointer to a
246 // nonarray object behaves the same as a pointer to the first element of
247 // an array of length one with the type of the object as its element type.
248 if (IsOnePastTheEnd && N == (uint64_t)-1)
249 IsOnePastTheEnd = false;
250 else if (!IsOnePastTheEnd && N == 1)
251 IsOnePastTheEnd = true;
252 else if (N != 0) {
253 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000254 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000255 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000256 }
257 };
258
Richard Smith47a1eed2011-10-29 20:57:55 +0000259 /// A core constant value. This can be the value of any constant expression,
260 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000261 ///
262 /// For an LValue, the base and offset are stored in the APValue subobject,
263 /// but the other information is stored in the SubobjectDesignator. For all
264 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000265 class CCValue : public APValue {
266 typedef llvm::APSInt APSInt;
267 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000268 /// If the value is a reference or pointer into a parameter or temporary,
269 /// this is the corresponding call stack frame.
270 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000271 /// If the value is a reference or pointer, this is a description of how the
272 /// subobject was specified.
273 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000274 public:
Richard Smith177dce72011-11-01 16:57:24 +0000275 struct GlobalValue {};
276
Richard Smith47a1eed2011-10-29 20:57:55 +0000277 CCValue() {}
278 explicit CCValue(const APSInt &I) : APValue(I) {}
279 explicit CCValue(const APFloat &F) : APValue(F) {}
280 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
281 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
282 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000283 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000284 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000285 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000286 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000287 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
288 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000289 CCValue(const ValueDecl *D, bool IsDerivedMember,
290 ArrayRef<const CXXRecordDecl*> Path) :
291 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000292 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
293 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000294
Richard Smith177dce72011-11-01 16:57:24 +0000295 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000296 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000297 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000298 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000299 SubobjectDesignator &getLValueDesignator() {
300 assert(getKind() == LValue);
301 return Designator;
302 }
303 const SubobjectDesignator &getLValueDesignator() const {
304 return const_cast<CCValue*>(this)->getLValueDesignator();
305 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000306 };
307
Richard Smithd0dccea2011-10-28 22:34:42 +0000308 /// A stack frame in the constexpr call stack.
309 struct CallStackFrame {
310 EvalInfo &Info;
311
312 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000313 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000314
Richard Smith08d6e032011-12-16 19:06:07 +0000315 /// CallLoc - The location of the call expression for this call.
316 SourceLocation CallLoc;
317
318 /// Callee - The function which was called.
319 const FunctionDecl *Callee;
320
Richard Smith180f4792011-11-10 06:34:14 +0000321 /// This - The binding for the this pointer in this call, if any.
322 const LValue *This;
323
Richard Smithd0dccea2011-10-28 22:34:42 +0000324 /// ParmBindings - Parameter bindings for this function call, indexed by
325 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000326 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000327
Richard Smithbd552ef2011-10-31 05:52:43 +0000328 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
329 typedef MapTy::const_iterator temp_iterator;
330 /// Temporaries - Temporary lvalues materialized within this stack frame.
331 MapTy Temporaries;
332
Richard Smith08d6e032011-12-16 19:06:07 +0000333 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
334 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000335 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000336 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000337 };
338
Richard Smithdd1f29b2011-12-12 09:28:41 +0000339 /// A partial diagnostic which we might know in advance that we are not going
340 /// to emit.
341 class OptionalDiagnostic {
342 PartialDiagnostic *Diag;
343
344 public:
345 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
346
347 template<typename T>
348 OptionalDiagnostic &operator<<(const T &v) {
349 if (Diag)
350 *Diag << v;
351 return *this;
352 }
Richard Smith789f9b62012-01-31 04:08:20 +0000353
354 OptionalDiagnostic &operator<<(const APSInt &I) {
355 if (Diag) {
356 llvm::SmallVector<char, 32> Buffer;
357 I.toString(Buffer);
358 *Diag << StringRef(Buffer.data(), Buffer.size());
359 }
360 return *this;
361 }
362
363 OptionalDiagnostic &operator<<(const APFloat &F) {
364 if (Diag) {
365 llvm::SmallVector<char, 32> Buffer;
366 F.toString(Buffer);
367 *Diag << StringRef(Buffer.data(), Buffer.size());
368 }
369 return *this;
370 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000371 };
372
Richard Smithbd552ef2011-10-31 05:52:43 +0000373 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000374 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000375
376 /// EvalStatus - Contains information about the evaluation.
377 Expr::EvalStatus &EvalStatus;
378
379 /// CurrentCall - The top of the constexpr call stack.
380 CallStackFrame *CurrentCall;
381
Richard Smithbd552ef2011-10-31 05:52:43 +0000382 /// CallStackDepth - The number of calls in the call stack right now.
383 unsigned CallStackDepth;
384
385 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
386 /// OpaqueValues - Values used as the common expression in a
387 /// BinaryConditionalOperator.
388 MapTy OpaqueValues;
389
390 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000391 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000392 CallStackFrame BottomFrame;
393
Richard Smith180f4792011-11-10 06:34:14 +0000394 /// EvaluatingDecl - This is the declaration whose initializer is being
395 /// evaluated, if any.
396 const VarDecl *EvaluatingDecl;
397
398 /// EvaluatingDeclValue - This is the value being constructed for the
399 /// declaration whose initializer is being evaluated, if any.
400 APValue *EvaluatingDeclValue;
401
Richard Smithc1c5f272011-12-13 06:39:58 +0000402 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
403 /// notes attached to it will also be stored, otherwise they will not be.
404 bool HasActiveDiagnostic;
405
Richard Smith745f5142012-01-27 01:14:48 +0000406 /// CheckingPotentialConstantExpression - Are we checking whether the
407 /// expression is a potential constant expression? If so, some diagnostics
408 /// are suppressed.
409 bool CheckingPotentialConstantExpression;
410
Richard Smithbd552ef2011-10-31 05:52:43 +0000411
412 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000413 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000414 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000415 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
416 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000417
Richard Smithbd552ef2011-10-31 05:52:43 +0000418 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
419 MapTy::const_iterator i = OpaqueValues.find(e);
420 if (i == OpaqueValues.end()) return 0;
421 return &i->second;
422 }
423
Richard Smith180f4792011-11-10 06:34:14 +0000424 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
425 EvaluatingDecl = VD;
426 EvaluatingDeclValue = &Value;
427 }
428
Richard Smithc18c4232011-11-21 19:36:32 +0000429 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
430
Richard Smithc1c5f272011-12-13 06:39:58 +0000431 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000432 // Don't perform any constexpr calls (other than the call we're checking)
433 // when checking a potential constant expression.
434 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
435 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000436 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
437 return true;
438 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
439 << getLangOpts().ConstexprCallDepth;
440 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000441 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000442
Richard Smithc1c5f272011-12-13 06:39:58 +0000443 private:
444 /// Add a diagnostic to the diagnostics list.
445 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
446 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
447 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
448 return EvalStatus.Diag->back().second;
449 }
450
Richard Smith08d6e032011-12-16 19:06:07 +0000451 /// Add notes containing a call stack to the current point of evaluation.
452 void addCallStack(unsigned Limit);
453
Richard Smithc1c5f272011-12-13 06:39:58 +0000454 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000455 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000456 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
457 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000458 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000459 // If we have a prior diagnostic, it will be noting that the expression
460 // isn't a constant expression. This diagnostic is more important.
461 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000462 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000463 unsigned CallStackNotes = CallStackDepth - 1;
464 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
465 if (Limit)
466 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000467 if (CheckingPotentialConstantExpression)
468 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000469
Richard Smithc1c5f272011-12-13 06:39:58 +0000470 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000471 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000472 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
473 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000474 if (!CheckingPotentialConstantExpression)
475 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000476 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000477 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000478 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000479 return OptionalDiagnostic();
480 }
481
482 /// Diagnose that the evaluation does not produce a C++11 core constant
483 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000484 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
485 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000486 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000487 // Don't override a previous diagnostic.
488 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
489 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 return Diag(Loc, DiagId, ExtraNotes);
491 }
492
493 /// Add a note to a prior diagnostic.
494 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
495 if (!HasActiveDiagnostic)
496 return OptionalDiagnostic();
497 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000498 }
Richard Smith099e7f62011-12-19 06:19:21 +0000499
500 /// Add a stack of notes to a prior diagnostic.
501 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
502 if (HasActiveDiagnostic) {
503 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
504 Diags.begin(), Diags.end());
505 }
506 }
Richard Smith745f5142012-01-27 01:14:48 +0000507
508 /// Should we continue evaluation as much as possible after encountering a
509 /// construct which can't be folded?
510 bool keepEvaluatingAfterFailure() {
511 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
512 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000513 };
Richard Smith08d6e032011-12-16 19:06:07 +0000514}
Richard Smithbd552ef2011-10-31 05:52:43 +0000515
Richard Smithb4e85ed2012-01-06 16:39:00 +0000516bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
517 CheckSubobjectKind CSK) {
518 if (Invalid)
519 return false;
520 if (isOnePastTheEnd()) {
521 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
522 << CSK;
523 setInvalid();
524 return false;
525 }
526 return true;
527}
528
529void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
530 const Expr *E, uint64_t N) {
531 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
532 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
533 << static_cast<int>(N) << /*array*/ 0
534 << static_cast<unsigned>(MostDerivedArraySize);
535 else
536 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
537 << static_cast<int>(N) << /*non-array*/ 1;
538 setInvalid();
539}
540
Richard Smith08d6e032011-12-16 19:06:07 +0000541CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
542 const FunctionDecl *Callee, const LValue *This,
543 const CCValue *Arguments)
544 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
545 This(This), Arguments(Arguments) {
546 Info.CurrentCall = this;
547 ++Info.CallStackDepth;
548}
549
550CallStackFrame::~CallStackFrame() {
551 assert(Info.CurrentCall == this && "calls retired out of order");
552 --Info.CallStackDepth;
553 Info.CurrentCall = Caller;
554}
555
556/// Produce a string describing the given constexpr call.
557static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
558 unsigned ArgIndex = 0;
559 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
560 !isa<CXXConstructorDecl>(Frame->Callee);
561
562 if (!IsMemberCall)
563 Out << *Frame->Callee << '(';
564
565 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
566 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000567 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000568 Out << ", ";
569
570 const ParmVarDecl *Param = *I;
571 const CCValue &Arg = Frame->Arguments[ArgIndex];
572 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
573 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
574 else {
575 // Deliberately slice off the frame to form an APValue we can print.
576 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
577 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000579 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
580 }
581
582 if (ArgIndex == 0 && IsMemberCall)
583 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000584 }
585
Richard Smith08d6e032011-12-16 19:06:07 +0000586 Out << ')';
587}
588
589void EvalInfo::addCallStack(unsigned Limit) {
590 // Determine which calls to skip, if any.
591 unsigned ActiveCalls = CallStackDepth - 1;
592 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
593 if (Limit && Limit < ActiveCalls) {
594 SkipStart = Limit / 2 + Limit % 2;
595 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000596 }
597
Richard Smith08d6e032011-12-16 19:06:07 +0000598 // Walk the call stack and add the diagnostics.
599 unsigned CallIdx = 0;
600 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
601 Frame = Frame->Caller, ++CallIdx) {
602 // Skip this call?
603 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
604 if (CallIdx == SkipStart) {
605 // Note that we're skipping calls.
606 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
607 << unsigned(ActiveCalls - Limit);
608 }
609 continue;
610 }
611
612 llvm::SmallVector<char, 128> Buffer;
613 llvm::raw_svector_ostream Out(Buffer);
614 describeCall(Frame, Out);
615 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
616 }
617}
618
619namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000620 struct ComplexValue {
621 private:
622 bool IsInt;
623
624 public:
625 APSInt IntReal, IntImag;
626 APFloat FloatReal, FloatImag;
627
628 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
629
630 void makeComplexFloat() { IsInt = false; }
631 bool isComplexFloat() const { return !IsInt; }
632 APFloat &getComplexFloatReal() { return FloatReal; }
633 APFloat &getComplexFloatImag() { return FloatImag; }
634
635 void makeComplexInt() { IsInt = true; }
636 bool isComplexInt() const { return IsInt; }
637 APSInt &getComplexIntReal() { return IntReal; }
638 APSInt &getComplexIntImag() { return IntImag; }
639
Richard Smith47a1eed2011-10-29 20:57:55 +0000640 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000641 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000642 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000643 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000644 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000645 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000646 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000647 assert(v.isComplexFloat() || v.isComplexInt());
648 if (v.isComplexFloat()) {
649 makeComplexFloat();
650 FloatReal = v.getComplexFloatReal();
651 FloatImag = v.getComplexFloatImag();
652 } else {
653 makeComplexInt();
654 IntReal = v.getComplexIntReal();
655 IntImag = v.getComplexIntImag();
656 }
657 }
John McCallf4cf1a12010-05-07 17:22:02 +0000658 };
John McCallefdb83e2010-05-07 21:00:08 +0000659
660 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000661 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000662 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000663 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000664 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000665
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000666 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000667 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000668 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000669 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000670 SubobjectDesignator &getLValueDesignator() { return Designator; }
671 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000672
Richard Smith47a1eed2011-10-29 20:57:55 +0000673 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000674 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000675 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000676 void setFrom(const CCValue &V) {
677 assert(V.isLValue());
678 Base = V.getLValueBase();
679 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000680 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000681 Designator = V.getLValueDesignator();
682 }
683
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000684 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
685 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000686 Offset = CharUnits::Zero();
687 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000688 Designator = SubobjectDesignator(getType(B));
689 }
690
691 // Check that this LValue is not based on a null pointer. If it is, produce
692 // a diagnostic and mark the designator as invalid.
693 bool checkNullPointer(EvalInfo &Info, const Expr *E,
694 CheckSubobjectKind CSK) {
695 if (Designator.Invalid)
696 return false;
697 if (!Base) {
698 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
699 << CSK;
700 Designator.setInvalid();
701 return false;
702 }
703 return true;
704 }
705
706 // Check this LValue refers to an object. If not, set the designator to be
707 // invalid and emit a diagnostic.
708 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
709 return checkNullPointer(Info, E, CSK) &&
710 Designator.checkSubobject(Info, E, CSK);
711 }
712
713 void addDecl(EvalInfo &Info, const Expr *E,
714 const Decl *D, bool Virtual = false) {
715 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
716 Designator.addDeclUnchecked(D, Virtual);
717 }
718 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
719 checkSubobject(Info, E, CSK_ArrayToPointer);
720 Designator.addArrayUnchecked(CAT);
721 }
722 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
723 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
724 return;
725 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000726 }
John McCallefdb83e2010-05-07 21:00:08 +0000727 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000728
729 struct MemberPtr {
730 MemberPtr() {}
731 explicit MemberPtr(const ValueDecl *Decl) :
732 DeclAndIsDerivedMember(Decl, false), Path() {}
733
734 /// The member or (direct or indirect) field referred to by this member
735 /// pointer, or 0 if this is a null member pointer.
736 const ValueDecl *getDecl() const {
737 return DeclAndIsDerivedMember.getPointer();
738 }
739 /// Is this actually a member of some type derived from the relevant class?
740 bool isDerivedMember() const {
741 return DeclAndIsDerivedMember.getInt();
742 }
743 /// Get the class which the declaration actually lives in.
744 const CXXRecordDecl *getContainingRecord() const {
745 return cast<CXXRecordDecl>(
746 DeclAndIsDerivedMember.getPointer()->getDeclContext());
747 }
748
749 void moveInto(CCValue &V) const {
750 V = CCValue(getDecl(), isDerivedMember(), Path);
751 }
752 void setFrom(const CCValue &V) {
753 assert(V.isMemberPointer());
754 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
755 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
756 Path.clear();
757 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
758 Path.insert(Path.end(), P.begin(), P.end());
759 }
760
761 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
762 /// whether the member is a member of some class derived from the class type
763 /// of the member pointer.
764 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
765 /// Path - The path of base/derived classes from the member declaration's
766 /// class (exclusive) to the class type of the member pointer (inclusive).
767 SmallVector<const CXXRecordDecl*, 4> Path;
768
769 /// Perform a cast towards the class of the Decl (either up or down the
770 /// hierarchy).
771 bool castBack(const CXXRecordDecl *Class) {
772 assert(!Path.empty());
773 const CXXRecordDecl *Expected;
774 if (Path.size() >= 2)
775 Expected = Path[Path.size() - 2];
776 else
777 Expected = getContainingRecord();
778 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
779 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
780 // if B does not contain the original member and is not a base or
781 // derived class of the class containing the original member, the result
782 // of the cast is undefined.
783 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
784 // (D::*). We consider that to be a language defect.
785 return false;
786 }
787 Path.pop_back();
788 return true;
789 }
790 /// Perform a base-to-derived member pointer cast.
791 bool castToDerived(const CXXRecordDecl *Derived) {
792 if (!getDecl())
793 return true;
794 if (!isDerivedMember()) {
795 Path.push_back(Derived);
796 return true;
797 }
798 if (!castBack(Derived))
799 return false;
800 if (Path.empty())
801 DeclAndIsDerivedMember.setInt(false);
802 return true;
803 }
804 /// Perform a derived-to-base member pointer cast.
805 bool castToBase(const CXXRecordDecl *Base) {
806 if (!getDecl())
807 return true;
808 if (Path.empty())
809 DeclAndIsDerivedMember.setInt(true);
810 if (isDerivedMember()) {
811 Path.push_back(Base);
812 return true;
813 }
814 return castBack(Base);
815 }
816 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000817
Richard Smithb02e4622012-02-01 01:42:44 +0000818 /// Compare two member pointers, which are assumed to be of the same type.
819 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
820 if (!LHS.getDecl() || !RHS.getDecl())
821 return !LHS.getDecl() && !RHS.getDecl();
822 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
823 return false;
824 return LHS.Path == RHS.Path;
825 }
826
Richard Smithc1c5f272011-12-13 06:39:58 +0000827 /// Kinds of constant expression checking, for diagnostics.
828 enum CheckConstantExpressionKind {
829 CCEK_Constant, ///< A normal constant.
830 CCEK_ReturnValue, ///< A constexpr function return value.
831 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
832 };
John McCallf4cf1a12010-05-07 17:22:02 +0000833}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000834
Richard Smith47a1eed2011-10-29 20:57:55 +0000835static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000836static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000837 const LValue &This, const Expr *E,
838 CheckConstantExpressionKind CCEK
839 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000840static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
841static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000842static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
843 EvalInfo &Info);
844static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000845static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000846static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000847 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000848static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000849static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000850
851//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000852// Misc utilities
853//===----------------------------------------------------------------------===//
854
Richard Smith180f4792011-11-10 06:34:14 +0000855/// Should this call expression be treated as a string literal?
856static bool IsStringLiteralCall(const CallExpr *E) {
857 unsigned Builtin = E->isBuiltinCall();
858 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
859 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
860}
861
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000862static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000863 // C++11 [expr.const]p3 An address constant expression is a prvalue core
864 // constant expression of pointer type that evaluates to...
865
866 // ... a null pointer value, or a prvalue core constant expression of type
867 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000868 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000869
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000870 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
871 // ... the address of an object with static storage duration,
872 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
873 return VD->hasGlobalStorage();
874 // ... the address of a function,
875 return isa<FunctionDecl>(D);
876 }
877
878 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000879 switch (E->getStmtClass()) {
880 default:
881 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000882 case Expr::CompoundLiteralExprClass:
883 return cast<CompoundLiteralExpr>(E)->isFileScope();
884 // A string literal has static storage duration.
885 case Expr::StringLiteralClass:
886 case Expr::PredefinedExprClass:
887 case Expr::ObjCStringLiteralClass:
888 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000889 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000890 return true;
891 case Expr::CallExprClass:
892 return IsStringLiteralCall(cast<CallExpr>(E));
893 // For GCC compatibility, &&label has static storage duration.
894 case Expr::AddrLabelExprClass:
895 return true;
896 // A Block literal expression may be used as the initialization value for
897 // Block variables at global or local static scope.
898 case Expr::BlockExprClass:
899 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000900 case Expr::ImplicitValueInitExprClass:
901 // FIXME:
902 // We can never form an lvalue with an implicit value initialization as its
903 // base through expression evaluation, so these only appear in one case: the
904 // implicit variable declaration we invent when checking whether a constexpr
905 // constructor can produce a constant expression. We must assume that such
906 // an expression might be a global lvalue.
907 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000908 }
John McCall42c8f872010-05-10 23:27:23 +0000909}
910
Richard Smith9a17a682011-11-07 05:07:52 +0000911/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000912/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000913/// either LValue or CCValue. Return true if we can fold this expression,
914/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000915template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000916static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000917 const T &LVal, APValue &Value,
918 CheckConstantExpressionKind CCEK) {
919 APValue::LValueBase Base = LVal.getLValueBase();
920 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
921
922 if (!IsGlobalLValue(Base)) {
923 if (Info.getLangOpts().CPlusPlus0x) {
924 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
925 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
926 << E->isGLValue() << !Designator.Entries.empty()
927 << !!VD << CCEK << VD;
928 if (VD)
929 Info.Note(VD->getLocation(), diag::note_declared_at);
930 else
931 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
932 diag::note_constexpr_temporary_here);
933 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000934 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000935 }
Richard Smith61e61622012-01-12 06:08:57 +0000936 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000937 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000938 }
Richard Smith9a17a682011-11-07 05:07:52 +0000939
Richard Smithb4e85ed2012-01-06 16:39:00 +0000940 bool IsReferenceType = E->isGLValue();
941
942 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000943 // This is not a core constant expression. An appropriate diagnostic will
944 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000945 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
946 APValue::NoLValuePath());
947 return true;
948 }
949
Richard Smithb4e85ed2012-01-06 16:39:00 +0000950 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
951 Designator.Entries, Designator.IsOnePastTheEnd);
952
953 // Allow address constant expressions to be past-the-end pointers. This is
954 // an extension: the standard requires them to point to an object.
955 if (!IsReferenceType)
956 return true;
957
958 // A reference constant expression must refer to an object.
959 if (!Base) {
960 // FIXME: diagnostic
961 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000962 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000963 }
964
Richard Smithc1c5f272011-12-13 06:39:58 +0000965 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000966 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000967 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
968 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
969 << !Designator.Entries.empty() << !!VD << VD;
970 if (VD)
971 Info.Note(VD->getLocation(), diag::note_declared_at);
972 else
973 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
974 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000975 }
976
Richard Smith9a17a682011-11-07 05:07:52 +0000977 return true;
978}
979
Richard Smith51201882011-12-30 21:15:51 +0000980/// Check that this core constant expression is of literal type, and if not,
981/// produce an appropriate diagnostic.
982static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
983 if (!E->isRValue() || E->getType()->isLiteralType())
984 return true;
985
986 // Prvalue constant expressions must be of literal types.
987 if (Info.getLangOpts().CPlusPlus0x)
988 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
989 << E->getType();
990 else
991 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
992 return false;
993}
994
Richard Smith47a1eed2011-10-29 20:57:55 +0000995/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000996/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000997/// If not, report an appropriate diagnostic. Does not check that the expression
998/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000999static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001000 const CCValue &CCValue, APValue &Value,
1001 CheckConstantExpressionKind CCEK
1002 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001003 if (!CCValue.isLValue()) {
1004 Value = CCValue;
1005 return true;
1006 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001007 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001008}
1009
Richard Smith9e36b532011-10-31 05:11:32 +00001010const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001011 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001012}
1013
1014static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001015 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001016}
1017
Richard Smith65ac5982011-11-01 21:06:14 +00001018static bool IsWeakLValue(const LValue &Value) {
1019 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001020 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001021}
1022
Richard Smithe24f5fc2011-11-17 22:56:20 +00001023static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001024 // A null base expression indicates a null pointer. These are always
1025 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001026 if (!Value.getLValueBase()) {
1027 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001028 return true;
1029 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001030
Richard Smithe24f5fc2011-11-17 22:56:20 +00001031 // We have a non-null base. These are generally known to be true, but if it's
1032 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001033 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001034 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001035 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001036}
1037
Richard Smith47a1eed2011-10-29 20:57:55 +00001038static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001039 switch (Val.getKind()) {
1040 case APValue::Uninitialized:
1041 return false;
1042 case APValue::Int:
1043 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001044 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001045 case APValue::Float:
1046 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001047 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001048 case APValue::ComplexInt:
1049 Result = Val.getComplexIntReal().getBoolValue() ||
1050 Val.getComplexIntImag().getBoolValue();
1051 return true;
1052 case APValue::ComplexFloat:
1053 Result = !Val.getComplexFloatReal().isZero() ||
1054 !Val.getComplexFloatImag().isZero();
1055 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001056 case APValue::LValue:
1057 return EvalPointerValueAsBool(Val, Result);
1058 case APValue::MemberPointer:
1059 Result = Val.getMemberPointerDecl();
1060 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001061 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001062 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001063 case APValue::Struct:
1064 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001065 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001066 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001067 }
1068
Richard Smithc49bd112011-10-28 17:51:58 +00001069 llvm_unreachable("unknown APValue kind");
1070}
1071
1072static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1073 EvalInfo &Info) {
1074 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001075 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001076 if (!Evaluate(Val, Info, E))
1077 return false;
1078 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001079}
1080
Richard Smithc1c5f272011-12-13 06:39:58 +00001081template<typename T>
1082static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1083 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001084 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001085 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001086 return false;
1087}
1088
1089static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1090 QualType SrcType, const APFloat &Value,
1091 QualType DestType, APSInt &Result) {
1092 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001093 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001094 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Richard Smithc1c5f272011-12-13 06:39:58 +00001096 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001097 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001098 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1099 & APFloat::opInvalidOp)
1100 return HandleOverflow(Info, E, Value, DestType);
1101 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001102}
1103
Richard Smithc1c5f272011-12-13 06:39:58 +00001104static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1105 QualType SrcType, QualType DestType,
1106 APFloat &Result) {
1107 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001108 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001109 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1110 APFloat::rmNearestTiesToEven, &ignored)
1111 & APFloat::opOverflow)
1112 return HandleOverflow(Info, E, Value, DestType);
1113 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001114}
1115
Richard Smithf72fccf2012-01-30 22:27:01 +00001116static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1117 QualType DestType, QualType SrcType,
1118 APSInt &Value) {
1119 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001120 APSInt Result = Value;
1121 // Figure out if this is a truncate, extend or noop cast.
1122 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001123 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001124 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001125 return Result;
1126}
1127
Richard Smithc1c5f272011-12-13 06:39:58 +00001128static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1129 QualType SrcType, const APSInt &Value,
1130 QualType DestType, APFloat &Result) {
1131 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1132 if (Result.convertFromAPInt(Value, Value.isSigned(),
1133 APFloat::rmNearestTiesToEven)
1134 & APFloat::opOverflow)
1135 return HandleOverflow(Info, E, Value, DestType);
1136 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001137}
1138
Eli Friedmane6a24e82011-12-22 03:51:45 +00001139static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1140 llvm::APInt &Res) {
1141 CCValue SVal;
1142 if (!Evaluate(SVal, Info, E))
1143 return false;
1144 if (SVal.isInt()) {
1145 Res = SVal.getInt();
1146 return true;
1147 }
1148 if (SVal.isFloat()) {
1149 Res = SVal.getFloat().bitcastToAPInt();
1150 return true;
1151 }
1152 if (SVal.isVector()) {
1153 QualType VecTy = E->getType();
1154 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1155 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1156 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1157 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1158 Res = llvm::APInt::getNullValue(VecSize);
1159 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1160 APValue &Elt = SVal.getVectorElt(i);
1161 llvm::APInt EltAsInt;
1162 if (Elt.isInt()) {
1163 EltAsInt = Elt.getInt();
1164 } else if (Elt.isFloat()) {
1165 EltAsInt = Elt.getFloat().bitcastToAPInt();
1166 } else {
1167 // Don't try to handle vectors of anything other than int or float
1168 // (not sure if it's possible to hit this case).
1169 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1170 return false;
1171 }
1172 unsigned BaseEltSize = EltAsInt.getBitWidth();
1173 if (BigEndian)
1174 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1175 else
1176 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1177 }
1178 return true;
1179 }
1180 // Give up if the input isn't an int, float, or vector. For example, we
1181 // reject "(v4i16)(intptr_t)&a".
1182 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1183 return false;
1184}
1185
Richard Smithb4e85ed2012-01-06 16:39:00 +00001186/// Cast an lvalue referring to a base subobject to a derived class, by
1187/// truncating the lvalue's path to the given length.
1188static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1189 const RecordDecl *TruncatedType,
1190 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001191 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001192
1193 // Check we actually point to a derived class object.
1194 if (TruncatedElements == D.Entries.size())
1195 return true;
1196 assert(TruncatedElements >= D.MostDerivedPathLength &&
1197 "not casting to a derived class");
1198 if (!Result.checkSubobject(Info, E, CSK_Derived))
1199 return false;
1200
1201 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001202 const RecordDecl *RD = TruncatedType;
1203 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001204 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1205 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001206 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001207 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001208 else
Richard Smith180f4792011-11-10 06:34:14 +00001209 Result.Offset -= Layout.getBaseClassOffset(Base);
1210 RD = Base;
1211 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001212 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001213 return true;
1214}
1215
Richard Smithb4e85ed2012-01-06 16:39:00 +00001216static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001217 const CXXRecordDecl *Derived,
1218 const CXXRecordDecl *Base,
1219 const ASTRecordLayout *RL = 0) {
1220 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1221 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001222 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001223}
1224
Richard Smithb4e85ed2012-01-06 16:39:00 +00001225static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001226 const CXXRecordDecl *DerivedDecl,
1227 const CXXBaseSpecifier *Base) {
1228 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1229
1230 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001231 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001232 return true;
1233 }
1234
Richard Smithb4e85ed2012-01-06 16:39:00 +00001235 SubobjectDesignator &D = Obj.Designator;
1236 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001237 return false;
1238
Richard Smithb4e85ed2012-01-06 16:39:00 +00001239 // Extract most-derived object and corresponding type.
1240 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1241 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1242 return false;
1243
1244 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001245 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1246 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001247 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001248 return true;
1249}
1250
1251/// Update LVal to refer to the given field, which must be a member of the type
1252/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001253static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001254 const FieldDecl *FD,
1255 const ASTRecordLayout *RL = 0) {
1256 if (!RL)
1257 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1258
1259 unsigned I = FD->getFieldIndex();
1260 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001261 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001262}
1263
Richard Smithd9b02e72012-01-25 22:15:11 +00001264/// Update LVal to refer to the given indirect field.
1265static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1266 LValue &LVal,
1267 const IndirectFieldDecl *IFD) {
1268 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1269 CE = IFD->chain_end(); C != CE; ++C)
1270 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1271}
1272
Richard Smith180f4792011-11-10 06:34:14 +00001273/// Get the size of the given type in char units.
1274static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1275 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1276 // extension.
1277 if (Type->isVoidType() || Type->isFunctionType()) {
1278 Size = CharUnits::One();
1279 return true;
1280 }
1281
1282 if (!Type->isConstantSizeType()) {
1283 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001284 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001285 return false;
1286 }
1287
1288 Size = Info.Ctx.getTypeSizeInChars(Type);
1289 return true;
1290}
1291
1292/// Update a pointer value to model pointer arithmetic.
1293/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001294/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001295/// \param LVal - The pointer value to be updated.
1296/// \param EltTy - The pointee type represented by LVal.
1297/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001298static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1299 LValue &LVal, QualType EltTy,
1300 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001301 CharUnits SizeOfPointee;
1302 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1303 return false;
1304
1305 // Compute the new offset in the appropriate width.
1306 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001307 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001308 return true;
1309}
1310
Richard Smith03f96112011-10-24 17:54:18 +00001311/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001312static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1313 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001314 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001315 // If this is a parameter to an active constexpr function call, perform
1316 // argument substitution.
1317 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001318 // Assume arguments of a potential constant expression are unknown
1319 // constant expressions.
1320 if (Info.CheckingPotentialConstantExpression)
1321 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001322 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001323 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001324 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001325 }
Richard Smith177dce72011-11-01 16:57:24 +00001326 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1327 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001328 }
Richard Smith03f96112011-10-24 17:54:18 +00001329
Richard Smith099e7f62011-12-19 06:19:21 +00001330 // Dig out the initializer, and use the declaration which it's attached to.
1331 const Expr *Init = VD->getAnyInitializer(VD);
1332 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001333 // If we're checking a potential constant expression, the variable could be
1334 // initialized later.
1335 if (!Info.CheckingPotentialConstantExpression)
1336 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001337 return false;
1338 }
1339
Richard Smith180f4792011-11-10 06:34:14 +00001340 // If we're currently evaluating the initializer of this declaration, use that
1341 // in-flight value.
1342 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001343 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1344 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001345 return !Result.isUninit();
1346 }
1347
Richard Smith65ac5982011-11-01 21:06:14 +00001348 // Never evaluate the initializer of a weak variable. We can't be sure that
1349 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001350 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001351 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001352 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001353 }
Richard Smith65ac5982011-11-01 21:06:14 +00001354
Richard Smith099e7f62011-12-19 06:19:21 +00001355 // Check that we can fold the initializer. In C++, we will have already done
1356 // this in the cases where it matters for conformance.
1357 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1358 if (!VD->evaluateValue(Notes)) {
1359 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1360 Notes.size() + 1) << VD;
1361 Info.Note(VD->getLocation(), diag::note_declared_at);
1362 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001363 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001364 } else if (!VD->checkInitIsICE()) {
1365 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1366 Notes.size() + 1) << VD;
1367 Info.Note(VD->getLocation(), diag::note_declared_at);
1368 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001369 }
Richard Smith03f96112011-10-24 17:54:18 +00001370
Richard Smithb4e85ed2012-01-06 16:39:00 +00001371 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001372 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001373}
1374
Richard Smithc49bd112011-10-28 17:51:58 +00001375static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001376 Qualifiers Quals = T.getQualifiers();
1377 return Quals.hasConst() && !Quals.hasVolatile();
1378}
1379
Richard Smith59efe262011-11-11 04:05:33 +00001380/// Get the base index of the given base class within an APValue representing
1381/// the given derived class.
1382static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1383 const CXXRecordDecl *Base) {
1384 Base = Base->getCanonicalDecl();
1385 unsigned Index = 0;
1386 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1387 E = Derived->bases_end(); I != E; ++I, ++Index) {
1388 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1389 return Index;
1390 }
1391
1392 llvm_unreachable("base class missing from derived class's bases list");
1393}
1394
Richard Smithcc5d4f62011-11-07 09:22:26 +00001395/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001396static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1397 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001398 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001399 if (Sub.Invalid)
1400 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001401 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001402 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001403 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001404 (unsigned)diag::note_constexpr_read_past_end :
1405 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001406 return false;
1407 }
Richard Smithf64699e2011-11-11 08:28:03 +00001408 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001409 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001410 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1411 // This object might be initialized later.
1412 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001413
1414 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1415 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001416 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001417 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001418 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001419 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001420 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001421 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001422 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001423 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001424 // Note, it should not be possible to form a pointer with a valid
1425 // designator which points more than one past the end of the array.
1426 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001427 (unsigned)diag::note_constexpr_read_past_end :
1428 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001429 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001430 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001431 if (O->getArrayInitializedElts() > Index)
1432 O = &O->getArrayInitializedElt(Index);
1433 else
1434 O = &O->getArrayFiller();
1435 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001436 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1437 // Next subobject is a class, struct or union field.
1438 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1439 if (RD->isUnion()) {
1440 const FieldDecl *UnionField = O->getUnionField();
1441 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001442 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001443 Info.Diag(E->getExprLoc(),
1444 diag::note_constexpr_read_inactive_union_member)
1445 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001446 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001447 }
Richard Smith180f4792011-11-10 06:34:14 +00001448 O = &O->getUnionValue();
1449 } else
1450 O = &O->getStructField(Field->getFieldIndex());
1451 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001452
1453 if (ObjType.isVolatileQualified()) {
1454 if (Info.getLangOpts().CPlusPlus) {
1455 // FIXME: Include a description of the path to the volatile subobject.
1456 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1457 << 2 << Field;
1458 Info.Note(Field->getLocation(), diag::note_declared_at);
1459 } else {
1460 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1461 }
1462 return false;
1463 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001464 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001465 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001466 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1467 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1468 O = &O->getStructBase(getBaseIndex(Derived, Base));
1469 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001470 }
Richard Smith180f4792011-11-10 06:34:14 +00001471
Richard Smithf48fdb02011-12-09 22:58:01 +00001472 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001473 if (!Info.CheckingPotentialConstantExpression)
1474 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001475 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001476 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001477 }
1478
Richard Smithb4e85ed2012-01-06 16:39:00 +00001479 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001480 return true;
1481}
1482
Richard Smith180f4792011-11-10 06:34:14 +00001483/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1484/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1485/// for looking up the glvalue referred to by an entity of reference type.
1486///
1487/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001488/// \param Conv - The expression for which we are performing the conversion.
1489/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001490/// \param Type - The type we expect this conversion to produce.
1491/// \param LVal - The glvalue on which we are attempting to perform this action.
1492/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001493static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1494 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001495 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001496 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1497 if (!Info.getLangOpts().CPlusPlus)
1498 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1499
Richard Smithb4e85ed2012-01-06 16:39:00 +00001500 if (LVal.Designator.Invalid)
1501 // A diagnostic will have already been produced.
1502 return false;
1503
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001504 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001505 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001506 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001507
Richard Smithf48fdb02011-12-09 22:58:01 +00001508 if (!LVal.Base) {
1509 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001510 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1511 return false;
1512 }
1513
1514 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1515 // is not a constant expression (even if the object is non-volatile). We also
1516 // apply this rule to C++98, in order to conform to the expected 'volatile'
1517 // semantics.
1518 if (Type.isVolatileQualified()) {
1519 if (Info.getLangOpts().CPlusPlus)
1520 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1521 else
1522 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001523 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001524 }
Richard Smithc49bd112011-10-28 17:51:58 +00001525
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001526 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001527 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1528 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001529 // expressions are constant expressions too. Inside constexpr functions,
1530 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001531 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001532 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001533 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001534 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001535 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001536 }
1537
Richard Smith7098cbd2011-12-21 05:04:46 +00001538 // DR1313: If the object is volatile-qualified but the glvalue was not,
1539 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001540 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001541 if (VT.isVolatileQualified()) {
1542 if (Info.getLangOpts().CPlusPlus) {
1543 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1544 Info.Note(VD->getLocation(), diag::note_declared_at);
1545 } else {
1546 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001547 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001548 return false;
1549 }
1550
1551 if (!isa<ParmVarDecl>(VD)) {
1552 if (VD->isConstexpr()) {
1553 // OK, we can read this variable.
1554 } else if (VT->isIntegralOrEnumerationType()) {
1555 if (!VT.isConstQualified()) {
1556 if (Info.getLangOpts().CPlusPlus) {
1557 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1558 Info.Note(VD->getLocation(), diag::note_declared_at);
1559 } else {
1560 Info.Diag(Loc);
1561 }
1562 return false;
1563 }
1564 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1565 // We support folding of const floating-point types, in order to make
1566 // static const data members of such types (supported as an extension)
1567 // more useful.
1568 if (Info.getLangOpts().CPlusPlus0x) {
1569 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1570 Info.Note(VD->getLocation(), diag::note_declared_at);
1571 } else {
1572 Info.CCEDiag(Loc);
1573 }
1574 } else {
1575 // FIXME: Allow folding of values of any literal type in all languages.
1576 if (Info.getLangOpts().CPlusPlus0x) {
1577 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1578 Info.Note(VD->getLocation(), diag::note_declared_at);
1579 } else {
1580 Info.Diag(Loc);
1581 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001582 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001583 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001584 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001585
Richard Smithf48fdb02011-12-09 22:58:01 +00001586 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001587 return false;
1588
Richard Smith47a1eed2011-10-29 20:57:55 +00001589 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001590 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001591
1592 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1593 // conversion. This happens when the declaration and the lvalue should be
1594 // considered synonymous, for instance when initializing an array of char
1595 // from a string literal. Continue as if the initializer lvalue was the
1596 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001597 assert(RVal.getLValueOffset().isZero() &&
1598 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001599 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001600 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001601 }
1602
Richard Smith7098cbd2011-12-21 05:04:46 +00001603 // Volatile temporary objects cannot be read in constant expressions.
1604 if (Base->getType().isVolatileQualified()) {
1605 if (Info.getLangOpts().CPlusPlus) {
1606 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1607 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1608 } else {
1609 Info.Diag(Loc);
1610 }
1611 return false;
1612 }
1613
Richard Smith0a3bdb62011-11-04 02:25:55 +00001614 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1615 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1616 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001617 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001618 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001619 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001620 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001621
1622 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001623 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001624 const ConstantArrayType *CAT =
1625 Info.Ctx.getAsConstantArrayType(S->getType());
1626 if (Index >= CAT->getSize().getZExtValue()) {
1627 // Note, it should not be possible to form a pointer which points more
1628 // than one past the end of the array without producing a prior const expr
1629 // diagnostic.
1630 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001631 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001632 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001633 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1634 Type->isUnsignedIntegerType());
1635 if (Index < S->getLength())
1636 Value = S->getCodeUnit(Index);
1637 RVal = CCValue(Value);
1638 return true;
1639 }
1640
Richard Smithcc5d4f62011-11-07 09:22:26 +00001641 if (Frame) {
1642 // If this is a temporary expression with a nontrivial initializer, grab the
1643 // value from the relevant stack frame.
1644 RVal = Frame->Temporaries[Base];
1645 } else if (const CompoundLiteralExpr *CLE
1646 = dyn_cast<CompoundLiteralExpr>(Base)) {
1647 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1648 // initializer until now for such expressions. Such an expression can't be
1649 // an ICE in C, so this only matters for fold.
1650 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1651 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1652 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001653 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001654 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001655 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001656 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001657
Richard Smithf48fdb02011-12-09 22:58:01 +00001658 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1659 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001660}
1661
Richard Smith59efe262011-11-11 04:05:33 +00001662/// Build an lvalue for the object argument of a member function call.
1663static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1664 LValue &This) {
1665 if (Object->getType()->isPointerType())
1666 return EvaluatePointer(Object, This, Info);
1667
1668 if (Object->isGLValue())
1669 return EvaluateLValue(Object, This, Info);
1670
Richard Smithe24f5fc2011-11-17 22:56:20 +00001671 if (Object->getType()->isLiteralType())
1672 return EvaluateTemporary(Object, This, Info);
1673
1674 return false;
1675}
1676
1677/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1678/// lvalue referring to the result.
1679///
1680/// \param Info - Information about the ongoing evaluation.
1681/// \param BO - The member pointer access operation.
1682/// \param LV - Filled in with a reference to the resulting object.
1683/// \param IncludeMember - Specifies whether the member itself is included in
1684/// the resulting LValue subobject designator. This is not possible when
1685/// creating a bound member function.
1686/// \return The field or method declaration to which the member pointer refers,
1687/// or 0 if evaluation fails.
1688static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1689 const BinaryOperator *BO,
1690 LValue &LV,
1691 bool IncludeMember = true) {
1692 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1693
Richard Smith745f5142012-01-27 01:14:48 +00001694 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1695 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001696 return 0;
1697
1698 MemberPtr MemPtr;
1699 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1700 return 0;
1701
1702 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1703 // member value, the behavior is undefined.
1704 if (!MemPtr.getDecl())
1705 return 0;
1706
Richard Smith745f5142012-01-27 01:14:48 +00001707 if (!EvalObjOK)
1708 return 0;
1709
Richard Smithe24f5fc2011-11-17 22:56:20 +00001710 if (MemPtr.isDerivedMember()) {
1711 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001712 // The end of the derived-to-base path for the base object must match the
1713 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001714 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001715 LV.Designator.Entries.size())
1716 return 0;
1717 unsigned PathLengthToMember =
1718 LV.Designator.Entries.size() - MemPtr.Path.size();
1719 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1720 const CXXRecordDecl *LVDecl = getAsBaseClass(
1721 LV.Designator.Entries[PathLengthToMember + I]);
1722 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1723 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1724 return 0;
1725 }
1726
1727 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001728 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1729 PathLengthToMember))
1730 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001731 } else if (!MemPtr.Path.empty()) {
1732 // Extend the LValue path with the member pointer's path.
1733 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1734 MemPtr.Path.size() + IncludeMember);
1735
1736 // Walk down to the appropriate base class.
1737 QualType LVType = BO->getLHS()->getType();
1738 if (const PointerType *PT = LVType->getAs<PointerType>())
1739 LVType = PT->getPointeeType();
1740 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1741 assert(RD && "member pointer access on non-class-type expression");
1742 // The first class in the path is that of the lvalue.
1743 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1744 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001745 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001746 RD = Base;
1747 }
1748 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001749 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001750 }
1751
1752 // Add the member. Note that we cannot build bound member functions here.
1753 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001754 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1755 HandleLValueMember(Info, BO, LV, FD);
1756 else if (const IndirectFieldDecl *IFD =
1757 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1758 HandleLValueIndirectMember(Info, BO, LV, IFD);
1759 else
1760 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001761 }
1762
1763 return MemPtr.getDecl();
1764}
1765
1766/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1767/// the provided lvalue, which currently refers to the base object.
1768static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1769 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001770 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001771 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001772 return false;
1773
Richard Smithb4e85ed2012-01-06 16:39:00 +00001774 QualType TargetQT = E->getType();
1775 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1776 TargetQT = PT->getPointeeType();
1777
1778 // Check this cast lands within the final derived-to-base subobject path.
1779 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1780 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1781 << D.MostDerivedType << TargetQT;
1782 return false;
1783 }
1784
Richard Smithe24f5fc2011-11-17 22:56:20 +00001785 // Check the type of the final cast. We don't need to check the path,
1786 // since a cast can only be formed if the path is unique.
1787 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001788 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1789 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001790 if (NewEntriesSize == D.MostDerivedPathLength)
1791 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1792 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001793 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001794 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1795 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1796 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001797 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001798 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001799
1800 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001801 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001802}
1803
Mike Stumpc4c90452009-10-27 22:09:17 +00001804namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001805enum EvalStmtResult {
1806 /// Evaluation failed.
1807 ESR_Failed,
1808 /// Hit a 'return' statement.
1809 ESR_Returned,
1810 /// Evaluation succeeded.
1811 ESR_Succeeded
1812};
1813}
1814
1815// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001816static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001817 const Stmt *S) {
1818 switch (S->getStmtClass()) {
1819 default:
1820 return ESR_Failed;
1821
1822 case Stmt::NullStmtClass:
1823 case Stmt::DeclStmtClass:
1824 return ESR_Succeeded;
1825
Richard Smithc1c5f272011-12-13 06:39:58 +00001826 case Stmt::ReturnStmtClass: {
1827 CCValue CCResult;
1828 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1829 if (!Evaluate(CCResult, Info, RetExpr) ||
1830 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1831 CCEK_ReturnValue))
1832 return ESR_Failed;
1833 return ESR_Returned;
1834 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001835
1836 case Stmt::CompoundStmtClass: {
1837 const CompoundStmt *CS = cast<CompoundStmt>(S);
1838 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1839 BE = CS->body_end(); BI != BE; ++BI) {
1840 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1841 if (ESR != ESR_Succeeded)
1842 return ESR;
1843 }
1844 return ESR_Succeeded;
1845 }
1846 }
1847}
1848
Richard Smith61802452011-12-22 02:22:31 +00001849/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1850/// default constructor. If so, we'll fold it whether or not it's marked as
1851/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1852/// so we need special handling.
1853static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001854 const CXXConstructorDecl *CD,
1855 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001856 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1857 return false;
1858
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001859 // Value-initialization does not call a trivial default constructor, so such a
1860 // call is a core constant expression whether or not the constructor is
1861 // constexpr.
1862 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001863 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001864 // FIXME: If DiagDecl is an implicitly-declared special member function,
1865 // we should be much more explicit about why it's not constexpr.
1866 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1867 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1868 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001869 } else {
1870 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1871 }
1872 }
1873 return true;
1874}
1875
Richard Smithc1c5f272011-12-13 06:39:58 +00001876/// CheckConstexprFunction - Check that a function can be called in a constant
1877/// expression.
1878static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1879 const FunctionDecl *Declaration,
1880 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001881 // Potential constant expressions can contain calls to declared, but not yet
1882 // defined, constexpr functions.
1883 if (Info.CheckingPotentialConstantExpression && !Definition &&
1884 Declaration->isConstexpr())
1885 return false;
1886
Richard Smithc1c5f272011-12-13 06:39:58 +00001887 // Can we evaluate this function call?
1888 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1889 return true;
1890
1891 if (Info.getLangOpts().CPlusPlus0x) {
1892 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001893 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1894 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001895 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1896 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1897 << DiagDecl;
1898 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1899 } else {
1900 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1901 }
1902 return false;
1903}
1904
Richard Smith180f4792011-11-10 06:34:14 +00001905namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001906typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001907}
1908
1909/// EvaluateArgs - Evaluate the arguments to a function call.
1910static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1911 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001912 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001913 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001914 I != E; ++I) {
1915 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1916 // If we're checking for a potential constant expression, evaluate all
1917 // initializers even if some of them fail.
1918 if (!Info.keepEvaluatingAfterFailure())
1919 return false;
1920 Success = false;
1921 }
1922 }
1923 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001924}
1925
Richard Smithd0dccea2011-10-28 22:34:42 +00001926/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001927static bool HandleFunctionCall(SourceLocation CallLoc,
1928 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001929 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001930 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001931 ArgVector ArgValues(Args.size());
1932 if (!EvaluateArgs(Args, ArgValues, Info))
1933 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001934
Richard Smith745f5142012-01-27 01:14:48 +00001935 if (!Info.CheckCallLimit(CallLoc))
1936 return false;
1937
1938 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001939 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1940}
1941
Richard Smith180f4792011-11-10 06:34:14 +00001942/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001943static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001944 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001945 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001946 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001947 ArgVector ArgValues(Args.size());
1948 if (!EvaluateArgs(Args, ArgValues, Info))
1949 return false;
1950
Richard Smith745f5142012-01-27 01:14:48 +00001951 if (!Info.CheckCallLimit(CallLoc))
1952 return false;
1953
1954 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001955
1956 // If it's a delegating constructor, just delegate.
1957 if (Definition->isDelegatingConstructor()) {
1958 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1959 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1960 }
1961
Richard Smith610a60c2012-01-10 04:32:03 +00001962 // For a trivial copy or move constructor, perform an APValue copy. This is
1963 // essential for unions, where the operations performed by the constructor
1964 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001965 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001966 if (Definition->isDefaulted() &&
1967 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1968 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1969 LValue RHS;
1970 RHS.setFrom(ArgValues[0]);
1971 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001972 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1973 RHS, Value))
1974 return false;
1975 assert((Value.isStruct() || Value.isUnion()) &&
1976 "trivial copy/move from non-class type?");
1977 // Any CCValue of class type must already be a constant expression.
1978 Result = Value;
1979 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001980 }
1981
1982 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001983 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001984 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1985 std::distance(RD->field_begin(), RD->field_end()));
1986
1987 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1988
Richard Smith745f5142012-01-27 01:14:48 +00001989 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001990 unsigned BasesSeen = 0;
1991#ifndef NDEBUG
1992 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1993#endif
1994 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1995 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001996 LValue Subobject = This;
1997 APValue *Value = &Result;
1998
1999 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002000 if ((*I)->isBaseInitializer()) {
2001 QualType BaseType((*I)->getBaseClass(), 0);
2002#ifndef NDEBUG
2003 // Non-virtual base classes are initialized in the order in the class
2004 // definition. We cannot have a virtual base class for a literal type.
2005 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2006 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2007 "base class initializers not in expected order");
2008 ++BaseIt;
2009#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002011 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002012 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002013 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002014 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002015 if (RD->isUnion()) {
2016 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002017 Value = &Result.getUnionValue();
2018 } else {
2019 Value = &Result.getStructField(FD->getFieldIndex());
2020 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002021 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002022 // Walk the indirect field decl's chain to find the object to initialize,
2023 // and make sure we've initialized every step along it.
2024 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2025 CE = IFD->chain_end();
2026 C != CE; ++C) {
2027 FieldDecl *FD = cast<FieldDecl>(*C);
2028 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2029 // Switch the union field if it differs. This happens if we had
2030 // preceding zero-initialization, and we're now initializing a union
2031 // subobject other than the first.
2032 // FIXME: In this case, the values of the other subobjects are
2033 // specified, since zero-initialization sets all padding bits to zero.
2034 if (Value->isUninit() ||
2035 (Value->isUnion() && Value->getUnionField() != FD)) {
2036 if (CD->isUnion())
2037 *Value = APValue(FD);
2038 else
2039 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2040 std::distance(CD->field_begin(), CD->field_end()));
2041 }
Richard Smith745f5142012-01-27 01:14:48 +00002042 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002043 if (CD->isUnion())
2044 Value = &Value->getUnionValue();
2045 else
2046 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002047 }
Richard Smith180f4792011-11-10 06:34:14 +00002048 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002049 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002050 }
Richard Smith745f5142012-01-27 01:14:48 +00002051
2052 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2053 (*I)->isBaseInitializer()
2054 ? CCEK_Constant : CCEK_MemberInit)) {
2055 // If we're checking for a potential constant expression, evaluate all
2056 // initializers even if some of them fail.
2057 if (!Info.keepEvaluatingAfterFailure())
2058 return false;
2059 Success = false;
2060 }
Richard Smith180f4792011-11-10 06:34:14 +00002061 }
2062
Richard Smith745f5142012-01-27 01:14:48 +00002063 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002064}
2065
Richard Smithd0dccea2011-10-28 22:34:42 +00002066namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002067class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002068 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002069 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002070public:
2071
Richard Smith1e12c592011-10-16 21:26:27 +00002072 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002073
2074 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002075 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002076 return true;
2077 }
2078
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002079 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2080 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002081 return Visit(E->getResultExpr());
2082 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002083 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002084 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002085 return true;
2086 return false;
2087 }
John McCallf85e1932011-06-15 23:02:42 +00002088 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002089 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002090 return true;
2091 return false;
2092 }
2093 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002094 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002095 return true;
2096 return false;
2097 }
2098
Mike Stumpc4c90452009-10-27 22:09:17 +00002099 // We don't want to evaluate BlockExprs multiple times, as they generate
2100 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002101 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2102 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2103 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002104 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002105 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2106 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2107 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2108 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2109 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2110 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002111 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002112 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002113 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002114 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002115 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002116 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2117 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2118 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2119 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002120 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002121 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2122 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2123 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2124 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2125 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002126 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002127 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002128 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002129 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002130 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002131
2132 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002133 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002134 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2135 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002136 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002137 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002138 return false;
2139 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002140
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002141 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002142};
2143
John McCall56ca35d2011-02-17 10:25:35 +00002144class OpaqueValueEvaluation {
2145 EvalInfo &info;
2146 OpaqueValueExpr *opaqueValue;
2147
2148public:
2149 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2150 Expr *value)
2151 : info(info), opaqueValue(opaqueValue) {
2152
2153 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002154 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002155 this->opaqueValue = 0;
2156 return;
2157 }
John McCall56ca35d2011-02-17 10:25:35 +00002158 }
2159
2160 bool hasError() const { return opaqueValue == 0; }
2161
2162 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002163 // FIXME: This will not work for recursive constexpr functions using opaque
2164 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002165 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2166 }
2167};
2168
Mike Stumpc4c90452009-10-27 22:09:17 +00002169} // end anonymous namespace
2170
Eli Friedman4efaa272008-11-12 09:44:48 +00002171//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002172// Generic Evaluation
2173//===----------------------------------------------------------------------===//
2174namespace {
2175
Richard Smithf48fdb02011-12-09 22:58:01 +00002176// FIXME: RetTy is always bool. Remove it.
2177template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002178class ExprEvaluatorBase
2179 : public ConstStmtVisitor<Derived, RetTy> {
2180private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002181 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002182 return static_cast<Derived*>(this)->Success(V, E);
2183 }
Richard Smith51201882011-12-30 21:15:51 +00002184 RetTy DerivedZeroInitialization(const Expr *E) {
2185 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002186 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002187
2188protected:
2189 EvalInfo &Info;
2190 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2191 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2192
Richard Smithdd1f29b2011-12-12 09:28:41 +00002193 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002194 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002195 }
2196
2197 /// Report an evaluation error. This should only be called when an error is
2198 /// first discovered. When propagating an error, just return false.
2199 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002200 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002201 return false;
2202 }
2203 bool Error(const Expr *E) {
2204 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2205 }
2206
Richard Smith51201882011-12-30 21:15:51 +00002207 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002208
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002209public:
2210 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2211
2212 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002213 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002214 }
2215 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002216 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002217 }
2218
2219 RetTy VisitParenExpr(const ParenExpr *E)
2220 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2221 RetTy VisitUnaryExtension(const UnaryOperator *E)
2222 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2223 RetTy VisitUnaryPlus(const UnaryOperator *E)
2224 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2225 RetTy VisitChooseExpr(const ChooseExpr *E)
2226 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2227 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2228 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002229 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2230 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002231 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2232 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002233 // We cannot create any objects for which cleanups are required, so there is
2234 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2235 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2236 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002237
Richard Smithc216a012011-12-12 12:46:16 +00002238 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2239 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2240 return static_cast<Derived*>(this)->VisitCastExpr(E);
2241 }
2242 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2243 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2244 return static_cast<Derived*>(this)->VisitCastExpr(E);
2245 }
2246
Richard Smithe24f5fc2011-11-17 22:56:20 +00002247 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2248 switch (E->getOpcode()) {
2249 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002250 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002251
2252 case BO_Comma:
2253 VisitIgnoredValue(E->getLHS());
2254 return StmtVisitorTy::Visit(E->getRHS());
2255
2256 case BO_PtrMemD:
2257 case BO_PtrMemI: {
2258 LValue Obj;
2259 if (!HandleMemberPointerAccess(Info, E, Obj))
2260 return false;
2261 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002262 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002263 return false;
2264 return DerivedSuccess(Result, E);
2265 }
2266 }
2267 }
2268
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002269 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2270 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2271 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002272 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002273
2274 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002275 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002276 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002277
2278 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2279 }
2280
2281 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2282 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002283 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002284 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002285
Richard Smithc49bd112011-10-28 17:51:58 +00002286 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002287 return StmtVisitorTy::Visit(EvalExpr);
2288 }
2289
2290 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002291 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002292 if (!Value) {
2293 const Expr *Source = E->getSourceExpr();
2294 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002295 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002296 if (Source == E) { // sanity checking.
2297 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002298 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002299 }
2300 return StmtVisitorTy::Visit(Source);
2301 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002302 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 }
Richard Smithf10d9172011-10-11 21:43:33 +00002304
Richard Smithd0dccea2011-10-28 22:34:42 +00002305 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002306 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002307 QualType CalleeType = Callee->getType();
2308
Richard Smithd0dccea2011-10-28 22:34:42 +00002309 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002310 LValue *This = 0, ThisVal;
2311 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002312
Richard Smith59efe262011-11-11 04:05:33 +00002313 // Extract function decl and 'this' pointer from the callee.
2314 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002315 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002316 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2317 // Explicit bound member calls, such as x.f() or p->g();
2318 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002319 return false;
2320 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002321 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002322 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2323 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002324 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2325 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002326 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002327 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002328 return Error(Callee);
2329
2330 FD = dyn_cast<FunctionDecl>(Member);
2331 if (!FD)
2332 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002333 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002334 LValue Call;
2335 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002336 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002337
Richard Smithb4e85ed2012-01-06 16:39:00 +00002338 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002339 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002340 FD = dyn_cast_or_null<FunctionDecl>(
2341 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002342 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002343 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002344
2345 // Overloaded operator calls to member functions are represented as normal
2346 // calls with '*this' as the first argument.
2347 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2348 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002349 // FIXME: When selecting an implicit conversion for an overloaded
2350 // operator delete, we sometimes try to evaluate calls to conversion
2351 // operators without a 'this' parameter!
2352 if (Args.empty())
2353 return Error(E);
2354
Richard Smith59efe262011-11-11 04:05:33 +00002355 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2356 return false;
2357 This = &ThisVal;
2358 Args = Args.slice(1);
2359 }
2360
2361 // Don't call function pointers which have been cast to some other type.
2362 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002363 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002364 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002365 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002366
Richard Smithb04035a2012-02-01 02:39:43 +00002367 if (This && !This->checkSubobject(Info, E, CSK_This))
2368 return false;
2369
Richard Smithc1c5f272011-12-13 06:39:58 +00002370 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002371 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002372 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002373
Richard Smithc1c5f272011-12-13 06:39:58 +00002374 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002375 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2376 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002377 return false;
2378
Richard Smithb4e85ed2012-01-06 16:39:00 +00002379 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002380 }
2381
Richard Smithc49bd112011-10-28 17:51:58 +00002382 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2383 return StmtVisitorTy::Visit(E->getInitializer());
2384 }
Richard Smithf10d9172011-10-11 21:43:33 +00002385 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002386 if (E->getNumInits() == 0)
2387 return DerivedZeroInitialization(E);
2388 if (E->getNumInits() == 1)
2389 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002390 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002391 }
2392 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002393 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002394 }
2395 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002396 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002397 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002398 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002399 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002400 }
Richard Smithf10d9172011-10-11 21:43:33 +00002401
Richard Smith180f4792011-11-10 06:34:14 +00002402 /// A member expression where the object is a prvalue is itself a prvalue.
2403 RetTy VisitMemberExpr(const MemberExpr *E) {
2404 assert(!E->isArrow() && "missing call to bound member function?");
2405
2406 CCValue Val;
2407 if (!Evaluate(Val, Info, E->getBase()))
2408 return false;
2409
2410 QualType BaseTy = E->getBase()->getType();
2411
2412 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002413 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002414 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2415 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2416 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2417
Richard Smithb4e85ed2012-01-06 16:39:00 +00002418 SubobjectDesignator Designator(BaseTy);
2419 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002420
Richard Smithf48fdb02011-12-09 22:58:01 +00002421 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002422 DerivedSuccess(Val, E);
2423 }
2424
Richard Smithc49bd112011-10-28 17:51:58 +00002425 RetTy VisitCastExpr(const CastExpr *E) {
2426 switch (E->getCastKind()) {
2427 default:
2428 break;
2429
David Chisnall7a7ee302012-01-16 17:27:18 +00002430 case CK_AtomicToNonAtomic:
2431 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002432 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002433 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002434 return StmtVisitorTy::Visit(E->getSubExpr());
2435
2436 case CK_LValueToRValue: {
2437 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002438 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2439 return false;
2440 CCValue RVal;
2441 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2442 return false;
2443 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002444 }
2445 }
2446
Richard Smithf48fdb02011-12-09 22:58:01 +00002447 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002448 }
2449
Richard Smith8327fad2011-10-24 18:44:57 +00002450 /// Visit a value which is evaluated, but whose value is ignored.
2451 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002452 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002453 if (!Evaluate(Scratch, Info, E))
2454 Info.EvalStatus.HasSideEffects = true;
2455 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002456};
2457
2458}
2459
2460//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002461// Common base class for lvalue and temporary evaluation.
2462//===----------------------------------------------------------------------===//
2463namespace {
2464template<class Derived>
2465class LValueExprEvaluatorBase
2466 : public ExprEvaluatorBase<Derived, bool> {
2467protected:
2468 LValue &Result;
2469 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2470 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2471
2472 bool Success(APValue::LValueBase B) {
2473 Result.set(B);
2474 return true;
2475 }
2476
2477public:
2478 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2479 ExprEvaluatorBaseTy(Info), Result(Result) {}
2480
2481 bool Success(const CCValue &V, const Expr *E) {
2482 Result.setFrom(V);
2483 return true;
2484 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002485
Richard Smithe24f5fc2011-11-17 22:56:20 +00002486 bool VisitMemberExpr(const MemberExpr *E) {
2487 // Handle non-static data members.
2488 QualType BaseTy;
2489 if (E->isArrow()) {
2490 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2491 return false;
2492 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002493 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002494 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002495 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2496 return false;
2497 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498 } else {
2499 if (!this->Visit(E->getBase()))
2500 return false;
2501 BaseTy = E->getBase()->getType();
2502 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002503
Richard Smithd9b02e72012-01-25 22:15:11 +00002504 const ValueDecl *MD = E->getMemberDecl();
2505 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2506 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2507 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2508 (void)BaseTy;
2509 HandleLValueMember(this->Info, E, Result, FD);
2510 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2511 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2512 } else
2513 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002514
Richard Smithd9b02e72012-01-25 22:15:11 +00002515 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002516 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002517 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002518 RefValue))
2519 return false;
2520 return Success(RefValue, E);
2521 }
2522 return true;
2523 }
2524
2525 bool VisitBinaryOperator(const BinaryOperator *E) {
2526 switch (E->getOpcode()) {
2527 default:
2528 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2529
2530 case BO_PtrMemD:
2531 case BO_PtrMemI:
2532 return HandleMemberPointerAccess(this->Info, E, Result);
2533 }
2534 }
2535
2536 bool VisitCastExpr(const CastExpr *E) {
2537 switch (E->getCastKind()) {
2538 default:
2539 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2540
2541 case CK_DerivedToBase:
2542 case CK_UncheckedDerivedToBase: {
2543 if (!this->Visit(E->getSubExpr()))
2544 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002545
2546 // Now figure out the necessary offset to add to the base LV to get from
2547 // the derived class to the base class.
2548 QualType Type = E->getSubExpr()->getType();
2549
2550 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2551 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002552 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002553 *PathI))
2554 return false;
2555 Type = (*PathI)->getType();
2556 }
2557
2558 return true;
2559 }
2560 }
2561 }
2562};
2563}
2564
2565//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002566// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002567//
2568// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2569// function designators (in C), decl references to void objects (in C), and
2570// temporaries (if building with -Wno-address-of-temporary).
2571//
2572// LValue evaluation produces values comprising a base expression of one of the
2573// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002574// - Declarations
2575// * VarDecl
2576// * FunctionDecl
2577// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002578// * CompoundLiteralExpr in C
2579// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002580// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002581// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002582// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002583// * ObjCEncodeExpr
2584// * AddrLabelExpr
2585// * BlockExpr
2586// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002587// - Locals and temporaries
2588// * Any Expr, with a Frame indicating the function in which the temporary was
2589// evaluated.
2590// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002591//===----------------------------------------------------------------------===//
2592namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002593class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002594 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002595public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002596 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2597 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Richard Smithc49bd112011-10-28 17:51:58 +00002599 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2600
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002601 bool VisitDeclRefExpr(const DeclRefExpr *E);
2602 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002603 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002604 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2605 bool VisitMemberExpr(const MemberExpr *E);
2606 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2607 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002608 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002609 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2610 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002611
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002612 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002613 switch (E->getCastKind()) {
2614 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002615 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002616
Eli Friedmandb924222011-10-11 00:13:24 +00002617 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002618 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002619 if (!Visit(E->getSubExpr()))
2620 return false;
2621 Result.Designator.setInvalid();
2622 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002623
Richard Smithe24f5fc2011-11-17 22:56:20 +00002624 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002625 if (!Visit(E->getSubExpr()))
2626 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002627 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002628 }
2629 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002630
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002631 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002632
Eli Friedman4efaa272008-11-12 09:44:48 +00002633};
2634} // end anonymous namespace
2635
Richard Smithc49bd112011-10-28 17:51:58 +00002636/// Evaluate an expression as an lvalue. This can be legitimately called on
2637/// expressions which are not glvalues, in a few cases:
2638/// * function designators in C,
2639/// * "extern void" objects,
2640/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002641static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002642 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2643 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2644 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002645 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002646}
2647
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002648bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002649 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2650 return Success(FD);
2651 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002652 return VisitVarDecl(E, VD);
2653 return Error(E);
2654}
Richard Smith436c8892011-10-24 23:14:33 +00002655
Richard Smithc49bd112011-10-28 17:51:58 +00002656bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002657 if (!VD->getType()->isReferenceType()) {
2658 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002659 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002660 return true;
2661 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002662 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002663 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002664
Richard Smith47a1eed2011-10-29 20:57:55 +00002665 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002666 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2667 return false;
2668 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002669}
2670
Richard Smithbd552ef2011-10-31 05:52:43 +00002671bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2672 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002673 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002674 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002675 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2676
2677 Result.set(E, Info.CurrentCall);
2678 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2679 Result, E->GetTemporaryExpr());
2680 }
2681
2682 // Materialization of an lvalue temporary occurs when we need to force a copy
2683 // (for instance, if it's a bitfield).
2684 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2685 if (!Visit(E->GetTemporaryExpr()))
2686 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002687 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002688 Info.CurrentCall->Temporaries[E]))
2689 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002690 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002691 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002692}
2693
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002694bool
2695LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002696 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2697 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2698 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002699 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002700}
2701
Richard Smith47d21452011-12-27 12:18:28 +00002702bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2703 if (E->isTypeOperand())
2704 return Success(E);
2705 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2706 if (RD && RD->isPolymorphic()) {
2707 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2708 << E->getExprOperand()->getType()
2709 << E->getExprOperand()->getSourceRange();
2710 return false;
2711 }
2712 return Success(E);
2713}
2714
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002715bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002716 // Handle static data members.
2717 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2718 VisitIgnoredValue(E->getBase());
2719 return VisitVarDecl(E, VD);
2720 }
2721
Richard Smithd0dccea2011-10-28 22:34:42 +00002722 // Handle static member functions.
2723 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2724 if (MD->isStatic()) {
2725 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002726 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002727 }
2728 }
2729
Richard Smith180f4792011-11-10 06:34:14 +00002730 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002731 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002732}
2733
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002734bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002735 // FIXME: Deal with vectors as array subscript bases.
2736 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002737 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002738
Anders Carlsson3068d112008-11-16 19:01:22 +00002739 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002740 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Anders Carlsson3068d112008-11-16 19:01:22 +00002742 APSInt Index;
2743 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002744 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002745 int64_t IndexValue
2746 = Index.isSigned() ? Index.getSExtValue()
2747 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002748
Richard Smithb4e85ed2012-01-06 16:39:00 +00002749 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002750}
Eli Friedman4efaa272008-11-12 09:44:48 +00002751
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002752bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002753 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002754}
2755
Eli Friedman4efaa272008-11-12 09:44:48 +00002756//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002757// Pointer Evaluation
2758//===----------------------------------------------------------------------===//
2759
Anders Carlssonc754aa62008-07-08 05:13:58 +00002760namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002761class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002762 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002763 LValue &Result;
2764
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002765 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002766 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002767 return true;
2768 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002769public:
Mike Stump1eb44332009-09-09 15:08:12 +00002770
John McCallefdb83e2010-05-07 21:00:08 +00002771 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002772 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002773
Richard Smith47a1eed2011-10-29 20:57:55 +00002774 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002775 Result.setFrom(V);
2776 return true;
2777 }
Richard Smith51201882011-12-30 21:15:51 +00002778 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002779 return Success((Expr*)0);
2780 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002781
John McCallefdb83e2010-05-07 21:00:08 +00002782 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002783 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002784 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002785 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002786 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002787 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002788 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002789 bool VisitCallExpr(const CallExpr *E);
2790 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002791 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002792 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002793 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002794 }
Richard Smith180f4792011-11-10 06:34:14 +00002795 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2796 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002797 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002798 Result = *Info.CurrentCall->This;
2799 return true;
2800 }
John McCall56ca35d2011-02-17 10:25:35 +00002801
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002802 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002803};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002804} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002805
John McCallefdb83e2010-05-07 21:00:08 +00002806static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002807 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002808 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002809}
2810
John McCallefdb83e2010-05-07 21:00:08 +00002811bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002812 if (E->getOpcode() != BO_Add &&
2813 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002814 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002816 const Expr *PExp = E->getLHS();
2817 const Expr *IExp = E->getRHS();
2818 if (IExp->getType()->isPointerType())
2819 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Richard Smith745f5142012-01-27 01:14:48 +00002821 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2822 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002823 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002824
John McCallefdb83e2010-05-07 21:00:08 +00002825 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002826 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002827 return false;
2828 int64_t AdditionalOffset
2829 = Offset.isSigned() ? Offset.getSExtValue()
2830 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002831 if (E->getOpcode() == BO_Sub)
2832 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002833
Richard Smith180f4792011-11-10 06:34:14 +00002834 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002835 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2836 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002837}
Eli Friedman4efaa272008-11-12 09:44:48 +00002838
John McCallefdb83e2010-05-07 21:00:08 +00002839bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2840 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002841}
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002843bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2844 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002845
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002846 switch (E->getCastKind()) {
2847 default:
2848 break;
2849
John McCall2de56d12010-08-25 11:45:40 +00002850 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002851 case CK_CPointerToObjCPointerCast:
2852 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002853 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002854 if (!Visit(SubExpr))
2855 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002856 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2857 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2858 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002859 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002860 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002861 if (SubExpr->getType()->isVoidPointerType())
2862 CCEDiag(E, diag::note_constexpr_invalid_cast)
2863 << 3 << SubExpr->getType();
2864 else
2865 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2866 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002867 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002868
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002869 case CK_DerivedToBase:
2870 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002871 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002872 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002873 if (!Result.Base && Result.Offset.isZero())
2874 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002875
Richard Smith180f4792011-11-10 06:34:14 +00002876 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002877 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002878 QualType Type =
2879 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002880
Richard Smith180f4792011-11-10 06:34:14 +00002881 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002882 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002883 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2884 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002885 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002886 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002887 }
2888
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002889 return true;
2890 }
2891
Richard Smithe24f5fc2011-11-17 22:56:20 +00002892 case CK_BaseToDerived:
2893 if (!Visit(E->getSubExpr()))
2894 return false;
2895 if (!Result.Base && Result.Offset.isZero())
2896 return true;
2897 return HandleBaseToDerivedCast(Info, E, Result);
2898
Richard Smith47a1eed2011-10-29 20:57:55 +00002899 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002900 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002901
John McCall2de56d12010-08-25 11:45:40 +00002902 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002903 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2904
Richard Smith47a1eed2011-10-29 20:57:55 +00002905 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002906 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002907 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002908
John McCallefdb83e2010-05-07 21:00:08 +00002909 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002910 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2911 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002912 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002913 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002914 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002915 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002916 return true;
2917 } else {
2918 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002919 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002920 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002921 }
2922 }
John McCall2de56d12010-08-25 11:45:40 +00002923 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002924 if (SubExpr->isGLValue()) {
2925 if (!EvaluateLValue(SubExpr, Result, Info))
2926 return false;
2927 } else {
2928 Result.set(SubExpr, Info.CurrentCall);
2929 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2930 Info, Result, SubExpr))
2931 return false;
2932 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002933 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002934 if (const ConstantArrayType *CAT
2935 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2936 Result.addArray(Info, E, CAT);
2937 else
2938 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002939 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002940
John McCall2de56d12010-08-25 11:45:40 +00002941 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002942 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002943 }
2944
Richard Smithc49bd112011-10-28 17:51:58 +00002945 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002946}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002947
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002948bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002949 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002950 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002951
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002952 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002953}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002954
2955//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002956// Member Pointer Evaluation
2957//===----------------------------------------------------------------------===//
2958
2959namespace {
2960class MemberPointerExprEvaluator
2961 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2962 MemberPtr &Result;
2963
2964 bool Success(const ValueDecl *D) {
2965 Result = MemberPtr(D);
2966 return true;
2967 }
2968public:
2969
2970 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2971 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2972
2973 bool Success(const CCValue &V, const Expr *E) {
2974 Result.setFrom(V);
2975 return true;
2976 }
Richard Smith51201882011-12-30 21:15:51 +00002977 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002978 return Success((const ValueDecl*)0);
2979 }
2980
2981 bool VisitCastExpr(const CastExpr *E);
2982 bool VisitUnaryAddrOf(const UnaryOperator *E);
2983};
2984} // end anonymous namespace
2985
2986static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2987 EvalInfo &Info) {
2988 assert(E->isRValue() && E->getType()->isMemberPointerType());
2989 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2990}
2991
2992bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2993 switch (E->getCastKind()) {
2994 default:
2995 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2996
2997 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002998 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002999
3000 case CK_BaseToDerivedMemberPointer: {
3001 if (!Visit(E->getSubExpr()))
3002 return false;
3003 if (E->path_empty())
3004 return true;
3005 // Base-to-derived member pointer casts store the path in derived-to-base
3006 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3007 // the wrong end of the derived->base arc, so stagger the path by one class.
3008 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3009 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3010 PathI != PathE; ++PathI) {
3011 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3012 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3013 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003014 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003015 }
3016 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3017 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003018 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003019 return true;
3020 }
3021
3022 case CK_DerivedToBaseMemberPointer:
3023 if (!Visit(E->getSubExpr()))
3024 return false;
3025 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3026 PathE = E->path_end(); PathI != PathE; ++PathI) {
3027 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3028 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3029 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003030 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003031 }
3032 return true;
3033 }
3034}
3035
3036bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3037 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3038 // member can be formed.
3039 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3040}
3041
3042//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003043// Record Evaluation
3044//===----------------------------------------------------------------------===//
3045
3046namespace {
3047 class RecordExprEvaluator
3048 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3049 const LValue &This;
3050 APValue &Result;
3051 public:
3052
3053 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3054 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3055
3056 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003057 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003058 }
Richard Smith51201882011-12-30 21:15:51 +00003059 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003060
Richard Smith59efe262011-11-11 04:05:33 +00003061 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003062 bool VisitInitListExpr(const InitListExpr *E);
3063 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3064 };
3065}
3066
Richard Smith51201882011-12-30 21:15:51 +00003067/// Perform zero-initialization on an object of non-union class type.
3068/// C++11 [dcl.init]p5:
3069/// To zero-initialize an object or reference of type T means:
3070/// [...]
3071/// -- if T is a (possibly cv-qualified) non-union class type,
3072/// each non-static data member and each base-class subobject is
3073/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003074static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3075 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003076 const LValue &This, APValue &Result) {
3077 assert(!RD->isUnion() && "Expected non-union class type");
3078 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3079 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3080 std::distance(RD->field_begin(), RD->field_end()));
3081
3082 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3083
3084 if (CD) {
3085 unsigned Index = 0;
3086 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003087 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003088 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3089 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003090 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3091 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003092 Result.getStructBase(Index)))
3093 return false;
3094 }
3095 }
3096
Richard Smithb4e85ed2012-01-06 16:39:00 +00003097 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3098 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003099 // -- if T is a reference type, no initialization is performed.
3100 if ((*I)->getType()->isReferenceType())
3101 continue;
3102
3103 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003104 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003105
3106 ImplicitValueInitExpr VIE((*I)->getType());
3107 if (!EvaluateConstantExpression(
3108 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3109 return false;
3110 }
3111
3112 return true;
3113}
3114
3115bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3116 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3117 if (RD->isUnion()) {
3118 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3119 // object's first non-static named data member is zero-initialized
3120 RecordDecl::field_iterator I = RD->field_begin();
3121 if (I == RD->field_end()) {
3122 Result = APValue((const FieldDecl*)0);
3123 return true;
3124 }
3125
3126 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003127 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003128 Result = APValue(*I);
3129 ImplicitValueInitExpr VIE((*I)->getType());
3130 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3131 Subobject, &VIE);
3132 }
3133
Richard Smithb4e85ed2012-01-06 16:39:00 +00003134 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003135}
3136
Richard Smith59efe262011-11-11 04:05:33 +00003137bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3138 switch (E->getCastKind()) {
3139 default:
3140 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3141
3142 case CK_ConstructorConversion:
3143 return Visit(E->getSubExpr());
3144
3145 case CK_DerivedToBase:
3146 case CK_UncheckedDerivedToBase: {
3147 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003148 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003149 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003150 if (!DerivedObject.isStruct())
3151 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003152
3153 // Derived-to-base rvalue conversion: just slice off the derived part.
3154 APValue *Value = &DerivedObject;
3155 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3156 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3157 PathE = E->path_end(); PathI != PathE; ++PathI) {
3158 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3159 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3160 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3161 RD = Base;
3162 }
3163 Result = *Value;
3164 return true;
3165 }
3166 }
3167}
3168
Richard Smith180f4792011-11-10 06:34:14 +00003169bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3170 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3171 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3172
3173 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003174 const FieldDecl *Field = E->getInitializedFieldInUnion();
3175 Result = APValue(Field);
3176 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003177 return true;
Richard Smithec789162012-01-12 18:54:33 +00003178
3179 // If the initializer list for a union does not contain any elements, the
3180 // first element of the union is value-initialized.
3181 ImplicitValueInitExpr VIE(Field->getType());
3182 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3183
Richard Smith180f4792011-11-10 06:34:14 +00003184 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003185 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003186 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003187 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003188 }
3189
3190 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3191 "initializer list for class with base classes");
3192 Result = APValue(APValue::UninitStruct(), 0,
3193 std::distance(RD->field_begin(), RD->field_end()));
3194 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003195 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003196 for (RecordDecl::field_iterator Field = RD->field_begin(),
3197 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3198 // Anonymous bit-fields are not considered members of the class for
3199 // purposes of aggregate initialization.
3200 if (Field->isUnnamedBitfield())
3201 continue;
3202
3203 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003204
Richard Smith745f5142012-01-27 01:14:48 +00003205 bool HaveInit = ElementNo < E->getNumInits();
3206
3207 // FIXME: Diagnostics here should point to the end of the initializer
3208 // list, not the start.
3209 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3210 *Field, &Layout);
3211
3212 // Perform an implicit value-initialization for members beyond the end of
3213 // the initializer list.
3214 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3215
3216 if (!EvaluateConstantExpression(
3217 Result.getStructField((*Field)->getFieldIndex()),
3218 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3219 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003220 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003221 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003222 }
3223 }
3224
Richard Smith745f5142012-01-27 01:14:48 +00003225 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003226}
3227
3228bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3229 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003230 bool ZeroInit = E->requiresZeroInitialization();
3231 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003232 // If we've already performed zero-initialization, we're already done.
3233 if (!Result.isUninit())
3234 return true;
3235
Richard Smith51201882011-12-30 21:15:51 +00003236 if (ZeroInit)
3237 return ZeroInitialization(E);
3238
Richard Smith61802452011-12-22 02:22:31 +00003239 const CXXRecordDecl *RD = FD->getParent();
3240 if (RD->isUnion())
3241 Result = APValue((FieldDecl*)0);
3242 else
3243 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3244 std::distance(RD->field_begin(), RD->field_end()));
3245 return true;
3246 }
3247
Richard Smith180f4792011-11-10 06:34:14 +00003248 const FunctionDecl *Definition = 0;
3249 FD->getBody(Definition);
3250
Richard Smithc1c5f272011-12-13 06:39:58 +00003251 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3252 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003253
Richard Smith610a60c2012-01-10 04:32:03 +00003254 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003255 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003256 if (const MaterializeTemporaryExpr *ME
3257 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3258 return Visit(ME->GetTemporaryExpr());
3259
Richard Smith51201882011-12-30 21:15:51 +00003260 if (ZeroInit && !ZeroInitialization(E))
3261 return false;
3262
Richard Smith180f4792011-11-10 06:34:14 +00003263 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003264 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003265 cast<CXXConstructorDecl>(Definition), Info,
3266 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003267}
3268
3269static bool EvaluateRecord(const Expr *E, const LValue &This,
3270 APValue &Result, EvalInfo &Info) {
3271 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003272 "can't evaluate expression as a record rvalue");
3273 return RecordExprEvaluator(Info, This, Result).Visit(E);
3274}
3275
3276//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003277// Temporary Evaluation
3278//
3279// Temporaries are represented in the AST as rvalues, but generally behave like
3280// lvalues. The full-object of which the temporary is a subobject is implicitly
3281// materialized so that a reference can bind to it.
3282//===----------------------------------------------------------------------===//
3283namespace {
3284class TemporaryExprEvaluator
3285 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3286public:
3287 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3288 LValueExprEvaluatorBaseTy(Info, Result) {}
3289
3290 /// Visit an expression which constructs the value of this temporary.
3291 bool VisitConstructExpr(const Expr *E) {
3292 Result.set(E, Info.CurrentCall);
3293 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3294 Result, E);
3295 }
3296
3297 bool VisitCastExpr(const CastExpr *E) {
3298 switch (E->getCastKind()) {
3299 default:
3300 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3301
3302 case CK_ConstructorConversion:
3303 return VisitConstructExpr(E->getSubExpr());
3304 }
3305 }
3306 bool VisitInitListExpr(const InitListExpr *E) {
3307 return VisitConstructExpr(E);
3308 }
3309 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3310 return VisitConstructExpr(E);
3311 }
3312 bool VisitCallExpr(const CallExpr *E) {
3313 return VisitConstructExpr(E);
3314 }
3315};
3316} // end anonymous namespace
3317
3318/// Evaluate an expression of record type as a temporary.
3319static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003320 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003321 return TemporaryExprEvaluator(Info, Result).Visit(E);
3322}
3323
3324//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003325// Vector Evaluation
3326//===----------------------------------------------------------------------===//
3327
3328namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003329 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003330 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3331 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003332 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Richard Smith07fc6572011-10-22 21:10:00 +00003334 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3335 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Richard Smith07fc6572011-10-22 21:10:00 +00003337 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3338 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3339 // FIXME: remove this APValue copy.
3340 Result = APValue(V.data(), V.size());
3341 return true;
3342 }
Richard Smith69c2c502011-11-04 05:33:44 +00003343 bool Success(const CCValue &V, const Expr *E) {
3344 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003345 Result = V;
3346 return true;
3347 }
Richard Smith51201882011-12-30 21:15:51 +00003348 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Richard Smith07fc6572011-10-22 21:10:00 +00003350 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003351 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003352 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003353 bool VisitInitListExpr(const InitListExpr *E);
3354 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003355 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003356 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003357 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003358 };
3359} // end anonymous namespace
3360
3361static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003362 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003363 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003364}
3365
Richard Smith07fc6572011-10-22 21:10:00 +00003366bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3367 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003368 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Richard Smithd62ca372011-12-06 22:44:34 +00003370 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003371 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003372
Eli Friedman46a52322011-03-25 00:43:55 +00003373 switch (E->getCastKind()) {
3374 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003375 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003376 if (SETy->isIntegerType()) {
3377 APSInt IntResult;
3378 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003379 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003380 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003381 } else if (SETy->isRealFloatingType()) {
3382 APFloat F(0.0);
3383 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003384 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003385 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003386 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003387 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003388 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003389
3390 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003391 SmallVector<APValue, 4> Elts(NElts, Val);
3392 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003393 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003394 case CK_BitCast: {
3395 // Evaluate the operand into an APInt we can extract from.
3396 llvm::APInt SValInt;
3397 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3398 return false;
3399 // Extract the elements
3400 QualType EltTy = VTy->getElementType();
3401 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3402 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3403 SmallVector<APValue, 4> Elts;
3404 if (EltTy->isRealFloatingType()) {
3405 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3406 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3407 unsigned FloatEltSize = EltSize;
3408 if (&Sem == &APFloat::x87DoubleExtended)
3409 FloatEltSize = 80;
3410 for (unsigned i = 0; i < NElts; i++) {
3411 llvm::APInt Elt;
3412 if (BigEndian)
3413 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3414 else
3415 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3416 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3417 }
3418 } else if (EltTy->isIntegerType()) {
3419 for (unsigned i = 0; i < NElts; i++) {
3420 llvm::APInt Elt;
3421 if (BigEndian)
3422 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3423 else
3424 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3425 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3426 }
3427 } else {
3428 return Error(E);
3429 }
3430 return Success(Elts, E);
3431 }
Eli Friedman46a52322011-03-25 00:43:55 +00003432 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003433 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003434 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003435}
3436
Richard Smith07fc6572011-10-22 21:10:00 +00003437bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003438VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003439 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003440 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003441 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Nate Begeman59b5da62009-01-18 03:20:47 +00003443 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003444 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003445
Eli Friedman3edd5a92012-01-03 23:24:20 +00003446 // The number of initializers can be less than the number of
3447 // vector elements. For OpenCL, this can be due to nested vector
3448 // initialization. For GCC compatibility, missing trailing elements
3449 // should be initialized with zeroes.
3450 unsigned CountInits = 0, CountElts = 0;
3451 while (CountElts < NumElements) {
3452 // Handle nested vector initialization.
3453 if (CountInits < NumInits
3454 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3455 APValue v;
3456 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3457 return Error(E);
3458 unsigned vlen = v.getVectorLength();
3459 for (unsigned j = 0; j < vlen; j++)
3460 Elements.push_back(v.getVectorElt(j));
3461 CountElts += vlen;
3462 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003463 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003464 if (CountInits < NumInits) {
3465 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3466 return Error(E);
3467 } else // trailing integer zero.
3468 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3469 Elements.push_back(APValue(sInt));
3470 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003471 } else {
3472 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003473 if (CountInits < NumInits) {
3474 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3475 return Error(E);
3476 } else // trailing float zero.
3477 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3478 Elements.push_back(APValue(f));
3479 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003480 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003481 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003482 }
Richard Smith07fc6572011-10-22 21:10:00 +00003483 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003484}
3485
Richard Smith07fc6572011-10-22 21:10:00 +00003486bool
Richard Smith51201882011-12-30 21:15:51 +00003487VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003488 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003489 QualType EltTy = VT->getElementType();
3490 APValue ZeroElement;
3491 if (EltTy->isIntegerType())
3492 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3493 else
3494 ZeroElement =
3495 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3496
Chris Lattner5f9e2722011-07-23 10:55:15 +00003497 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003498 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003499}
3500
Richard Smith07fc6572011-10-22 21:10:00 +00003501bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003502 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003503 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003504}
3505
Nate Begeman59b5da62009-01-18 03:20:47 +00003506//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003507// Array Evaluation
3508//===----------------------------------------------------------------------===//
3509
3510namespace {
3511 class ArrayExprEvaluator
3512 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003513 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003514 APValue &Result;
3515 public:
3516
Richard Smith180f4792011-11-10 06:34:14 +00003517 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3518 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003519
3520 bool Success(const APValue &V, const Expr *E) {
3521 assert(V.isArray() && "Expected array type");
3522 Result = V;
3523 return true;
3524 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003525
Richard Smith51201882011-12-30 21:15:51 +00003526 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003527 const ConstantArrayType *CAT =
3528 Info.Ctx.getAsConstantArrayType(E->getType());
3529 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003530 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003531
3532 Result = APValue(APValue::UninitArray(), 0,
3533 CAT->getSize().getZExtValue());
3534 if (!Result.hasArrayFiller()) return true;
3535
Richard Smith51201882011-12-30 21:15:51 +00003536 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003537 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003538 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003539 ImplicitValueInitExpr VIE(CAT->getElementType());
3540 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3541 Subobject, &VIE);
3542 }
3543
Richard Smithcc5d4f62011-11-07 09:22:26 +00003544 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003545 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003546 };
3547} // end anonymous namespace
3548
Richard Smith180f4792011-11-10 06:34:14 +00003549static bool EvaluateArray(const Expr *E, const LValue &This,
3550 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003551 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003552 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003553}
3554
3555bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3556 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3557 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003558 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003559
Richard Smith974c5f92011-12-22 01:07:19 +00003560 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3561 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003562 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003563 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3564 LValue LV;
3565 if (!EvaluateLValue(E->getInit(0), LV, Info))
3566 return false;
3567 uint64_t NumElements = CAT->getSize().getZExtValue();
3568 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3569
3570 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003571 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003572 for (uint64_t I = 0; I < NumElements; ++I) {
3573 CCValue Char;
3574 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003575 CAT->getElementType(), LV, Char) ||
3576 !CheckConstantExpression(Info, E->getInit(0), Char,
3577 Result.getArrayInitializedElt(I)) ||
3578 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003579 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003580 return false;
3581 }
3582 return true;
3583 }
3584
Richard Smith745f5142012-01-27 01:14:48 +00003585 bool Success = true;
3586
Richard Smithcc5d4f62011-11-07 09:22:26 +00003587 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3588 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003589 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003590 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003591 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003592 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003593 I != End; ++I, ++Index) {
3594 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003595 Info, Subobject, cast<Expr>(*I)) ||
3596 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3597 CAT->getElementType(), 1)) {
3598 if (!Info.keepEvaluatingAfterFailure())
3599 return false;
3600 Success = false;
3601 }
Richard Smith180f4792011-11-10 06:34:14 +00003602 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003603
Richard Smith745f5142012-01-27 01:14:48 +00003604 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003605 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003606 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3607 // but sometimes does:
3608 // struct S { constexpr S() : p(&p) {} void *p; };
3609 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003610 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003611 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003612}
3613
Richard Smithe24f5fc2011-11-17 22:56:20 +00003614bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3615 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3616 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003617 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003618
Richard Smithec789162012-01-12 18:54:33 +00003619 bool HadZeroInit = !Result.isUninit();
3620 if (!HadZeroInit)
3621 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003622 if (!Result.hasArrayFiller())
3623 return true;
3624
3625 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003626
Richard Smith51201882011-12-30 21:15:51 +00003627 bool ZeroInit = E->requiresZeroInitialization();
3628 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003629 if (HadZeroInit)
3630 return true;
3631
Richard Smith51201882011-12-30 21:15:51 +00003632 if (ZeroInit) {
3633 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003634 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003635 ImplicitValueInitExpr VIE(CAT->getElementType());
3636 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3637 Subobject, &VIE);
3638 }
3639
Richard Smith61802452011-12-22 02:22:31 +00003640 const CXXRecordDecl *RD = FD->getParent();
3641 if (RD->isUnion())
3642 Result.getArrayFiller() = APValue((FieldDecl*)0);
3643 else
3644 Result.getArrayFiller() =
3645 APValue(APValue::UninitStruct(), RD->getNumBases(),
3646 std::distance(RD->field_begin(), RD->field_end()));
3647 return true;
3648 }
3649
Richard Smithe24f5fc2011-11-17 22:56:20 +00003650 const FunctionDecl *Definition = 0;
3651 FD->getBody(Definition);
3652
Richard Smithc1c5f272011-12-13 06:39:58 +00003653 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3654 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003655
3656 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3657 // but sometimes does:
3658 // struct S { constexpr S() : p(&p) {} void *p; };
3659 // S s[10];
3660 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003661 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003662
Richard Smithec789162012-01-12 18:54:33 +00003663 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003664 ImplicitValueInitExpr VIE(CAT->getElementType());
3665 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3666 &VIE))
3667 return false;
3668 }
3669
Richard Smithe24f5fc2011-11-17 22:56:20 +00003670 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003671 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003672 cast<CXXConstructorDecl>(Definition),
3673 Info, Result.getArrayFiller());
3674}
3675
Richard Smithcc5d4f62011-11-07 09:22:26 +00003676//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003677// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003678//
3679// As a GNU extension, we support casting pointers to sufficiently-wide integer
3680// types and back in constant folding. Integer values are thus represented
3681// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003682//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003683
3684namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003685class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003686 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003687 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003688public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003689 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003690 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003691
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003692 bool Success(const llvm::APSInt &SI, const Expr *E) {
3693 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003694 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003695 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003696 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003697 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003698 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003699 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003700 return true;
3701 }
3702
Daniel Dunbar131eb432009-02-19 09:06:44 +00003703 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003704 assert(E->getType()->isIntegralOrEnumerationType() &&
3705 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003706 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003707 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003708 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003709 Result.getInt().setIsUnsigned(
3710 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003711 return true;
3712 }
3713
3714 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003715 assert(E->getType()->isIntegralOrEnumerationType() &&
3716 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003717 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003718 return true;
3719 }
3720
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003721 bool Success(CharUnits Size, const Expr *E) {
3722 return Success(Size.getQuantity(), E);
3723 }
3724
Richard Smith47a1eed2011-10-29 20:57:55 +00003725 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003726 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003727 Result = V;
3728 return true;
3729 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003730 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003731 }
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Richard Smith51201882011-12-30 21:15:51 +00003733 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003734
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003735 //===--------------------------------------------------------------------===//
3736 // Visitor Methods
3737 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003738
Chris Lattner4c4867e2008-07-12 00:38:25 +00003739 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003740 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003741 }
3742 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003743 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003744 }
Eli Friedman04309752009-11-24 05:28:59 +00003745
3746 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3747 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003748 if (CheckReferencedDecl(E, E->getDecl()))
3749 return true;
3750
3751 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003752 }
3753 bool VisitMemberExpr(const MemberExpr *E) {
3754 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003755 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003756 return true;
3757 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003758
3759 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003760 }
3761
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003762 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003763 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003764 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003765 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003766
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003767 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003768 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003769
Anders Carlsson3068d112008-11-16 19:01:22 +00003770 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003771 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003772 }
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Richard Smithf10d9172011-10-11 21:43:33 +00003774 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003775 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003776 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003777 }
3778
Sebastian Redl64b45f72009-01-05 20:52:13 +00003779 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003780 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003781 }
3782
Francois Pichet6ad6f282010-12-07 00:08:36 +00003783 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3784 return Success(E->getValue(), E);
3785 }
3786
John Wiegley21ff2e52011-04-28 00:16:57 +00003787 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3788 return Success(E->getValue(), E);
3789 }
3790
John Wiegley55262202011-04-25 06:54:41 +00003791 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3792 return Success(E->getValue(), E);
3793 }
3794
Eli Friedman722c7172009-02-28 03:59:05 +00003795 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003796 bool VisitUnaryImag(const UnaryOperator *E);
3797
Sebastian Redl295995c2010-09-10 20:55:47 +00003798 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003799 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003800
Chris Lattnerfcee0012008-07-11 21:24:13 +00003801private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003802 CharUnits GetAlignOfExpr(const Expr *E);
3803 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003804 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003805 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003806 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003807};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003808} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003809
Richard Smithc49bd112011-10-28 17:51:58 +00003810/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3811/// produce either the integer value or a pointer.
3812///
3813/// GCC has a heinous extension which folds casts between pointer types and
3814/// pointer-sized integral types. We support this by allowing the evaluation of
3815/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3816/// Some simple arithmetic on such values is supported (they are treated much
3817/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003818static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003819 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003820 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003821 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003822}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003823
Richard Smithf48fdb02011-12-09 22:58:01 +00003824static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003825 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003826 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003827 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003828 if (!Val.isInt()) {
3829 // FIXME: It would be better to produce the diagnostic for casting
3830 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003831 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003832 return false;
3833 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003834 Result = Val.getInt();
3835 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003836}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003837
Richard Smithf48fdb02011-12-09 22:58:01 +00003838/// Check whether the given declaration can be directly converted to an integral
3839/// rvalue. If not, no diagnostic is produced; there are other things we can
3840/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003841bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003842 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003843 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003844 // Check for signedness/width mismatches between E type and ECD value.
3845 bool SameSign = (ECD->getInitVal().isSigned()
3846 == E->getType()->isSignedIntegerOrEnumerationType());
3847 bool SameWidth = (ECD->getInitVal().getBitWidth()
3848 == Info.Ctx.getIntWidth(E->getType()));
3849 if (SameSign && SameWidth)
3850 return Success(ECD->getInitVal(), E);
3851 else {
3852 // Get rid of mismatch (otherwise Success assertions will fail)
3853 // by computing a new value matching the type of E.
3854 llvm::APSInt Val = ECD->getInitVal();
3855 if (!SameSign)
3856 Val.setIsSigned(!ECD->getInitVal().isSigned());
3857 if (!SameWidth)
3858 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3859 return Success(Val, E);
3860 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003861 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003862 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003863}
3864
Chris Lattnera4d55d82008-10-06 06:40:35 +00003865/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3866/// as GCC.
3867static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3868 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003869 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003870 enum gcc_type_class {
3871 no_type_class = -1,
3872 void_type_class, integer_type_class, char_type_class,
3873 enumeral_type_class, boolean_type_class,
3874 pointer_type_class, reference_type_class, offset_type_class,
3875 real_type_class, complex_type_class,
3876 function_type_class, method_type_class,
3877 record_type_class, union_type_class,
3878 array_type_class, string_type_class,
3879 lang_type_class
3880 };
Mike Stump1eb44332009-09-09 15:08:12 +00003881
3882 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003883 // ideal, however it is what gcc does.
3884 if (E->getNumArgs() == 0)
3885 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Chris Lattnera4d55d82008-10-06 06:40:35 +00003887 QualType ArgTy = E->getArg(0)->getType();
3888 if (ArgTy->isVoidType())
3889 return void_type_class;
3890 else if (ArgTy->isEnumeralType())
3891 return enumeral_type_class;
3892 else if (ArgTy->isBooleanType())
3893 return boolean_type_class;
3894 else if (ArgTy->isCharType())
3895 return string_type_class; // gcc doesn't appear to use char_type_class
3896 else if (ArgTy->isIntegerType())
3897 return integer_type_class;
3898 else if (ArgTy->isPointerType())
3899 return pointer_type_class;
3900 else if (ArgTy->isReferenceType())
3901 return reference_type_class;
3902 else if (ArgTy->isRealType())
3903 return real_type_class;
3904 else if (ArgTy->isComplexType())
3905 return complex_type_class;
3906 else if (ArgTy->isFunctionType())
3907 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003908 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003909 return record_type_class;
3910 else if (ArgTy->isUnionType())
3911 return union_type_class;
3912 else if (ArgTy->isArrayType())
3913 return array_type_class;
3914 else if (ArgTy->isUnionType())
3915 return union_type_class;
3916 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003917 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003918}
3919
Richard Smith80d4b552011-12-28 19:48:30 +00003920/// EvaluateBuiltinConstantPForLValue - Determine the result of
3921/// __builtin_constant_p when applied to the given lvalue.
3922///
3923/// An lvalue is only "constant" if it is a pointer or reference to the first
3924/// character of a string literal.
3925template<typename LValue>
3926static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3927 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3928 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3929}
3930
3931/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3932/// GCC as we can manage.
3933static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3934 QualType ArgType = Arg->getType();
3935
3936 // __builtin_constant_p always has one operand. The rules which gcc follows
3937 // are not precisely documented, but are as follows:
3938 //
3939 // - If the operand is of integral, floating, complex or enumeration type,
3940 // and can be folded to a known value of that type, it returns 1.
3941 // - If the operand and can be folded to a pointer to the first character
3942 // of a string literal (or such a pointer cast to an integral type), it
3943 // returns 1.
3944 //
3945 // Otherwise, it returns 0.
3946 //
3947 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3948 // its support for this does not currently work.
3949 if (ArgType->isIntegralOrEnumerationType()) {
3950 Expr::EvalResult Result;
3951 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3952 return false;
3953
3954 APValue &V = Result.Val;
3955 if (V.getKind() == APValue::Int)
3956 return true;
3957
3958 return EvaluateBuiltinConstantPForLValue(V);
3959 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3960 return Arg->isEvaluatable(Ctx);
3961 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3962 LValue LV;
3963 Expr::EvalStatus Status;
3964 EvalInfo Info(Ctx, Status);
3965 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3966 : EvaluatePointer(Arg, LV, Info)) &&
3967 !Status.HasSideEffects)
3968 return EvaluateBuiltinConstantPForLValue(LV);
3969 }
3970
3971 // Anything else isn't considered to be sufficiently constant.
3972 return false;
3973}
3974
John McCall42c8f872010-05-10 23:27:23 +00003975/// Retrieves the "underlying object type" of the given expression,
3976/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003977QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3978 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3979 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003980 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003981 } else if (const Expr *E = B.get<const Expr*>()) {
3982 if (isa<CompoundLiteralExpr>(E))
3983 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003984 }
3985
3986 return QualType();
3987}
3988
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003989bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003990 // TODO: Perhaps we should let LLVM lower this?
3991 LValue Base;
3992 if (!EvaluatePointer(E->getArg(0), Base, Info))
3993 return false;
3994
3995 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003996 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003997
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003998 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003999 if (T.isNull() ||
4000 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004001 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004002 T->isVariablyModifiedType() ||
4003 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004004 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004005
4006 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4007 CharUnits Offset = Base.getLValueOffset();
4008
4009 if (!Offset.isNegative() && Offset <= Size)
4010 Size -= Offset;
4011 else
4012 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004013 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004014}
4015
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004016bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004017 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004018 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004019 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004020
4021 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004022 if (TryEvaluateBuiltinObjectSize(E))
4023 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004024
Eric Christopherb2aaf512010-01-19 22:58:35 +00004025 // If evaluating the argument has side-effects we can't determine
4026 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004027 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004028 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004029 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004030 return Success(0, E);
4031 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004032
Richard Smithf48fdb02011-12-09 22:58:01 +00004033 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004034 }
4035
Chris Lattner019f4e82008-10-06 05:28:25 +00004036 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004037 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Richard Smith80d4b552011-12-28 19:48:30 +00004039 case Builtin::BI__builtin_constant_p:
4040 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004041
Chris Lattner21fb98e2009-09-23 06:06:36 +00004042 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004043 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004044 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004045 return Success(Operand, E);
4046 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004047
4048 case Builtin::BI__builtin_expect:
4049 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004050
Douglas Gregor5726d402010-09-10 06:27:15 +00004051 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004052 // A call to strlen is not a constant expression.
4053 if (Info.getLangOpts().CPlusPlus0x)
4054 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4055 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4056 else
4057 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4058 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004059 case Builtin::BI__builtin_strlen:
4060 // As an extension, we support strlen() and __builtin_strlen() as constant
4061 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004062 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004063 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4064 // The string literal may have embedded null characters. Find the first
4065 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004066 StringRef Str = S->getString();
4067 StringRef::size_type Pos = Str.find(0);
4068 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004069 Str = Str.substr(0, Pos);
4070
4071 return Success(Str.size(), E);
4072 }
4073
Richard Smithf48fdb02011-12-09 22:58:01 +00004074 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004075
4076 case Builtin::BI__atomic_is_lock_free: {
4077 APSInt SizeVal;
4078 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4079 return false;
4080
4081 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4082 // of two less than the maximum inline atomic width, we know it is
4083 // lock-free. If the size isn't a power of two, or greater than the
4084 // maximum alignment where we promote atomics, we know it is not lock-free
4085 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4086 // the answer can only be determined at runtime; for example, 16-byte
4087 // atomics have lock-free implementations on some, but not all,
4088 // x86-64 processors.
4089
4090 // Check power-of-two.
4091 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4092 if (!Size.isPowerOfTwo())
4093#if 0
4094 // FIXME: Suppress this folding until the ABI for the promotion width
4095 // settles.
4096 return Success(0, E);
4097#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004098 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004099#endif
4100
4101#if 0
4102 // Check against promotion width.
4103 // FIXME: Suppress this folding until the ABI for the promotion width
4104 // settles.
4105 unsigned PromoteWidthBits =
4106 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4107 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4108 return Success(0, E);
4109#endif
4110
4111 // Check against inlining width.
4112 unsigned InlineWidthBits =
4113 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4114 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4115 return Success(1, E);
4116
Richard Smithf48fdb02011-12-09 22:58:01 +00004117 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004118 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004119 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004120}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004121
Richard Smith625b8072011-10-31 01:37:14 +00004122static bool HasSameBase(const LValue &A, const LValue &B) {
4123 if (!A.getLValueBase())
4124 return !B.getLValueBase();
4125 if (!B.getLValueBase())
4126 return false;
4127
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004128 if (A.getLValueBase().getOpaqueValue() !=
4129 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004130 const Decl *ADecl = GetLValueBaseDecl(A);
4131 if (!ADecl)
4132 return false;
4133 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004134 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004135 return false;
4136 }
4137
4138 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004139 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004140}
4141
Richard Smith7b48a292012-02-01 05:53:12 +00004142/// Perform the given integer operation, which is known to need at most BitWidth
4143/// bits, and check for overflow in the original type (if that type was not an
4144/// unsigned type).
4145template<typename Operation>
4146static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4147 const APSInt &LHS, const APSInt &RHS,
4148 unsigned BitWidth, Operation Op) {
4149 if (LHS.isUnsigned())
4150 return Op(LHS, RHS);
4151
4152 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4153 APSInt Result = Value.trunc(LHS.getBitWidth());
4154 if (Result.extend(BitWidth) != Value)
4155 HandleOverflow(Info, E, Value, E->getType());
4156 return Result;
4157}
4158
Chris Lattnerb542afe2008-07-11 19:10:17 +00004159bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004160 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004161 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004162
John McCall2de56d12010-08-25 11:45:40 +00004163 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004164 VisitIgnoredValue(E->getLHS());
4165 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004166 }
4167
4168 if (E->isLogicalOp()) {
4169 // These need to be handled specially because the operands aren't
4170 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004171 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004172
Richard Smithc49bd112011-10-28 17:51:58 +00004173 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004174 // We were able to evaluate the LHS, see if we can get away with not
4175 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004176 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004177 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004178
Richard Smithc49bd112011-10-28 17:51:58 +00004179 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004180 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004181 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004182 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004183 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004184 }
4185 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004186 // FIXME: If both evaluations fail, we should produce the diagnostic from
4187 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4188 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004189 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004190 // We can't evaluate the LHS; however, sometimes the result
4191 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004192 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004193 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004194 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004195 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004196
4197 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004198 }
4199 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004200 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004201
Eli Friedmana6afa762008-11-13 06:09:17 +00004202 return false;
4203 }
4204
Anders Carlsson286f85e2008-11-16 07:17:21 +00004205 QualType LHSTy = E->getLHS()->getType();
4206 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004207
4208 if (LHSTy->isAnyComplexType()) {
4209 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004210 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004211
Richard Smith745f5142012-01-27 01:14:48 +00004212 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4213 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004214 return false;
4215
Richard Smith745f5142012-01-27 01:14:48 +00004216 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004217 return false;
4218
4219 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004220 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004221 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004222 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004223 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4224
John McCall2de56d12010-08-25 11:45:40 +00004225 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004226 return Success((CR_r == APFloat::cmpEqual &&
4227 CR_i == APFloat::cmpEqual), E);
4228 else {
John McCall2de56d12010-08-25 11:45:40 +00004229 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004230 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004231 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004232 CR_r == APFloat::cmpLessThan ||
4233 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004234 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004235 CR_i == APFloat::cmpLessThan ||
4236 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004237 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004238 } else {
John McCall2de56d12010-08-25 11:45:40 +00004239 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004240 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4241 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4242 else {
John McCall2de56d12010-08-25 11:45:40 +00004243 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004244 "Invalid compex comparison.");
4245 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4246 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4247 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004248 }
4249 }
Mike Stump1eb44332009-09-09 15:08:12 +00004250
Anders Carlsson286f85e2008-11-16 07:17:21 +00004251 if (LHSTy->isRealFloatingType() &&
4252 RHSTy->isRealFloatingType()) {
4253 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004254
Richard Smith745f5142012-01-27 01:14:48 +00004255 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4256 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004257 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004258
Richard Smith745f5142012-01-27 01:14:48 +00004259 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004260 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004261
Anders Carlsson286f85e2008-11-16 07:17:21 +00004262 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004263
Anders Carlsson286f85e2008-11-16 07:17:21 +00004264 switch (E->getOpcode()) {
4265 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004266 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004267 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004268 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004269 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004270 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004271 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004272 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004273 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004274 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004275 E);
John McCall2de56d12010-08-25 11:45:40 +00004276 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004277 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004278 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004279 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004280 || CR == APFloat::cmpLessThan
4281 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004282 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004285 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004286 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004287 LValue LHSValue, RHSValue;
4288
4289 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4290 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004291 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004292
Richard Smith745f5142012-01-27 01:14:48 +00004293 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004294 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004295
Richard Smith625b8072011-10-31 01:37:14 +00004296 // Reject differing bases from the normal codepath; we special-case
4297 // comparisons to null.
4298 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004299 if (E->getOpcode() == BO_Sub) {
4300 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004301 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4302 return false;
4303 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4304 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4305 if (!LHSExpr || !RHSExpr)
4306 return false;
4307 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4308 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4309 if (!LHSAddrExpr || !RHSAddrExpr)
4310 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004311 // Make sure both labels come from the same function.
4312 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4313 RHSAddrExpr->getLabel()->getDeclContext())
4314 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004315 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4316 return true;
4317 }
Richard Smith9e36b532011-10-31 05:11:32 +00004318 // Inequalities and subtractions between unrelated pointers have
4319 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004320 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004321 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004322 // A constant address may compare equal to the address of a symbol.
4323 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004324 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004325 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4326 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004327 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004328 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004329 // distinct addresses. In clang, the result of such a comparison is
4330 // unspecified, so it is not a constant expression. However, we do know
4331 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004332 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4333 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004334 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004335 // We can't tell whether weak symbols will end up pointing to the same
4336 // object.
4337 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004338 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004339 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004340 // (Note that clang defaults to -fmerge-all-constants, which can
4341 // lead to inconsistent results for comparisons involving the address
4342 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004343 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004344 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004345
Richard Smithcc5d4f62011-11-07 09:22:26 +00004346 // FIXME: Implement the C++11 restrictions:
4347 // - Pointer subtractions must be on elements of the same array.
4348 // - Pointer comparisons must be between members with the same access.
4349
Richard Smith15efc4d2012-02-01 08:10:20 +00004350 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4351 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4352
John McCall2de56d12010-08-25 11:45:40 +00004353 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004354 QualType Type = E->getLHS()->getType();
4355 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004356
Richard Smith180f4792011-11-10 06:34:14 +00004357 CharUnits ElementSize;
4358 if (!HandleSizeof(Info, ElementType, ElementSize))
4359 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004360
Richard Smith15efc4d2012-02-01 08:10:20 +00004361 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4362 // and produce incorrect results when it overflows. Such behavior
4363 // appears to be non-conforming, but is common, so perhaps we should
4364 // assume the standard intended for such cases to be undefined behavior
4365 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004366
Richard Smith15efc4d2012-02-01 08:10:20 +00004367 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4368 // overflow in the final conversion to ptrdiff_t.
4369 APSInt LHS(
4370 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4371 APSInt RHS(
4372 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4373 APSInt ElemSize(
4374 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4375 APSInt TrueResult = (LHS - RHS) / ElemSize;
4376 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4377
4378 if (Result.extend(65) != TrueResult)
4379 HandleOverflow(Info, E, TrueResult, E->getType());
4380 return Success(Result, E);
4381 }
Richard Smith82f28582012-01-31 06:41:30 +00004382
4383 // C++11 [expr.rel]p3:
4384 // Pointers to void (after pointer conversions) can be compared, with a
4385 // result defined as follows: If both pointers represent the same
4386 // address or are both the null pointer value, the result is true if the
4387 // operator is <= or >= and false otherwise; otherwise the result is
4388 // unspecified.
4389 // We interpret this as applying to pointers to *cv* void.
4390 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
4391 E->getOpcode() != BO_EQ && E->getOpcode() != BO_NE)
4392 CCEDiag(E, diag::note_constexpr_void_comparison);
4393
Richard Smith625b8072011-10-31 01:37:14 +00004394 switch (E->getOpcode()) {
4395 default: llvm_unreachable("missing comparison operator");
4396 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4397 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4398 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4399 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4400 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4401 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004402 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004403 }
4404 }
Richard Smithb02e4622012-02-01 01:42:44 +00004405
4406 if (LHSTy->isMemberPointerType()) {
4407 assert(E->isEqualityOp() && "unexpected member pointer operation");
4408 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4409
4410 MemberPtr LHSValue, RHSValue;
4411
4412 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4413 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4414 return false;
4415
4416 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4417 return false;
4418
4419 // C++11 [expr.eq]p2:
4420 // If both operands are null, they compare equal. Otherwise if only one is
4421 // null, they compare unequal.
4422 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4423 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4424 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4425 }
4426
4427 // Otherwise if either is a pointer to a virtual member function, the
4428 // result is unspecified.
4429 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4430 if (MD->isVirtual())
4431 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4432 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4433 if (MD->isVirtual())
4434 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4435
4436 // Otherwise they compare equal if and only if they would refer to the
4437 // same member of the same most derived object or the same subobject if
4438 // they were dereferenced with a hypothetical object of the associated
4439 // class type.
4440 bool Equal = LHSValue == RHSValue;
4441 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4442 }
4443
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004444 if (!LHSTy->isIntegralOrEnumerationType() ||
4445 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004446 // We can't continue from here for non-integral types.
4447 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004448 }
4449
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004450 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004451 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004452
4453 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4454 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004455 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004456
Richard Smith745f5142012-01-27 01:14:48 +00004457 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004458 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004459
Richard Smith47a1eed2011-10-29 20:57:55 +00004460 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004461
4462 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004463 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004464 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4465 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004466 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004467 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004468 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004469 LHSVal.getLValueOffset() -= AdditionalOffset;
4470 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004471 return true;
4472 }
4473
4474 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004475 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004476 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004477 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4478 LHSVal.getInt().getZExtValue());
4479 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004480 return true;
4481 }
4482
Eli Friedman65639282012-01-04 23:13:47 +00004483 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4484 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004485 if (!LHSVal.getLValueOffset().isZero() ||
4486 !RHSVal.getLValueOffset().isZero())
4487 return false;
4488 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4489 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4490 if (!LHSExpr || !RHSExpr)
4491 return false;
4492 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4493 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4494 if (!LHSAddrExpr || !RHSAddrExpr)
4495 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004496 // Make sure both labels come from the same function.
4497 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4498 RHSAddrExpr->getLabel()->getDeclContext())
4499 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004500 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4501 return true;
4502 }
4503
Eli Friedman42edd0d2009-03-24 01:14:50 +00004504 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004505 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004506 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004507
Richard Smithc49bd112011-10-28 17:51:58 +00004508 APSInt &LHS = LHSVal.getInt();
4509 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004510
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004511 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004512 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004513 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004514 case BO_Mul:
4515 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4516 LHS.getBitWidth() * 2,
4517 std::multiplies<APSInt>()), E);
4518 case BO_Add:
4519 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4520 LHS.getBitWidth() + 1,
4521 std::plus<APSInt>()), E);
4522 case BO_Sub:
4523 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4524 LHS.getBitWidth() + 1,
4525 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004526 case BO_And: return Success(LHS & RHS, E);
4527 case BO_Xor: return Success(LHS ^ RHS, E);
4528 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004529 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004530 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004531 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004532 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004533 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4534 // actually undefined behavior in C++11 due to a language defect.
4535 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4536 LHS.isSigned() && LHS.isMinSignedValue())
4537 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4538 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004539 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004540 // During constant-folding, a negative shift is an opposite shift. Such a
4541 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004542 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004543 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004544 RHS = -RHS;
4545 goto shift_right;
4546 }
4547
4548 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004549 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4550 // shifted type.
4551 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4552 if (SA != RHS) {
4553 CCEDiag(E, diag::note_constexpr_large_shift)
4554 << RHS << E->getType() << LHS.getBitWidth();
4555 } else if (LHS.isSigned()) {
4556 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4557 // operand, and must not overflow.
4558 if (LHS.isNegative())
4559 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4560 else if (LHS.countLeadingZeros() <= SA)
4561 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4562 E->getType());
4563 }
4564
Richard Smithc49bd112011-10-28 17:51:58 +00004565 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004566 }
John McCall2de56d12010-08-25 11:45:40 +00004567 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004568 // During constant-folding, a negative shift is an opposite shift. Such a
4569 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004570 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004571 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004572 RHS = -RHS;
4573 goto shift_left;
4574 }
4575
4576 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004577 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4578 // shifted type.
4579 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4580 if (SA != RHS)
4581 CCEDiag(E, diag::note_constexpr_large_shift)
4582 << RHS << E->getType() << LHS.getBitWidth();
4583
Richard Smithc49bd112011-10-28 17:51:58 +00004584 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004585 }
Mike Stump1eb44332009-09-09 15:08:12 +00004586
Richard Smithc49bd112011-10-28 17:51:58 +00004587 case BO_LT: return Success(LHS < RHS, E);
4588 case BO_GT: return Success(LHS > RHS, E);
4589 case BO_LE: return Success(LHS <= RHS, E);
4590 case BO_GE: return Success(LHS >= RHS, E);
4591 case BO_EQ: return Success(LHS == RHS, E);
4592 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004593 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004594}
4595
Ken Dyck8b752f12010-01-27 17:10:57 +00004596CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004597 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4598 // the result is the size of the referenced type."
4599 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4600 // result shall be the alignment of the referenced type."
4601 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4602 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004603
4604 // __alignof is defined to return the preferred alignment.
4605 return Info.Ctx.toCharUnitsFromBits(
4606 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004607}
4608
Ken Dyck8b752f12010-01-27 17:10:57 +00004609CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004610 E = E->IgnoreParens();
4611
4612 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004613 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004614 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004615 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4616 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004617
Chris Lattneraf707ab2009-01-24 21:53:27 +00004618 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004619 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4620 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004621
Chris Lattnere9feb472009-01-24 21:09:06 +00004622 return GetAlignOfType(E->getType());
4623}
4624
4625
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004626/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4627/// a result as the expression's type.
4628bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4629 const UnaryExprOrTypeTraitExpr *E) {
4630 switch(E->getKind()) {
4631 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004632 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004633 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004634 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004635 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004636 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004637
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004638 case UETT_VecStep: {
4639 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004640
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004641 if (Ty->isVectorType()) {
4642 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004643
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004644 // The vec_step built-in functions that take a 3-component
4645 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4646 if (n == 3)
4647 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004648
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004649 return Success(n, E);
4650 } else
4651 return Success(1, E);
4652 }
4653
4654 case UETT_SizeOf: {
4655 QualType SrcTy = E->getTypeOfArgument();
4656 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4657 // the result is the size of the referenced type."
4658 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4659 // result shall be the alignment of the referenced type."
4660 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4661 SrcTy = Ref->getPointeeType();
4662
Richard Smith180f4792011-11-10 06:34:14 +00004663 CharUnits Sizeof;
4664 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004665 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004666 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004667 }
4668 }
4669
4670 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004671}
4672
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004673bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004674 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004675 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004676 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004677 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004678 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004679 for (unsigned i = 0; i != n; ++i) {
4680 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4681 switch (ON.getKind()) {
4682 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004683 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004684 APSInt IdxResult;
4685 if (!EvaluateInteger(Idx, IdxResult, Info))
4686 return false;
4687 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4688 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004689 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004690 CurrentType = AT->getElementType();
4691 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4692 Result += IdxResult.getSExtValue() * ElementSize;
4693 break;
4694 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004695
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004696 case OffsetOfExpr::OffsetOfNode::Field: {
4697 FieldDecl *MemberDecl = ON.getField();
4698 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004699 if (!RT)
4700 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004701 RecordDecl *RD = RT->getDecl();
4702 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004703 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004704 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004705 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004706 CurrentType = MemberDecl->getType().getNonReferenceType();
4707 break;
4708 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004709
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004710 case OffsetOfExpr::OffsetOfNode::Identifier:
4711 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004712
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004713 case OffsetOfExpr::OffsetOfNode::Base: {
4714 CXXBaseSpecifier *BaseSpec = ON.getBase();
4715 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004716 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004717
4718 // Find the layout of the class whose base we are looking into.
4719 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004720 if (!RT)
4721 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004722 RecordDecl *RD = RT->getDecl();
4723 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4724
4725 // Find the base class itself.
4726 CurrentType = BaseSpec->getType();
4727 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4728 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004729 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004730
4731 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004732 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004733 break;
4734 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004735 }
4736 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004737 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004738}
4739
Chris Lattnerb542afe2008-07-11 19:10:17 +00004740bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004741 switch (E->getOpcode()) {
4742 default:
4743 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4744 // See C99 6.6p3.
4745 return Error(E);
4746 case UO_Extension:
4747 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4748 // If so, we could clear the diagnostic ID.
4749 return Visit(E->getSubExpr());
4750 case UO_Plus:
4751 // The result is just the value.
4752 return Visit(E->getSubExpr());
4753 case UO_Minus: {
4754 if (!Visit(E->getSubExpr()))
4755 return false;
4756 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004757 const APSInt &Value = Result.getInt();
4758 if (Value.isSigned() && Value.isMinSignedValue())
4759 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4760 E->getType());
4761 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004762 }
4763 case UO_Not: {
4764 if (!Visit(E->getSubExpr()))
4765 return false;
4766 if (!Result.isInt()) return Error(E);
4767 return Success(~Result.getInt(), E);
4768 }
4769 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004770 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004771 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004772 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004773 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004774 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004775 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004776}
Mike Stump1eb44332009-09-09 15:08:12 +00004777
Chris Lattner732b2232008-07-12 01:15:53 +00004778/// HandleCast - This is used to evaluate implicit or explicit casts where the
4779/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004780bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4781 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004782 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004783 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004784
Eli Friedman46a52322011-03-25 00:43:55 +00004785 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004786 case CK_BaseToDerived:
4787 case CK_DerivedToBase:
4788 case CK_UncheckedDerivedToBase:
4789 case CK_Dynamic:
4790 case CK_ToUnion:
4791 case CK_ArrayToPointerDecay:
4792 case CK_FunctionToPointerDecay:
4793 case CK_NullToPointer:
4794 case CK_NullToMemberPointer:
4795 case CK_BaseToDerivedMemberPointer:
4796 case CK_DerivedToBaseMemberPointer:
4797 case CK_ConstructorConversion:
4798 case CK_IntegralToPointer:
4799 case CK_ToVoid:
4800 case CK_VectorSplat:
4801 case CK_IntegralToFloating:
4802 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004803 case CK_CPointerToObjCPointerCast:
4804 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004805 case CK_AnyPointerToBlockPointerCast:
4806 case CK_ObjCObjectLValueCast:
4807 case CK_FloatingRealToComplex:
4808 case CK_FloatingComplexToReal:
4809 case CK_FloatingComplexCast:
4810 case CK_FloatingComplexToIntegralComplex:
4811 case CK_IntegralRealToComplex:
4812 case CK_IntegralComplexCast:
4813 case CK_IntegralComplexToFloatingComplex:
4814 llvm_unreachable("invalid cast kind for integral value");
4815
Eli Friedmane50c2972011-03-25 19:07:11 +00004816 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004817 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004818 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004819 case CK_ARCProduceObject:
4820 case CK_ARCConsumeObject:
4821 case CK_ARCReclaimReturnedObject:
4822 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004823 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004824
Richard Smith7d580a42012-01-17 21:17:26 +00004825 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004826 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004827 case CK_AtomicToNonAtomic:
4828 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004829 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004830 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004831
4832 case CK_MemberPointerToBoolean:
4833 case CK_PointerToBoolean:
4834 case CK_IntegralToBoolean:
4835 case CK_FloatingToBoolean:
4836 case CK_FloatingComplexToBoolean:
4837 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004838 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004839 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004840 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004841 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004842 }
4843
Eli Friedman46a52322011-03-25 00:43:55 +00004844 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004845 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004846 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004847
Eli Friedmanbe265702009-02-20 01:15:07 +00004848 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004849 // Allow casts of address-of-label differences if they are no-ops
4850 // or narrowing. (The narrowing case isn't actually guaranteed to
4851 // be constant-evaluatable except in some narrow cases which are hard
4852 // to detect here. We let it through on the assumption the user knows
4853 // what they are doing.)
4854 if (Result.isAddrLabelDiff())
4855 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004856 // Only allow casts of lvalues if they are lossless.
4857 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4858 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004859
Richard Smithf72fccf2012-01-30 22:27:01 +00004860 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
4861 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004862 }
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Eli Friedman46a52322011-03-25 00:43:55 +00004864 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004865 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4866
John McCallefdb83e2010-05-07 21:00:08 +00004867 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004868 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004869 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004870
Daniel Dunbardd211642009-02-19 22:24:01 +00004871 if (LV.getLValueBase()) {
4872 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00004873 // FIXME: Allow a larger integer size than the pointer size, and allow
4874 // narrowing back down to pointer width in subsequent integral casts.
4875 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00004876 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004877 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004878
Richard Smithb755a9d2011-11-16 07:18:12 +00004879 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004880 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004881 return true;
4882 }
4883
Ken Dycka7305832010-01-15 12:37:54 +00004884 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4885 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00004886 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004887 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004888
Eli Friedman46a52322011-03-25 00:43:55 +00004889 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004890 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004891 if (!EvaluateComplex(SubExpr, C, Info))
4892 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004893 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004894 }
Eli Friedman2217c872009-02-22 11:46:18 +00004895
Eli Friedman46a52322011-03-25 00:43:55 +00004896 case CK_FloatingToIntegral: {
4897 APFloat F(0.0);
4898 if (!EvaluateFloat(SubExpr, F, Info))
4899 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004900
Richard Smithc1c5f272011-12-13 06:39:58 +00004901 APSInt Value;
4902 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4903 return false;
4904 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004905 }
4906 }
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Eli Friedman46a52322011-03-25 00:43:55 +00004908 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004909}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004910
Eli Friedman722c7172009-02-28 03:59:05 +00004911bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4912 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004913 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004914 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4915 return false;
4916 if (!LV.isComplexInt())
4917 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004918 return Success(LV.getComplexIntReal(), E);
4919 }
4920
4921 return Visit(E->getSubExpr());
4922}
4923
Eli Friedman664a1042009-02-27 04:45:43 +00004924bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004925 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004926 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004927 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4928 return false;
4929 if (!LV.isComplexInt())
4930 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004931 return Success(LV.getComplexIntImag(), E);
4932 }
4933
Richard Smith8327fad2011-10-24 18:44:57 +00004934 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004935 return Success(0, E);
4936}
4937
Douglas Gregoree8aff02011-01-04 17:33:58 +00004938bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4939 return Success(E->getPackLength(), E);
4940}
4941
Sebastian Redl295995c2010-09-10 20:55:47 +00004942bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4943 return Success(E->getValue(), E);
4944}
4945
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004946//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004947// Float Evaluation
4948//===----------------------------------------------------------------------===//
4949
4950namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004951class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004952 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004953 APFloat &Result;
4954public:
4955 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004956 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004957
Richard Smith47a1eed2011-10-29 20:57:55 +00004958 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004959 Result = V.getFloat();
4960 return true;
4961 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004962
Richard Smith51201882011-12-30 21:15:51 +00004963 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004964 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4965 return true;
4966 }
4967
Chris Lattner019f4e82008-10-06 05:28:25 +00004968 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004969
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004970 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004971 bool VisitBinaryOperator(const BinaryOperator *E);
4972 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004973 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004974
John McCallabd3a852010-05-07 22:08:54 +00004975 bool VisitUnaryReal(const UnaryOperator *E);
4976 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004977
Richard Smith51201882011-12-30 21:15:51 +00004978 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004979};
4980} // end anonymous namespace
4981
4982static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004983 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004984 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004985}
4986
Jay Foad4ba2a172011-01-12 09:06:06 +00004987static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004988 QualType ResultTy,
4989 const Expr *Arg,
4990 bool SNaN,
4991 llvm::APFloat &Result) {
4992 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4993 if (!S) return false;
4994
4995 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4996
4997 llvm::APInt fill;
4998
4999 // Treat empty strings as if they were zero.
5000 if (S->getString().empty())
5001 fill = llvm::APInt(32, 0);
5002 else if (S->getString().getAsInteger(0, fill))
5003 return false;
5004
5005 if (SNaN)
5006 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5007 else
5008 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5009 return true;
5010}
5011
Chris Lattner019f4e82008-10-06 05:28:25 +00005012bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005013 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005014 default:
5015 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5016
Chris Lattner019f4e82008-10-06 05:28:25 +00005017 case Builtin::BI__builtin_huge_val:
5018 case Builtin::BI__builtin_huge_valf:
5019 case Builtin::BI__builtin_huge_vall:
5020 case Builtin::BI__builtin_inf:
5021 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005022 case Builtin::BI__builtin_infl: {
5023 const llvm::fltSemantics &Sem =
5024 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005025 Result = llvm::APFloat::getInf(Sem);
5026 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005027 }
Mike Stump1eb44332009-09-09 15:08:12 +00005028
John McCalldb7b72a2010-02-28 13:00:19 +00005029 case Builtin::BI__builtin_nans:
5030 case Builtin::BI__builtin_nansf:
5031 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005032 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5033 true, Result))
5034 return Error(E);
5035 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005036
Chris Lattner9e621712008-10-06 06:31:58 +00005037 case Builtin::BI__builtin_nan:
5038 case Builtin::BI__builtin_nanf:
5039 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005040 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005041 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005042 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5043 false, Result))
5044 return Error(E);
5045 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005046
5047 case Builtin::BI__builtin_fabs:
5048 case Builtin::BI__builtin_fabsf:
5049 case Builtin::BI__builtin_fabsl:
5050 if (!EvaluateFloat(E->getArg(0), Result, Info))
5051 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005052
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005053 if (Result.isNegative())
5054 Result.changeSign();
5055 return true;
5056
Mike Stump1eb44332009-09-09 15:08:12 +00005057 case Builtin::BI__builtin_copysign:
5058 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005059 case Builtin::BI__builtin_copysignl: {
5060 APFloat RHS(0.);
5061 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5062 !EvaluateFloat(E->getArg(1), RHS, Info))
5063 return false;
5064 Result.copySign(RHS);
5065 return true;
5066 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005067 }
5068}
5069
John McCallabd3a852010-05-07 22:08:54 +00005070bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005071 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5072 ComplexValue CV;
5073 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5074 return false;
5075 Result = CV.FloatReal;
5076 return true;
5077 }
5078
5079 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005080}
5081
5082bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005083 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5084 ComplexValue CV;
5085 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5086 return false;
5087 Result = CV.FloatImag;
5088 return true;
5089 }
5090
Richard Smith8327fad2011-10-24 18:44:57 +00005091 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005092 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5093 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005094 return true;
5095}
5096
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005097bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005098 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005099 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005100 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005101 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005102 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005103 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5104 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005105 Result.changeSign();
5106 return true;
5107 }
5108}
Chris Lattner019f4e82008-10-06 05:28:25 +00005109
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005110bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005111 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5112 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005113
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005114 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005115 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5116 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005117 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005118 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005119 return false;
5120
5121 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005122 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005123 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005124 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005125 break;
John McCall2de56d12010-08-25 11:45:40 +00005126 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005127 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005128 break;
John McCall2de56d12010-08-25 11:45:40 +00005129 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005130 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005131 break;
John McCall2de56d12010-08-25 11:45:40 +00005132 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005133 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005134 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005135 }
Richard Smith7b48a292012-02-01 05:53:12 +00005136
5137 if (Result.isInfinity() || Result.isNaN())
5138 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5139 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005140}
5141
5142bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5143 Result = E->getValue();
5144 return true;
5145}
5146
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005147bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5148 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005149
Eli Friedman2a523ee2011-03-25 00:54:52 +00005150 switch (E->getCastKind()) {
5151 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005152 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005153
5154 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005155 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005156 return EvaluateInteger(SubExpr, IntResult, Info) &&
5157 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5158 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005159 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005160
5161 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005162 if (!Visit(SubExpr))
5163 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005164 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5165 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005166 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005167
Eli Friedman2a523ee2011-03-25 00:54:52 +00005168 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005169 ComplexValue V;
5170 if (!EvaluateComplex(SubExpr, V, Info))
5171 return false;
5172 Result = V.getComplexFloatReal();
5173 return true;
5174 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005175 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005176}
5177
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005178//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005179// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005180//===----------------------------------------------------------------------===//
5181
5182namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005183class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005184 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005185 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005186
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005187public:
John McCallf4cf1a12010-05-07 17:22:02 +00005188 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005189 : ExprEvaluatorBaseTy(info), Result(Result) {}
5190
Richard Smith47a1eed2011-10-29 20:57:55 +00005191 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005192 Result.setFrom(V);
5193 return true;
5194 }
Mike Stump1eb44332009-09-09 15:08:12 +00005195
Eli Friedman7ead5c72012-01-10 04:58:17 +00005196 bool ZeroInitialization(const Expr *E);
5197
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005198 //===--------------------------------------------------------------------===//
5199 // Visitor Methods
5200 //===--------------------------------------------------------------------===//
5201
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005202 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005203 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005204 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005205 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005206 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005207};
5208} // end anonymous namespace
5209
John McCallf4cf1a12010-05-07 17:22:02 +00005210static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5211 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005212 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005213 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005214}
5215
Eli Friedman7ead5c72012-01-10 04:58:17 +00005216bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005217 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005218 if (ElemTy->isRealFloatingType()) {
5219 Result.makeComplexFloat();
5220 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5221 Result.FloatReal = Zero;
5222 Result.FloatImag = Zero;
5223 } else {
5224 Result.makeComplexInt();
5225 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5226 Result.IntReal = Zero;
5227 Result.IntImag = Zero;
5228 }
5229 return true;
5230}
5231
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005232bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5233 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005234
5235 if (SubExpr->getType()->isRealFloatingType()) {
5236 Result.makeComplexFloat();
5237 APFloat &Imag = Result.FloatImag;
5238 if (!EvaluateFloat(SubExpr, Imag, Info))
5239 return false;
5240
5241 Result.FloatReal = APFloat(Imag.getSemantics());
5242 return true;
5243 } else {
5244 assert(SubExpr->getType()->isIntegerType() &&
5245 "Unexpected imaginary literal.");
5246
5247 Result.makeComplexInt();
5248 APSInt &Imag = Result.IntImag;
5249 if (!EvaluateInteger(SubExpr, Imag, Info))
5250 return false;
5251
5252 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5253 return true;
5254 }
5255}
5256
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005257bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005258
John McCall8786da72010-12-14 17:51:41 +00005259 switch (E->getCastKind()) {
5260 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005261 case CK_BaseToDerived:
5262 case CK_DerivedToBase:
5263 case CK_UncheckedDerivedToBase:
5264 case CK_Dynamic:
5265 case CK_ToUnion:
5266 case CK_ArrayToPointerDecay:
5267 case CK_FunctionToPointerDecay:
5268 case CK_NullToPointer:
5269 case CK_NullToMemberPointer:
5270 case CK_BaseToDerivedMemberPointer:
5271 case CK_DerivedToBaseMemberPointer:
5272 case CK_MemberPointerToBoolean:
5273 case CK_ConstructorConversion:
5274 case CK_IntegralToPointer:
5275 case CK_PointerToIntegral:
5276 case CK_PointerToBoolean:
5277 case CK_ToVoid:
5278 case CK_VectorSplat:
5279 case CK_IntegralCast:
5280 case CK_IntegralToBoolean:
5281 case CK_IntegralToFloating:
5282 case CK_FloatingToIntegral:
5283 case CK_FloatingToBoolean:
5284 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005285 case CK_CPointerToObjCPointerCast:
5286 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005287 case CK_AnyPointerToBlockPointerCast:
5288 case CK_ObjCObjectLValueCast:
5289 case CK_FloatingComplexToReal:
5290 case CK_FloatingComplexToBoolean:
5291 case CK_IntegralComplexToReal:
5292 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005293 case CK_ARCProduceObject:
5294 case CK_ARCConsumeObject:
5295 case CK_ARCReclaimReturnedObject:
5296 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005297 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005298
John McCall8786da72010-12-14 17:51:41 +00005299 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005300 case CK_AtomicToNonAtomic:
5301 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005302 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005303 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005304
5305 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005306 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005307 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005308 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005309
5310 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005311 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005312 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005313 return false;
5314
John McCall8786da72010-12-14 17:51:41 +00005315 Result.makeComplexFloat();
5316 Result.FloatImag = APFloat(Real.getSemantics());
5317 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005318 }
5319
John McCall8786da72010-12-14 17:51:41 +00005320 case CK_FloatingComplexCast: {
5321 if (!Visit(E->getSubExpr()))
5322 return false;
5323
5324 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5325 QualType From
5326 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5327
Richard Smithc1c5f272011-12-13 06:39:58 +00005328 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5329 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005330 }
5331
5332 case CK_FloatingComplexToIntegralComplex: {
5333 if (!Visit(E->getSubExpr()))
5334 return false;
5335
5336 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5337 QualType From
5338 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5339 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005340 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5341 To, Result.IntReal) &&
5342 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5343 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005344 }
5345
5346 case CK_IntegralRealToComplex: {
5347 APSInt &Real = Result.IntReal;
5348 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5349 return false;
5350
5351 Result.makeComplexInt();
5352 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5353 return true;
5354 }
5355
5356 case CK_IntegralComplexCast: {
5357 if (!Visit(E->getSubExpr()))
5358 return false;
5359
5360 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5361 QualType From
5362 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5363
Richard Smithf72fccf2012-01-30 22:27:01 +00005364 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5365 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005366 return true;
5367 }
5368
5369 case CK_IntegralComplexToFloatingComplex: {
5370 if (!Visit(E->getSubExpr()))
5371 return false;
5372
5373 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5374 QualType From
5375 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5376 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005377 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5378 To, Result.FloatReal) &&
5379 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5380 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005381 }
5382 }
5383
5384 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005385}
5386
John McCallf4cf1a12010-05-07 17:22:02 +00005387bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005388 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005389 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5390
Richard Smith745f5142012-01-27 01:14:48 +00005391 bool LHSOK = Visit(E->getLHS());
5392 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005393 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005394
John McCallf4cf1a12010-05-07 17:22:02 +00005395 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005396 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005397 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005398
Daniel Dunbar3f279872009-01-29 01:32:56 +00005399 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5400 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005401 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005402 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005403 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005404 if (Result.isComplexFloat()) {
5405 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5406 APFloat::rmNearestTiesToEven);
5407 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5408 APFloat::rmNearestTiesToEven);
5409 } else {
5410 Result.getComplexIntReal() += RHS.getComplexIntReal();
5411 Result.getComplexIntImag() += RHS.getComplexIntImag();
5412 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005413 break;
John McCall2de56d12010-08-25 11:45:40 +00005414 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005415 if (Result.isComplexFloat()) {
5416 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5417 APFloat::rmNearestTiesToEven);
5418 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5419 APFloat::rmNearestTiesToEven);
5420 } else {
5421 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5422 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5423 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005424 break;
John McCall2de56d12010-08-25 11:45:40 +00005425 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005426 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005427 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005428 APFloat &LHS_r = LHS.getComplexFloatReal();
5429 APFloat &LHS_i = LHS.getComplexFloatImag();
5430 APFloat &RHS_r = RHS.getComplexFloatReal();
5431 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Daniel Dunbar3f279872009-01-29 01:32:56 +00005433 APFloat Tmp = LHS_r;
5434 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5435 Result.getComplexFloatReal() = Tmp;
5436 Tmp = LHS_i;
5437 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5438 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5439
5440 Tmp = LHS_r;
5441 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5442 Result.getComplexFloatImag() = Tmp;
5443 Tmp = LHS_i;
5444 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5445 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5446 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005447 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005448 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005449 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5450 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005451 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005452 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5453 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5454 }
5455 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005456 case BO_Div:
5457 if (Result.isComplexFloat()) {
5458 ComplexValue LHS = Result;
5459 APFloat &LHS_r = LHS.getComplexFloatReal();
5460 APFloat &LHS_i = LHS.getComplexFloatImag();
5461 APFloat &RHS_r = RHS.getComplexFloatReal();
5462 APFloat &RHS_i = RHS.getComplexFloatImag();
5463 APFloat &Res_r = Result.getComplexFloatReal();
5464 APFloat &Res_i = Result.getComplexFloatImag();
5465
5466 APFloat Den = RHS_r;
5467 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5468 APFloat Tmp = RHS_i;
5469 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5470 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5471
5472 Res_r = LHS_r;
5473 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5474 Tmp = LHS_i;
5475 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5476 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5477 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5478
5479 Res_i = LHS_i;
5480 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5481 Tmp = LHS_r;
5482 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5483 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5484 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5485 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005486 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5487 return Error(E, diag::note_expr_divide_by_zero);
5488
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005489 ComplexValue LHS = Result;
5490 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5491 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5492 Result.getComplexIntReal() =
5493 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5494 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5495 Result.getComplexIntImag() =
5496 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5497 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5498 }
5499 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005500 }
5501
John McCallf4cf1a12010-05-07 17:22:02 +00005502 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005503}
5504
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005505bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5506 // Get the operand value into 'Result'.
5507 if (!Visit(E->getSubExpr()))
5508 return false;
5509
5510 switch (E->getOpcode()) {
5511 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005512 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005513 case UO_Extension:
5514 return true;
5515 case UO_Plus:
5516 // The result is always just the subexpr.
5517 return true;
5518 case UO_Minus:
5519 if (Result.isComplexFloat()) {
5520 Result.getComplexFloatReal().changeSign();
5521 Result.getComplexFloatImag().changeSign();
5522 }
5523 else {
5524 Result.getComplexIntReal() = -Result.getComplexIntReal();
5525 Result.getComplexIntImag() = -Result.getComplexIntImag();
5526 }
5527 return true;
5528 case UO_Not:
5529 if (Result.isComplexFloat())
5530 Result.getComplexFloatImag().changeSign();
5531 else
5532 Result.getComplexIntImag() = -Result.getComplexIntImag();
5533 return true;
5534 }
5535}
5536
Eli Friedman7ead5c72012-01-10 04:58:17 +00005537bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5538 if (E->getNumInits() == 2) {
5539 if (E->getType()->isComplexType()) {
5540 Result.makeComplexFloat();
5541 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5542 return false;
5543 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5544 return false;
5545 } else {
5546 Result.makeComplexInt();
5547 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5548 return false;
5549 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5550 return false;
5551 }
5552 return true;
5553 }
5554 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5555}
5556
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005557//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005558// Void expression evaluation, primarily for a cast to void on the LHS of a
5559// comma operator
5560//===----------------------------------------------------------------------===//
5561
5562namespace {
5563class VoidExprEvaluator
5564 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5565public:
5566 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5567
5568 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005569
5570 bool VisitCastExpr(const CastExpr *E) {
5571 switch (E->getCastKind()) {
5572 default:
5573 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5574 case CK_ToVoid:
5575 VisitIgnoredValue(E->getSubExpr());
5576 return true;
5577 }
5578 }
5579};
5580} // end anonymous namespace
5581
5582static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5583 assert(E->isRValue() && E->getType()->isVoidType());
5584 return VoidExprEvaluator(Info).Visit(E);
5585}
5586
5587//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005588// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005589//===----------------------------------------------------------------------===//
5590
Richard Smith47a1eed2011-10-29 20:57:55 +00005591static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005592 // In C, function designators are not lvalues, but we evaluate them as if they
5593 // are.
5594 if (E->isGLValue() || E->getType()->isFunctionType()) {
5595 LValue LV;
5596 if (!EvaluateLValue(E, LV, Info))
5597 return false;
5598 LV.moveInto(Result);
5599 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005600 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005601 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005602 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005603 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005604 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005605 } else if (E->getType()->hasPointerRepresentation()) {
5606 LValue LV;
5607 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005608 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005609 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005610 } else if (E->getType()->isRealFloatingType()) {
5611 llvm::APFloat F(0.0);
5612 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005613 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005614 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005615 } else if (E->getType()->isAnyComplexType()) {
5616 ComplexValue C;
5617 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005618 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005619 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005620 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005621 MemberPtr P;
5622 if (!EvaluateMemberPointer(E, P, Info))
5623 return false;
5624 P.moveInto(Result);
5625 return true;
Richard Smith51201882011-12-30 21:15:51 +00005626 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005627 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005628 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005629 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005630 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005631 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005632 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005633 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005634 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005635 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5636 return false;
5637 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005638 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005639 if (Info.getLangOpts().CPlusPlus0x)
5640 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5641 << E->getType();
5642 else
5643 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005644 if (!EvaluateVoid(E, Info))
5645 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005646 } else if (Info.getLangOpts().CPlusPlus0x) {
5647 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5648 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005649 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005650 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005651 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005652 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005653
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005654 return true;
5655}
5656
Richard Smith69c2c502011-11-04 05:33:44 +00005657/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5658/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5659/// since later initializers for an object can indirectly refer to subobjects
5660/// which were initialized earlier.
5661static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005662 const LValue &This, const Expr *E,
5663 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005664 if (!CheckLiteralType(Info, E))
5665 return false;
5666
5667 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005668 // Evaluate arrays and record types in-place, so that later initializers can
5669 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005670 if (E->getType()->isArrayType())
5671 return EvaluateArray(E, This, Result, Info);
5672 else if (E->getType()->isRecordType())
5673 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005674 }
5675
5676 // For any other type, in-place evaluation is unimportant.
5677 CCValue CoreConstResult;
5678 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005679 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005680}
5681
Richard Smithf48fdb02011-12-09 22:58:01 +00005682/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5683/// lvalue-to-rvalue cast if it is an lvalue.
5684static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005685 if (!CheckLiteralType(Info, E))
5686 return false;
5687
Richard Smithf48fdb02011-12-09 22:58:01 +00005688 CCValue Value;
5689 if (!::Evaluate(Value, Info, E))
5690 return false;
5691
5692 if (E->isGLValue()) {
5693 LValue LV;
5694 LV.setFrom(Value);
5695 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5696 return false;
5697 }
5698
5699 // Check this core constant expression is a constant expression, and if so,
5700 // convert it to one.
5701 return CheckConstantExpression(Info, E, Value, Result);
5702}
Richard Smithc49bd112011-10-28 17:51:58 +00005703
Richard Smith51f47082011-10-29 00:50:52 +00005704/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005705/// any crazy technique (that has nothing to do with language standards) that
5706/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005707/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5708/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005709bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005710 // Fast-path evaluations of integer literals, since we sometimes see files
5711 // containing vast quantities of these.
5712 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5713 Result.Val = APValue(APSInt(L->getValue(),
5714 L->getType()->isUnsignedIntegerType()));
5715 return true;
5716 }
5717
Richard Smith2d6a5672012-01-14 04:30:29 +00005718 // FIXME: Evaluating values of large array and record types can cause
5719 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005720 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5721 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005722 return false;
5723
Richard Smithf48fdb02011-12-09 22:58:01 +00005724 EvalInfo Info(Ctx, Result);
5725 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005726}
5727
Jay Foad4ba2a172011-01-12 09:06:06 +00005728bool Expr::EvaluateAsBooleanCondition(bool &Result,
5729 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005730 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005731 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005732 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5733 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005734 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005735}
5736
Richard Smith80d4b552011-12-28 19:48:30 +00005737bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5738 SideEffectsKind AllowSideEffects) const {
5739 if (!getType()->isIntegralOrEnumerationType())
5740 return false;
5741
Richard Smithc49bd112011-10-28 17:51:58 +00005742 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005743 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5744 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005745 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005746
Richard Smithc49bd112011-10-28 17:51:58 +00005747 Result = ExprResult.Val.getInt();
5748 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005749}
5750
Jay Foad4ba2a172011-01-12 09:06:06 +00005751bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005752 EvalInfo Info(Ctx, Result);
5753
John McCallefdb83e2010-05-07 21:00:08 +00005754 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005755 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005756 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5757 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005758}
5759
Richard Smith099e7f62011-12-19 06:19:21 +00005760bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5761 const VarDecl *VD,
5762 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005763 // FIXME: Evaluating initializers for large array and record types can cause
5764 // performance problems. Only do so in C++11 for now.
5765 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5766 !Ctx.getLangOptions().CPlusPlus0x)
5767 return false;
5768
Richard Smith099e7f62011-12-19 06:19:21 +00005769 Expr::EvalStatus EStatus;
5770 EStatus.Diag = &Notes;
5771
5772 EvalInfo InitInfo(Ctx, EStatus);
5773 InitInfo.setEvaluatingDecl(VD, Value);
5774
Richard Smith51201882011-12-30 21:15:51 +00005775 if (!CheckLiteralType(InitInfo, this))
5776 return false;
5777
Richard Smith099e7f62011-12-19 06:19:21 +00005778 LValue LVal;
5779 LVal.set(VD);
5780
Richard Smith51201882011-12-30 21:15:51 +00005781 // C++11 [basic.start.init]p2:
5782 // Variables with static storage duration or thread storage duration shall be
5783 // zero-initialized before any other initialization takes place.
5784 // This behavior is not present in C.
5785 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5786 !VD->getType()->isReferenceType()) {
5787 ImplicitValueInitExpr VIE(VD->getType());
5788 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5789 return false;
5790 }
5791
Richard Smith099e7f62011-12-19 06:19:21 +00005792 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5793 !EStatus.HasSideEffects;
5794}
5795
Richard Smith51f47082011-10-29 00:50:52 +00005796/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5797/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005798bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005799 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005800 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005801}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005802
Jay Foad4ba2a172011-01-12 09:06:06 +00005803bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005804 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005805}
5806
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005807APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005808 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005809 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005810 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005811 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005812 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005813
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005814 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005815}
John McCalld905f5a2010-05-07 05:32:02 +00005816
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005817 bool Expr::EvalResult::isGlobalLValue() const {
5818 assert(Val.isLValue());
5819 return IsGlobalLValue(Val.getLValueBase());
5820 }
5821
5822
John McCalld905f5a2010-05-07 05:32:02 +00005823/// isIntegerConstantExpr - this recursive routine will test if an expression is
5824/// an integer constant expression.
5825
5826/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5827/// comma, etc
5828///
5829/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5830/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5831/// cast+dereference.
5832
5833// CheckICE - This function does the fundamental ICE checking: the returned
5834// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5835// Note that to reduce code duplication, this helper does no evaluation
5836// itself; the caller checks whether the expression is evaluatable, and
5837// in the rare cases where CheckICE actually cares about the evaluated
5838// value, it calls into Evalute.
5839//
5840// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005841// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005842// 1: This expression is not an ICE, but if it isn't evaluated, it's
5843// a legal subexpression for an ICE. This return value is used to handle
5844// the comma operator in C99 mode.
5845// 2: This expression is not an ICE, and is not a legal subexpression for one.
5846
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005847namespace {
5848
John McCalld905f5a2010-05-07 05:32:02 +00005849struct ICEDiag {
5850 unsigned Val;
5851 SourceLocation Loc;
5852
5853 public:
5854 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5855 ICEDiag() : Val(0) {}
5856};
5857
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005858}
5859
5860static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005861
5862static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5863 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005864 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005865 !EVResult.Val.isInt()) {
5866 return ICEDiag(2, E->getLocStart());
5867 }
5868 return NoDiag();
5869}
5870
5871static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5872 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005873 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005874 return ICEDiag(2, E->getLocStart());
5875 }
5876
5877 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005878#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005879#define STMT(Node, Base) case Expr::Node##Class:
5880#define EXPR(Node, Base)
5881#include "clang/AST/StmtNodes.inc"
5882 case Expr::PredefinedExprClass:
5883 case Expr::FloatingLiteralClass:
5884 case Expr::ImaginaryLiteralClass:
5885 case Expr::StringLiteralClass:
5886 case Expr::ArraySubscriptExprClass:
5887 case Expr::MemberExprClass:
5888 case Expr::CompoundAssignOperatorClass:
5889 case Expr::CompoundLiteralExprClass:
5890 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005891 case Expr::DesignatedInitExprClass:
5892 case Expr::ImplicitValueInitExprClass:
5893 case Expr::ParenListExprClass:
5894 case Expr::VAArgExprClass:
5895 case Expr::AddrLabelExprClass:
5896 case Expr::StmtExprClass:
5897 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005898 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005899 case Expr::CXXDynamicCastExprClass:
5900 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005901 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005902 case Expr::CXXNullPtrLiteralExprClass:
5903 case Expr::CXXThisExprClass:
5904 case Expr::CXXThrowExprClass:
5905 case Expr::CXXNewExprClass:
5906 case Expr::CXXDeleteExprClass:
5907 case Expr::CXXPseudoDestructorExprClass:
5908 case Expr::UnresolvedLookupExprClass:
5909 case Expr::DependentScopeDeclRefExprClass:
5910 case Expr::CXXConstructExprClass:
5911 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005912 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005913 case Expr::CXXTemporaryObjectExprClass:
5914 case Expr::CXXUnresolvedConstructExprClass:
5915 case Expr::CXXDependentScopeMemberExprClass:
5916 case Expr::UnresolvedMemberExprClass:
5917 case Expr::ObjCStringLiteralClass:
5918 case Expr::ObjCEncodeExprClass:
5919 case Expr::ObjCMessageExprClass:
5920 case Expr::ObjCSelectorExprClass:
5921 case Expr::ObjCProtocolExprClass:
5922 case Expr::ObjCIvarRefExprClass:
5923 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005924 case Expr::ObjCIsaExprClass:
5925 case Expr::ShuffleVectorExprClass:
5926 case Expr::BlockExprClass:
5927 case Expr::BlockDeclRefExprClass:
5928 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005929 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005930 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005931 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005932 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005933 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005934 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005935 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005936 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005937 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005938 return ICEDiag(2, E->getLocStart());
5939
Douglas Gregoree8aff02011-01-04 17:33:58 +00005940 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005941 case Expr::GNUNullExprClass:
5942 // GCC considers the GNU __null value to be an integral constant expression.
5943 return NoDiag();
5944
John McCall91a57552011-07-15 05:09:51 +00005945 case Expr::SubstNonTypeTemplateParmExprClass:
5946 return
5947 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5948
John McCalld905f5a2010-05-07 05:32:02 +00005949 case Expr::ParenExprClass:
5950 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005951 case Expr::GenericSelectionExprClass:
5952 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005953 case Expr::IntegerLiteralClass:
5954 case Expr::CharacterLiteralClass:
5955 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005956 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005957 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005958 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005959 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005960 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005961 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005962 return NoDiag();
5963 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005964 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005965 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5966 // constant expressions, but they can never be ICEs because an ICE cannot
5967 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005968 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005969 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005970 return CheckEvalInICE(E, Ctx);
5971 return ICEDiag(2, E->getLocStart());
5972 }
5973 case Expr::DeclRefExprClass:
5974 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5975 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005976 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005977 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5978
5979 // Parameter variables are never constants. Without this check,
5980 // getAnyInitializer() can find a default argument, which leads
5981 // to chaos.
5982 if (isa<ParmVarDecl>(D))
5983 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5984
5985 // C++ 7.1.5.1p2
5986 // A variable of non-volatile const-qualified integral or enumeration
5987 // type initialized by an ICE can be used in ICEs.
5988 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005989 if (!Dcl->getType()->isIntegralOrEnumerationType())
5990 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5991
Richard Smith099e7f62011-12-19 06:19:21 +00005992 const VarDecl *VD;
5993 // Look for a declaration of this variable that has an initializer, and
5994 // check whether it is an ICE.
5995 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5996 return NoDiag();
5997 else
5998 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005999 }
6000 }
6001 return ICEDiag(2, E->getLocStart());
6002 case Expr::UnaryOperatorClass: {
6003 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6004 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006005 case UO_PostInc:
6006 case UO_PostDec:
6007 case UO_PreInc:
6008 case UO_PreDec:
6009 case UO_AddrOf:
6010 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006011 // C99 6.6/3 allows increment and decrement within unevaluated
6012 // subexpressions of constant expressions, but they can never be ICEs
6013 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006014 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006015 case UO_Extension:
6016 case UO_LNot:
6017 case UO_Plus:
6018 case UO_Minus:
6019 case UO_Not:
6020 case UO_Real:
6021 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006022 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006023 }
6024
6025 // OffsetOf falls through here.
6026 }
6027 case Expr::OffsetOfExprClass: {
6028 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006029 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006030 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006031 // compliance: we should warn earlier for offsetof expressions with
6032 // array subscripts that aren't ICEs, and if the array subscripts
6033 // are ICEs, the value of the offsetof must be an integer constant.
6034 return CheckEvalInICE(E, Ctx);
6035 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006036 case Expr::UnaryExprOrTypeTraitExprClass: {
6037 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6038 if ((Exp->getKind() == UETT_SizeOf) &&
6039 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006040 return ICEDiag(2, E->getLocStart());
6041 return NoDiag();
6042 }
6043 case Expr::BinaryOperatorClass: {
6044 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6045 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006046 case BO_PtrMemD:
6047 case BO_PtrMemI:
6048 case BO_Assign:
6049 case BO_MulAssign:
6050 case BO_DivAssign:
6051 case BO_RemAssign:
6052 case BO_AddAssign:
6053 case BO_SubAssign:
6054 case BO_ShlAssign:
6055 case BO_ShrAssign:
6056 case BO_AndAssign:
6057 case BO_XorAssign:
6058 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006059 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6060 // constant expressions, but they can never be ICEs because an ICE cannot
6061 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006062 return ICEDiag(2, E->getLocStart());
6063
John McCall2de56d12010-08-25 11:45:40 +00006064 case BO_Mul:
6065 case BO_Div:
6066 case BO_Rem:
6067 case BO_Add:
6068 case BO_Sub:
6069 case BO_Shl:
6070 case BO_Shr:
6071 case BO_LT:
6072 case BO_GT:
6073 case BO_LE:
6074 case BO_GE:
6075 case BO_EQ:
6076 case BO_NE:
6077 case BO_And:
6078 case BO_Xor:
6079 case BO_Or:
6080 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006081 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6082 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006083 if (Exp->getOpcode() == BO_Div ||
6084 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006085 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006086 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006087 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006088 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006089 if (REval == 0)
6090 return ICEDiag(1, E->getLocStart());
6091 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006092 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006093 if (LEval.isMinSignedValue())
6094 return ICEDiag(1, E->getLocStart());
6095 }
6096 }
6097 }
John McCall2de56d12010-08-25 11:45:40 +00006098 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006099 if (Ctx.getLangOptions().C99) {
6100 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6101 // if it isn't evaluated.
6102 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6103 return ICEDiag(1, E->getLocStart());
6104 } else {
6105 // In both C89 and C++, commas in ICEs are illegal.
6106 return ICEDiag(2, E->getLocStart());
6107 }
6108 }
6109 if (LHSResult.Val >= RHSResult.Val)
6110 return LHSResult;
6111 return RHSResult;
6112 }
John McCall2de56d12010-08-25 11:45:40 +00006113 case BO_LAnd:
6114 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006115 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6116 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6117 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6118 // Rare case where the RHS has a comma "side-effect"; we need
6119 // to actually check the condition to see whether the side
6120 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006121 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006122 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006123 return RHSResult;
6124 return NoDiag();
6125 }
6126
6127 if (LHSResult.Val >= RHSResult.Val)
6128 return LHSResult;
6129 return RHSResult;
6130 }
6131 }
6132 }
6133 case Expr::ImplicitCastExprClass:
6134 case Expr::CStyleCastExprClass:
6135 case Expr::CXXFunctionalCastExprClass:
6136 case Expr::CXXStaticCastExprClass:
6137 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006138 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006139 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006140 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006141 if (isa<ExplicitCastExpr>(E)) {
6142 if (const FloatingLiteral *FL
6143 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6144 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6145 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6146 APSInt IgnoredVal(DestWidth, !DestSigned);
6147 bool Ignored;
6148 // If the value does not fit in the destination type, the behavior is
6149 // undefined, so we are not required to treat it as a constant
6150 // expression.
6151 if (FL->getValue().convertToInteger(IgnoredVal,
6152 llvm::APFloat::rmTowardZero,
6153 &Ignored) & APFloat::opInvalidOp)
6154 return ICEDiag(2, E->getLocStart());
6155 return NoDiag();
6156 }
6157 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006158 switch (cast<CastExpr>(E)->getCastKind()) {
6159 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006160 case CK_AtomicToNonAtomic:
6161 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006162 case CK_NoOp:
6163 case CK_IntegralToBoolean:
6164 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006165 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006166 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006167 return ICEDiag(2, E->getLocStart());
6168 }
John McCalld905f5a2010-05-07 05:32:02 +00006169 }
John McCall56ca35d2011-02-17 10:25:35 +00006170 case Expr::BinaryConditionalOperatorClass: {
6171 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6172 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6173 if (CommonResult.Val == 2) return CommonResult;
6174 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6175 if (FalseResult.Val == 2) return FalseResult;
6176 if (CommonResult.Val == 1) return CommonResult;
6177 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006178 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006179 return FalseResult;
6180 }
John McCalld905f5a2010-05-07 05:32:02 +00006181 case Expr::ConditionalOperatorClass: {
6182 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6183 // If the condition (ignoring parens) is a __builtin_constant_p call,
6184 // then only the true side is actually considered in an integer constant
6185 // expression, and it is fully evaluated. This is an important GNU
6186 // extension. See GCC PR38377 for discussion.
6187 if (const CallExpr *CallCE
6188 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006189 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6190 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006191 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006192 if (CondResult.Val == 2)
6193 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006194
Richard Smithf48fdb02011-12-09 22:58:01 +00006195 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6196 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006197
John McCalld905f5a2010-05-07 05:32:02 +00006198 if (TrueResult.Val == 2)
6199 return TrueResult;
6200 if (FalseResult.Val == 2)
6201 return FalseResult;
6202 if (CondResult.Val == 1)
6203 return CondResult;
6204 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6205 return NoDiag();
6206 // Rare case where the diagnostics depend on which side is evaluated
6207 // Note that if we get here, CondResult is 0, and at least one of
6208 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006209 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006210 return FalseResult;
6211 }
6212 return TrueResult;
6213 }
6214 case Expr::CXXDefaultArgExprClass:
6215 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6216 case Expr::ChooseExprClass: {
6217 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6218 }
6219 }
6220
David Blaikie30263482012-01-20 21:50:17 +00006221 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006222}
6223
Richard Smithf48fdb02011-12-09 22:58:01 +00006224/// Evaluate an expression as a C++11 integral constant expression.
6225static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6226 const Expr *E,
6227 llvm::APSInt *Value,
6228 SourceLocation *Loc) {
6229 if (!E->getType()->isIntegralOrEnumerationType()) {
6230 if (Loc) *Loc = E->getExprLoc();
6231 return false;
6232 }
6233
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006234 APValue Result;
6235 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006236 return false;
6237
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006238 assert(Result.isInt() && "pointer cast to int is not an ICE");
6239 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006240 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006241}
6242
Richard Smithdd1f29b2011-12-12 09:28:41 +00006243bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006244 if (Ctx.getLangOptions().CPlusPlus0x)
6245 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6246
John McCalld905f5a2010-05-07 05:32:02 +00006247 ICEDiag d = CheckICE(this, Ctx);
6248 if (d.Val != 0) {
6249 if (Loc) *Loc = d.Loc;
6250 return false;
6251 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006252 return true;
6253}
6254
6255bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6256 SourceLocation *Loc, bool isEvaluated) const {
6257 if (Ctx.getLangOptions().CPlusPlus0x)
6258 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6259
6260 if (!isIntegerConstantExpr(Ctx, Loc))
6261 return false;
6262 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006263 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006264 return true;
6265}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006266
6267bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6268 SourceLocation *Loc) const {
6269 // We support this checking in C++98 mode in order to diagnose compatibility
6270 // issues.
6271 assert(Ctx.getLangOptions().CPlusPlus);
6272
6273 Expr::EvalStatus Status;
6274 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6275 Status.Diag = &Diags;
6276 EvalInfo Info(Ctx, Status);
6277
6278 APValue Scratch;
6279 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6280
6281 if (!Diags.empty()) {
6282 IsConstExpr = false;
6283 if (Loc) *Loc = Diags[0].first;
6284 } else if (!IsConstExpr) {
6285 // FIXME: This shouldn't happen.
6286 if (Loc) *Loc = getExprLoc();
6287 }
6288
6289 return IsConstExpr;
6290}
Richard Smith745f5142012-01-27 01:14:48 +00006291
6292bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6293 llvm::SmallVectorImpl<
6294 PartialDiagnosticAt> &Diags) {
6295 // FIXME: It would be useful to check constexpr function templates, but at the
6296 // moment the constant expression evaluator cannot cope with the non-rigorous
6297 // ASTs which we build for dependent expressions.
6298 if (FD->isDependentContext())
6299 return true;
6300
6301 Expr::EvalStatus Status;
6302 Status.Diag = &Diags;
6303
6304 EvalInfo Info(FD->getASTContext(), Status);
6305 Info.CheckingPotentialConstantExpression = true;
6306
6307 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6308 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6309
6310 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6311 // is a temporary being used as the 'this' pointer.
6312 LValue This;
6313 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6314 This.set(&VIE, Info.CurrentCall);
6315
6316 APValue Scratch;
6317 ArrayRef<const Expr*> Args;
6318
6319 SourceLocation Loc = FD->getLocation();
6320
6321 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6322 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6323 } else
6324 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6325 Args, FD->getBody(), Info, Scratch);
6326
6327 return Diags.empty();
6328}