blob: fcba037afc77cc3ca43a2f629b8ecdbd247603f9 [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
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
108 } else if (const FieldDecl *FD = getAsField(Path[I])) {
109 Type = FD->getType();
110 ArraySize = 0;
111 MostDerivedLength = I + 1;
112 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000113 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 ArraySize = 0;
115 }
Richard Smith9a17a682011-11-07 05:07:52 +0000116 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000117 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000118 }
119
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 // The order of this enum is important for diagnostics.
121 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000122 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
123 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000124 };
125
Richard Smith0a3bdb62011-11-04 02:25:55 +0000126 /// A path from a glvalue to a subobject of that glvalue.
127 struct SubobjectDesignator {
128 /// True if the subobject was named in a manner not supported by C++11. Such
129 /// lvalues can still be folded, but they are not core constant expressions
130 /// and we cannot perform lvalue-to-rvalue conversions on them.
131 bool Invalid : 1;
132
Richard Smithb4e85ed2012-01-06 16:39:00 +0000133 /// Is this a pointer one past the end of an object?
134 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000135
Richard Smithb4e85ed2012-01-06 16:39:00 +0000136 /// The length of the path to the most-derived object of which this is a
137 /// subobject.
138 unsigned MostDerivedPathLength : 30;
139
140 /// The size of the array of which the most-derived object is an element, or
141 /// 0 if the most-derived object is not an array element.
142 uint64_t MostDerivedArraySize;
143
144 /// The type of the most derived object referred to by this address.
145 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146
Richard Smith9a17a682011-11-07 05:07:52 +0000147 typedef APValue::LValuePathEntry PathEntry;
148
Richard Smith0a3bdb62011-11-04 02:25:55 +0000149 /// The entries on the path from the glvalue to the designated subobject.
150 SmallVector<PathEntry, 8> Entries;
151
Richard Smithb4e85ed2012-01-06 16:39:00 +0000152 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000153
Richard Smithb4e85ed2012-01-06 16:39:00 +0000154 explicit SubobjectDesignator(QualType T)
155 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
156 MostDerivedArraySize(0), MostDerivedType(T) {}
157
158 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
159 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
160 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000161 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000162 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000163 ArrayRef<PathEntry> VEntries = V.getLValuePath();
164 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
165 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000166 MostDerivedPathLength =
167 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
168 V.getLValuePath(), MostDerivedArraySize,
169 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000170 }
171 }
172
Richard Smith0a3bdb62011-11-04 02:25:55 +0000173 void setInvalid() {
174 Invalid = true;
175 Entries.clear();
176 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000177
178 /// Determine whether this is a one-past-the-end pointer.
179 bool isOnePastTheEnd() const {
180 if (IsOnePastTheEnd)
181 return true;
182 if (MostDerivedArraySize &&
183 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
184 return true;
185 return false;
186 }
187
188 /// Check that this refers to a valid subobject.
189 bool isValidSubobject() const {
190 if (Invalid)
191 return false;
192 return !isOnePastTheEnd();
193 }
194 /// Check that this refers to a valid subobject, and if not, produce a
195 /// relevant diagnostic and set the designator as invalid.
196 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
197
198 /// Update this designator to refer to the first element within this array.
199 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000200 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000201 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000202 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000203
204 // This is a most-derived object.
205 MostDerivedType = CAT->getElementType();
206 MostDerivedArraySize = CAT->getSize().getZExtValue();
207 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 }
209 /// Update this designator to refer to the given base or member of this
210 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000212 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000213 APValue::BaseOrMemberType Value(D, Virtual);
214 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000215 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216
217 // If this isn't a base class, it's a new most-derived object.
218 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
219 MostDerivedType = FD->getType();
220 MostDerivedArraySize = 0;
221 MostDerivedPathLength = Entries.size();
222 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000223 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000224 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000225 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000226 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000227 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000228 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000229 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000230 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
231 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
232 setInvalid();
233 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 return;
235 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000236 // [expr.add]p4: For the purposes of these operators, a pointer to a
237 // nonarray object behaves the same as a pointer to the first element of
238 // an array of length one with the type of the object as its element type.
239 if (IsOnePastTheEnd && N == (uint64_t)-1)
240 IsOnePastTheEnd = false;
241 else if (!IsOnePastTheEnd && N == 1)
242 IsOnePastTheEnd = true;
243 else if (N != 0) {
244 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000247 }
248 };
249
Richard Smith47a1eed2011-10-29 20:57:55 +0000250 /// A core constant value. This can be the value of any constant expression,
251 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000252 ///
253 /// For an LValue, the base and offset are stored in the APValue subobject,
254 /// but the other information is stored in the SubobjectDesignator. For all
255 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000256 class CCValue : public APValue {
257 typedef llvm::APSInt APSInt;
258 typedef llvm::APFloat APFloat;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000259 /// If the value is a reference or pointer, this is a description of how the
260 /// subobject was specified.
261 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000262 public:
Richard Smith177dce72011-11-01 16:57:24 +0000263 struct GlobalValue {};
264
Richard Smith47a1eed2011-10-29 20:57:55 +0000265 CCValue() {}
266 explicit CCValue(const APSInt &I) : APValue(I) {}
267 explicit CCValue(const APFloat &F) : APValue(F) {}
268 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
269 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
270 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith83587db2012-02-15 02:18:13 +0000271 CCValue(const CCValue &V) : APValue(V), Designator(V.Designator) {}
272 CCValue(LValueBase B, const CharUnits &O, unsigned I,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000273 const SubobjectDesignator &D) :
Richard Smith83587db2012-02-15 02:18:13 +0000274 APValue(B, O, APValue::NoLValuePath(), I), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000275 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
Richard Smith83587db2012-02-15 02:18:13 +0000276 APValue(V), Designator(Ctx, V) {
277 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000278 CCValue(const ValueDecl *D, bool IsDerivedMember,
279 ArrayRef<const CXXRecordDecl*> Path) :
280 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000281 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
282 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000283
Richard Smith0a3bdb62011-11-04 02:25:55 +0000284 SubobjectDesignator &getLValueDesignator() {
285 assert(getKind() == LValue);
286 return Designator;
287 }
288 const SubobjectDesignator &getLValueDesignator() const {
289 return const_cast<CCValue*>(this)->getLValueDesignator();
290 }
Richard Smith83587db2012-02-15 02:18:13 +0000291 APValue toAPValue() const {
292 if (!isLValue())
293 return *this;
294
295 if (Designator.Invalid) {
296 // This is not a core constant expression. An appropriate diagnostic
297 // will have already been produced.
298 return APValue(getLValueBase(), getLValueOffset(),
299 APValue::NoLValuePath(), getLValueCallIndex());
300 }
301
302 return APValue(getLValueBase(), getLValueOffset(),
303 Designator.Entries, Designator.IsOnePastTheEnd,
304 getLValueCallIndex());
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 Smith83587db2012-02-15 02:18:13 +0000321 /// Index - The call index of this call.
322 unsigned Index;
323
Richard Smith180f4792011-11-10 06:34:14 +0000324 /// This - The binding for the this pointer in this call, if any.
325 const LValue *This;
326
Richard Smithd0dccea2011-10-28 22:34:42 +0000327 /// ParmBindings - Parameter bindings for this function call, indexed by
328 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000329 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000330
Richard Smithbd552ef2011-10-31 05:52:43 +0000331 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
334 MapTy Temporaries;
335
Richard Smith08d6e032011-12-16 19:06:07 +0000336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000338 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000339 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000340 };
341
Richard Smithdd1f29b2011-12-12 09:28:41 +0000342 /// A partial diagnostic which we might know in advance that we are not going
343 /// to emit.
344 class OptionalDiagnostic {
345 PartialDiagnostic *Diag;
346
347 public:
348 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
349
350 template<typename T>
351 OptionalDiagnostic &operator<<(const T &v) {
352 if (Diag)
353 *Diag << v;
354 return *this;
355 }
Richard Smith789f9b62012-01-31 04:08:20 +0000356
357 OptionalDiagnostic &operator<<(const APSInt &I) {
358 if (Diag) {
359 llvm::SmallVector<char, 32> Buffer;
360 I.toString(Buffer);
361 *Diag << StringRef(Buffer.data(), Buffer.size());
362 }
363 return *this;
364 }
365
366 OptionalDiagnostic &operator<<(const APFloat &F) {
367 if (Diag) {
368 llvm::SmallVector<char, 32> Buffer;
369 F.toString(Buffer);
370 *Diag << StringRef(Buffer.data(), Buffer.size());
371 }
372 return *this;
373 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000374 };
375
Richard Smith83587db2012-02-15 02:18:13 +0000376 /// EvalInfo - This is a private struct used by the evaluator to capture
377 /// information about a subexpression as it is folded. It retains information
378 /// about the AST context, but also maintains information about the folded
379 /// expression.
380 ///
381 /// If an expression could be evaluated, it is still possible it is not a C
382 /// "integer constant expression" or constant expression. If not, this struct
383 /// captures information about how and why not.
384 ///
385 /// One bit of information passed *into* the request for constant folding
386 /// indicates whether the subexpression is "evaluated" or not according to C
387 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
388 /// evaluate the expression regardless of what the RHS is, but C only allows
389 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000392
393 /// EvalStatus - Contains information about the evaluation.
394 Expr::EvalStatus &EvalStatus;
395
396 /// CurrentCall - The top of the constexpr call stack.
397 CallStackFrame *CurrentCall;
398
Richard Smithbd552ef2011-10-31 05:52:43 +0000399 /// CallStackDepth - The number of calls in the call stack right now.
400 unsigned CallStackDepth;
401
Richard Smith83587db2012-02-15 02:18:13 +0000402 /// NextCallIndex - The next call index to assign.
403 unsigned NextCallIndex;
404
Richard Smithbd552ef2011-10-31 05:52:43 +0000405 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
406 /// OpaqueValues - Values used as the common expression in a
407 /// BinaryConditionalOperator.
408 MapTy OpaqueValues;
409
410 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000411 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000412 CallStackFrame BottomFrame;
413
Richard Smith180f4792011-11-10 06:34:14 +0000414 /// EvaluatingDecl - This is the declaration whose initializer is being
415 /// evaluated, if any.
416 const VarDecl *EvaluatingDecl;
417
418 /// EvaluatingDeclValue - This is the value being constructed for the
419 /// declaration whose initializer is being evaluated, if any.
420 APValue *EvaluatingDeclValue;
421
Richard Smithc1c5f272011-12-13 06:39:58 +0000422 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
423 /// notes attached to it will also be stored, otherwise they will not be.
424 bool HasActiveDiagnostic;
425
Richard Smith745f5142012-01-27 01:14:48 +0000426 /// CheckingPotentialConstantExpression - Are we checking whether the
427 /// expression is a potential constant expression? If so, some diagnostics
428 /// are suppressed.
429 bool CheckingPotentialConstantExpression;
430
Richard Smithbd552ef2011-10-31 05:52:43 +0000431
432 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000433 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000434 CallStackDepth(0), NextCallIndex(1),
435 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000436 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
437 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000438
Richard Smithbd552ef2011-10-31 05:52:43 +0000439 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
440 MapTy::const_iterator i = OpaqueValues.find(e);
441 if (i == OpaqueValues.end()) return 0;
442 return &i->second;
443 }
444
Richard Smith180f4792011-11-10 06:34:14 +0000445 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
446 EvaluatingDecl = VD;
447 EvaluatingDeclValue = &Value;
448 }
449
Richard Smithc18c4232011-11-21 19:36:32 +0000450 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
451
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000453 // Don't perform any constexpr calls (other than the call we're checking)
454 // when checking a potential constant expression.
455 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
456 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000457 if (NextCallIndex == 0) {
458 // NextCallIndex has wrapped around.
459 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
460 return false;
461 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000462 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
463 return true;
464 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
465 << getLangOpts().ConstexprCallDepth;
466 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000467 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000468
Richard Smith83587db2012-02-15 02:18:13 +0000469 CallStackFrame *getCallFrame(unsigned CallIndex) {
470 assert(CallIndex && "no call index in getCallFrame");
471 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
472 // be null in this loop.
473 CallStackFrame *Frame = CurrentCall;
474 while (Frame->Index > CallIndex)
475 Frame = Frame->Caller;
476 return (Frame->Index == CallIndex) ? Frame : 0;
477 }
478
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 private:
480 /// Add a diagnostic to the diagnostics list.
481 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
482 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
483 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
484 return EvalStatus.Diag->back().second;
485 }
486
Richard Smith08d6e032011-12-16 19:06:07 +0000487 /// Add notes containing a call stack to the current point of evaluation.
488 void addCallStack(unsigned Limit);
489
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000491 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000492 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
493 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000494 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000495 // If we have a prior diagnostic, it will be noting that the expression
496 // isn't a constant expression. This diagnostic is more important.
497 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000498 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000499 unsigned CallStackNotes = CallStackDepth - 1;
500 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
501 if (Limit)
502 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000503 if (CheckingPotentialConstantExpression)
504 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000505
Richard Smithc1c5f272011-12-13 06:39:58 +0000506 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000507 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000508 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
509 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000510 if (!CheckingPotentialConstantExpression)
511 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000512 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000513 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000514 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000515 return OptionalDiagnostic();
516 }
517
518 /// Diagnose that the evaluation does not produce a C++11 core constant
519 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000520 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
521 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000522 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000523 // Don't override a previous diagnostic.
524 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
525 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000526 return Diag(Loc, DiagId, ExtraNotes);
527 }
528
529 /// Add a note to a prior diagnostic.
530 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
531 if (!HasActiveDiagnostic)
532 return OptionalDiagnostic();
533 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000534 }
Richard Smith099e7f62011-12-19 06:19:21 +0000535
536 /// Add a stack of notes to a prior diagnostic.
537 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
538 if (HasActiveDiagnostic) {
539 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
540 Diags.begin(), Diags.end());
541 }
542 }
Richard Smith745f5142012-01-27 01:14:48 +0000543
544 /// Should we continue evaluation as much as possible after encountering a
545 /// construct which can't be folded?
546 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000547 return CheckingPotentialConstantExpression &&
548 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000549 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000550 };
Richard Smithf15fda02012-02-02 01:16:57 +0000551
552 /// Object used to treat all foldable expressions as constant expressions.
553 struct FoldConstant {
554 bool Enabled;
555
556 explicit FoldConstant(EvalInfo &Info)
557 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
558 !Info.EvalStatus.HasSideEffects) {
559 }
560 // Treat the value we've computed since this object was created as constant.
561 void Fold(EvalInfo &Info) {
562 if (Enabled && !Info.EvalStatus.Diag->empty() &&
563 !Info.EvalStatus.HasSideEffects)
564 Info.EvalStatus.Diag->clear();
565 }
566 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000567
568 /// RAII object used to suppress diagnostics and side-effects from a
569 /// speculative evaluation.
570 class SpeculativeEvaluationRAII {
571 EvalInfo &Info;
572 Expr::EvalStatus Old;
573
574 public:
575 SpeculativeEvaluationRAII(EvalInfo &Info,
576 llvm::SmallVectorImpl<PartialDiagnosticAt>
577 *NewDiag = 0)
578 : Info(Info), Old(Info.EvalStatus) {
579 Info.EvalStatus.Diag = NewDiag;
580 }
581 ~SpeculativeEvaluationRAII() {
582 Info.EvalStatus = Old;
583 }
584 };
Richard Smith08d6e032011-12-16 19:06:07 +0000585}
Richard Smithbd552ef2011-10-31 05:52:43 +0000586
Richard Smithb4e85ed2012-01-06 16:39:00 +0000587bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
588 CheckSubobjectKind CSK) {
589 if (Invalid)
590 return false;
591 if (isOnePastTheEnd()) {
592 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
593 << CSK;
594 setInvalid();
595 return false;
596 }
597 return true;
598}
599
600void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
601 const Expr *E, uint64_t N) {
602 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
603 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
604 << static_cast<int>(N) << /*array*/ 0
605 << static_cast<unsigned>(MostDerivedArraySize);
606 else
607 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
608 << static_cast<int>(N) << /*non-array*/ 1;
609 setInvalid();
610}
611
Richard Smith08d6e032011-12-16 19:06:07 +0000612CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
613 const FunctionDecl *Callee, const LValue *This,
614 const CCValue *Arguments)
615 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000616 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000617 Info.CurrentCall = this;
618 ++Info.CallStackDepth;
619}
620
621CallStackFrame::~CallStackFrame() {
622 assert(Info.CurrentCall == this && "calls retired out of order");
623 --Info.CallStackDepth;
624 Info.CurrentCall = Caller;
625}
626
627/// Produce a string describing the given constexpr call.
628static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
629 unsigned ArgIndex = 0;
630 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000631 !isa<CXXConstructorDecl>(Frame->Callee) &&
632 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000633
634 if (!IsMemberCall)
635 Out << *Frame->Callee << '(';
636
637 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
638 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000639 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000640 Out << ", ";
641
642 const ParmVarDecl *Param = *I;
643 const CCValue &Arg = Frame->Arguments[ArgIndex];
644 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
645 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
646 else {
Richard Smith83587db2012-02-15 02:18:13 +0000647 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000648 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
649 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000650 Arg.getLValueDesignator().IsOnePastTheEnd,
651 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000652 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
653 }
654
655 if (ArgIndex == 0 && IsMemberCall)
656 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000657 }
658
Richard Smith08d6e032011-12-16 19:06:07 +0000659 Out << ')';
660}
661
662void EvalInfo::addCallStack(unsigned Limit) {
663 // Determine which calls to skip, if any.
664 unsigned ActiveCalls = CallStackDepth - 1;
665 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
666 if (Limit && Limit < ActiveCalls) {
667 SkipStart = Limit / 2 + Limit % 2;
668 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000669 }
670
Richard Smith08d6e032011-12-16 19:06:07 +0000671 // Walk the call stack and add the diagnostics.
672 unsigned CallIdx = 0;
673 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
674 Frame = Frame->Caller, ++CallIdx) {
675 // Skip this call?
676 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
677 if (CallIdx == SkipStart) {
678 // Note that we're skipping calls.
679 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
680 << unsigned(ActiveCalls - Limit);
681 }
682 continue;
683 }
684
685 llvm::SmallVector<char, 128> Buffer;
686 llvm::raw_svector_ostream Out(Buffer);
687 describeCall(Frame, Out);
688 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
689 }
690}
691
692namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000693 struct ComplexValue {
694 private:
695 bool IsInt;
696
697 public:
698 APSInt IntReal, IntImag;
699 APFloat FloatReal, FloatImag;
700
701 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
702
703 void makeComplexFloat() { IsInt = false; }
704 bool isComplexFloat() const { return !IsInt; }
705 APFloat &getComplexFloatReal() { return FloatReal; }
706 APFloat &getComplexFloatImag() { return FloatImag; }
707
708 void makeComplexInt() { IsInt = true; }
709 bool isComplexInt() const { return IsInt; }
710 APSInt &getComplexIntReal() { return IntReal; }
711 APSInt &getComplexIntImag() { return IntImag; }
712
Richard Smith47a1eed2011-10-29 20:57:55 +0000713 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000714 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000716 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000717 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000718 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000719 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000720 assert(v.isComplexFloat() || v.isComplexInt());
721 if (v.isComplexFloat()) {
722 makeComplexFloat();
723 FloatReal = v.getComplexFloatReal();
724 FloatImag = v.getComplexFloatImag();
725 } else {
726 makeComplexInt();
727 IntReal = v.getComplexIntReal();
728 IntImag = v.getComplexIntImag();
729 }
730 }
John McCallf4cf1a12010-05-07 17:22:02 +0000731 };
John McCallefdb83e2010-05-07 21:00:08 +0000732
733 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000734 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000735 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000736 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000737 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000738
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000739 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000740 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000741 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000742 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000743 SubobjectDesignator &getLValueDesignator() { return Designator; }
744 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000745
Richard Smith47a1eed2011-10-29 20:57:55 +0000746 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000747 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000748 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000749 void setFrom(const CCValue &V) {
750 assert(V.isLValue());
751 Base = V.getLValueBase();
752 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000753 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000754 Designator = V.getLValueDesignator();
755 }
756
Richard Smith83587db2012-02-15 02:18:13 +0000757 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000758 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000759 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000760 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000761 Designator = SubobjectDesignator(getType(B));
762 }
763
764 // Check that this LValue is not based on a null pointer. If it is, produce
765 // a diagnostic and mark the designator as invalid.
766 bool checkNullPointer(EvalInfo &Info, const Expr *E,
767 CheckSubobjectKind CSK) {
768 if (Designator.Invalid)
769 return false;
770 if (!Base) {
771 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
772 << CSK;
773 Designator.setInvalid();
774 return false;
775 }
776 return true;
777 }
778
779 // Check this LValue refers to an object. If not, set the designator to be
780 // invalid and emit a diagnostic.
781 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
782 return checkNullPointer(Info, E, CSK) &&
783 Designator.checkSubobject(Info, E, CSK);
784 }
785
786 void addDecl(EvalInfo &Info, const Expr *E,
787 const Decl *D, bool Virtual = false) {
788 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
789 Designator.addDeclUnchecked(D, Virtual);
790 }
791 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
792 checkSubobject(Info, E, CSK_ArrayToPointer);
793 Designator.addArrayUnchecked(CAT);
794 }
795 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
796 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
797 return;
798 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000799 }
John McCallefdb83e2010-05-07 21:00:08 +0000800 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000801
802 struct MemberPtr {
803 MemberPtr() {}
804 explicit MemberPtr(const ValueDecl *Decl) :
805 DeclAndIsDerivedMember(Decl, false), Path() {}
806
807 /// The member or (direct or indirect) field referred to by this member
808 /// pointer, or 0 if this is a null member pointer.
809 const ValueDecl *getDecl() const {
810 return DeclAndIsDerivedMember.getPointer();
811 }
812 /// Is this actually a member of some type derived from the relevant class?
813 bool isDerivedMember() const {
814 return DeclAndIsDerivedMember.getInt();
815 }
816 /// Get the class which the declaration actually lives in.
817 const CXXRecordDecl *getContainingRecord() const {
818 return cast<CXXRecordDecl>(
819 DeclAndIsDerivedMember.getPointer()->getDeclContext());
820 }
821
822 void moveInto(CCValue &V) const {
823 V = CCValue(getDecl(), isDerivedMember(), Path);
824 }
825 void setFrom(const CCValue &V) {
826 assert(V.isMemberPointer());
827 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
828 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
829 Path.clear();
830 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
831 Path.insert(Path.end(), P.begin(), P.end());
832 }
833
834 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
835 /// whether the member is a member of some class derived from the class type
836 /// of the member pointer.
837 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
838 /// Path - The path of base/derived classes from the member declaration's
839 /// class (exclusive) to the class type of the member pointer (inclusive).
840 SmallVector<const CXXRecordDecl*, 4> Path;
841
842 /// Perform a cast towards the class of the Decl (either up or down the
843 /// hierarchy).
844 bool castBack(const CXXRecordDecl *Class) {
845 assert(!Path.empty());
846 const CXXRecordDecl *Expected;
847 if (Path.size() >= 2)
848 Expected = Path[Path.size() - 2];
849 else
850 Expected = getContainingRecord();
851 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
852 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
853 // if B does not contain the original member and is not a base or
854 // derived class of the class containing the original member, the result
855 // of the cast is undefined.
856 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
857 // (D::*). We consider that to be a language defect.
858 return false;
859 }
860 Path.pop_back();
861 return true;
862 }
863 /// Perform a base-to-derived member pointer cast.
864 bool castToDerived(const CXXRecordDecl *Derived) {
865 if (!getDecl())
866 return true;
867 if (!isDerivedMember()) {
868 Path.push_back(Derived);
869 return true;
870 }
871 if (!castBack(Derived))
872 return false;
873 if (Path.empty())
874 DeclAndIsDerivedMember.setInt(false);
875 return true;
876 }
877 /// Perform a derived-to-base member pointer cast.
878 bool castToBase(const CXXRecordDecl *Base) {
879 if (!getDecl())
880 return true;
881 if (Path.empty())
882 DeclAndIsDerivedMember.setInt(true);
883 if (isDerivedMember()) {
884 Path.push_back(Base);
885 return true;
886 }
887 return castBack(Base);
888 }
889 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000890
Richard Smithb02e4622012-02-01 01:42:44 +0000891 /// Compare two member pointers, which are assumed to be of the same type.
892 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
893 if (!LHS.getDecl() || !RHS.getDecl())
894 return !LHS.getDecl() && !RHS.getDecl();
895 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
896 return false;
897 return LHS.Path == RHS.Path;
898 }
899
Richard Smithc1c5f272011-12-13 06:39:58 +0000900 /// Kinds of constant expression checking, for diagnostics.
901 enum CheckConstantExpressionKind {
902 CCEK_Constant, ///< A normal constant.
903 CCEK_ReturnValue, ///< A constexpr function return value.
904 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
905 };
John McCallf4cf1a12010-05-07 17:22:02 +0000906}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000907
Richard Smith47a1eed2011-10-29 20:57:55 +0000908static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000909static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
910 const LValue &This, const Expr *E,
911 CheckConstantExpressionKind CCEK = CCEK_Constant,
912 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000913static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
914static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000915static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
916 EvalInfo &Info);
917static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000918static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000919static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000920 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000921static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000922static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000923
924//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000925// Misc utilities
926//===----------------------------------------------------------------------===//
927
Richard Smith180f4792011-11-10 06:34:14 +0000928/// Should this call expression be treated as a string literal?
929static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
933}
934
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000935static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
938
939 // ... a null pointer value, or a prvalue core constant expression of type
940 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000941 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000942
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
949 }
950
951 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000952 switch (E->getStmtClass()) {
953 default:
954 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000955 case Expr::CompoundLiteralExprClass: {
956 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
957 return CLE->isFileScope() && CLE->isLValue();
958 }
Richard Smith180f4792011-11-10 06:34:14 +0000959 // A string literal has static storage duration.
960 case Expr::StringLiteralClass:
961 case Expr::PredefinedExprClass:
962 case Expr::ObjCStringLiteralClass:
963 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000964 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000965 return true;
966 case Expr::CallExprClass:
967 return IsStringLiteralCall(cast<CallExpr>(E));
968 // For GCC compatibility, &&label has static storage duration.
969 case Expr::AddrLabelExprClass:
970 return true;
971 // A Block literal expression may be used as the initialization value for
972 // Block variables at global or local static scope.
973 case Expr::BlockExprClass:
974 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000975 case Expr::ImplicitValueInitExprClass:
976 // FIXME:
977 // We can never form an lvalue with an implicit value initialization as its
978 // base through expression evaluation, so these only appear in one case: the
979 // implicit variable declaration we invent when checking whether a constexpr
980 // constructor can produce a constant expression. We must assume that such
981 // an expression might be a global lvalue.
982 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000983 }
John McCall42c8f872010-05-10 23:27:23 +0000984}
985
Richard Smith83587db2012-02-15 02:18:13 +0000986static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
987 assert(Base && "no location for a null lvalue");
988 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
989 if (VD)
990 Info.Note(VD->getLocation(), diag::note_declared_at);
991 else
992 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
993 diag::note_constexpr_temporary_here);
994}
995
Richard Smith9a17a682011-11-07 05:07:52 +0000996/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000997/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000998/// either LValue or CCValue. Return true if we can fold this expression,
999/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00001000static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1001 QualType Type, const LValue &LVal) {
1002 bool IsReferenceType = Type->isReferenceType();
1003
Richard Smithc1c5f272011-12-13 06:39:58 +00001004 APValue::LValueBase Base = LVal.getLValueBase();
1005 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1006
Richard Smithb78ae972012-02-18 04:58:18 +00001007 // Check that the object is a global. Note that the fake 'this' object we
1008 // manufacture when checking potential constant expressions is conservatively
1009 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 if (!IsGlobalLValue(Base)) {
1011 if (Info.getLangOpts().CPlusPlus0x) {
1012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1014 << IsReferenceType << !Designator.Entries.empty()
1015 << !!VD << VD;
1016 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001018 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 }
Richard Smith61e61622012-01-12 06:08:57 +00001020 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001021 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001022 }
Richard Smith83587db2012-02-15 02:18:13 +00001023 assert((Info.CheckingPotentialConstantExpression ||
1024 LVal.getLValueCallIndex() == 0) &&
1025 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001026
1027 // Allow address constant expressions to be past-the-end pointers. This is
1028 // an extension: the standard requires them to point to an object.
1029 if (!IsReferenceType)
1030 return true;
1031
1032 // A reference constant expression must refer to an object.
1033 if (!Base) {
1034 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001035 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001036 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001037 }
1038
Richard Smithc1c5f272011-12-13 06:39:58 +00001039 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001040 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001041 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001042 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001043 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001044 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001045 }
1046
Richard Smith9a17a682011-11-07 05:07:52 +00001047 return true;
1048}
1049
Richard Smith51201882011-12-30 21:15:51 +00001050/// Check that this core constant expression is of literal type, and if not,
1051/// produce an appropriate diagnostic.
1052static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1053 if (!E->isRValue() || E->getType()->isLiteralType())
1054 return true;
1055
1056 // Prvalue constant expressions must be of literal types.
1057 if (Info.getLangOpts().CPlusPlus0x)
1058 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1059 << E->getType();
1060 else
1061 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1062 return false;
1063}
1064
Richard Smith47a1eed2011-10-29 20:57:55 +00001065/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001066/// constant expression. If not, report an appropriate diagnostic. Does not
1067/// check that the expression is of literal type.
1068static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1069 QualType Type, const APValue &Value) {
1070 // Core issue 1454: For a literal constant expression of array or class type,
1071 // each subobject of its value shall have been initialized by a constant
1072 // expression.
1073 if (Value.isArray()) {
1074 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1075 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1076 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1077 Value.getArrayInitializedElt(I)))
1078 return false;
1079 }
1080 if (!Value.hasArrayFiller())
1081 return true;
1082 return CheckConstantExpression(Info, DiagLoc, EltTy,
1083 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001084 }
Richard Smith83587db2012-02-15 02:18:13 +00001085 if (Value.isUnion() && Value.getUnionField()) {
1086 return CheckConstantExpression(Info, DiagLoc,
1087 Value.getUnionField()->getType(),
1088 Value.getUnionValue());
1089 }
1090 if (Value.isStruct()) {
1091 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1092 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1093 unsigned BaseIndex = 0;
1094 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1095 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1096 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1097 Value.getStructBase(BaseIndex)))
1098 return false;
1099 }
1100 }
1101 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1102 I != E; ++I) {
1103 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1104 Value.getStructField((*I)->getFieldIndex())))
1105 return false;
1106 }
1107 }
1108
1109 if (Value.isLValue()) {
1110 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1111 LValue LVal;
1112 LVal.setFrom(Val);
1113 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1114 }
1115
1116 // Everything else is fine.
1117 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001118}
1119
Richard Smith9e36b532011-10-31 05:11:32 +00001120const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001121 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001122}
1123
1124static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001125 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001126}
1127
Richard Smith65ac5982011-11-01 21:06:14 +00001128static bool IsWeakLValue(const LValue &Value) {
1129 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001130 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001131}
1132
Richard Smithe24f5fc2011-11-17 22:56:20 +00001133static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001134 // A null base expression indicates a null pointer. These are always
1135 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 if (!Value.getLValueBase()) {
1137 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001138 return true;
1139 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001140
Richard Smithe24f5fc2011-11-17 22:56:20 +00001141 // We have a non-null base. These are generally known to be true, but if it's
1142 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001143 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001144 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001145 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001146}
1147
Richard Smith47a1eed2011-10-29 20:57:55 +00001148static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001149 switch (Val.getKind()) {
1150 case APValue::Uninitialized:
1151 return false;
1152 case APValue::Int:
1153 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001154 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001155 case APValue::Float:
1156 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001157 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001158 case APValue::ComplexInt:
1159 Result = Val.getComplexIntReal().getBoolValue() ||
1160 Val.getComplexIntImag().getBoolValue();
1161 return true;
1162 case APValue::ComplexFloat:
1163 Result = !Val.getComplexFloatReal().isZero() ||
1164 !Val.getComplexFloatImag().isZero();
1165 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001166 case APValue::LValue:
1167 return EvalPointerValueAsBool(Val, Result);
1168 case APValue::MemberPointer:
1169 Result = Val.getMemberPointerDecl();
1170 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001171 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001172 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001173 case APValue::Struct:
1174 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001175 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001176 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001177 }
1178
Richard Smithc49bd112011-10-28 17:51:58 +00001179 llvm_unreachable("unknown APValue kind");
1180}
1181
1182static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1183 EvalInfo &Info) {
1184 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001185 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001186 if (!Evaluate(Val, Info, E))
1187 return false;
1188 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001189}
1190
Richard Smithc1c5f272011-12-13 06:39:58 +00001191template<typename T>
1192static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1193 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001194 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001195 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001196 return false;
1197}
1198
1199static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1200 QualType SrcType, const APFloat &Value,
1201 QualType DestType, APSInt &Result) {
1202 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001203 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001204 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Richard Smithc1c5f272011-12-13 06:39:58 +00001206 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001207 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001208 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1209 & APFloat::opInvalidOp)
1210 return HandleOverflow(Info, E, Value, DestType);
1211 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001212}
1213
Richard Smithc1c5f272011-12-13 06:39:58 +00001214static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1215 QualType SrcType, QualType DestType,
1216 APFloat &Result) {
1217 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001218 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001219 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1220 APFloat::rmNearestTiesToEven, &ignored)
1221 & APFloat::opOverflow)
1222 return HandleOverflow(Info, E, Value, DestType);
1223 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001224}
1225
Richard Smithf72fccf2012-01-30 22:27:01 +00001226static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1227 QualType DestType, QualType SrcType,
1228 APSInt &Value) {
1229 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001230 APSInt Result = Value;
1231 // Figure out if this is a truncate, extend or noop cast.
1232 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001233 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001234 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001235 return Result;
1236}
1237
Richard Smithc1c5f272011-12-13 06:39:58 +00001238static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1239 QualType SrcType, const APSInt &Value,
1240 QualType DestType, APFloat &Result) {
1241 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1242 if (Result.convertFromAPInt(Value, Value.isSigned(),
1243 APFloat::rmNearestTiesToEven)
1244 & APFloat::opOverflow)
1245 return HandleOverflow(Info, E, Value, DestType);
1246 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001247}
1248
Eli Friedmane6a24e82011-12-22 03:51:45 +00001249static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1250 llvm::APInt &Res) {
1251 CCValue SVal;
1252 if (!Evaluate(SVal, Info, E))
1253 return false;
1254 if (SVal.isInt()) {
1255 Res = SVal.getInt();
1256 return true;
1257 }
1258 if (SVal.isFloat()) {
1259 Res = SVal.getFloat().bitcastToAPInt();
1260 return true;
1261 }
1262 if (SVal.isVector()) {
1263 QualType VecTy = E->getType();
1264 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1265 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1266 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1267 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1268 Res = llvm::APInt::getNullValue(VecSize);
1269 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1270 APValue &Elt = SVal.getVectorElt(i);
1271 llvm::APInt EltAsInt;
1272 if (Elt.isInt()) {
1273 EltAsInt = Elt.getInt();
1274 } else if (Elt.isFloat()) {
1275 EltAsInt = Elt.getFloat().bitcastToAPInt();
1276 } else {
1277 // Don't try to handle vectors of anything other than int or float
1278 // (not sure if it's possible to hit this case).
1279 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1280 return false;
1281 }
1282 unsigned BaseEltSize = EltAsInt.getBitWidth();
1283 if (BigEndian)
1284 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1285 else
1286 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1287 }
1288 return true;
1289 }
1290 // Give up if the input isn't an int, float, or vector. For example, we
1291 // reject "(v4i16)(intptr_t)&a".
1292 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1293 return false;
1294}
1295
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296/// Cast an lvalue referring to a base subobject to a derived class, by
1297/// truncating the lvalue's path to the given length.
1298static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1299 const RecordDecl *TruncatedType,
1300 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001301 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302
1303 // Check we actually point to a derived class object.
1304 if (TruncatedElements == D.Entries.size())
1305 return true;
1306 assert(TruncatedElements >= D.MostDerivedPathLength &&
1307 "not casting to a derived class");
1308 if (!Result.checkSubobject(Info, E, CSK_Derived))
1309 return false;
1310
1311 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001312 const RecordDecl *RD = TruncatedType;
1313 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001314 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1315 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001316 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001317 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001318 else
Richard Smith180f4792011-11-10 06:34:14 +00001319 Result.Offset -= Layout.getBaseClassOffset(Base);
1320 RD = Base;
1321 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001322 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001323 return true;
1324}
1325
Richard Smithb4e85ed2012-01-06 16:39:00 +00001326static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001327 const CXXRecordDecl *Derived,
1328 const CXXRecordDecl *Base,
1329 const ASTRecordLayout *RL = 0) {
1330 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1331 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001332 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001333}
1334
Richard Smithb4e85ed2012-01-06 16:39:00 +00001335static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001336 const CXXRecordDecl *DerivedDecl,
1337 const CXXBaseSpecifier *Base) {
1338 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1339
1340 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001341 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001342 return true;
1343 }
1344
Richard Smithb4e85ed2012-01-06 16:39:00 +00001345 SubobjectDesignator &D = Obj.Designator;
1346 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001347 return false;
1348
Richard Smithb4e85ed2012-01-06 16:39:00 +00001349 // Extract most-derived object and corresponding type.
1350 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1351 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1352 return false;
1353
1354 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001355 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1356 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001357 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001358 return true;
1359}
1360
1361/// Update LVal to refer to the given field, which must be a member of the type
1362/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001363static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001364 const FieldDecl *FD,
1365 const ASTRecordLayout *RL = 0) {
1366 if (!RL)
1367 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1368
1369 unsigned I = FD->getFieldIndex();
1370 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001371 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001372}
1373
Richard Smithd9b02e72012-01-25 22:15:11 +00001374/// Update LVal to refer to the given indirect field.
1375static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1376 LValue &LVal,
1377 const IndirectFieldDecl *IFD) {
1378 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1379 CE = IFD->chain_end(); C != CE; ++C)
1380 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1381}
1382
Richard Smith180f4792011-11-10 06:34:14 +00001383/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001384static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1385 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001386 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1387 // extension.
1388 if (Type->isVoidType() || Type->isFunctionType()) {
1389 Size = CharUnits::One();
1390 return true;
1391 }
1392
1393 if (!Type->isConstantSizeType()) {
1394 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001395 // FIXME: Better diagnostic.
1396 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001397 return false;
1398 }
1399
1400 Size = Info.Ctx.getTypeSizeInChars(Type);
1401 return true;
1402}
1403
1404/// Update a pointer value to model pointer arithmetic.
1405/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001406/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001407/// \param LVal - The pointer value to be updated.
1408/// \param EltTy - The pointee type represented by LVal.
1409/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001410static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1411 LValue &LVal, QualType EltTy,
1412 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001413 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001414 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001415 return false;
1416
1417 // Compute the new offset in the appropriate width.
1418 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001419 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001420 return true;
1421}
1422
Richard Smith03f96112011-10-24 17:54:18 +00001423/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001424static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1425 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001426 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001427 // If this is a parameter to an active constexpr function call, perform
1428 // argument substitution.
1429 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001430 // Assume arguments of a potential constant expression are unknown
1431 // constant expressions.
1432 if (Info.CheckingPotentialConstantExpression)
1433 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001434 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001435 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001436 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001437 }
Richard Smith177dce72011-11-01 16:57:24 +00001438 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1439 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001440 }
Richard Smith03f96112011-10-24 17:54:18 +00001441
Richard Smith099e7f62011-12-19 06:19:21 +00001442 // Dig out the initializer, and use the declaration which it's attached to.
1443 const Expr *Init = VD->getAnyInitializer(VD);
1444 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001445 // If we're checking a potential constant expression, the variable could be
1446 // initialized later.
1447 if (!Info.CheckingPotentialConstantExpression)
1448 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001449 return false;
1450 }
1451
Richard Smith180f4792011-11-10 06:34:14 +00001452 // If we're currently evaluating the initializer of this declaration, use that
1453 // in-flight value.
1454 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001455 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1456 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001457 return !Result.isUninit();
1458 }
1459
Richard Smith65ac5982011-11-01 21:06:14 +00001460 // Never evaluate the initializer of a weak variable. We can't be sure that
1461 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001462 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001463 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001464 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001465 }
Richard Smith65ac5982011-11-01 21:06:14 +00001466
Richard Smith099e7f62011-12-19 06:19:21 +00001467 // Check that we can fold the initializer. In C++, we will have already done
1468 // this in the cases where it matters for conformance.
1469 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1470 if (!VD->evaluateValue(Notes)) {
1471 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1472 Notes.size() + 1) << VD;
1473 Info.Note(VD->getLocation(), diag::note_declared_at);
1474 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001475 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001476 } else if (!VD->checkInitIsICE()) {
1477 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1478 Notes.size() + 1) << VD;
1479 Info.Note(VD->getLocation(), diag::note_declared_at);
1480 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001481 }
Richard Smith03f96112011-10-24 17:54:18 +00001482
Richard Smithb4e85ed2012-01-06 16:39:00 +00001483 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001484 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001485}
1486
Richard Smithc49bd112011-10-28 17:51:58 +00001487static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001488 Qualifiers Quals = T.getQualifiers();
1489 return Quals.hasConst() && !Quals.hasVolatile();
1490}
1491
Richard Smith59efe262011-11-11 04:05:33 +00001492/// Get the base index of the given base class within an APValue representing
1493/// the given derived class.
1494static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1495 const CXXRecordDecl *Base) {
1496 Base = Base->getCanonicalDecl();
1497 unsigned Index = 0;
1498 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1499 E = Derived->bases_end(); I != E; ++I, ++Index) {
1500 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1501 return Index;
1502 }
1503
1504 llvm_unreachable("base class missing from derived class's bases list");
1505}
1506
Richard Smithf3908f22012-02-17 03:35:37 +00001507/// Extract the value of a character from a string literal.
1508static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1509 uint64_t Index) {
1510 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1511 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1512 assert(S && "unexpected string literal expression kind");
1513
1514 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1515 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1516 if (Index < S->getLength())
1517 Value = S->getCodeUnit(Index);
1518 return Value;
1519}
1520
Richard Smithcc5d4f62011-11-07 09:22:26 +00001521/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001522static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1523 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001524 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001525 if (Sub.Invalid)
1526 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001528 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001529 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001530 (unsigned)diag::note_constexpr_read_past_end :
1531 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001532 return false;
1533 }
Richard Smithf64699e2011-11-11 08:28:03 +00001534 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001536 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1537 // This object might be initialized later.
1538 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539
Richard Smithcc5d4f62011-11-07 09:22:26 +00001540 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001541 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001542 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001543 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001544 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001546 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001549 // Note, it should not be possible to form a pointer with a valid
1550 // designator which points more than one past the end of the array.
1551 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001552 (unsigned)diag::note_constexpr_read_past_end :
1553 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001554 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001555 }
Richard Smithf3908f22012-02-17 03:35:37 +00001556 // An array object is represented as either an Array APValue or as an
1557 // LValue which refers to a string literal.
1558 if (O->isLValue()) {
1559 assert(I == N - 1 && "extracting subobject of character?");
1560 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1561 Obj = CCValue(ExtractStringLiteralCharacter(
1562 Info, O->getLValueBase().get<const Expr*>(), Index));
1563 return true;
1564 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001565 O = &O->getArrayInitializedElt(Index);
1566 else
1567 O = &O->getArrayFiller();
1568 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001569 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001570 if (Field->isMutable()) {
1571 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1572 << Field;
1573 Info.Note(Field->getLocation(), diag::note_declared_at);
1574 return false;
1575 }
1576
Richard Smith180f4792011-11-10 06:34:14 +00001577 // Next subobject is a class, struct or union field.
1578 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1579 if (RD->isUnion()) {
1580 const FieldDecl *UnionField = O->getUnionField();
1581 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001582 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001583 Info.Diag(E->getExprLoc(),
1584 diag::note_constexpr_read_inactive_union_member)
1585 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001586 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001587 }
Richard Smith180f4792011-11-10 06:34:14 +00001588 O = &O->getUnionValue();
1589 } else
1590 O = &O->getStructField(Field->getFieldIndex());
1591 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001592
1593 if (ObjType.isVolatileQualified()) {
1594 if (Info.getLangOpts().CPlusPlus) {
1595 // FIXME: Include a description of the path to the volatile subobject.
1596 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1597 << 2 << Field;
1598 Info.Note(Field->getLocation(), diag::note_declared_at);
1599 } else {
1600 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1601 }
1602 return false;
1603 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001604 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001605 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001606 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1607 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1608 O = &O->getStructBase(getBaseIndex(Derived, Base));
1609 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001610 }
Richard Smith180f4792011-11-10 06:34:14 +00001611
Richard Smithf48fdb02011-12-09 22:58:01 +00001612 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001613 if (!Info.CheckingPotentialConstantExpression)
1614 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001615 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001616 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001617 }
1618
Richard Smithb4e85ed2012-01-06 16:39:00 +00001619 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001620 return true;
1621}
1622
Richard Smithf15fda02012-02-02 01:16:57 +00001623/// Find the position where two subobject designators diverge, or equivalently
1624/// the length of the common initial subsequence.
1625static unsigned FindDesignatorMismatch(QualType ObjType,
1626 const SubobjectDesignator &A,
1627 const SubobjectDesignator &B,
1628 bool &WasArrayIndex) {
1629 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1630 for (/**/; I != N; ++I) {
1631 if (!ObjType.isNull() && ObjType->isArrayType()) {
1632 // Next subobject is an array element.
1633 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1634 WasArrayIndex = true;
1635 return I;
1636 }
1637 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1638 } else {
1639 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1640 WasArrayIndex = false;
1641 return I;
1642 }
1643 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1644 // Next subobject is a field.
1645 ObjType = FD->getType();
1646 else
1647 // Next subobject is a base class.
1648 ObjType = QualType();
1649 }
1650 }
1651 WasArrayIndex = false;
1652 return I;
1653}
1654
1655/// Determine whether the given subobject designators refer to elements of the
1656/// same array object.
1657static bool AreElementsOfSameArray(QualType ObjType,
1658 const SubobjectDesignator &A,
1659 const SubobjectDesignator &B) {
1660 if (A.Entries.size() != B.Entries.size())
1661 return false;
1662
1663 bool IsArray = A.MostDerivedArraySize != 0;
1664 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1665 // A is a subobject of the array element.
1666 return false;
1667
1668 // If A (and B) designates an array element, the last entry will be the array
1669 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1670 // of length 1' case, and the entire path must match.
1671 bool WasArrayIndex;
1672 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1673 return CommonLength >= A.Entries.size() - IsArray;
1674}
1675
Richard Smith180f4792011-11-10 06:34:14 +00001676/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1677/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1678/// for looking up the glvalue referred to by an entity of reference type.
1679///
1680/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001681/// \param Conv - The expression for which we are performing the conversion.
1682/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001683/// \param Type - The type we expect this conversion to produce, before
1684/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001685/// \param LVal - The glvalue on which we are attempting to perform this action.
1686/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001687static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1688 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001689 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001690 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1691 if (!Info.getLangOpts().CPlusPlus)
1692 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1693
Richard Smithb4e85ed2012-01-06 16:39:00 +00001694 if (LVal.Designator.Invalid)
1695 // A diagnostic will have already been produced.
1696 return false;
1697
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001698 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001699 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001700
Richard Smithf48fdb02011-12-09 22:58:01 +00001701 if (!LVal.Base) {
1702 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001703 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1704 return false;
1705 }
1706
Richard Smith83587db2012-02-15 02:18:13 +00001707 CallStackFrame *Frame = 0;
1708 if (LVal.CallIndex) {
1709 Frame = Info.getCallFrame(LVal.CallIndex);
1710 if (!Frame) {
1711 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1712 NoteLValueLocation(Info, LVal.Base);
1713 return false;
1714 }
1715 }
1716
Richard Smith7098cbd2011-12-21 05:04:46 +00001717 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1718 // is not a constant expression (even if the object is non-volatile). We also
1719 // apply this rule to C++98, in order to conform to the expected 'volatile'
1720 // semantics.
1721 if (Type.isVolatileQualified()) {
1722 if (Info.getLangOpts().CPlusPlus)
1723 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1724 else
1725 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001726 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001727 }
Richard Smithc49bd112011-10-28 17:51:58 +00001728
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001729 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001730 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1731 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001732 // expressions are constant expressions too. Inside constexpr functions,
1733 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001734 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001735 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001736 if (const VarDecl *VDef = VD->getDefinition())
1737 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001738 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001739 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001740 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001741 }
1742
Richard Smith7098cbd2011-12-21 05:04:46 +00001743 // DR1313: If the object is volatile-qualified but the glvalue was not,
1744 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001745 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001746 if (VT.isVolatileQualified()) {
1747 if (Info.getLangOpts().CPlusPlus) {
1748 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1749 Info.Note(VD->getLocation(), diag::note_declared_at);
1750 } else {
1751 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001752 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001753 return false;
1754 }
1755
1756 if (!isa<ParmVarDecl>(VD)) {
1757 if (VD->isConstexpr()) {
1758 // OK, we can read this variable.
1759 } else if (VT->isIntegralOrEnumerationType()) {
1760 if (!VT.isConstQualified()) {
1761 if (Info.getLangOpts().CPlusPlus) {
1762 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1763 Info.Note(VD->getLocation(), diag::note_declared_at);
1764 } else {
1765 Info.Diag(Loc);
1766 }
1767 return false;
1768 }
1769 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1770 // We support folding of const floating-point types, in order to make
1771 // static const data members of such types (supported as an extension)
1772 // more useful.
1773 if (Info.getLangOpts().CPlusPlus0x) {
1774 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1775 Info.Note(VD->getLocation(), diag::note_declared_at);
1776 } else {
1777 Info.CCEDiag(Loc);
1778 }
1779 } else {
1780 // FIXME: Allow folding of values of any literal type in all languages.
1781 if (Info.getLangOpts().CPlusPlus0x) {
1782 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1783 Info.Note(VD->getLocation(), diag::note_declared_at);
1784 } else {
1785 Info.Diag(Loc);
1786 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001787 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001788 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001789 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001790
Richard Smithf48fdb02011-12-09 22:58:01 +00001791 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001792 return false;
1793
Richard Smith47a1eed2011-10-29 20:57:55 +00001794 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001795 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001796
1797 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1798 // conversion. This happens when the declaration and the lvalue should be
1799 // considered synonymous, for instance when initializing an array of char
1800 // from a string literal. Continue as if the initializer lvalue was the
1801 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001802 assert(RVal.getLValueOffset().isZero() &&
1803 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001804 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001805
1806 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1807 Frame = Info.getCallFrame(CallIndex);
1808 if (!Frame) {
1809 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1810 NoteLValueLocation(Info, RVal.getLValueBase());
1811 return false;
1812 }
1813 } else {
1814 Frame = 0;
1815 }
Richard Smithc49bd112011-10-28 17:51:58 +00001816 }
1817
Richard Smith7098cbd2011-12-21 05:04:46 +00001818 // Volatile temporary objects cannot be read in constant expressions.
1819 if (Base->getType().isVolatileQualified()) {
1820 if (Info.getLangOpts().CPlusPlus) {
1821 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1822 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1823 } else {
1824 Info.Diag(Loc);
1825 }
1826 return false;
1827 }
1828
Richard Smithcc5d4f62011-11-07 09:22:26 +00001829 if (Frame) {
1830 // If this is a temporary expression with a nontrivial initializer, grab the
1831 // value from the relevant stack frame.
1832 RVal = Frame->Temporaries[Base];
1833 } else if (const CompoundLiteralExpr *CLE
1834 = dyn_cast<CompoundLiteralExpr>(Base)) {
1835 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1836 // initializer until now for such expressions. Such an expression can't be
1837 // an ICE in C, so this only matters for fold.
1838 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1839 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1840 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001841 } else if (isa<StringLiteral>(Base)) {
1842 // We represent a string literal array as an lvalue pointing at the
1843 // corresponding expression, rather than building an array of chars.
1844 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1845 RVal = CCValue(Info.Ctx,
1846 APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0),
1847 CCValue::GlobalValue());
Richard Smithf48fdb02011-12-09 22:58:01 +00001848 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001849 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001850 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001851 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001852
Richard Smithf48fdb02011-12-09 22:58:01 +00001853 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1854 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001855}
1856
Richard Smith59efe262011-11-11 04:05:33 +00001857/// Build an lvalue for the object argument of a member function call.
1858static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1859 LValue &This) {
1860 if (Object->getType()->isPointerType())
1861 return EvaluatePointer(Object, This, Info);
1862
1863 if (Object->isGLValue())
1864 return EvaluateLValue(Object, This, Info);
1865
Richard Smithe24f5fc2011-11-17 22:56:20 +00001866 if (Object->getType()->isLiteralType())
1867 return EvaluateTemporary(Object, This, Info);
1868
1869 return false;
1870}
1871
1872/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1873/// lvalue referring to the result.
1874///
1875/// \param Info - Information about the ongoing evaluation.
1876/// \param BO - The member pointer access operation.
1877/// \param LV - Filled in with a reference to the resulting object.
1878/// \param IncludeMember - Specifies whether the member itself is included in
1879/// the resulting LValue subobject designator. This is not possible when
1880/// creating a bound member function.
1881/// \return The field or method declaration to which the member pointer refers,
1882/// or 0 if evaluation fails.
1883static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1884 const BinaryOperator *BO,
1885 LValue &LV,
1886 bool IncludeMember = true) {
1887 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1888
Richard Smith745f5142012-01-27 01:14:48 +00001889 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1890 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001891 return 0;
1892
1893 MemberPtr MemPtr;
1894 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1895 return 0;
1896
1897 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1898 // member value, the behavior is undefined.
1899 if (!MemPtr.getDecl())
1900 return 0;
1901
Richard Smith745f5142012-01-27 01:14:48 +00001902 if (!EvalObjOK)
1903 return 0;
1904
Richard Smithe24f5fc2011-11-17 22:56:20 +00001905 if (MemPtr.isDerivedMember()) {
1906 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001907 // The end of the derived-to-base path for the base object must match the
1908 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001909 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001910 LV.Designator.Entries.size())
1911 return 0;
1912 unsigned PathLengthToMember =
1913 LV.Designator.Entries.size() - MemPtr.Path.size();
1914 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1915 const CXXRecordDecl *LVDecl = getAsBaseClass(
1916 LV.Designator.Entries[PathLengthToMember + I]);
1917 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1918 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1919 return 0;
1920 }
1921
1922 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001923 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1924 PathLengthToMember))
1925 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001926 } else if (!MemPtr.Path.empty()) {
1927 // Extend the LValue path with the member pointer's path.
1928 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1929 MemPtr.Path.size() + IncludeMember);
1930
1931 // Walk down to the appropriate base class.
1932 QualType LVType = BO->getLHS()->getType();
1933 if (const PointerType *PT = LVType->getAs<PointerType>())
1934 LVType = PT->getPointeeType();
1935 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1936 assert(RD && "member pointer access on non-class-type expression");
1937 // The first class in the path is that of the lvalue.
1938 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1939 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001940 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001941 RD = Base;
1942 }
1943 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001944 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001945 }
1946
1947 // Add the member. Note that we cannot build bound member functions here.
1948 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001949 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1950 HandleLValueMember(Info, BO, LV, FD);
1951 else if (const IndirectFieldDecl *IFD =
1952 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1953 HandleLValueIndirectMember(Info, BO, LV, IFD);
1954 else
1955 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001956 }
1957
1958 return MemPtr.getDecl();
1959}
1960
1961/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1962/// the provided lvalue, which currently refers to the base object.
1963static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1964 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001965 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001966 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001967 return false;
1968
Richard Smithb4e85ed2012-01-06 16:39:00 +00001969 QualType TargetQT = E->getType();
1970 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1971 TargetQT = PT->getPointeeType();
1972
1973 // Check this cast lands within the final derived-to-base subobject path.
1974 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1975 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1976 << D.MostDerivedType << TargetQT;
1977 return false;
1978 }
1979
Richard Smithe24f5fc2011-11-17 22:56:20 +00001980 // Check the type of the final cast. We don't need to check the path,
1981 // since a cast can only be formed if the path is unique.
1982 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001983 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1984 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001985 if (NewEntriesSize == D.MostDerivedPathLength)
1986 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1987 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001988 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001989 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1990 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1991 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001992 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001993 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001994
1995 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001996 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001997}
1998
Mike Stumpc4c90452009-10-27 22:09:17 +00001999namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002000enum EvalStmtResult {
2001 /// Evaluation failed.
2002 ESR_Failed,
2003 /// Hit a 'return' statement.
2004 ESR_Returned,
2005 /// Evaluation succeeded.
2006 ESR_Succeeded
2007};
2008}
2009
2010// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00002011static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002012 const Stmt *S) {
2013 switch (S->getStmtClass()) {
2014 default:
2015 return ESR_Failed;
2016
2017 case Stmt::NullStmtClass:
2018 case Stmt::DeclStmtClass:
2019 return ESR_Succeeded;
2020
Richard Smithc1c5f272011-12-13 06:39:58 +00002021 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002022 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002023 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002024 return ESR_Failed;
2025 return ESR_Returned;
2026 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002027
2028 case Stmt::CompoundStmtClass: {
2029 const CompoundStmt *CS = cast<CompoundStmt>(S);
2030 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2031 BE = CS->body_end(); BI != BE; ++BI) {
2032 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2033 if (ESR != ESR_Succeeded)
2034 return ESR;
2035 }
2036 return ESR_Succeeded;
2037 }
2038 }
2039}
2040
Richard Smith61802452011-12-22 02:22:31 +00002041/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2042/// default constructor. If so, we'll fold it whether or not it's marked as
2043/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2044/// so we need special handling.
2045static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002046 const CXXConstructorDecl *CD,
2047 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002048 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2049 return false;
2050
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002051 // Value-initialization does not call a trivial default constructor, so such a
2052 // call is a core constant expression whether or not the constructor is
2053 // constexpr.
2054 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002055 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002056 // FIXME: If DiagDecl is an implicitly-declared special member function,
2057 // we should be much more explicit about why it's not constexpr.
2058 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2059 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2060 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002061 } else {
2062 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2063 }
2064 }
2065 return true;
2066}
2067
Richard Smithc1c5f272011-12-13 06:39:58 +00002068/// CheckConstexprFunction - Check that a function can be called in a constant
2069/// expression.
2070static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2071 const FunctionDecl *Declaration,
2072 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002073 // Potential constant expressions can contain calls to declared, but not yet
2074 // defined, constexpr functions.
2075 if (Info.CheckingPotentialConstantExpression && !Definition &&
2076 Declaration->isConstexpr())
2077 return false;
2078
Richard Smithc1c5f272011-12-13 06:39:58 +00002079 // Can we evaluate this function call?
2080 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2081 return true;
2082
2083 if (Info.getLangOpts().CPlusPlus0x) {
2084 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002085 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2086 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002087 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2088 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2089 << DiagDecl;
2090 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2091 } else {
2092 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2093 }
2094 return false;
2095}
2096
Richard Smith180f4792011-11-10 06:34:14 +00002097namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002098typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002099}
2100
2101/// EvaluateArgs - Evaluate the arguments to a function call.
2102static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2103 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002104 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002105 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002106 I != E; ++I) {
2107 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2108 // If we're checking for a potential constant expression, evaluate all
2109 // initializers even if some of them fail.
2110 if (!Info.keepEvaluatingAfterFailure())
2111 return false;
2112 Success = false;
2113 }
2114 }
2115 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002116}
2117
Richard Smithd0dccea2011-10-28 22:34:42 +00002118/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002119static bool HandleFunctionCall(SourceLocation CallLoc,
2120 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002121 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002122 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002123 ArgVector ArgValues(Args.size());
2124 if (!EvaluateArgs(Args, ArgValues, Info))
2125 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002126
Richard Smith745f5142012-01-27 01:14:48 +00002127 if (!Info.CheckCallLimit(CallLoc))
2128 return false;
2129
2130 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002131 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2132}
2133
Richard Smith180f4792011-11-10 06:34:14 +00002134/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002135static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002136 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002137 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002138 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002139 ArgVector ArgValues(Args.size());
2140 if (!EvaluateArgs(Args, ArgValues, Info))
2141 return false;
2142
Richard Smith745f5142012-01-27 01:14:48 +00002143 if (!Info.CheckCallLimit(CallLoc))
2144 return false;
2145
Richard Smith86c3ae42012-02-13 03:54:03 +00002146 const CXXRecordDecl *RD = Definition->getParent();
2147 if (RD->getNumVBases()) {
2148 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2149 return false;
2150 }
2151
Richard Smith745f5142012-01-27 01:14:48 +00002152 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002153
2154 // If it's a delegating constructor, just delegate.
2155 if (Definition->isDelegatingConstructor()) {
2156 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002157 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002158 }
2159
Richard Smith610a60c2012-01-10 04:32:03 +00002160 // For a trivial copy or move constructor, perform an APValue copy. This is
2161 // essential for unions, where the operations performed by the constructor
2162 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002163 if (Definition->isDefaulted() &&
2164 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2165 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2166 LValue RHS;
2167 RHS.setFrom(ArgValues[0]);
2168 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002169 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2170 RHS, Value))
2171 return false;
2172 assert((Value.isStruct() || Value.isUnion()) &&
2173 "trivial copy/move from non-class type?");
2174 // Any CCValue of class type must already be a constant expression.
2175 Result = Value;
2176 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002177 }
2178
2179 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002180 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002181 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2182 std::distance(RD->field_begin(), RD->field_end()));
2183
2184 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2185
Richard Smith745f5142012-01-27 01:14:48 +00002186 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002187 unsigned BasesSeen = 0;
2188#ifndef NDEBUG
2189 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2190#endif
2191 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2192 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002193 LValue Subobject = This;
2194 APValue *Value = &Result;
2195
2196 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002197 if ((*I)->isBaseInitializer()) {
2198 QualType BaseType((*I)->getBaseClass(), 0);
2199#ifndef NDEBUG
2200 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002201 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002202 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2203 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2204 "base class initializers not in expected order");
2205 ++BaseIt;
2206#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002207 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002208 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002209 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002210 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002211 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002212 if (RD->isUnion()) {
2213 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002214 Value = &Result.getUnionValue();
2215 } else {
2216 Value = &Result.getStructField(FD->getFieldIndex());
2217 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002218 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002219 // Walk the indirect field decl's chain to find the object to initialize,
2220 // and make sure we've initialized every step along it.
2221 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2222 CE = IFD->chain_end();
2223 C != CE; ++C) {
2224 FieldDecl *FD = cast<FieldDecl>(*C);
2225 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2226 // Switch the union field if it differs. This happens if we had
2227 // preceding zero-initialization, and we're now initializing a union
2228 // subobject other than the first.
2229 // FIXME: In this case, the values of the other subobjects are
2230 // specified, since zero-initialization sets all padding bits to zero.
2231 if (Value->isUninit() ||
2232 (Value->isUnion() && Value->getUnionField() != FD)) {
2233 if (CD->isUnion())
2234 *Value = APValue(FD);
2235 else
2236 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2237 std::distance(CD->field_begin(), CD->field_end()));
2238 }
Richard Smith745f5142012-01-27 01:14:48 +00002239 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002240 if (CD->isUnion())
2241 Value = &Value->getUnionValue();
2242 else
2243 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002244 }
Richard Smith180f4792011-11-10 06:34:14 +00002245 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002246 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002247 }
Richard Smith745f5142012-01-27 01:14:48 +00002248
Richard Smith83587db2012-02-15 02:18:13 +00002249 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2250 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002251 ? CCEK_Constant : CCEK_MemberInit)) {
2252 // If we're checking for a potential constant expression, evaluate all
2253 // initializers even if some of them fail.
2254 if (!Info.keepEvaluatingAfterFailure())
2255 return false;
2256 Success = false;
2257 }
Richard Smith180f4792011-11-10 06:34:14 +00002258 }
2259
Richard Smith745f5142012-01-27 01:14:48 +00002260 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002261}
2262
Richard Smithd0dccea2011-10-28 22:34:42 +00002263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002264class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002265 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002266 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002267public:
2268
Richard Smith1e12c592011-10-16 21:26:27 +00002269 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002270
2271 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002272 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002273 return true;
2274 }
2275
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002276 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2277 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002278 return Visit(E->getResultExpr());
2279 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002280 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002281 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002282 return true;
2283 return false;
2284 }
John McCallf85e1932011-06-15 23:02:42 +00002285 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002286 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002287 return true;
2288 return false;
2289 }
2290 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002291 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002292 return true;
2293 return false;
2294 }
2295
Mike Stumpc4c90452009-10-27 22:09:17 +00002296 // We don't want to evaluate BlockExprs multiple times, as they generate
2297 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2299 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002301 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002302 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2303 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2304 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2305 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2306 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2307 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002308 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002310 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002312 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2314 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2315 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2316 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002317 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002318 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2319 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2320 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2321 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2322 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002323 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002324 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002325 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002326 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002327 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002328
2329 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002330 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002331 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2332 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002333 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002334 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002335 return false;
2336 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002337
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002338 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002339};
2340
John McCall56ca35d2011-02-17 10:25:35 +00002341class OpaqueValueEvaluation {
2342 EvalInfo &info;
2343 OpaqueValueExpr *opaqueValue;
2344
2345public:
2346 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2347 Expr *value)
2348 : info(info), opaqueValue(opaqueValue) {
2349
2350 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002351 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002352 this->opaqueValue = 0;
2353 return;
2354 }
John McCall56ca35d2011-02-17 10:25:35 +00002355 }
2356
2357 bool hasError() const { return opaqueValue == 0; }
2358
2359 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002360 // FIXME: For a recursive constexpr call, an outer stack frame might have
2361 // been using this opaque value too, and will now have to re-evaluate the
2362 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002363 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2364 }
2365};
2366
Mike Stumpc4c90452009-10-27 22:09:17 +00002367} // end anonymous namespace
2368
Eli Friedman4efaa272008-11-12 09:44:48 +00002369//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002370// Generic Evaluation
2371//===----------------------------------------------------------------------===//
2372namespace {
2373
Richard Smithf48fdb02011-12-09 22:58:01 +00002374// FIXME: RetTy is always bool. Remove it.
2375template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376class ExprEvaluatorBase
2377 : public ConstStmtVisitor<Derived, RetTy> {
2378private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002379 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002380 return static_cast<Derived*>(this)->Success(V, E);
2381 }
Richard Smith51201882011-12-30 21:15:51 +00002382 RetTy DerivedZeroInitialization(const Expr *E) {
2383 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002384 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002385
Richard Smith74e1ad92012-02-16 02:46:34 +00002386 // Check whether a conditional operator with a non-constant condition is a
2387 // potential constant expression. If neither arm is a potential constant
2388 // expression, then the conditional operator is not either.
2389 template<typename ConditionalOperator>
2390 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2391 assert(Info.CheckingPotentialConstantExpression);
2392
2393 // Speculatively evaluate both arms.
2394 {
2395 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2396 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2397
2398 StmtVisitorTy::Visit(E->getFalseExpr());
2399 if (Diag.empty())
2400 return;
2401
2402 Diag.clear();
2403 StmtVisitorTy::Visit(E->getTrueExpr());
2404 if (Diag.empty())
2405 return;
2406 }
2407
2408 Error(E, diag::note_constexpr_conditional_never_const);
2409 }
2410
2411
2412 template<typename ConditionalOperator>
2413 bool HandleConditionalOperator(const ConditionalOperator *E) {
2414 bool BoolResult;
2415 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2416 if (Info.CheckingPotentialConstantExpression)
2417 CheckPotentialConstantConditional(E);
2418 return false;
2419 }
2420
2421 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2422 return StmtVisitorTy::Visit(EvalExpr);
2423 }
2424
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002425protected:
2426 EvalInfo &Info;
2427 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2428 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2429
Richard Smithdd1f29b2011-12-12 09:28:41 +00002430 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002431 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 }
2433
2434 /// Report an evaluation error. This should only be called when an error is
2435 /// first discovered. When propagating an error, just return false.
2436 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002437 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002438 return false;
2439 }
2440 bool Error(const Expr *E) {
2441 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2442 }
2443
Richard Smith51201882011-12-30 21:15:51 +00002444 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002445
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002446public:
2447 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2448
2449 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002450 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002451 }
2452 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002453 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002454 }
2455
2456 RetTy VisitParenExpr(const ParenExpr *E)
2457 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2458 RetTy VisitUnaryExtension(const UnaryOperator *E)
2459 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2460 RetTy VisitUnaryPlus(const UnaryOperator *E)
2461 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2462 RetTy VisitChooseExpr(const ChooseExpr *E)
2463 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2464 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2465 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002466 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2467 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002468 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2469 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002470 // We cannot create any objects for which cleanups are required, so there is
2471 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2472 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2473 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002474
Richard Smithc216a012011-12-12 12:46:16 +00002475 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2476 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2477 return static_cast<Derived*>(this)->VisitCastExpr(E);
2478 }
2479 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2480 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2481 return static_cast<Derived*>(this)->VisitCastExpr(E);
2482 }
2483
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2485 switch (E->getOpcode()) {
2486 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002487 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488
2489 case BO_Comma:
2490 VisitIgnoredValue(E->getLHS());
2491 return StmtVisitorTy::Visit(E->getRHS());
2492
2493 case BO_PtrMemD:
2494 case BO_PtrMemI: {
2495 LValue Obj;
2496 if (!HandleMemberPointerAccess(Info, E, Obj))
2497 return false;
2498 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002499 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500 return false;
2501 return DerivedSuccess(Result, E);
2502 }
2503 }
2504 }
2505
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002507 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2509 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002510 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002511
Richard Smith74e1ad92012-02-16 02:46:34 +00002512 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513 }
2514
2515 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002516 bool IsBcpCall = false;
2517 // If the condition (ignoring parens) is a __builtin_constant_p call,
2518 // the result is a constant expression if it can be folded without
2519 // side-effects. This is an important GNU extension. See GCC PR38377
2520 // for discussion.
2521 if (const CallExpr *CallCE =
2522 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2523 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2524 IsBcpCall = true;
2525
2526 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2527 // constant expression; we can't check whether it's potentially foldable.
2528 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2529 return false;
2530
2531 FoldConstant Fold(Info);
2532
Richard Smith74e1ad92012-02-16 02:46:34 +00002533 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002534 return false;
2535
2536 if (IsBcpCall)
2537 Fold.Fold(Info);
2538
2539 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002540 }
2541
2542 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002543 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002544 if (!Value) {
2545 const Expr *Source = E->getSourceExpr();
2546 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002547 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002548 if (Source == E) { // sanity checking.
2549 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002551 }
2552 return StmtVisitorTy::Visit(Source);
2553 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002554 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002555 }
Richard Smithf10d9172011-10-11 21:43:33 +00002556
Richard Smithd0dccea2011-10-28 22:34:42 +00002557 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002558 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002559 QualType CalleeType = Callee->getType();
2560
Richard Smithd0dccea2011-10-28 22:34:42 +00002561 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002562 LValue *This = 0, ThisVal;
2563 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002564 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002565
Richard Smith59efe262011-11-11 04:05:33 +00002566 // Extract function decl and 'this' pointer from the callee.
2567 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002569 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2570 // Explicit bound member calls, such as x.f() or p->g();
2571 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return false;
2573 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002575 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2577 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002578 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2579 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002581 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002582 return Error(Callee);
2583
2584 FD = dyn_cast<FunctionDecl>(Member);
2585 if (!FD)
2586 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002587 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002588 LValue Call;
2589 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002590 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002591
Richard Smithb4e85ed2012-01-06 16:39:00 +00002592 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002593 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002594 FD = dyn_cast_or_null<FunctionDecl>(
2595 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002596 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002597 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002598
2599 // Overloaded operator calls to member functions are represented as normal
2600 // calls with '*this' as the first argument.
2601 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2602 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002603 // FIXME: When selecting an implicit conversion for an overloaded
2604 // operator delete, we sometimes try to evaluate calls to conversion
2605 // operators without a 'this' parameter!
2606 if (Args.empty())
2607 return Error(E);
2608
Richard Smith59efe262011-11-11 04:05:33 +00002609 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2610 return false;
2611 This = &ThisVal;
2612 Args = Args.slice(1);
2613 }
2614
2615 // Don't call function pointers which have been cast to some other type.
2616 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002618 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002619 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002620
Richard Smithb04035a2012-02-01 02:39:43 +00002621 if (This && !This->checkSubobject(Info, E, CSK_This))
2622 return false;
2623
Richard Smith86c3ae42012-02-13 03:54:03 +00002624 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2625 // calls to such functions in constant expressions.
2626 if (This && !HasQualifier &&
2627 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2628 return Error(E, diag::note_constexpr_virtual_call);
2629
Richard Smithc1c5f272011-12-13 06:39:58 +00002630 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002631 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002632 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002633
Richard Smithc1c5f272011-12-13 06:39:58 +00002634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002635 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2636 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002637 return false;
2638
Richard Smith83587db2012-02-15 02:18:13 +00002639 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002640 }
2641
Richard Smithc49bd112011-10-28 17:51:58 +00002642 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2643 return StmtVisitorTy::Visit(E->getInitializer());
2644 }
Richard Smithf10d9172011-10-11 21:43:33 +00002645 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002646 if (E->getNumInits() == 0)
2647 return DerivedZeroInitialization(E);
2648 if (E->getNumInits() == 1)
2649 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002650 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002651 }
2652 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002653 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002654 }
2655 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002656 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002657 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002658 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002659 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002660 }
Richard Smithf10d9172011-10-11 21:43:33 +00002661
Richard Smith180f4792011-11-10 06:34:14 +00002662 /// A member expression where the object is a prvalue is itself a prvalue.
2663 RetTy VisitMemberExpr(const MemberExpr *E) {
2664 assert(!E->isArrow() && "missing call to bound member function?");
2665
2666 CCValue Val;
2667 if (!Evaluate(Val, Info, E->getBase()))
2668 return false;
2669
2670 QualType BaseTy = E->getBase()->getType();
2671
2672 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002673 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002674 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2675 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2676 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2677
Richard Smithb4e85ed2012-01-06 16:39:00 +00002678 SubobjectDesignator Designator(BaseTy);
2679 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002680
Richard Smithf48fdb02011-12-09 22:58:01 +00002681 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002682 DerivedSuccess(Val, E);
2683 }
2684
Richard Smithc49bd112011-10-28 17:51:58 +00002685 RetTy VisitCastExpr(const CastExpr *E) {
2686 switch (E->getCastKind()) {
2687 default:
2688 break;
2689
David Chisnall7a7ee302012-01-16 17:27:18 +00002690 case CK_AtomicToNonAtomic:
2691 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002692 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002693 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002694 return StmtVisitorTy::Visit(E->getSubExpr());
2695
2696 case CK_LValueToRValue: {
2697 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002698 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2699 return false;
2700 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002701 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2702 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2703 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002704 return false;
2705 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002706 }
2707 }
2708
Richard Smithf48fdb02011-12-09 22:58:01 +00002709 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002710 }
2711
Richard Smith8327fad2011-10-24 18:44:57 +00002712 /// Visit a value which is evaluated, but whose value is ignored.
2713 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002714 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002715 if (!Evaluate(Scratch, Info, E))
2716 Info.EvalStatus.HasSideEffects = true;
2717 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002718};
2719
2720}
2721
2722//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002723// Common base class for lvalue and temporary evaluation.
2724//===----------------------------------------------------------------------===//
2725namespace {
2726template<class Derived>
2727class LValueExprEvaluatorBase
2728 : public ExprEvaluatorBase<Derived, bool> {
2729protected:
2730 LValue &Result;
2731 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2732 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2733
2734 bool Success(APValue::LValueBase B) {
2735 Result.set(B);
2736 return true;
2737 }
2738
2739public:
2740 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2741 ExprEvaluatorBaseTy(Info), Result(Result) {}
2742
2743 bool Success(const CCValue &V, const Expr *E) {
2744 Result.setFrom(V);
2745 return true;
2746 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002747
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 bool VisitMemberExpr(const MemberExpr *E) {
2749 // Handle non-static data members.
2750 QualType BaseTy;
2751 if (E->isArrow()) {
2752 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2753 return false;
2754 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002755 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002756 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002757 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2758 return false;
2759 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002760 } else {
2761 if (!this->Visit(E->getBase()))
2762 return false;
2763 BaseTy = E->getBase()->getType();
2764 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002765
Richard Smithd9b02e72012-01-25 22:15:11 +00002766 const ValueDecl *MD = E->getMemberDecl();
2767 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2768 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2769 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2770 (void)BaseTy;
2771 HandleLValueMember(this->Info, E, Result, FD);
2772 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2773 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2774 } else
2775 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776
Richard Smithd9b02e72012-01-25 22:15:11 +00002777 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002778 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002779 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 RefValue))
2781 return false;
2782 return Success(RefValue, E);
2783 }
2784 return true;
2785 }
2786
2787 bool VisitBinaryOperator(const BinaryOperator *E) {
2788 switch (E->getOpcode()) {
2789 default:
2790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2791
2792 case BO_PtrMemD:
2793 case BO_PtrMemI:
2794 return HandleMemberPointerAccess(this->Info, E, Result);
2795 }
2796 }
2797
2798 bool VisitCastExpr(const CastExpr *E) {
2799 switch (E->getCastKind()) {
2800 default:
2801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2802
2803 case CK_DerivedToBase:
2804 case CK_UncheckedDerivedToBase: {
2805 if (!this->Visit(E->getSubExpr()))
2806 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002807
2808 // Now figure out the necessary offset to add to the base LV to get from
2809 // the derived class to the base class.
2810 QualType Type = E->getSubExpr()->getType();
2811
2812 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2813 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002814 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002815 *PathI))
2816 return false;
2817 Type = (*PathI)->getType();
2818 }
2819
2820 return true;
2821 }
2822 }
2823 }
2824};
2825}
2826
2827//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002828// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002829//
2830// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2831// function designators (in C), decl references to void objects (in C), and
2832// temporaries (if building with -Wno-address-of-temporary).
2833//
2834// LValue evaluation produces values comprising a base expression of one of the
2835// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002836// - Declarations
2837// * VarDecl
2838// * FunctionDecl
2839// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002840// * CompoundLiteralExpr in C
2841// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002842// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002843// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002844// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002845// * ObjCEncodeExpr
2846// * AddrLabelExpr
2847// * BlockExpr
2848// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002849// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002850// * Any Expr, with a CallIndex indicating the function in which the temporary
2851// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002852// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002853//===----------------------------------------------------------------------===//
2854namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002855class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002856 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002857public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002858 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2859 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Richard Smithc49bd112011-10-28 17:51:58 +00002861 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 bool VisitDeclRefExpr(const DeclRefExpr *E);
2864 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002865 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2867 bool VisitMemberExpr(const MemberExpr *E);
2868 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2869 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002870 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002871 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2872 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002873
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002874 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002875 switch (E->getCastKind()) {
2876 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002878
Eli Friedmandb924222011-10-11 00:13:24 +00002879 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002880 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002881 if (!Visit(E->getSubExpr()))
2882 return false;
2883 Result.Designator.setInvalid();
2884 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002885
Richard Smithe24f5fc2011-11-17 22:56:20 +00002886 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002887 if (!Visit(E->getSubExpr()))
2888 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002889 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002890 }
2891 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002892
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002893 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002894
Eli Friedman4efaa272008-11-12 09:44:48 +00002895};
2896} // end anonymous namespace
2897
Richard Smithc49bd112011-10-28 17:51:58 +00002898/// Evaluate an expression as an lvalue. This can be legitimately called on
2899/// expressions which are not glvalues, in a few cases:
2900/// * function designators in C,
2901/// * "extern void" objects,
2902/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002903static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002904 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2905 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2906 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002907 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002908}
2909
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002910bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002911 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2912 return Success(FD);
2913 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002914 return VisitVarDecl(E, VD);
2915 return Error(E);
2916}
Richard Smith436c8892011-10-24 23:14:33 +00002917
Richard Smithc49bd112011-10-28 17:51:58 +00002918bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002919 if (!VD->getType()->isReferenceType()) {
2920 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002921 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002922 return true;
2923 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002924 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002925 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002926
Richard Smith47a1eed2011-10-29 20:57:55 +00002927 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002928 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2929 return false;
2930 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002931}
2932
Richard Smithbd552ef2011-10-31 05:52:43 +00002933bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2934 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002935 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002936 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002937 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2938
Richard Smith83587db2012-02-15 02:18:13 +00002939 Result.set(E, Info.CurrentCall->Index);
2940 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2941 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002942 }
2943
2944 // Materialization of an lvalue temporary occurs when we need to force a copy
2945 // (for instance, if it's a bitfield).
2946 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2947 if (!Visit(E->GetTemporaryExpr()))
2948 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002949 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002950 Info.CurrentCall->Temporaries[E]))
2951 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002952 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002953 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002954}
2955
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002956bool
2957LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002958 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2959 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2960 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002961 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002962}
2963
Richard Smith47d21452011-12-27 12:18:28 +00002964bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2965 if (E->isTypeOperand())
2966 return Success(E);
2967 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2968 if (RD && RD->isPolymorphic()) {
2969 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2970 << E->getExprOperand()->getType()
2971 << E->getExprOperand()->getSourceRange();
2972 return false;
2973 }
2974 return Success(E);
2975}
2976
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002977bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002978 // Handle static data members.
2979 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2980 VisitIgnoredValue(E->getBase());
2981 return VisitVarDecl(E, VD);
2982 }
2983
Richard Smithd0dccea2011-10-28 22:34:42 +00002984 // Handle static member functions.
2985 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2986 if (MD->isStatic()) {
2987 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002988 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002989 }
2990 }
2991
Richard Smith180f4792011-11-10 06:34:14 +00002992 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002993 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002994}
2995
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002996bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002997 // FIXME: Deal with vectors as array subscript bases.
2998 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002999 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003000
Anders Carlsson3068d112008-11-16 19:01:22 +00003001 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003002 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Anders Carlsson3068d112008-11-16 19:01:22 +00003004 APSInt Index;
3005 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003006 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003007 int64_t IndexValue
3008 = Index.isSigned() ? Index.getSExtValue()
3009 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003010
Richard Smithb4e85ed2012-01-06 16:39:00 +00003011 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003012}
Eli Friedman4efaa272008-11-12 09:44:48 +00003013
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003014bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003015 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003016}
3017
Eli Friedman4efaa272008-11-12 09:44:48 +00003018//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003019// Pointer Evaluation
3020//===----------------------------------------------------------------------===//
3021
Anders Carlssonc754aa62008-07-08 05:13:58 +00003022namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003023class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003024 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003025 LValue &Result;
3026
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003027 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003028 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003029 return true;
3030 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003031public:
Mike Stump1eb44332009-09-09 15:08:12 +00003032
John McCallefdb83e2010-05-07 21:00:08 +00003033 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003034 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003035
Richard Smith47a1eed2011-10-29 20:57:55 +00003036 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003037 Result.setFrom(V);
3038 return true;
3039 }
Richard Smith51201882011-12-30 21:15:51 +00003040 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003041 return Success((Expr*)0);
3042 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003043
John McCallefdb83e2010-05-07 21:00:08 +00003044 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003045 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003046 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003047 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003048 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003049 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003050 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051 bool VisitCallExpr(const CallExpr *E);
3052 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003053 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003054 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003055 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003056 }
Richard Smith180f4792011-11-10 06:34:14 +00003057 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3058 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003059 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003060 Result = *Info.CurrentCall->This;
3061 return true;
3062 }
John McCall56ca35d2011-02-17 10:25:35 +00003063
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003064 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003065};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003066} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003067
John McCallefdb83e2010-05-07 21:00:08 +00003068static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003069 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003070 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003071}
3072
John McCallefdb83e2010-05-07 21:00:08 +00003073bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003074 if (E->getOpcode() != BO_Add &&
3075 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003076 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003078 const Expr *PExp = E->getLHS();
3079 const Expr *IExp = E->getRHS();
3080 if (IExp->getType()->isPointerType())
3081 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Richard Smith745f5142012-01-27 01:14:48 +00003083 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3084 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003085 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003086
John McCallefdb83e2010-05-07 21:00:08 +00003087 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003088 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003089 return false;
3090 int64_t AdditionalOffset
3091 = Offset.isSigned() ? Offset.getSExtValue()
3092 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003093 if (E->getOpcode() == BO_Sub)
3094 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003095
Richard Smith180f4792011-11-10 06:34:14 +00003096 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003097 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3098 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003099}
Eli Friedman4efaa272008-11-12 09:44:48 +00003100
John McCallefdb83e2010-05-07 21:00:08 +00003101bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3102 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003103}
Mike Stump1eb44332009-09-09 15:08:12 +00003104
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003105bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3106 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003107
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003108 switch (E->getCastKind()) {
3109 default:
3110 break;
3111
John McCall2de56d12010-08-25 11:45:40 +00003112 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003113 case CK_CPointerToObjCPointerCast:
3114 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003115 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003116 if (!Visit(SubExpr))
3117 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003118 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3119 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3120 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003121 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003122 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003123 if (SubExpr->getType()->isVoidPointerType())
3124 CCEDiag(E, diag::note_constexpr_invalid_cast)
3125 << 3 << SubExpr->getType();
3126 else
3127 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3128 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003129 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003130
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003131 case CK_DerivedToBase:
3132 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003133 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003134 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003135 if (!Result.Base && Result.Offset.isZero())
3136 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003137
Richard Smith180f4792011-11-10 06:34:14 +00003138 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003139 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003140 QualType Type =
3141 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003142
Richard Smith180f4792011-11-10 06:34:14 +00003143 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003144 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003145 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3146 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003147 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003148 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003149 }
3150
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003151 return true;
3152 }
3153
Richard Smithe24f5fc2011-11-17 22:56:20 +00003154 case CK_BaseToDerived:
3155 if (!Visit(E->getSubExpr()))
3156 return false;
3157 if (!Result.Base && Result.Offset.isZero())
3158 return true;
3159 return HandleBaseToDerivedCast(Info, E, Result);
3160
Richard Smith47a1eed2011-10-29 20:57:55 +00003161 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003162 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003163
John McCall2de56d12010-08-25 11:45:40 +00003164 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003165 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3166
Richard Smith47a1eed2011-10-29 20:57:55 +00003167 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003168 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003169 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003170
John McCallefdb83e2010-05-07 21:00:08 +00003171 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003172 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3173 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003174 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003175 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003176 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003177 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003178 return true;
3179 } else {
3180 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003181 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003182 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003183 }
3184 }
John McCall2de56d12010-08-25 11:45:40 +00003185 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003186 if (SubExpr->isGLValue()) {
3187 if (!EvaluateLValue(SubExpr, Result, Info))
3188 return false;
3189 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003190 Result.set(SubExpr, Info.CurrentCall->Index);
3191 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3192 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003193 return false;
3194 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003195 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003196 if (const ConstantArrayType *CAT
3197 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3198 Result.addArray(Info, E, CAT);
3199 else
3200 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003201 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003202
John McCall2de56d12010-08-25 11:45:40 +00003203 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003204 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003205 }
3206
Richard Smithc49bd112011-10-28 17:51:58 +00003207 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003208}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003209
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003210bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003211 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003212 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003213
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003214 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003215}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003216
3217//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003218// Member Pointer Evaluation
3219//===----------------------------------------------------------------------===//
3220
3221namespace {
3222class MemberPointerExprEvaluator
3223 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3224 MemberPtr &Result;
3225
3226 bool Success(const ValueDecl *D) {
3227 Result = MemberPtr(D);
3228 return true;
3229 }
3230public:
3231
3232 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3233 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3234
3235 bool Success(const CCValue &V, const Expr *E) {
3236 Result.setFrom(V);
3237 return true;
3238 }
Richard Smith51201882011-12-30 21:15:51 +00003239 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003240 return Success((const ValueDecl*)0);
3241 }
3242
3243 bool VisitCastExpr(const CastExpr *E);
3244 bool VisitUnaryAddrOf(const UnaryOperator *E);
3245};
3246} // end anonymous namespace
3247
3248static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3249 EvalInfo &Info) {
3250 assert(E->isRValue() && E->getType()->isMemberPointerType());
3251 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3252}
3253
3254bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3255 switch (E->getCastKind()) {
3256 default:
3257 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3258
3259 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003260 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003261
3262 case CK_BaseToDerivedMemberPointer: {
3263 if (!Visit(E->getSubExpr()))
3264 return false;
3265 if (E->path_empty())
3266 return true;
3267 // Base-to-derived member pointer casts store the path in derived-to-base
3268 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3269 // the wrong end of the derived->base arc, so stagger the path by one class.
3270 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3271 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3272 PathI != PathE; ++PathI) {
3273 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3274 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3275 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003276 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003277 }
3278 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3279 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003280 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003281 return true;
3282 }
3283
3284 case CK_DerivedToBaseMemberPointer:
3285 if (!Visit(E->getSubExpr()))
3286 return false;
3287 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3288 PathE = E->path_end(); PathI != PathE; ++PathI) {
3289 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3290 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3291 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003292 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003293 }
3294 return true;
3295 }
3296}
3297
3298bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3299 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3300 // member can be formed.
3301 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3302}
3303
3304//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003305// Record Evaluation
3306//===----------------------------------------------------------------------===//
3307
3308namespace {
3309 class RecordExprEvaluator
3310 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3311 const LValue &This;
3312 APValue &Result;
3313 public:
3314
3315 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3316 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3317
3318 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003319 Result = V;
3320 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003321 }
Richard Smith51201882011-12-30 21:15:51 +00003322 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003323
Richard Smith59efe262011-11-11 04:05:33 +00003324 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003325 bool VisitInitListExpr(const InitListExpr *E);
3326 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3327 };
3328}
3329
Richard Smith51201882011-12-30 21:15:51 +00003330/// Perform zero-initialization on an object of non-union class type.
3331/// C++11 [dcl.init]p5:
3332/// To zero-initialize an object or reference of type T means:
3333/// [...]
3334/// -- if T is a (possibly cv-qualified) non-union class type,
3335/// each non-static data member and each base-class subobject is
3336/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003337static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3338 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003339 const LValue &This, APValue &Result) {
3340 assert(!RD->isUnion() && "Expected non-union class type");
3341 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3342 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3343 std::distance(RD->field_begin(), RD->field_end()));
3344
3345 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3346
3347 if (CD) {
3348 unsigned Index = 0;
3349 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003350 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003351 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3352 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003353 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3354 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003355 Result.getStructBase(Index)))
3356 return false;
3357 }
3358 }
3359
Richard Smithb4e85ed2012-01-06 16:39:00 +00003360 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3361 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003362 // -- if T is a reference type, no initialization is performed.
3363 if ((*I)->getType()->isReferenceType())
3364 continue;
3365
3366 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003367 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003368
3369 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003370 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003371 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3372 return false;
3373 }
3374
3375 return true;
3376}
3377
3378bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3379 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3380 if (RD->isUnion()) {
3381 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3382 // object's first non-static named data member is zero-initialized
3383 RecordDecl::field_iterator I = RD->field_begin();
3384 if (I == RD->field_end()) {
3385 Result = APValue((const FieldDecl*)0);
3386 return true;
3387 }
3388
3389 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003390 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003391 Result = APValue(*I);
3392 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003393 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003394 }
3395
Richard Smithce582fe2012-02-17 00:44:16 +00003396 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3397 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3398 return false;
3399 }
3400
Richard Smithb4e85ed2012-01-06 16:39:00 +00003401 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003402}
3403
Richard Smith59efe262011-11-11 04:05:33 +00003404bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3405 switch (E->getCastKind()) {
3406 default:
3407 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3408
3409 case CK_ConstructorConversion:
3410 return Visit(E->getSubExpr());
3411
3412 case CK_DerivedToBase:
3413 case CK_UncheckedDerivedToBase: {
3414 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003415 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003416 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003417 if (!DerivedObject.isStruct())
3418 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003419
3420 // Derived-to-base rvalue conversion: just slice off the derived part.
3421 APValue *Value = &DerivedObject;
3422 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3423 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3424 PathE = E->path_end(); PathI != PathE; ++PathI) {
3425 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3426 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3427 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3428 RD = Base;
3429 }
3430 Result = *Value;
3431 return true;
3432 }
3433 }
3434}
3435
Richard Smith180f4792011-11-10 06:34:14 +00003436bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3437 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3438 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3439
3440 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003441 const FieldDecl *Field = E->getInitializedFieldInUnion();
3442 Result = APValue(Field);
3443 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003444 return true;
Richard Smithec789162012-01-12 18:54:33 +00003445
3446 // If the initializer list for a union does not contain any elements, the
3447 // first element of the union is value-initialized.
3448 ImplicitValueInitExpr VIE(Field->getType());
3449 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3450
Richard Smith180f4792011-11-10 06:34:14 +00003451 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003452 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003453 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003454 }
3455
3456 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3457 "initializer list for class with base classes");
3458 Result = APValue(APValue::UninitStruct(), 0,
3459 std::distance(RD->field_begin(), RD->field_end()));
3460 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003461 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003462 for (RecordDecl::field_iterator Field = RD->field_begin(),
3463 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3464 // Anonymous bit-fields are not considered members of the class for
3465 // purposes of aggregate initialization.
3466 if (Field->isUnnamedBitfield())
3467 continue;
3468
3469 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003470
Richard Smith745f5142012-01-27 01:14:48 +00003471 bool HaveInit = ElementNo < E->getNumInits();
3472
3473 // FIXME: Diagnostics here should point to the end of the initializer
3474 // list, not the start.
3475 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3476 *Field, &Layout);
3477
3478 // Perform an implicit value-initialization for members beyond the end of
3479 // the initializer list.
3480 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3481
Richard Smith83587db2012-02-15 02:18:13 +00003482 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003483 Result.getStructField((*Field)->getFieldIndex()),
3484 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3485 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003486 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003487 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003488 }
3489 }
3490
Richard Smith745f5142012-01-27 01:14:48 +00003491 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003492}
3493
3494bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3495 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003496 bool ZeroInit = E->requiresZeroInitialization();
3497 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003498 // If we've already performed zero-initialization, we're already done.
3499 if (!Result.isUninit())
3500 return true;
3501
Richard Smith51201882011-12-30 21:15:51 +00003502 if (ZeroInit)
3503 return ZeroInitialization(E);
3504
Richard Smith61802452011-12-22 02:22:31 +00003505 const CXXRecordDecl *RD = FD->getParent();
3506 if (RD->isUnion())
3507 Result = APValue((FieldDecl*)0);
3508 else
3509 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3510 std::distance(RD->field_begin(), RD->field_end()));
3511 return true;
3512 }
3513
Richard Smith180f4792011-11-10 06:34:14 +00003514 const FunctionDecl *Definition = 0;
3515 FD->getBody(Definition);
3516
Richard Smithc1c5f272011-12-13 06:39:58 +00003517 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3518 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003519
Richard Smith610a60c2012-01-10 04:32:03 +00003520 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003521 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003522 if (const MaterializeTemporaryExpr *ME
3523 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3524 return Visit(ME->GetTemporaryExpr());
3525
Richard Smith51201882011-12-30 21:15:51 +00003526 if (ZeroInit && !ZeroInitialization(E))
3527 return false;
3528
Richard Smith180f4792011-11-10 06:34:14 +00003529 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003530 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003531 cast<CXXConstructorDecl>(Definition), Info,
3532 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003533}
3534
3535static bool EvaluateRecord(const Expr *E, const LValue &This,
3536 APValue &Result, EvalInfo &Info) {
3537 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003538 "can't evaluate expression as a record rvalue");
3539 return RecordExprEvaluator(Info, This, Result).Visit(E);
3540}
3541
3542//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003543// Temporary Evaluation
3544//
3545// Temporaries are represented in the AST as rvalues, but generally behave like
3546// lvalues. The full-object of which the temporary is a subobject is implicitly
3547// materialized so that a reference can bind to it.
3548//===----------------------------------------------------------------------===//
3549namespace {
3550class TemporaryExprEvaluator
3551 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3552public:
3553 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3554 LValueExprEvaluatorBaseTy(Info, Result) {}
3555
3556 /// Visit an expression which constructs the value of this temporary.
3557 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003558 Result.set(E, Info.CurrentCall->Index);
3559 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003560 }
3561
3562 bool VisitCastExpr(const CastExpr *E) {
3563 switch (E->getCastKind()) {
3564 default:
3565 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3566
3567 case CK_ConstructorConversion:
3568 return VisitConstructExpr(E->getSubExpr());
3569 }
3570 }
3571 bool VisitInitListExpr(const InitListExpr *E) {
3572 return VisitConstructExpr(E);
3573 }
3574 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3575 return VisitConstructExpr(E);
3576 }
3577 bool VisitCallExpr(const CallExpr *E) {
3578 return VisitConstructExpr(E);
3579 }
3580};
3581} // end anonymous namespace
3582
3583/// Evaluate an expression of record type as a temporary.
3584static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003585 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003586 return TemporaryExprEvaluator(Info, Result).Visit(E);
3587}
3588
3589//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003590// Vector Evaluation
3591//===----------------------------------------------------------------------===//
3592
3593namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003594 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003595 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3596 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003597 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Richard Smith07fc6572011-10-22 21:10:00 +00003599 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3600 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Richard Smith07fc6572011-10-22 21:10:00 +00003602 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3603 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3604 // FIXME: remove this APValue copy.
3605 Result = APValue(V.data(), V.size());
3606 return true;
3607 }
Richard Smith69c2c502011-11-04 05:33:44 +00003608 bool Success(const CCValue &V, const Expr *E) {
3609 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003610 Result = V;
3611 return true;
3612 }
Richard Smith51201882011-12-30 21:15:51 +00003613 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Richard Smith07fc6572011-10-22 21:10:00 +00003615 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003616 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003617 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003618 bool VisitInitListExpr(const InitListExpr *E);
3619 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003620 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003621 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003622 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003623 };
3624} // end anonymous namespace
3625
3626static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003627 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003628 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003629}
3630
Richard Smith07fc6572011-10-22 21:10:00 +00003631bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3632 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003633 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Richard Smithd62ca372011-12-06 22:44:34 +00003635 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003636 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003637
Eli Friedman46a52322011-03-25 00:43:55 +00003638 switch (E->getCastKind()) {
3639 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003640 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003641 if (SETy->isIntegerType()) {
3642 APSInt IntResult;
3643 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003644 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003645 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003646 } else if (SETy->isRealFloatingType()) {
3647 APFloat F(0.0);
3648 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003649 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003650 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003651 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003652 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003653 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003654
3655 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003656 SmallVector<APValue, 4> Elts(NElts, Val);
3657 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003658 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003659 case CK_BitCast: {
3660 // Evaluate the operand into an APInt we can extract from.
3661 llvm::APInt SValInt;
3662 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3663 return false;
3664 // Extract the elements
3665 QualType EltTy = VTy->getElementType();
3666 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3667 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3668 SmallVector<APValue, 4> Elts;
3669 if (EltTy->isRealFloatingType()) {
3670 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3671 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3672 unsigned FloatEltSize = EltSize;
3673 if (&Sem == &APFloat::x87DoubleExtended)
3674 FloatEltSize = 80;
3675 for (unsigned i = 0; i < NElts; i++) {
3676 llvm::APInt Elt;
3677 if (BigEndian)
3678 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3679 else
3680 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3681 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3682 }
3683 } else if (EltTy->isIntegerType()) {
3684 for (unsigned i = 0; i < NElts; i++) {
3685 llvm::APInt Elt;
3686 if (BigEndian)
3687 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3688 else
3689 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3690 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3691 }
3692 } else {
3693 return Error(E);
3694 }
3695 return Success(Elts, E);
3696 }
Eli Friedman46a52322011-03-25 00:43:55 +00003697 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003698 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003699 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003700}
3701
Richard Smith07fc6572011-10-22 21:10:00 +00003702bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003703VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003704 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003705 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003706 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Nate Begeman59b5da62009-01-18 03:20:47 +00003708 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003709 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003710
Eli Friedman3edd5a92012-01-03 23:24:20 +00003711 // The number of initializers can be less than the number of
3712 // vector elements. For OpenCL, this can be due to nested vector
3713 // initialization. For GCC compatibility, missing trailing elements
3714 // should be initialized with zeroes.
3715 unsigned CountInits = 0, CountElts = 0;
3716 while (CountElts < NumElements) {
3717 // Handle nested vector initialization.
3718 if (CountInits < NumInits
3719 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3720 APValue v;
3721 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3722 return Error(E);
3723 unsigned vlen = v.getVectorLength();
3724 for (unsigned j = 0; j < vlen; j++)
3725 Elements.push_back(v.getVectorElt(j));
3726 CountElts += vlen;
3727 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003728 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003729 if (CountInits < NumInits) {
3730 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3731 return Error(E);
3732 } else // trailing integer zero.
3733 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3734 Elements.push_back(APValue(sInt));
3735 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003736 } else {
3737 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003738 if (CountInits < NumInits) {
3739 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3740 return Error(E);
3741 } else // trailing float zero.
3742 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3743 Elements.push_back(APValue(f));
3744 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003745 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003746 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003747 }
Richard Smith07fc6572011-10-22 21:10:00 +00003748 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003749}
3750
Richard Smith07fc6572011-10-22 21:10:00 +00003751bool
Richard Smith51201882011-12-30 21:15:51 +00003752VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003753 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003754 QualType EltTy = VT->getElementType();
3755 APValue ZeroElement;
3756 if (EltTy->isIntegerType())
3757 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3758 else
3759 ZeroElement =
3760 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3761
Chris Lattner5f9e2722011-07-23 10:55:15 +00003762 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003763 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003764}
3765
Richard Smith07fc6572011-10-22 21:10:00 +00003766bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003767 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003768 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003769}
3770
Nate Begeman59b5da62009-01-18 03:20:47 +00003771//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003772// Array Evaluation
3773//===----------------------------------------------------------------------===//
3774
3775namespace {
3776 class ArrayExprEvaluator
3777 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003778 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003779 APValue &Result;
3780 public:
3781
Richard Smith180f4792011-11-10 06:34:14 +00003782 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3783 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003784
3785 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003786 assert((V.isArray() || V.isLValue()) &&
3787 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003788 Result = V;
3789 return true;
3790 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003791
Richard Smith51201882011-12-30 21:15:51 +00003792 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003793 const ConstantArrayType *CAT =
3794 Info.Ctx.getAsConstantArrayType(E->getType());
3795 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003796 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003797
3798 Result = APValue(APValue::UninitArray(), 0,
3799 CAT->getSize().getZExtValue());
3800 if (!Result.hasArrayFiller()) return true;
3801
Richard Smith51201882011-12-30 21:15:51 +00003802 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003803 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003804 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003805 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003806 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003807 }
3808
Richard Smithcc5d4f62011-11-07 09:22:26 +00003809 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003810 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003811 };
3812} // end anonymous namespace
3813
Richard Smith180f4792011-11-10 06:34:14 +00003814static bool EvaluateArray(const Expr *E, const LValue &This,
3815 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003816 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003817 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003818}
3819
3820bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3821 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3822 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003823 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003824
Richard Smith974c5f92011-12-22 01:07:19 +00003825 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3826 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003827 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003828 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3829 LValue LV;
3830 if (!EvaluateLValue(E->getInit(0), LV, Info))
3831 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00003832 CCValue Val;
3833 LV.moveInto(Val);
3834 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003835 }
3836
Richard Smith745f5142012-01-27 01:14:48 +00003837 bool Success = true;
3838
Richard Smithcc5d4f62011-11-07 09:22:26 +00003839 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3840 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003841 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003842 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003843 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003844 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003845 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003846 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3847 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003848 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3849 CAT->getElementType(), 1)) {
3850 if (!Info.keepEvaluatingAfterFailure())
3851 return false;
3852 Success = false;
3853 }
Richard Smith180f4792011-11-10 06:34:14 +00003854 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003855
Richard Smith745f5142012-01-27 01:14:48 +00003856 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003857 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003858 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3859 // but sometimes does:
3860 // struct S { constexpr S() : p(&p) {} void *p; };
3861 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003862 return EvaluateInPlace(Result.getArrayFiller(), Info,
3863 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003864}
3865
Richard Smithe24f5fc2011-11-17 22:56:20 +00003866bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3867 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3868 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003869 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003870
Richard Smithec789162012-01-12 18:54:33 +00003871 bool HadZeroInit = !Result.isUninit();
3872 if (!HadZeroInit)
3873 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003874 if (!Result.hasArrayFiller())
3875 return true;
3876
3877 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003878
Richard Smith51201882011-12-30 21:15:51 +00003879 bool ZeroInit = E->requiresZeroInitialization();
3880 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003881 if (HadZeroInit)
3882 return true;
3883
Richard Smith51201882011-12-30 21:15:51 +00003884 if (ZeroInit) {
3885 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003886 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003887 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003888 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003889 }
3890
Richard Smith61802452011-12-22 02:22:31 +00003891 const CXXRecordDecl *RD = FD->getParent();
3892 if (RD->isUnion())
3893 Result.getArrayFiller() = APValue((FieldDecl*)0);
3894 else
3895 Result.getArrayFiller() =
3896 APValue(APValue::UninitStruct(), RD->getNumBases(),
3897 std::distance(RD->field_begin(), RD->field_end()));
3898 return true;
3899 }
3900
Richard Smithe24f5fc2011-11-17 22:56:20 +00003901 const FunctionDecl *Definition = 0;
3902 FD->getBody(Definition);
3903
Richard Smithc1c5f272011-12-13 06:39:58 +00003904 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3905 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003906
3907 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3908 // but sometimes does:
3909 // struct S { constexpr S() : p(&p) {} void *p; };
3910 // S s[10];
3911 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003912 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003913
Richard Smithec789162012-01-12 18:54:33 +00003914 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003915 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003916 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003917 return false;
3918 }
3919
Richard Smithe24f5fc2011-11-17 22:56:20 +00003920 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003921 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003922 cast<CXXConstructorDecl>(Definition),
3923 Info, Result.getArrayFiller());
3924}
3925
Richard Smithcc5d4f62011-11-07 09:22:26 +00003926//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003927// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003928//
3929// As a GNU extension, we support casting pointers to sufficiently-wide integer
3930// types and back in constant folding. Integer values are thus represented
3931// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003932//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003933
3934namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003935class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003936 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003937 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003938public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003939 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003940 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003941
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003942 bool Success(const llvm::APSInt &SI, const Expr *E) {
3943 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003944 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003945 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003946 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003947 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003948 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003949 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003950 return true;
3951 }
3952
Daniel Dunbar131eb432009-02-19 09:06:44 +00003953 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003954 assert(E->getType()->isIntegralOrEnumerationType() &&
3955 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003956 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003957 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003958 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003959 Result.getInt().setIsUnsigned(
3960 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003961 return true;
3962 }
3963
3964 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003965 assert(E->getType()->isIntegralOrEnumerationType() &&
3966 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003967 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003968 return true;
3969 }
3970
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003971 bool Success(CharUnits Size, const Expr *E) {
3972 return Success(Size.getQuantity(), E);
3973 }
3974
Richard Smith47a1eed2011-10-29 20:57:55 +00003975 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003976 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003977 Result = V;
3978 return true;
3979 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003980 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003981 }
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Richard Smith51201882011-12-30 21:15:51 +00003983 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003984
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003985 //===--------------------------------------------------------------------===//
3986 // Visitor Methods
3987 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003988
Chris Lattner4c4867e2008-07-12 00:38:25 +00003989 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003990 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003991 }
3992 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003993 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003994 }
Eli Friedman04309752009-11-24 05:28:59 +00003995
3996 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3997 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003998 if (CheckReferencedDecl(E, E->getDecl()))
3999 return true;
4000
4001 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004002 }
4003 bool VisitMemberExpr(const MemberExpr *E) {
4004 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004005 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004006 return true;
4007 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004008
4009 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004010 }
4011
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004012 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004013 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004014 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004015 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004016
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004017 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004018 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004019
Anders Carlsson3068d112008-11-16 19:01:22 +00004020 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004021 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004022 }
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Richard Smithf10d9172011-10-11 21:43:33 +00004024 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004025 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004026 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004027 }
4028
Sebastian Redl64b45f72009-01-05 20:52:13 +00004029 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004030 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004031 }
4032
Francois Pichet6ad6f282010-12-07 00:08:36 +00004033 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4034 return Success(E->getValue(), E);
4035 }
4036
John Wiegley21ff2e52011-04-28 00:16:57 +00004037 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4038 return Success(E->getValue(), E);
4039 }
4040
John Wiegley55262202011-04-25 06:54:41 +00004041 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4042 return Success(E->getValue(), E);
4043 }
4044
Eli Friedman722c7172009-02-28 03:59:05 +00004045 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004046 bool VisitUnaryImag(const UnaryOperator *E);
4047
Sebastian Redl295995c2010-09-10 20:55:47 +00004048 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004049 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004050
Chris Lattnerfcee0012008-07-11 21:24:13 +00004051private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004052 CharUnits GetAlignOfExpr(const Expr *E);
4053 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004054 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004055 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004056 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004057};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004058} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004059
Richard Smithc49bd112011-10-28 17:51:58 +00004060/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4061/// produce either the integer value or a pointer.
4062///
4063/// GCC has a heinous extension which folds casts between pointer types and
4064/// pointer-sized integral types. We support this by allowing the evaluation of
4065/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4066/// Some simple arithmetic on such values is supported (they are treated much
4067/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004068static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004069 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004070 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004071 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004072}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004073
Richard Smithf48fdb02011-12-09 22:58:01 +00004074static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004075 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004076 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004077 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004078 if (!Val.isInt()) {
4079 // FIXME: It would be better to produce the diagnostic for casting
4080 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004081 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004082 return false;
4083 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004084 Result = Val.getInt();
4085 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004086}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004087
Richard Smithf48fdb02011-12-09 22:58:01 +00004088/// Check whether the given declaration can be directly converted to an integral
4089/// rvalue. If not, no diagnostic is produced; there are other things we can
4090/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004091bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004092 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004093 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004094 // Check for signedness/width mismatches between E type and ECD value.
4095 bool SameSign = (ECD->getInitVal().isSigned()
4096 == E->getType()->isSignedIntegerOrEnumerationType());
4097 bool SameWidth = (ECD->getInitVal().getBitWidth()
4098 == Info.Ctx.getIntWidth(E->getType()));
4099 if (SameSign && SameWidth)
4100 return Success(ECD->getInitVal(), E);
4101 else {
4102 // Get rid of mismatch (otherwise Success assertions will fail)
4103 // by computing a new value matching the type of E.
4104 llvm::APSInt Val = ECD->getInitVal();
4105 if (!SameSign)
4106 Val.setIsSigned(!ECD->getInitVal().isSigned());
4107 if (!SameWidth)
4108 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4109 return Success(Val, E);
4110 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004111 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004112 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004113}
4114
Chris Lattnera4d55d82008-10-06 06:40:35 +00004115/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4116/// as GCC.
4117static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4118 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004119 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004120 enum gcc_type_class {
4121 no_type_class = -1,
4122 void_type_class, integer_type_class, char_type_class,
4123 enumeral_type_class, boolean_type_class,
4124 pointer_type_class, reference_type_class, offset_type_class,
4125 real_type_class, complex_type_class,
4126 function_type_class, method_type_class,
4127 record_type_class, union_type_class,
4128 array_type_class, string_type_class,
4129 lang_type_class
4130 };
Mike Stump1eb44332009-09-09 15:08:12 +00004131
4132 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004133 // ideal, however it is what gcc does.
4134 if (E->getNumArgs() == 0)
4135 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Chris Lattnera4d55d82008-10-06 06:40:35 +00004137 QualType ArgTy = E->getArg(0)->getType();
4138 if (ArgTy->isVoidType())
4139 return void_type_class;
4140 else if (ArgTy->isEnumeralType())
4141 return enumeral_type_class;
4142 else if (ArgTy->isBooleanType())
4143 return boolean_type_class;
4144 else if (ArgTy->isCharType())
4145 return string_type_class; // gcc doesn't appear to use char_type_class
4146 else if (ArgTy->isIntegerType())
4147 return integer_type_class;
4148 else if (ArgTy->isPointerType())
4149 return pointer_type_class;
4150 else if (ArgTy->isReferenceType())
4151 return reference_type_class;
4152 else if (ArgTy->isRealType())
4153 return real_type_class;
4154 else if (ArgTy->isComplexType())
4155 return complex_type_class;
4156 else if (ArgTy->isFunctionType())
4157 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004158 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004159 return record_type_class;
4160 else if (ArgTy->isUnionType())
4161 return union_type_class;
4162 else if (ArgTy->isArrayType())
4163 return array_type_class;
4164 else if (ArgTy->isUnionType())
4165 return union_type_class;
4166 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004167 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004168}
4169
Richard Smith80d4b552011-12-28 19:48:30 +00004170/// EvaluateBuiltinConstantPForLValue - Determine the result of
4171/// __builtin_constant_p when applied to the given lvalue.
4172///
4173/// An lvalue is only "constant" if it is a pointer or reference to the first
4174/// character of a string literal.
4175template<typename LValue>
4176static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4177 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4178 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4179}
4180
4181/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4182/// GCC as we can manage.
4183static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4184 QualType ArgType = Arg->getType();
4185
4186 // __builtin_constant_p always has one operand. The rules which gcc follows
4187 // are not precisely documented, but are as follows:
4188 //
4189 // - If the operand is of integral, floating, complex or enumeration type,
4190 // and can be folded to a known value of that type, it returns 1.
4191 // - If the operand and can be folded to a pointer to the first character
4192 // of a string literal (or such a pointer cast to an integral type), it
4193 // returns 1.
4194 //
4195 // Otherwise, it returns 0.
4196 //
4197 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4198 // its support for this does not currently work.
4199 if (ArgType->isIntegralOrEnumerationType()) {
4200 Expr::EvalResult Result;
4201 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4202 return false;
4203
4204 APValue &V = Result.Val;
4205 if (V.getKind() == APValue::Int)
4206 return true;
4207
4208 return EvaluateBuiltinConstantPForLValue(V);
4209 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4210 return Arg->isEvaluatable(Ctx);
4211 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4212 LValue LV;
4213 Expr::EvalStatus Status;
4214 EvalInfo Info(Ctx, Status);
4215 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4216 : EvaluatePointer(Arg, LV, Info)) &&
4217 !Status.HasSideEffects)
4218 return EvaluateBuiltinConstantPForLValue(LV);
4219 }
4220
4221 // Anything else isn't considered to be sufficiently constant.
4222 return false;
4223}
4224
John McCall42c8f872010-05-10 23:27:23 +00004225/// Retrieves the "underlying object type" of the given expression,
4226/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004227QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4228 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4229 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004230 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004231 } else if (const Expr *E = B.get<const Expr*>()) {
4232 if (isa<CompoundLiteralExpr>(E))
4233 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004234 }
4235
4236 return QualType();
4237}
4238
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004239bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004240 // TODO: Perhaps we should let LLVM lower this?
4241 LValue Base;
4242 if (!EvaluatePointer(E->getArg(0), Base, Info))
4243 return false;
4244
4245 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004246 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004247
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004248 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004249 if (T.isNull() ||
4250 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004251 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004252 T->isVariablyModifiedType() ||
4253 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004254 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004255
4256 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4257 CharUnits Offset = Base.getLValueOffset();
4258
4259 if (!Offset.isNegative() && Offset <= Size)
4260 Size -= Offset;
4261 else
4262 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004263 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004264}
4265
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004266bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004267 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004268 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004269 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004270
4271 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004272 if (TryEvaluateBuiltinObjectSize(E))
4273 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004274
Eric Christopherb2aaf512010-01-19 22:58:35 +00004275 // If evaluating the argument has side-effects we can't determine
4276 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004277 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004278 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004279 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004280 return Success(0, E);
4281 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004282
Richard Smithf48fdb02011-12-09 22:58:01 +00004283 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004284 }
4285
Chris Lattner019f4e82008-10-06 05:28:25 +00004286 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004287 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004288
Richard Smith80d4b552011-12-28 19:48:30 +00004289 case Builtin::BI__builtin_constant_p:
4290 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004291
Chris Lattner21fb98e2009-09-23 06:06:36 +00004292 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004293 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004294 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004295 return Success(Operand, E);
4296 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004297
4298 case Builtin::BI__builtin_expect:
4299 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004300
Douglas Gregor5726d402010-09-10 06:27:15 +00004301 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004302 // A call to strlen is not a constant expression.
4303 if (Info.getLangOpts().CPlusPlus0x)
4304 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4305 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4306 else
4307 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4308 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004309 case Builtin::BI__builtin_strlen:
4310 // As an extension, we support strlen() and __builtin_strlen() as constant
4311 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004312 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004313 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4314 // The string literal may have embedded null characters. Find the first
4315 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004316 StringRef Str = S->getString();
4317 StringRef::size_type Pos = Str.find(0);
4318 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004319 Str = Str.substr(0, Pos);
4320
4321 return Success(Str.size(), E);
4322 }
4323
Richard Smithf48fdb02011-12-09 22:58:01 +00004324 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004325
4326 case Builtin::BI__atomic_is_lock_free: {
4327 APSInt SizeVal;
4328 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4329 return false;
4330
4331 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4332 // of two less than the maximum inline atomic width, we know it is
4333 // lock-free. If the size isn't a power of two, or greater than the
4334 // maximum alignment where we promote atomics, we know it is not lock-free
4335 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4336 // the answer can only be determined at runtime; for example, 16-byte
4337 // atomics have lock-free implementations on some, but not all,
4338 // x86-64 processors.
4339
4340 // Check power-of-two.
4341 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4342 if (!Size.isPowerOfTwo())
4343#if 0
4344 // FIXME: Suppress this folding until the ABI for the promotion width
4345 // settles.
4346 return Success(0, E);
4347#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004348 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004349#endif
4350
4351#if 0
4352 // Check against promotion width.
4353 // FIXME: Suppress this folding until the ABI for the promotion width
4354 // settles.
4355 unsigned PromoteWidthBits =
4356 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4357 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4358 return Success(0, E);
4359#endif
4360
4361 // Check against inlining width.
4362 unsigned InlineWidthBits =
4363 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4364 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4365 return Success(1, E);
4366
Richard Smithf48fdb02011-12-09 22:58:01 +00004367 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004368 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004369 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004370}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004371
Richard Smith625b8072011-10-31 01:37:14 +00004372static bool HasSameBase(const LValue &A, const LValue &B) {
4373 if (!A.getLValueBase())
4374 return !B.getLValueBase();
4375 if (!B.getLValueBase())
4376 return false;
4377
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004378 if (A.getLValueBase().getOpaqueValue() !=
4379 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004380 const Decl *ADecl = GetLValueBaseDecl(A);
4381 if (!ADecl)
4382 return false;
4383 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004384 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004385 return false;
4386 }
4387
4388 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004389 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004390}
4391
Richard Smith7b48a292012-02-01 05:53:12 +00004392/// Perform the given integer operation, which is known to need at most BitWidth
4393/// bits, and check for overflow in the original type (if that type was not an
4394/// unsigned type).
4395template<typename Operation>
4396static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4397 const APSInt &LHS, const APSInt &RHS,
4398 unsigned BitWidth, Operation Op) {
4399 if (LHS.isUnsigned())
4400 return Op(LHS, RHS);
4401
4402 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4403 APSInt Result = Value.trunc(LHS.getBitWidth());
4404 if (Result.extend(BitWidth) != Value)
4405 HandleOverflow(Info, E, Value, E->getType());
4406 return Result;
4407}
4408
Chris Lattnerb542afe2008-07-11 19:10:17 +00004409bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004410 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004411 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004412
John McCall2de56d12010-08-25 11:45:40 +00004413 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004414 VisitIgnoredValue(E->getLHS());
4415 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004416 }
4417
4418 if (E->isLogicalOp()) {
4419 // These need to be handled specially because the operands aren't
Richard Smith74e1ad92012-02-16 02:46:34 +00004420 // necessarily integral nor evaluated.
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004421 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Richard Smithc49bd112011-10-28 17:51:58 +00004423 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004424 // We were able to evaluate the LHS, see if we can get away with not
4425 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004426 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004427 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004428
Richard Smithc49bd112011-10-28 17:51:58 +00004429 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004430 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004431 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004432 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004433 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004434 }
4435 } else {
Richard Smith74e1ad92012-02-16 02:46:34 +00004436 // Since we weren't able to evaluate the left hand side, it
4437 // must have had side effects.
4438 Info.EvalStatus.HasSideEffects = true;
4439
4440 // Suppress diagnostics from this arm.
4441 SpeculativeEvaluationRAII Speculative(Info);
Richard Smithc49bd112011-10-28 17:51:58 +00004442 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004443 // We can't evaluate the LHS; however, sometimes the result
4444 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smith74e1ad92012-02-16 02:46:34 +00004445 if (rhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar131eb432009-02-19 09:06:44 +00004446 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004447 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004448 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004449
Eli Friedmana6afa762008-11-13 06:09:17 +00004450 return false;
4451 }
4452
Anders Carlsson286f85e2008-11-16 07:17:21 +00004453 QualType LHSTy = E->getLHS()->getType();
4454 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004455
4456 if (LHSTy->isAnyComplexType()) {
4457 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004458 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004459
Richard Smith745f5142012-01-27 01:14:48 +00004460 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4461 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004462 return false;
4463
Richard Smith745f5142012-01-27 01:14:48 +00004464 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004465 return false;
4466
4467 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004468 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004469 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004470 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004471 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4472
John McCall2de56d12010-08-25 11:45:40 +00004473 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004474 return Success((CR_r == APFloat::cmpEqual &&
4475 CR_i == APFloat::cmpEqual), E);
4476 else {
John McCall2de56d12010-08-25 11:45:40 +00004477 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004478 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004479 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004480 CR_r == APFloat::cmpLessThan ||
4481 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004482 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004483 CR_i == APFloat::cmpLessThan ||
4484 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004485 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004486 } else {
John McCall2de56d12010-08-25 11:45:40 +00004487 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004488 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4489 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4490 else {
John McCall2de56d12010-08-25 11:45:40 +00004491 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004492 "Invalid compex comparison.");
4493 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4494 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4495 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004496 }
4497 }
Mike Stump1eb44332009-09-09 15:08:12 +00004498
Anders Carlsson286f85e2008-11-16 07:17:21 +00004499 if (LHSTy->isRealFloatingType() &&
4500 RHSTy->isRealFloatingType()) {
4501 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004502
Richard Smith745f5142012-01-27 01:14:48 +00004503 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4504 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004505 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004506
Richard Smith745f5142012-01-27 01:14:48 +00004507 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004508 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Anders Carlsson286f85e2008-11-16 07:17:21 +00004510 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004511
Anders Carlsson286f85e2008-11-16 07:17:21 +00004512 switch (E->getOpcode()) {
4513 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004514 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004515 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004516 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004517 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004518 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004519 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004520 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004521 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004522 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004523 E);
John McCall2de56d12010-08-25 11:45:40 +00004524 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004525 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004526 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004527 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004528 || CR == APFloat::cmpLessThan
4529 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004530 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004531 }
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004533 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004534 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004535 LValue LHSValue, RHSValue;
4536
4537 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4538 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004539 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004540
Richard Smith745f5142012-01-27 01:14:48 +00004541 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004542 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004543
Richard Smith625b8072011-10-31 01:37:14 +00004544 // Reject differing bases from the normal codepath; we special-case
4545 // comparisons to null.
4546 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004547 if (E->getOpcode() == BO_Sub) {
4548 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004549 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4550 return false;
4551 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4552 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4553 if (!LHSExpr || !RHSExpr)
4554 return false;
4555 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4556 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4557 if (!LHSAddrExpr || !RHSAddrExpr)
4558 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004559 // Make sure both labels come from the same function.
4560 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4561 RHSAddrExpr->getLabel()->getDeclContext())
4562 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004563 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4564 return true;
4565 }
Richard Smith9e36b532011-10-31 05:11:32 +00004566 // Inequalities and subtractions between unrelated pointers have
4567 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004568 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004569 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004570 // A constant address may compare equal to the address of a symbol.
4571 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004572 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004573 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4574 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004575 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004576 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004577 // distinct addresses. In clang, the result of such a comparison is
4578 // unspecified, so it is not a constant expression. However, we do know
4579 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004580 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4581 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004582 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004583 // We can't tell whether weak symbols will end up pointing to the same
4584 // object.
4585 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004586 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004587 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004588 // (Note that clang defaults to -fmerge-all-constants, which can
4589 // lead to inconsistent results for comparisons involving the address
4590 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004591 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004592 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004593
Richard Smith15efc4d2012-02-01 08:10:20 +00004594 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4595 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4596
Richard Smithf15fda02012-02-02 01:16:57 +00004597 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4598 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4599
John McCall2de56d12010-08-25 11:45:40 +00004600 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004601 // C++11 [expr.add]p6:
4602 // Unless both pointers point to elements of the same array object, or
4603 // one past the last element of the array object, the behavior is
4604 // undefined.
4605 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4606 !AreElementsOfSameArray(getType(LHSValue.Base),
4607 LHSDesignator, RHSDesignator))
4608 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4609
Chris Lattner4992bdd2010-04-20 17:13:14 +00004610 QualType Type = E->getLHS()->getType();
4611 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004612
Richard Smith180f4792011-11-10 06:34:14 +00004613 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004614 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004615 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004616
Richard Smith15efc4d2012-02-01 08:10:20 +00004617 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4618 // and produce incorrect results when it overflows. Such behavior
4619 // appears to be non-conforming, but is common, so perhaps we should
4620 // assume the standard intended for such cases to be undefined behavior
4621 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004622
Richard Smith15efc4d2012-02-01 08:10:20 +00004623 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4624 // overflow in the final conversion to ptrdiff_t.
4625 APSInt LHS(
4626 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4627 APSInt RHS(
4628 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4629 APSInt ElemSize(
4630 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4631 APSInt TrueResult = (LHS - RHS) / ElemSize;
4632 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4633
4634 if (Result.extend(65) != TrueResult)
4635 HandleOverflow(Info, E, TrueResult, E->getType());
4636 return Success(Result, E);
4637 }
Richard Smith82f28582012-01-31 06:41:30 +00004638
4639 // C++11 [expr.rel]p3:
4640 // Pointers to void (after pointer conversions) can be compared, with a
4641 // result defined as follows: If both pointers represent the same
4642 // address or are both the null pointer value, the result is true if the
4643 // operator is <= or >= and false otherwise; otherwise the result is
4644 // unspecified.
4645 // We interpret this as applying to pointers to *cv* void.
4646 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004647 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004648 CCEDiag(E, diag::note_constexpr_void_comparison);
4649
Richard Smithf15fda02012-02-02 01:16:57 +00004650 // C++11 [expr.rel]p2:
4651 // - If two pointers point to non-static data members of the same object,
4652 // or to subobjects or array elements fo such members, recursively, the
4653 // pointer to the later declared member compares greater provided the
4654 // two members have the same access control and provided their class is
4655 // not a union.
4656 // [...]
4657 // - Otherwise pointer comparisons are unspecified.
4658 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4659 E->isRelationalOp()) {
4660 bool WasArrayIndex;
4661 unsigned Mismatch =
4662 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4663 RHSDesignator, WasArrayIndex);
4664 // At the point where the designators diverge, the comparison has a
4665 // specified value if:
4666 // - we are comparing array indices
4667 // - we are comparing fields of a union, or fields with the same access
4668 // Otherwise, the result is unspecified and thus the comparison is not a
4669 // constant expression.
4670 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4671 Mismatch < RHSDesignator.Entries.size()) {
4672 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4673 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4674 if (!LF && !RF)
4675 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4676 else if (!LF)
4677 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4678 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4679 << RF->getParent() << RF;
4680 else if (!RF)
4681 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4682 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4683 << LF->getParent() << LF;
4684 else if (!LF->getParent()->isUnion() &&
4685 LF->getAccess() != RF->getAccess())
4686 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4687 << LF << LF->getAccess() << RF << RF->getAccess()
4688 << LF->getParent();
4689 }
4690 }
4691
Richard Smith625b8072011-10-31 01:37:14 +00004692 switch (E->getOpcode()) {
4693 default: llvm_unreachable("missing comparison operator");
4694 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4695 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4696 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4697 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4698 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4699 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004700 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004701 }
4702 }
Richard Smithb02e4622012-02-01 01:42:44 +00004703
4704 if (LHSTy->isMemberPointerType()) {
4705 assert(E->isEqualityOp() && "unexpected member pointer operation");
4706 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4707
4708 MemberPtr LHSValue, RHSValue;
4709
4710 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4711 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4712 return false;
4713
4714 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4715 return false;
4716
4717 // C++11 [expr.eq]p2:
4718 // If both operands are null, they compare equal. Otherwise if only one is
4719 // null, they compare unequal.
4720 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4721 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4722 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4723 }
4724
4725 // Otherwise if either is a pointer to a virtual member function, the
4726 // result is unspecified.
4727 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4728 if (MD->isVirtual())
4729 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4730 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4731 if (MD->isVirtual())
4732 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4733
4734 // Otherwise they compare equal if and only if they would refer to the
4735 // same member of the same most derived object or the same subobject if
4736 // they were dereferenced with a hypothetical object of the associated
4737 // class type.
4738 bool Equal = LHSValue == RHSValue;
4739 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4740 }
4741
Richard Smith26f2cac2012-02-14 22:35:28 +00004742 if (LHSTy->isNullPtrType()) {
4743 assert(E->isComparisonOp() && "unexpected nullptr operation");
4744 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4745 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4746 // are compared, the result is true of the operator is <=, >= or ==, and
4747 // false otherwise.
4748 BinaryOperator::Opcode Opcode = E->getOpcode();
4749 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4750 }
4751
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004752 if (!LHSTy->isIntegralOrEnumerationType() ||
4753 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004754 // We can't continue from here for non-integral types.
4755 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004756 }
4757
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004758 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004759 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004760
4761 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4762 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004763 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004764
Richard Smith745f5142012-01-27 01:14:48 +00004765 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004766 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004767
Richard Smith47a1eed2011-10-29 20:57:55 +00004768 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004769
4770 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004771 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004772 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4773 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004774 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004775 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004776 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004777 LHSVal.getLValueOffset() -= AdditionalOffset;
4778 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004779 return true;
4780 }
4781
4782 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004783 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004784 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004785 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4786 LHSVal.getInt().getZExtValue());
4787 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004788 return true;
4789 }
4790
Eli Friedman65639282012-01-04 23:13:47 +00004791 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4792 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004793 if (!LHSVal.getLValueOffset().isZero() ||
4794 !RHSVal.getLValueOffset().isZero())
4795 return false;
4796 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4797 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4798 if (!LHSExpr || !RHSExpr)
4799 return false;
4800 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4801 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4802 if (!LHSAddrExpr || !RHSAddrExpr)
4803 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004804 // Make sure both labels come from the same function.
4805 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4806 RHSAddrExpr->getLabel()->getDeclContext())
4807 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004808 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4809 return true;
4810 }
4811
Eli Friedman42edd0d2009-03-24 01:14:50 +00004812 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004813 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004814 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004815
Richard Smithc49bd112011-10-28 17:51:58 +00004816 APSInt &LHS = LHSVal.getInt();
4817 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004818
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004819 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004820 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004821 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004822 case BO_Mul:
4823 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4824 LHS.getBitWidth() * 2,
4825 std::multiplies<APSInt>()), E);
4826 case BO_Add:
4827 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4828 LHS.getBitWidth() + 1,
4829 std::plus<APSInt>()), E);
4830 case BO_Sub:
4831 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4832 LHS.getBitWidth() + 1,
4833 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004834 case BO_And: return Success(LHS & RHS, E);
4835 case BO_Xor: return Success(LHS ^ RHS, E);
4836 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004837 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004838 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004839 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004840 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004841 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4842 // actually undefined behavior in C++11 due to a language defect.
4843 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4844 LHS.isSigned() && LHS.isMinSignedValue())
4845 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4846 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004847 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004848 // During constant-folding, a negative shift is an opposite shift. Such a
4849 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004850 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004851 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004852 RHS = -RHS;
4853 goto shift_right;
4854 }
4855
4856 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004857 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4858 // shifted type.
4859 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4860 if (SA != RHS) {
4861 CCEDiag(E, diag::note_constexpr_large_shift)
4862 << RHS << E->getType() << LHS.getBitWidth();
4863 } else if (LHS.isSigned()) {
4864 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004865 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004866 if (LHS.isNegative())
4867 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004868 else if (LHS.countLeadingZeros() < SA)
4869 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004870 }
4871
Richard Smithc49bd112011-10-28 17:51:58 +00004872 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004873 }
John McCall2de56d12010-08-25 11:45:40 +00004874 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004875 // During constant-folding, a negative shift is an opposite shift. Such a
4876 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004877 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004878 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004879 RHS = -RHS;
4880 goto shift_left;
4881 }
4882
4883 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004884 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4885 // shifted type.
4886 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4887 if (SA != RHS)
4888 CCEDiag(E, diag::note_constexpr_large_shift)
4889 << RHS << E->getType() << LHS.getBitWidth();
4890
Richard Smithc49bd112011-10-28 17:51:58 +00004891 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004892 }
Mike Stump1eb44332009-09-09 15:08:12 +00004893
Richard Smithc49bd112011-10-28 17:51:58 +00004894 case BO_LT: return Success(LHS < RHS, E);
4895 case BO_GT: return Success(LHS > RHS, E);
4896 case BO_LE: return Success(LHS <= RHS, E);
4897 case BO_GE: return Success(LHS >= RHS, E);
4898 case BO_EQ: return Success(LHS == RHS, E);
4899 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004900 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004901}
4902
Ken Dyck8b752f12010-01-27 17:10:57 +00004903CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004904 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4905 // result shall be the alignment of the referenced type."
4906 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4907 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004908
4909 // __alignof is defined to return the preferred alignment.
4910 return Info.Ctx.toCharUnitsFromBits(
4911 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004912}
4913
Ken Dyck8b752f12010-01-27 17:10:57 +00004914CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004915 E = E->IgnoreParens();
4916
4917 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004918 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004919 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004920 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4921 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004922
Chris Lattneraf707ab2009-01-24 21:53:27 +00004923 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004924 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4925 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004926
Chris Lattnere9feb472009-01-24 21:09:06 +00004927 return GetAlignOfType(E->getType());
4928}
4929
4930
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004931/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4932/// a result as the expression's type.
4933bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4934 const UnaryExprOrTypeTraitExpr *E) {
4935 switch(E->getKind()) {
4936 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004937 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004938 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004939 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004940 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004941 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004942
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004943 case UETT_VecStep: {
4944 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004945
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004946 if (Ty->isVectorType()) {
4947 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004948
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004949 // The vec_step built-in functions that take a 3-component
4950 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4951 if (n == 3)
4952 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004953
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004954 return Success(n, E);
4955 } else
4956 return Success(1, E);
4957 }
4958
4959 case UETT_SizeOf: {
4960 QualType SrcTy = E->getTypeOfArgument();
4961 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4962 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004963 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4964 SrcTy = Ref->getPointeeType();
4965
Richard Smith180f4792011-11-10 06:34:14 +00004966 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00004967 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004968 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004969 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004970 }
4971 }
4972
4973 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004974}
4975
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004976bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004977 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004978 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004979 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004980 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004981 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004982 for (unsigned i = 0; i != n; ++i) {
4983 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4984 switch (ON.getKind()) {
4985 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004986 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004987 APSInt IdxResult;
4988 if (!EvaluateInteger(Idx, IdxResult, Info))
4989 return false;
4990 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4991 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004992 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004993 CurrentType = AT->getElementType();
4994 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4995 Result += IdxResult.getSExtValue() * ElementSize;
4996 break;
4997 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004998
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004999 case OffsetOfExpr::OffsetOfNode::Field: {
5000 FieldDecl *MemberDecl = ON.getField();
5001 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005002 if (!RT)
5003 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005004 RecordDecl *RD = RT->getDecl();
5005 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005006 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005007 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005008 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005009 CurrentType = MemberDecl->getType().getNonReferenceType();
5010 break;
5011 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005012
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005013 case OffsetOfExpr::OffsetOfNode::Identifier:
5014 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005015
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005016 case OffsetOfExpr::OffsetOfNode::Base: {
5017 CXXBaseSpecifier *BaseSpec = ON.getBase();
5018 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005019 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005020
5021 // Find the layout of the class whose base we are looking into.
5022 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005023 if (!RT)
5024 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005025 RecordDecl *RD = RT->getDecl();
5026 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5027
5028 // Find the base class itself.
5029 CurrentType = BaseSpec->getType();
5030 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5031 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005032 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005033
5034 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005035 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005036 break;
5037 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005038 }
5039 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005040 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005041}
5042
Chris Lattnerb542afe2008-07-11 19:10:17 +00005043bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005044 switch (E->getOpcode()) {
5045 default:
5046 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5047 // See C99 6.6p3.
5048 return Error(E);
5049 case UO_Extension:
5050 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5051 // If so, we could clear the diagnostic ID.
5052 return Visit(E->getSubExpr());
5053 case UO_Plus:
5054 // The result is just the value.
5055 return Visit(E->getSubExpr());
5056 case UO_Minus: {
5057 if (!Visit(E->getSubExpr()))
5058 return false;
5059 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005060 const APSInt &Value = Result.getInt();
5061 if (Value.isSigned() && Value.isMinSignedValue())
5062 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5063 E->getType());
5064 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005065 }
5066 case UO_Not: {
5067 if (!Visit(E->getSubExpr()))
5068 return false;
5069 if (!Result.isInt()) return Error(E);
5070 return Success(~Result.getInt(), E);
5071 }
5072 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005073 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005074 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005075 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005076 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005077 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005078 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005079}
Mike Stump1eb44332009-09-09 15:08:12 +00005080
Chris Lattner732b2232008-07-12 01:15:53 +00005081/// HandleCast - This is used to evaluate implicit or explicit casts where the
5082/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005083bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5084 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005085 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005086 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005087
Eli Friedman46a52322011-03-25 00:43:55 +00005088 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005089 case CK_BaseToDerived:
5090 case CK_DerivedToBase:
5091 case CK_UncheckedDerivedToBase:
5092 case CK_Dynamic:
5093 case CK_ToUnion:
5094 case CK_ArrayToPointerDecay:
5095 case CK_FunctionToPointerDecay:
5096 case CK_NullToPointer:
5097 case CK_NullToMemberPointer:
5098 case CK_BaseToDerivedMemberPointer:
5099 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005100 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005101 case CK_ConstructorConversion:
5102 case CK_IntegralToPointer:
5103 case CK_ToVoid:
5104 case CK_VectorSplat:
5105 case CK_IntegralToFloating:
5106 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005107 case CK_CPointerToObjCPointerCast:
5108 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005109 case CK_AnyPointerToBlockPointerCast:
5110 case CK_ObjCObjectLValueCast:
5111 case CK_FloatingRealToComplex:
5112 case CK_FloatingComplexToReal:
5113 case CK_FloatingComplexCast:
5114 case CK_FloatingComplexToIntegralComplex:
5115 case CK_IntegralRealToComplex:
5116 case CK_IntegralComplexCast:
5117 case CK_IntegralComplexToFloatingComplex:
5118 llvm_unreachable("invalid cast kind for integral value");
5119
Eli Friedmane50c2972011-03-25 19:07:11 +00005120 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005121 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005122 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005123 case CK_ARCProduceObject:
5124 case CK_ARCConsumeObject:
5125 case CK_ARCReclaimReturnedObject:
5126 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005127 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005128
Richard Smith7d580a42012-01-17 21:17:26 +00005129 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005130 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005131 case CK_AtomicToNonAtomic:
5132 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005133 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005134 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005135
5136 case CK_MemberPointerToBoolean:
5137 case CK_PointerToBoolean:
5138 case CK_IntegralToBoolean:
5139 case CK_FloatingToBoolean:
5140 case CK_FloatingComplexToBoolean:
5141 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005142 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005143 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005144 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005145 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005146 }
5147
Eli Friedman46a52322011-03-25 00:43:55 +00005148 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005149 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005150 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005151
Eli Friedmanbe265702009-02-20 01:15:07 +00005152 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005153 // Allow casts of address-of-label differences if they are no-ops
5154 // or narrowing. (The narrowing case isn't actually guaranteed to
5155 // be constant-evaluatable except in some narrow cases which are hard
5156 // to detect here. We let it through on the assumption the user knows
5157 // what they are doing.)
5158 if (Result.isAddrLabelDiff())
5159 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005160 // Only allow casts of lvalues if they are lossless.
5161 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5162 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005163
Richard Smithf72fccf2012-01-30 22:27:01 +00005164 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5165 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005166 }
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Eli Friedman46a52322011-03-25 00:43:55 +00005168 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005169 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5170
John McCallefdb83e2010-05-07 21:00:08 +00005171 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005172 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005173 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005174
Daniel Dunbardd211642009-02-19 22:24:01 +00005175 if (LV.getLValueBase()) {
5176 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005177 // FIXME: Allow a larger integer size than the pointer size, and allow
5178 // narrowing back down to pointer width in subsequent integral casts.
5179 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005180 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005181 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005182
Richard Smithb755a9d2011-11-16 07:18:12 +00005183 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005184 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005185 return true;
5186 }
5187
Ken Dycka7305832010-01-15 12:37:54 +00005188 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5189 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005190 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005191 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005192
Eli Friedman46a52322011-03-25 00:43:55 +00005193 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005194 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005195 if (!EvaluateComplex(SubExpr, C, Info))
5196 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005197 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005198 }
Eli Friedman2217c872009-02-22 11:46:18 +00005199
Eli Friedman46a52322011-03-25 00:43:55 +00005200 case CK_FloatingToIntegral: {
5201 APFloat F(0.0);
5202 if (!EvaluateFloat(SubExpr, F, Info))
5203 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005204
Richard Smithc1c5f272011-12-13 06:39:58 +00005205 APSInt Value;
5206 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5207 return false;
5208 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005209 }
5210 }
Mike Stump1eb44332009-09-09 15:08:12 +00005211
Eli Friedman46a52322011-03-25 00:43:55 +00005212 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005213}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005214
Eli Friedman722c7172009-02-28 03:59:05 +00005215bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5216 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005217 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005218 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5219 return false;
5220 if (!LV.isComplexInt())
5221 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005222 return Success(LV.getComplexIntReal(), E);
5223 }
5224
5225 return Visit(E->getSubExpr());
5226}
5227
Eli Friedman664a1042009-02-27 04:45:43 +00005228bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005229 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005230 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005231 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5232 return false;
5233 if (!LV.isComplexInt())
5234 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005235 return Success(LV.getComplexIntImag(), E);
5236 }
5237
Richard Smith8327fad2011-10-24 18:44:57 +00005238 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005239 return Success(0, E);
5240}
5241
Douglas Gregoree8aff02011-01-04 17:33:58 +00005242bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5243 return Success(E->getPackLength(), E);
5244}
5245
Sebastian Redl295995c2010-09-10 20:55:47 +00005246bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5247 return Success(E->getValue(), E);
5248}
5249
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005250//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005251// Float Evaluation
5252//===----------------------------------------------------------------------===//
5253
5254namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005255class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005256 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005257 APFloat &Result;
5258public:
5259 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005260 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005261
Richard Smith47a1eed2011-10-29 20:57:55 +00005262 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005263 Result = V.getFloat();
5264 return true;
5265 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005266
Richard Smith51201882011-12-30 21:15:51 +00005267 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005268 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5269 return true;
5270 }
5271
Chris Lattner019f4e82008-10-06 05:28:25 +00005272 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005273
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005274 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005275 bool VisitBinaryOperator(const BinaryOperator *E);
5276 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005277 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005278
John McCallabd3a852010-05-07 22:08:54 +00005279 bool VisitUnaryReal(const UnaryOperator *E);
5280 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005281
Richard Smith51201882011-12-30 21:15:51 +00005282 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005283};
5284} // end anonymous namespace
5285
5286static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005287 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005288 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005289}
5290
Jay Foad4ba2a172011-01-12 09:06:06 +00005291static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005292 QualType ResultTy,
5293 const Expr *Arg,
5294 bool SNaN,
5295 llvm::APFloat &Result) {
5296 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5297 if (!S) return false;
5298
5299 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5300
5301 llvm::APInt fill;
5302
5303 // Treat empty strings as if they were zero.
5304 if (S->getString().empty())
5305 fill = llvm::APInt(32, 0);
5306 else if (S->getString().getAsInteger(0, fill))
5307 return false;
5308
5309 if (SNaN)
5310 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5311 else
5312 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5313 return true;
5314}
5315
Chris Lattner019f4e82008-10-06 05:28:25 +00005316bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005317 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005318 default:
5319 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5320
Chris Lattner019f4e82008-10-06 05:28:25 +00005321 case Builtin::BI__builtin_huge_val:
5322 case Builtin::BI__builtin_huge_valf:
5323 case Builtin::BI__builtin_huge_vall:
5324 case Builtin::BI__builtin_inf:
5325 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005326 case Builtin::BI__builtin_infl: {
5327 const llvm::fltSemantics &Sem =
5328 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005329 Result = llvm::APFloat::getInf(Sem);
5330 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005331 }
Mike Stump1eb44332009-09-09 15:08:12 +00005332
John McCalldb7b72a2010-02-28 13:00:19 +00005333 case Builtin::BI__builtin_nans:
5334 case Builtin::BI__builtin_nansf:
5335 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005336 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5337 true, Result))
5338 return Error(E);
5339 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005340
Chris Lattner9e621712008-10-06 06:31:58 +00005341 case Builtin::BI__builtin_nan:
5342 case Builtin::BI__builtin_nanf:
5343 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005344 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005345 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005346 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5347 false, Result))
5348 return Error(E);
5349 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005350
5351 case Builtin::BI__builtin_fabs:
5352 case Builtin::BI__builtin_fabsf:
5353 case Builtin::BI__builtin_fabsl:
5354 if (!EvaluateFloat(E->getArg(0), Result, Info))
5355 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005356
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005357 if (Result.isNegative())
5358 Result.changeSign();
5359 return true;
5360
Mike Stump1eb44332009-09-09 15:08:12 +00005361 case Builtin::BI__builtin_copysign:
5362 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005363 case Builtin::BI__builtin_copysignl: {
5364 APFloat RHS(0.);
5365 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5366 !EvaluateFloat(E->getArg(1), RHS, Info))
5367 return false;
5368 Result.copySign(RHS);
5369 return true;
5370 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005371 }
5372}
5373
John McCallabd3a852010-05-07 22:08:54 +00005374bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005375 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5376 ComplexValue CV;
5377 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5378 return false;
5379 Result = CV.FloatReal;
5380 return true;
5381 }
5382
5383 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005384}
5385
5386bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005387 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5388 ComplexValue CV;
5389 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5390 return false;
5391 Result = CV.FloatImag;
5392 return true;
5393 }
5394
Richard Smith8327fad2011-10-24 18:44:57 +00005395 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005396 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5397 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005398 return true;
5399}
5400
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005401bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005402 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005403 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005404 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005405 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005406 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005407 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5408 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005409 Result.changeSign();
5410 return true;
5411 }
5412}
Chris Lattner019f4e82008-10-06 05:28:25 +00005413
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005414bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005415 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5416 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005417
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005418 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005419 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5420 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005421 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005422 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005423 return false;
5424
5425 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005426 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005427 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005428 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005429 break;
John McCall2de56d12010-08-25 11:45:40 +00005430 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005431 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005432 break;
John McCall2de56d12010-08-25 11:45:40 +00005433 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005434 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005435 break;
John McCall2de56d12010-08-25 11:45:40 +00005436 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005437 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005438 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005439 }
Richard Smith7b48a292012-02-01 05:53:12 +00005440
5441 if (Result.isInfinity() || Result.isNaN())
5442 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5443 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005444}
5445
5446bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5447 Result = E->getValue();
5448 return true;
5449}
5450
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005451bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5452 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005453
Eli Friedman2a523ee2011-03-25 00:54:52 +00005454 switch (E->getCastKind()) {
5455 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005456 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005457
5458 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005459 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005460 return EvaluateInteger(SubExpr, IntResult, Info) &&
5461 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5462 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005463 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005464
5465 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005466 if (!Visit(SubExpr))
5467 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005468 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5469 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005470 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005471
Eli Friedman2a523ee2011-03-25 00:54:52 +00005472 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005473 ComplexValue V;
5474 if (!EvaluateComplex(SubExpr, V, Info))
5475 return false;
5476 Result = V.getComplexFloatReal();
5477 return true;
5478 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005479 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005480}
5481
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005482//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005483// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005484//===----------------------------------------------------------------------===//
5485
5486namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005487class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005488 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005489 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005490
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005491public:
John McCallf4cf1a12010-05-07 17:22:02 +00005492 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005493 : ExprEvaluatorBaseTy(info), Result(Result) {}
5494
Richard Smith47a1eed2011-10-29 20:57:55 +00005495 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005496 Result.setFrom(V);
5497 return true;
5498 }
Mike Stump1eb44332009-09-09 15:08:12 +00005499
Eli Friedman7ead5c72012-01-10 04:58:17 +00005500 bool ZeroInitialization(const Expr *E);
5501
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005502 //===--------------------------------------------------------------------===//
5503 // Visitor Methods
5504 //===--------------------------------------------------------------------===//
5505
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005506 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005507 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005508 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005509 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005510 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005511};
5512} // end anonymous namespace
5513
John McCallf4cf1a12010-05-07 17:22:02 +00005514static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5515 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005516 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005517 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005518}
5519
Eli Friedman7ead5c72012-01-10 04:58:17 +00005520bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005521 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005522 if (ElemTy->isRealFloatingType()) {
5523 Result.makeComplexFloat();
5524 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5525 Result.FloatReal = Zero;
5526 Result.FloatImag = Zero;
5527 } else {
5528 Result.makeComplexInt();
5529 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5530 Result.IntReal = Zero;
5531 Result.IntImag = Zero;
5532 }
5533 return true;
5534}
5535
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005536bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5537 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005538
5539 if (SubExpr->getType()->isRealFloatingType()) {
5540 Result.makeComplexFloat();
5541 APFloat &Imag = Result.FloatImag;
5542 if (!EvaluateFloat(SubExpr, Imag, Info))
5543 return false;
5544
5545 Result.FloatReal = APFloat(Imag.getSemantics());
5546 return true;
5547 } else {
5548 assert(SubExpr->getType()->isIntegerType() &&
5549 "Unexpected imaginary literal.");
5550
5551 Result.makeComplexInt();
5552 APSInt &Imag = Result.IntImag;
5553 if (!EvaluateInteger(SubExpr, Imag, Info))
5554 return false;
5555
5556 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5557 return true;
5558 }
5559}
5560
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005561bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005562
John McCall8786da72010-12-14 17:51:41 +00005563 switch (E->getCastKind()) {
5564 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005565 case CK_BaseToDerived:
5566 case CK_DerivedToBase:
5567 case CK_UncheckedDerivedToBase:
5568 case CK_Dynamic:
5569 case CK_ToUnion:
5570 case CK_ArrayToPointerDecay:
5571 case CK_FunctionToPointerDecay:
5572 case CK_NullToPointer:
5573 case CK_NullToMemberPointer:
5574 case CK_BaseToDerivedMemberPointer:
5575 case CK_DerivedToBaseMemberPointer:
5576 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005577 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005578 case CK_ConstructorConversion:
5579 case CK_IntegralToPointer:
5580 case CK_PointerToIntegral:
5581 case CK_PointerToBoolean:
5582 case CK_ToVoid:
5583 case CK_VectorSplat:
5584 case CK_IntegralCast:
5585 case CK_IntegralToBoolean:
5586 case CK_IntegralToFloating:
5587 case CK_FloatingToIntegral:
5588 case CK_FloatingToBoolean:
5589 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005590 case CK_CPointerToObjCPointerCast:
5591 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005592 case CK_AnyPointerToBlockPointerCast:
5593 case CK_ObjCObjectLValueCast:
5594 case CK_FloatingComplexToReal:
5595 case CK_FloatingComplexToBoolean:
5596 case CK_IntegralComplexToReal:
5597 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005598 case CK_ARCProduceObject:
5599 case CK_ARCConsumeObject:
5600 case CK_ARCReclaimReturnedObject:
5601 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005602 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005603
John McCall8786da72010-12-14 17:51:41 +00005604 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005605 case CK_AtomicToNonAtomic:
5606 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005607 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005608 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005609
5610 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005611 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005612 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005613 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005614
5615 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005616 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005617 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005618 return false;
5619
John McCall8786da72010-12-14 17:51:41 +00005620 Result.makeComplexFloat();
5621 Result.FloatImag = APFloat(Real.getSemantics());
5622 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005623 }
5624
John McCall8786da72010-12-14 17:51:41 +00005625 case CK_FloatingComplexCast: {
5626 if (!Visit(E->getSubExpr()))
5627 return false;
5628
5629 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5630 QualType From
5631 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5632
Richard Smithc1c5f272011-12-13 06:39:58 +00005633 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5634 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005635 }
5636
5637 case CK_FloatingComplexToIntegralComplex: {
5638 if (!Visit(E->getSubExpr()))
5639 return false;
5640
5641 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5642 QualType From
5643 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5644 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005645 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5646 To, Result.IntReal) &&
5647 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5648 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005649 }
5650
5651 case CK_IntegralRealToComplex: {
5652 APSInt &Real = Result.IntReal;
5653 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5654 return false;
5655
5656 Result.makeComplexInt();
5657 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5658 return true;
5659 }
5660
5661 case CK_IntegralComplexCast: {
5662 if (!Visit(E->getSubExpr()))
5663 return false;
5664
5665 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5666 QualType From
5667 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5668
Richard Smithf72fccf2012-01-30 22:27:01 +00005669 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5670 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005671 return true;
5672 }
5673
5674 case CK_IntegralComplexToFloatingComplex: {
5675 if (!Visit(E->getSubExpr()))
5676 return false;
5677
5678 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5679 QualType From
5680 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5681 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005682 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5683 To, Result.FloatReal) &&
5684 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5685 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005686 }
5687 }
5688
5689 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005690}
5691
John McCallf4cf1a12010-05-07 17:22:02 +00005692bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005693 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005694 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5695
Richard Smith745f5142012-01-27 01:14:48 +00005696 bool LHSOK = Visit(E->getLHS());
5697 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005698 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005699
John McCallf4cf1a12010-05-07 17:22:02 +00005700 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005701 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005702 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005703
Daniel Dunbar3f279872009-01-29 01:32:56 +00005704 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5705 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005706 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005707 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005708 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005709 if (Result.isComplexFloat()) {
5710 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5711 APFloat::rmNearestTiesToEven);
5712 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5713 APFloat::rmNearestTiesToEven);
5714 } else {
5715 Result.getComplexIntReal() += RHS.getComplexIntReal();
5716 Result.getComplexIntImag() += RHS.getComplexIntImag();
5717 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005718 break;
John McCall2de56d12010-08-25 11:45:40 +00005719 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005720 if (Result.isComplexFloat()) {
5721 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5722 APFloat::rmNearestTiesToEven);
5723 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5724 APFloat::rmNearestTiesToEven);
5725 } else {
5726 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5727 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5728 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005729 break;
John McCall2de56d12010-08-25 11:45:40 +00005730 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005731 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005732 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005733 APFloat &LHS_r = LHS.getComplexFloatReal();
5734 APFloat &LHS_i = LHS.getComplexFloatImag();
5735 APFloat &RHS_r = RHS.getComplexFloatReal();
5736 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005737
Daniel Dunbar3f279872009-01-29 01:32:56 +00005738 APFloat Tmp = LHS_r;
5739 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5740 Result.getComplexFloatReal() = Tmp;
5741 Tmp = LHS_i;
5742 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5743 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5744
5745 Tmp = LHS_r;
5746 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5747 Result.getComplexFloatImag() = Tmp;
5748 Tmp = LHS_i;
5749 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5750 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5751 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005752 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005753 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005754 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5755 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005756 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005757 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5758 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5759 }
5760 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005761 case BO_Div:
5762 if (Result.isComplexFloat()) {
5763 ComplexValue LHS = Result;
5764 APFloat &LHS_r = LHS.getComplexFloatReal();
5765 APFloat &LHS_i = LHS.getComplexFloatImag();
5766 APFloat &RHS_r = RHS.getComplexFloatReal();
5767 APFloat &RHS_i = RHS.getComplexFloatImag();
5768 APFloat &Res_r = Result.getComplexFloatReal();
5769 APFloat &Res_i = Result.getComplexFloatImag();
5770
5771 APFloat Den = RHS_r;
5772 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5773 APFloat Tmp = RHS_i;
5774 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5775 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5776
5777 Res_r = LHS_r;
5778 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5779 Tmp = LHS_i;
5780 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5781 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5782 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5783
5784 Res_i = LHS_i;
5785 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5786 Tmp = LHS_r;
5787 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5788 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5789 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5790 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005791 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5792 return Error(E, diag::note_expr_divide_by_zero);
5793
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005794 ComplexValue LHS = Result;
5795 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5796 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5797 Result.getComplexIntReal() =
5798 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5799 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5800 Result.getComplexIntImag() =
5801 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5802 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5803 }
5804 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005805 }
5806
John McCallf4cf1a12010-05-07 17:22:02 +00005807 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005808}
5809
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005810bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5811 // Get the operand value into 'Result'.
5812 if (!Visit(E->getSubExpr()))
5813 return false;
5814
5815 switch (E->getOpcode()) {
5816 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005817 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005818 case UO_Extension:
5819 return true;
5820 case UO_Plus:
5821 // The result is always just the subexpr.
5822 return true;
5823 case UO_Minus:
5824 if (Result.isComplexFloat()) {
5825 Result.getComplexFloatReal().changeSign();
5826 Result.getComplexFloatImag().changeSign();
5827 }
5828 else {
5829 Result.getComplexIntReal() = -Result.getComplexIntReal();
5830 Result.getComplexIntImag() = -Result.getComplexIntImag();
5831 }
5832 return true;
5833 case UO_Not:
5834 if (Result.isComplexFloat())
5835 Result.getComplexFloatImag().changeSign();
5836 else
5837 Result.getComplexIntImag() = -Result.getComplexIntImag();
5838 return true;
5839 }
5840}
5841
Eli Friedman7ead5c72012-01-10 04:58:17 +00005842bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5843 if (E->getNumInits() == 2) {
5844 if (E->getType()->isComplexType()) {
5845 Result.makeComplexFloat();
5846 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5847 return false;
5848 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5849 return false;
5850 } else {
5851 Result.makeComplexInt();
5852 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5853 return false;
5854 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5855 return false;
5856 }
5857 return true;
5858 }
5859 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5860}
5861
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005862//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005863// Void expression evaluation, primarily for a cast to void on the LHS of a
5864// comma operator
5865//===----------------------------------------------------------------------===//
5866
5867namespace {
5868class VoidExprEvaluator
5869 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5870public:
5871 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5872
5873 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005874
5875 bool VisitCastExpr(const CastExpr *E) {
5876 switch (E->getCastKind()) {
5877 default:
5878 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5879 case CK_ToVoid:
5880 VisitIgnoredValue(E->getSubExpr());
5881 return true;
5882 }
5883 }
5884};
5885} // end anonymous namespace
5886
5887static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5888 assert(E->isRValue() && E->getType()->isVoidType());
5889 return VoidExprEvaluator(Info).Visit(E);
5890}
5891
5892//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005893// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005894//===----------------------------------------------------------------------===//
5895
Richard Smith47a1eed2011-10-29 20:57:55 +00005896static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005897 // In C, function designators are not lvalues, but we evaluate them as if they
5898 // are.
5899 if (E->isGLValue() || E->getType()->isFunctionType()) {
5900 LValue LV;
5901 if (!EvaluateLValue(E, LV, Info))
5902 return false;
5903 LV.moveInto(Result);
5904 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005905 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005906 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005907 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005908 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005909 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005910 } else if (E->getType()->hasPointerRepresentation()) {
5911 LValue LV;
5912 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005913 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005914 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005915 } else if (E->getType()->isRealFloatingType()) {
5916 llvm::APFloat F(0.0);
5917 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005918 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005919 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005920 } else if (E->getType()->isAnyComplexType()) {
5921 ComplexValue C;
5922 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005923 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005924 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005925 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005926 MemberPtr P;
5927 if (!EvaluateMemberPointer(E, P, Info))
5928 return false;
5929 P.moveInto(Result);
5930 return true;
Richard Smith51201882011-12-30 21:15:51 +00005931 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005932 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005933 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005934 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005935 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005936 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005937 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005938 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005939 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005940 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5941 return false;
5942 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005943 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005944 if (Info.getLangOpts().CPlusPlus0x)
5945 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5946 << E->getType();
5947 else
5948 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005949 if (!EvaluateVoid(E, Info))
5950 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005951 } else if (Info.getLangOpts().CPlusPlus0x) {
5952 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5953 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005954 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005955 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005956 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005957 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005958
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005959 return true;
5960}
5961
Richard Smith83587db2012-02-15 02:18:13 +00005962/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
5963/// cases, the in-place evaluation is essential, since later initializers for
5964/// an object can indirectly refer to subobjects which were initialized earlier.
5965static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
5966 const Expr *E, CheckConstantExpressionKind CCEK,
5967 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00005968 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00005969 return false;
5970
5971 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005972 // Evaluate arrays and record types in-place, so that later initializers can
5973 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005974 if (E->getType()->isArrayType())
5975 return EvaluateArray(E, This, Result, Info);
5976 else if (E->getType()->isRecordType())
5977 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005978 }
5979
5980 // For any other type, in-place evaluation is unimportant.
5981 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00005982 if (!Evaluate(CoreConstResult, Info, E))
5983 return false;
5984 Result = CoreConstResult.toAPValue();
5985 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00005986}
5987
Richard Smithf48fdb02011-12-09 22:58:01 +00005988/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5989/// lvalue-to-rvalue cast if it is an lvalue.
5990static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005991 if (!CheckLiteralType(Info, E))
5992 return false;
5993
Richard Smithf48fdb02011-12-09 22:58:01 +00005994 CCValue Value;
5995 if (!::Evaluate(Value, Info, E))
5996 return false;
5997
5998 if (E->isGLValue()) {
5999 LValue LV;
6000 LV.setFrom(Value);
6001 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
6002 return false;
6003 }
6004
6005 // Check this core constant expression is a constant expression, and if so,
6006 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006007 Result = Value.toAPValue();
6008 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006009}
Richard Smithc49bd112011-10-28 17:51:58 +00006010
Richard Smith51f47082011-10-29 00:50:52 +00006011/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006012/// any crazy technique (that has nothing to do with language standards) that
6013/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006014/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6015/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006016bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006017 // Fast-path evaluations of integer literals, since we sometimes see files
6018 // containing vast quantities of these.
6019 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6020 Result.Val = APValue(APSInt(L->getValue(),
6021 L->getType()->isUnsignedIntegerType()));
6022 return true;
6023 }
6024
Richard Smith2d6a5672012-01-14 04:30:29 +00006025 // FIXME: Evaluating values of large array and record types can cause
6026 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006027 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6028 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006029 return false;
6030
Richard Smithf48fdb02011-12-09 22:58:01 +00006031 EvalInfo Info(Ctx, Result);
6032 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006033}
6034
Jay Foad4ba2a172011-01-12 09:06:06 +00006035bool Expr::EvaluateAsBooleanCondition(bool &Result,
6036 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006037 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006038 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006039 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6040 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006041 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006042}
6043
Richard Smith80d4b552011-12-28 19:48:30 +00006044bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6045 SideEffectsKind AllowSideEffects) const {
6046 if (!getType()->isIntegralOrEnumerationType())
6047 return false;
6048
Richard Smithc49bd112011-10-28 17:51:58 +00006049 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006050 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6051 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006052 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006053
Richard Smithc49bd112011-10-28 17:51:58 +00006054 Result = ExprResult.Val.getInt();
6055 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006056}
6057
Jay Foad4ba2a172011-01-12 09:06:06 +00006058bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006059 EvalInfo Info(Ctx, Result);
6060
John McCallefdb83e2010-05-07 21:00:08 +00006061 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006062 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6063 !CheckLValueConstantExpression(Info, getExprLoc(),
6064 Ctx.getLValueReferenceType(getType()), LV))
6065 return false;
6066
6067 CCValue Tmp;
6068 LV.moveInto(Tmp);
6069 Result.Val = Tmp.toAPValue();
6070 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006071}
6072
Richard Smith099e7f62011-12-19 06:19:21 +00006073bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6074 const VarDecl *VD,
6075 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006076 // FIXME: Evaluating initializers for large array and record types can cause
6077 // performance problems. Only do so in C++11 for now.
6078 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6079 !Ctx.getLangOptions().CPlusPlus0x)
6080 return false;
6081
Richard Smith099e7f62011-12-19 06:19:21 +00006082 Expr::EvalStatus EStatus;
6083 EStatus.Diag = &Notes;
6084
6085 EvalInfo InitInfo(Ctx, EStatus);
6086 InitInfo.setEvaluatingDecl(VD, Value);
6087
6088 LValue LVal;
6089 LVal.set(VD);
6090
Richard Smith51201882011-12-30 21:15:51 +00006091 // C++11 [basic.start.init]p2:
6092 // Variables with static storage duration or thread storage duration shall be
6093 // zero-initialized before any other initialization takes place.
6094 // This behavior is not present in C.
6095 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6096 !VD->getType()->isReferenceType()) {
6097 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006098 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6099 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006100 return false;
6101 }
6102
Richard Smith83587db2012-02-15 02:18:13 +00006103 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6104 /*AllowNonLiteralTypes=*/true) ||
6105 EStatus.HasSideEffects)
6106 return false;
6107
6108 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6109 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006110}
6111
Richard Smith51f47082011-10-29 00:50:52 +00006112/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6113/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006114bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006115 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006116 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006117}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006118
Jay Foad4ba2a172011-01-12 09:06:06 +00006119bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006120 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006121}
6122
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006123APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006124 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006125 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006126 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006127 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006128 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006129
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006130 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006131}
John McCalld905f5a2010-05-07 05:32:02 +00006132
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006133 bool Expr::EvalResult::isGlobalLValue() const {
6134 assert(Val.isLValue());
6135 return IsGlobalLValue(Val.getLValueBase());
6136 }
6137
6138
John McCalld905f5a2010-05-07 05:32:02 +00006139/// isIntegerConstantExpr - this recursive routine will test if an expression is
6140/// an integer constant expression.
6141
6142/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6143/// comma, etc
6144///
6145/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6146/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6147/// cast+dereference.
6148
6149// CheckICE - This function does the fundamental ICE checking: the returned
6150// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6151// Note that to reduce code duplication, this helper does no evaluation
6152// itself; the caller checks whether the expression is evaluatable, and
6153// in the rare cases where CheckICE actually cares about the evaluated
6154// value, it calls into Evalute.
6155//
6156// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006157// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006158// 1: This expression is not an ICE, but if it isn't evaluated, it's
6159// a legal subexpression for an ICE. This return value is used to handle
6160// the comma operator in C99 mode.
6161// 2: This expression is not an ICE, and is not a legal subexpression for one.
6162
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006163namespace {
6164
John McCalld905f5a2010-05-07 05:32:02 +00006165struct ICEDiag {
6166 unsigned Val;
6167 SourceLocation Loc;
6168
6169 public:
6170 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6171 ICEDiag() : Val(0) {}
6172};
6173
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006174}
6175
6176static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006177
6178static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6179 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006180 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006181 !EVResult.Val.isInt()) {
6182 return ICEDiag(2, E->getLocStart());
6183 }
6184 return NoDiag();
6185}
6186
6187static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6188 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006189 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006190 return ICEDiag(2, E->getLocStart());
6191 }
6192
6193 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006194#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006195#define STMT(Node, Base) case Expr::Node##Class:
6196#define EXPR(Node, Base)
6197#include "clang/AST/StmtNodes.inc"
6198 case Expr::PredefinedExprClass:
6199 case Expr::FloatingLiteralClass:
6200 case Expr::ImaginaryLiteralClass:
6201 case Expr::StringLiteralClass:
6202 case Expr::ArraySubscriptExprClass:
6203 case Expr::MemberExprClass:
6204 case Expr::CompoundAssignOperatorClass:
6205 case Expr::CompoundLiteralExprClass:
6206 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006207 case Expr::DesignatedInitExprClass:
6208 case Expr::ImplicitValueInitExprClass:
6209 case Expr::ParenListExprClass:
6210 case Expr::VAArgExprClass:
6211 case Expr::AddrLabelExprClass:
6212 case Expr::StmtExprClass:
6213 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006214 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006215 case Expr::CXXDynamicCastExprClass:
6216 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006217 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006218 case Expr::CXXNullPtrLiteralExprClass:
6219 case Expr::CXXThisExprClass:
6220 case Expr::CXXThrowExprClass:
6221 case Expr::CXXNewExprClass:
6222 case Expr::CXXDeleteExprClass:
6223 case Expr::CXXPseudoDestructorExprClass:
6224 case Expr::UnresolvedLookupExprClass:
6225 case Expr::DependentScopeDeclRefExprClass:
6226 case Expr::CXXConstructExprClass:
6227 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006228 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006229 case Expr::CXXTemporaryObjectExprClass:
6230 case Expr::CXXUnresolvedConstructExprClass:
6231 case Expr::CXXDependentScopeMemberExprClass:
6232 case Expr::UnresolvedMemberExprClass:
6233 case Expr::ObjCStringLiteralClass:
6234 case Expr::ObjCEncodeExprClass:
6235 case Expr::ObjCMessageExprClass:
6236 case Expr::ObjCSelectorExprClass:
6237 case Expr::ObjCProtocolExprClass:
6238 case Expr::ObjCIvarRefExprClass:
6239 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006240 case Expr::ObjCIsaExprClass:
6241 case Expr::ShuffleVectorExprClass:
6242 case Expr::BlockExprClass:
6243 case Expr::BlockDeclRefExprClass:
6244 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006245 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006246 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006247 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006248 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006249 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006250 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006251 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006252 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006253 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006254 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006255 return ICEDiag(2, E->getLocStart());
6256
Douglas Gregoree8aff02011-01-04 17:33:58 +00006257 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006258 case Expr::GNUNullExprClass:
6259 // GCC considers the GNU __null value to be an integral constant expression.
6260 return NoDiag();
6261
John McCall91a57552011-07-15 05:09:51 +00006262 case Expr::SubstNonTypeTemplateParmExprClass:
6263 return
6264 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6265
John McCalld905f5a2010-05-07 05:32:02 +00006266 case Expr::ParenExprClass:
6267 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006268 case Expr::GenericSelectionExprClass:
6269 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006270 case Expr::IntegerLiteralClass:
6271 case Expr::CharacterLiteralClass:
6272 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006273 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006274 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006275 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006276 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006277 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006278 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006279 return NoDiag();
6280 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006281 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006282 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6283 // constant expressions, but they can never be ICEs because an ICE cannot
6284 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006285 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006286 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006287 return CheckEvalInICE(E, Ctx);
6288 return ICEDiag(2, E->getLocStart());
6289 }
6290 case Expr::DeclRefExprClass:
6291 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6292 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006293 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006294 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6295
6296 // Parameter variables are never constants. Without this check,
6297 // getAnyInitializer() can find a default argument, which leads
6298 // to chaos.
6299 if (isa<ParmVarDecl>(D))
6300 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6301
6302 // C++ 7.1.5.1p2
6303 // A variable of non-volatile const-qualified integral or enumeration
6304 // type initialized by an ICE can be used in ICEs.
6305 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006306 if (!Dcl->getType()->isIntegralOrEnumerationType())
6307 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6308
Richard Smith099e7f62011-12-19 06:19:21 +00006309 const VarDecl *VD;
6310 // Look for a declaration of this variable that has an initializer, and
6311 // check whether it is an ICE.
6312 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6313 return NoDiag();
6314 else
6315 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006316 }
6317 }
6318 return ICEDiag(2, E->getLocStart());
6319 case Expr::UnaryOperatorClass: {
6320 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6321 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006322 case UO_PostInc:
6323 case UO_PostDec:
6324 case UO_PreInc:
6325 case UO_PreDec:
6326 case UO_AddrOf:
6327 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006328 // C99 6.6/3 allows increment and decrement within unevaluated
6329 // subexpressions of constant expressions, but they can never be ICEs
6330 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006331 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006332 case UO_Extension:
6333 case UO_LNot:
6334 case UO_Plus:
6335 case UO_Minus:
6336 case UO_Not:
6337 case UO_Real:
6338 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006339 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006340 }
6341
6342 // OffsetOf falls through here.
6343 }
6344 case Expr::OffsetOfExprClass: {
6345 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006346 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006347 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006348 // compliance: we should warn earlier for offsetof expressions with
6349 // array subscripts that aren't ICEs, and if the array subscripts
6350 // are ICEs, the value of the offsetof must be an integer constant.
6351 return CheckEvalInICE(E, Ctx);
6352 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006353 case Expr::UnaryExprOrTypeTraitExprClass: {
6354 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6355 if ((Exp->getKind() == UETT_SizeOf) &&
6356 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006357 return ICEDiag(2, E->getLocStart());
6358 return NoDiag();
6359 }
6360 case Expr::BinaryOperatorClass: {
6361 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6362 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006363 case BO_PtrMemD:
6364 case BO_PtrMemI:
6365 case BO_Assign:
6366 case BO_MulAssign:
6367 case BO_DivAssign:
6368 case BO_RemAssign:
6369 case BO_AddAssign:
6370 case BO_SubAssign:
6371 case BO_ShlAssign:
6372 case BO_ShrAssign:
6373 case BO_AndAssign:
6374 case BO_XorAssign:
6375 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006376 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6377 // constant expressions, but they can never be ICEs because an ICE cannot
6378 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006379 return ICEDiag(2, E->getLocStart());
6380
John McCall2de56d12010-08-25 11:45:40 +00006381 case BO_Mul:
6382 case BO_Div:
6383 case BO_Rem:
6384 case BO_Add:
6385 case BO_Sub:
6386 case BO_Shl:
6387 case BO_Shr:
6388 case BO_LT:
6389 case BO_GT:
6390 case BO_LE:
6391 case BO_GE:
6392 case BO_EQ:
6393 case BO_NE:
6394 case BO_And:
6395 case BO_Xor:
6396 case BO_Or:
6397 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006398 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6399 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006400 if (Exp->getOpcode() == BO_Div ||
6401 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006402 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006403 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006404 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006405 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006406 if (REval == 0)
6407 return ICEDiag(1, E->getLocStart());
6408 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006409 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006410 if (LEval.isMinSignedValue())
6411 return ICEDiag(1, E->getLocStart());
6412 }
6413 }
6414 }
John McCall2de56d12010-08-25 11:45:40 +00006415 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006416 if (Ctx.getLangOptions().C99) {
6417 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6418 // if it isn't evaluated.
6419 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6420 return ICEDiag(1, E->getLocStart());
6421 } else {
6422 // In both C89 and C++, commas in ICEs are illegal.
6423 return ICEDiag(2, E->getLocStart());
6424 }
6425 }
6426 if (LHSResult.Val >= RHSResult.Val)
6427 return LHSResult;
6428 return RHSResult;
6429 }
John McCall2de56d12010-08-25 11:45:40 +00006430 case BO_LAnd:
6431 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006432 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6433 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6434 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6435 // Rare case where the RHS has a comma "side-effect"; we need
6436 // to actually check the condition to see whether the side
6437 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006438 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006439 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006440 return RHSResult;
6441 return NoDiag();
6442 }
6443
6444 if (LHSResult.Val >= RHSResult.Val)
6445 return LHSResult;
6446 return RHSResult;
6447 }
6448 }
6449 }
6450 case Expr::ImplicitCastExprClass:
6451 case Expr::CStyleCastExprClass:
6452 case Expr::CXXFunctionalCastExprClass:
6453 case Expr::CXXStaticCastExprClass:
6454 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006455 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006456 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006457 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006458 if (isa<ExplicitCastExpr>(E)) {
6459 if (const FloatingLiteral *FL
6460 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6461 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6462 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6463 APSInt IgnoredVal(DestWidth, !DestSigned);
6464 bool Ignored;
6465 // If the value does not fit in the destination type, the behavior is
6466 // undefined, so we are not required to treat it as a constant
6467 // expression.
6468 if (FL->getValue().convertToInteger(IgnoredVal,
6469 llvm::APFloat::rmTowardZero,
6470 &Ignored) & APFloat::opInvalidOp)
6471 return ICEDiag(2, E->getLocStart());
6472 return NoDiag();
6473 }
6474 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006475 switch (cast<CastExpr>(E)->getCastKind()) {
6476 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006477 case CK_AtomicToNonAtomic:
6478 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006479 case CK_NoOp:
6480 case CK_IntegralToBoolean:
6481 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006482 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006483 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006484 return ICEDiag(2, E->getLocStart());
6485 }
John McCalld905f5a2010-05-07 05:32:02 +00006486 }
John McCall56ca35d2011-02-17 10:25:35 +00006487 case Expr::BinaryConditionalOperatorClass: {
6488 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6489 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6490 if (CommonResult.Val == 2) return CommonResult;
6491 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6492 if (FalseResult.Val == 2) return FalseResult;
6493 if (CommonResult.Val == 1) return CommonResult;
6494 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006495 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006496 return FalseResult;
6497 }
John McCalld905f5a2010-05-07 05:32:02 +00006498 case Expr::ConditionalOperatorClass: {
6499 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6500 // If the condition (ignoring parens) is a __builtin_constant_p call,
6501 // then only the true side is actually considered in an integer constant
6502 // expression, and it is fully evaluated. This is an important GNU
6503 // extension. See GCC PR38377 for discussion.
6504 if (const CallExpr *CallCE
6505 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006506 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6507 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006508 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006509 if (CondResult.Val == 2)
6510 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006511
Richard Smithf48fdb02011-12-09 22:58:01 +00006512 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6513 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006514
John McCalld905f5a2010-05-07 05:32:02 +00006515 if (TrueResult.Val == 2)
6516 return TrueResult;
6517 if (FalseResult.Val == 2)
6518 return FalseResult;
6519 if (CondResult.Val == 1)
6520 return CondResult;
6521 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6522 return NoDiag();
6523 // Rare case where the diagnostics depend on which side is evaluated
6524 // Note that if we get here, CondResult is 0, and at least one of
6525 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006526 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006527 return FalseResult;
6528 }
6529 return TrueResult;
6530 }
6531 case Expr::CXXDefaultArgExprClass:
6532 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6533 case Expr::ChooseExprClass: {
6534 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6535 }
6536 }
6537
David Blaikie30263482012-01-20 21:50:17 +00006538 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006539}
6540
Richard Smithf48fdb02011-12-09 22:58:01 +00006541/// Evaluate an expression as a C++11 integral constant expression.
6542static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6543 const Expr *E,
6544 llvm::APSInt *Value,
6545 SourceLocation *Loc) {
6546 if (!E->getType()->isIntegralOrEnumerationType()) {
6547 if (Loc) *Loc = E->getExprLoc();
6548 return false;
6549 }
6550
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006551 APValue Result;
6552 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006553 return false;
6554
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006555 assert(Result.isInt() && "pointer cast to int is not an ICE");
6556 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006557 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006558}
6559
Richard Smithdd1f29b2011-12-12 09:28:41 +00006560bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006561 if (Ctx.getLangOptions().CPlusPlus0x)
6562 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6563
John McCalld905f5a2010-05-07 05:32:02 +00006564 ICEDiag d = CheckICE(this, Ctx);
6565 if (d.Val != 0) {
6566 if (Loc) *Loc = d.Loc;
6567 return false;
6568 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006569 return true;
6570}
6571
6572bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6573 SourceLocation *Loc, bool isEvaluated) const {
6574 if (Ctx.getLangOptions().CPlusPlus0x)
6575 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6576
6577 if (!isIntegerConstantExpr(Ctx, Loc))
6578 return false;
6579 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006580 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006581 return true;
6582}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006583
Richard Smith70488e22012-02-14 21:38:30 +00006584bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6585 return CheckICE(this, Ctx).Val == 0;
6586}
6587
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006588bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6589 SourceLocation *Loc) const {
6590 // We support this checking in C++98 mode in order to diagnose compatibility
6591 // issues.
6592 assert(Ctx.getLangOptions().CPlusPlus);
6593
Richard Smith70488e22012-02-14 21:38:30 +00006594 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006595 Expr::EvalStatus Status;
6596 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6597 Status.Diag = &Diags;
6598 EvalInfo Info(Ctx, Status);
6599
6600 APValue Scratch;
6601 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6602
6603 if (!Diags.empty()) {
6604 IsConstExpr = false;
6605 if (Loc) *Loc = Diags[0].first;
6606 } else if (!IsConstExpr) {
6607 // FIXME: This shouldn't happen.
6608 if (Loc) *Loc = getExprLoc();
6609 }
6610
6611 return IsConstExpr;
6612}
Richard Smith745f5142012-01-27 01:14:48 +00006613
6614bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6615 llvm::SmallVectorImpl<
6616 PartialDiagnosticAt> &Diags) {
6617 // FIXME: It would be useful to check constexpr function templates, but at the
6618 // moment the constant expression evaluator cannot cope with the non-rigorous
6619 // ASTs which we build for dependent expressions.
6620 if (FD->isDependentContext())
6621 return true;
6622
6623 Expr::EvalStatus Status;
6624 Status.Diag = &Diags;
6625
6626 EvalInfo Info(FD->getASTContext(), Status);
6627 Info.CheckingPotentialConstantExpression = true;
6628
6629 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6630 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6631
6632 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6633 // is a temporary being used as the 'this' pointer.
6634 LValue This;
6635 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006636 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006637
Richard Smith745f5142012-01-27 01:14:48 +00006638 ArrayRef<const Expr*> Args;
6639
6640 SourceLocation Loc = FD->getLocation();
6641
6642 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006643 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006644 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006645 } else {
6646 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006647 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6648 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006649 }
Richard Smith745f5142012-01-27 01:14:48 +00006650
6651 return Diags.empty();
6652}