blob: 135e70e96ad6cb3d14ea44a73a35a9ee9dd4a0bb [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-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 Smith253c2a32012-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
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
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 Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000051#define DEBUG_TYPE "exprconstant"
52
Anders Carlsson7a241ba2008-07-03 04:20:39 +000053using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000054using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000055using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000056
Richard Smithb228a862012-02-15 02:18:13 +000057static bool IsGlobalLValue(APValue::LValueBase B);
58
John McCall93d91dc2010-05-07 17:22:02 +000059namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000060 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000061 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000062 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000063
Richard Smithb228a862012-02-15 02:18:13 +000064 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000065 if (!B) return QualType();
66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
Richard Smith6f4f0f12017-10-20 22:56:25 +000067 // FIXME: It's unclear where we're supposed to take the type from, and
68 // this actually matters for arrays of unknown bound. Using the type of
69 // the most recent declaration isn't clearly correct in general. Eg:
70 //
71 // extern int arr[]; void f() { extern int arr[3]; };
72 // constexpr int *p = &arr[1]; // valid?
73 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
Richard Smith84401042013-06-03 05:03:02 +000074
75 const Expr *Base = B.get<const Expr*>();
76
77 // For a materialized temporary, the type of the temporary we materialized
78 // may not be the type of the expression.
79 if (const MaterializeTemporaryExpr *MTE =
80 dyn_cast<MaterializeTemporaryExpr>(Base)) {
81 SmallVector<const Expr *, 2> CommaLHSs;
82 SmallVector<SubobjectAdjustment, 2> Adjustments;
83 const Expr *Temp = MTE->GetTemporaryExpr();
84 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
85 Adjustments);
86 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000087 // for it directly. Otherwise use the type after adjustment.
88 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000089 return Inner->getType();
90 }
91
92 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000093 }
94
Richard Smithd62306a2011-11-10 06:34:14 +000095 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000096 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000097 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000098 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000099 APValue::BaseOrMemberType Value;
100 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000101 return Value;
102 }
103
104 /// Get an LValue path entry, which is known to not be an array index, as a
105 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000106 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000107 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000108 }
109 /// Get an LValue path entry, which is known to not be an array index, as a
110 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000111 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000112 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000113 }
114 /// Determine whether this LValue path entry for a base class names a virtual
115 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119
George Burgess IVe3763372016-12-22 02:50:20 +0000120 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
121 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
122 const FunctionDecl *Callee = CE->getDirectCallee();
123 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124 }
125
126 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127 /// This will look through a single cast.
128 ///
129 /// Returns null if we couldn't unwrap a function with alloc_size.
130 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131 if (!E->getType()->isPointerType())
132 return nullptr;
133
134 E = E->IgnoreParens();
135 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV9753b792018-03-06 07:42:36 +0000136 // probably be a cast of some kind. In exotic cases, we might also see a
137 // top-level ExprWithCleanups. Ignore them either way.
138 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
139 E = EC->getSubExpr()->IgnoreParens();
140
George Burgess IVe3763372016-12-22 02:50:20 +0000141 if (const auto *Cast = dyn_cast<CastExpr>(E))
142 E = Cast->getSubExpr()->IgnoreParens();
143
144 if (const auto *CE = dyn_cast<CallExpr>(E))
145 return getAllocSizeAttr(CE) ? CE : nullptr;
146 return nullptr;
147 }
148
149 /// Determines whether or not the given Base contains a call to a function
150 /// with the alloc_size attribute.
151 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
152 const auto *E = Base.dyn_cast<const Expr *>();
153 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
154 }
155
Richard Smith6f4f0f12017-10-20 22:56:25 +0000156 /// The bound to claim that an array of unknown bound has.
157 /// The value in MostDerivedArraySize is undefined in this case. So, set it
158 /// to an arbitrary value that's likely to loudly break things if it's used.
159 static const uint64_t AssumedSizeForUnsizedArray =
160 std::numeric_limits<uint64_t>::max() / 2;
161
George Burgess IVe3763372016-12-22 02:50:20 +0000162 /// Determines if an LValue with the given LValueBase will have an unsized
163 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000164 /// Find the path length and type of the most-derived subobject in the given
165 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000166 static unsigned
167 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
168 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000169 uint64_t &ArraySize, QualType &Type, bool &IsArray,
170 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000171 // This only accepts LValueBases from APValues, and APValues don't support
172 // arrays that lack size info.
173 assert(!isBaseAnAllocSizeCall(Base) &&
174 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000175 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000176 Type = getType(Base);
177
Richard Smith80815602011-11-07 05:07:52 +0000178 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000179 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000180 const ArrayType *AT = Ctx.getAsArrayType(Type);
181 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000182 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000183 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000184
185 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
186 ArraySize = CAT->getSize().getZExtValue();
187 } else {
188 assert(I == 0 && "unexpected unsized array designator");
189 FirstEntryIsUnsizedArray = true;
190 ArraySize = AssumedSizeForUnsizedArray;
191 }
Richard Smith66c96992012-02-18 22:04:06 +0000192 } else if (Type->isAnyComplexType()) {
193 const ComplexType *CT = Type->castAs<ComplexType>();
194 Type = CT->getElementType();
195 ArraySize = 2;
196 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000197 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 } else if (const FieldDecl *FD = getAsField(Path[I])) {
199 Type = FD->getType();
200 ArraySize = 0;
201 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 } else {
Richard Smith80815602011-11-07 05:07:52 +0000204 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 }
Richard Smith80815602011-11-07 05:07:52 +0000208 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000210 }
211
Richard Smitha8105bc2012-01-06 16:39:00 +0000212 // The order of this enum is important for diagnostics.
213 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000214 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000215 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000216 };
217
Richard Smith96e0c102011-11-04 02:25:55 +0000218 /// A path from a glvalue to a subobject of that glvalue.
219 struct SubobjectDesignator {
220 /// True if the subobject was named in a manner not supported by C++11. Such
221 /// lvalues can still be folded, but they are not core constant expressions
222 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000223 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000224
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000226 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000227
Daniel Jasperffdee092017-05-02 19:21:42 +0000228 /// Indicator of whether the first entry is an unsized array.
229 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000230
George Burgess IVa51c4072015-10-16 01:49:01 +0000231 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000232 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000233
Richard Smitha8105bc2012-01-06 16:39:00 +0000234 /// The length of the path to the most-derived object of which this is a
235 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000236 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000237
George Burgess IVa51c4072015-10-16 01:49:01 +0000238 /// The size of the array of which the most-derived object is an element.
239 /// This will always be 0 if the most-derived object is not an array
240 /// element. 0 is not an indicator of whether or not the most-derived object
241 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000242 ///
243 /// If the current array is an unsized array, the value of this is
244 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 uint64_t MostDerivedArraySize;
246
247 /// The type of the most derived object referred to by this address.
248 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000249
Richard Smith80815602011-11-07 05:07:52 +0000250 typedef APValue::LValuePathEntry PathEntry;
251
Richard Smith96e0c102011-11-04 02:25:55 +0000252 /// The entries on the path from the glvalue to the designated subobject.
253 SmallVector<PathEntry, 8> Entries;
254
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000256
Richard Smitha8105bc2012-01-06 16:39:00 +0000257 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000258 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000259 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000260 MostDerivedPathLength(0), MostDerivedArraySize(0),
261 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000262
263 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000264 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000265 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000266 MostDerivedPathLength(0), MostDerivedArraySize(0) {
267 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000268 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000269 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000270 ArrayRef<PathEntry> VEntries = V.getLValuePath();
271 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 if (V.getLValueBase()) {
273 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000274 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000275 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000276 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000277 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000278 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000279 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000280 }
Richard Smith80815602011-11-07 05:07:52 +0000281 }
282 }
283
Richard Smith96e0c102011-11-04 02:25:55 +0000284 void setInvalid() {
285 Invalid = true;
286 Entries.clear();
287 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000288
George Burgess IVe3763372016-12-22 02:50:20 +0000289 /// Determine whether the most derived subobject is an array without a
290 /// known bound.
291 bool isMostDerivedAnUnsizedArray() const {
292 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000293 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000294 }
295
296 /// Determine what the most derived array's size is. Results in an assertion
297 /// failure if the most derived array lacks a size.
298 uint64_t getMostDerivedArraySize() const {
299 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
300 return MostDerivedArraySize;
301 }
302
Richard Smitha8105bc2012-01-06 16:39:00 +0000303 /// Determine whether this is a one-past-the-end pointer.
304 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000305 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000306 if (IsOnePastTheEnd)
307 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000308 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000309 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
310 return true;
311 return false;
312 }
313
314 /// Check that this refers to a valid subobject.
315 bool isValidSubobject() const {
316 if (Invalid)
317 return false;
318 return !isOnePastTheEnd();
319 }
320 /// Check that this refers to a valid subobject, and if not, produce a
321 /// relevant diagnostic and set the designator as invalid.
322 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
323
324 /// Update this designator to refer to the first element within this array.
325 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000326 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000327 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000328 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000329
330 // This is a most-derived object.
331 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000332 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000333 MostDerivedArraySize = CAT->getSize().getZExtValue();
334 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000335 }
George Burgess IVe3763372016-12-22 02:50:20 +0000336 /// Update this designator to refer to the first element within the array of
337 /// elements of type T. This is an array of unknown size.
338 void addUnsizedArrayUnchecked(QualType ElemTy) {
339 PathEntry Entry;
340 Entry.ArrayIndex = 0;
341 Entries.push_back(Entry);
342
343 MostDerivedType = ElemTy;
344 MostDerivedIsArrayElement = true;
345 // The value in MostDerivedArraySize is undefined in this case. So, set it
346 // to an arbitrary value that's likely to loudly break things if it's
347 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000348 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000349 MostDerivedPathLength = Entries.size();
350 }
Richard Smith96e0c102011-11-04 02:25:55 +0000351 /// Update this designator to refer to the given base or member of this
352 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000353 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000354 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000355 APValue::BaseOrMemberType Value(D, Virtual);
356 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000357 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000358
359 // If this isn't a base class, it's a new most-derived object.
360 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
361 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000362 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000363 MostDerivedArraySize = 0;
364 MostDerivedPathLength = Entries.size();
365 }
Richard Smith96e0c102011-11-04 02:25:55 +0000366 }
Richard Smith66c96992012-02-18 22:04:06 +0000367 /// Update this designator to refer to the given complex component.
368 void addComplexUnchecked(QualType EltTy, bool Imag) {
369 PathEntry Entry;
370 Entry.ArrayIndex = Imag;
371 Entries.push_back(Entry);
372
373 // This is technically a most-derived object, though in practice this
374 // is unlikely to matter.
375 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000376 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000377 MostDerivedArraySize = 2;
378 MostDerivedPathLength = Entries.size();
379 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000380 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000381 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
382 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000383 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000384 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
385 if (Invalid || !N) return;
386 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
387 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000388 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000389 // Can't verify -- trust that the user is doing the right thing (or if
390 // not, trust that the caller will catch the bad behavior).
391 // FIXME: Should we reject if this overflows, at least?
392 Entries.back().ArrayIndex += TruncatedN;
393 return;
394 }
395
396 // [expr.add]p4: For the purposes of these operators, a pointer to a
397 // nonarray object behaves the same as a pointer to the first element of
398 // an array of length one with the type of the object as its element type.
399 bool IsArray = MostDerivedPathLength == Entries.size() &&
400 MostDerivedIsArrayElement;
401 uint64_t ArrayIndex =
402 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
403 uint64_t ArraySize =
404 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
405
406 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
407 // Calculate the actual index in a wide enough type, so we can include
408 // it in the note.
409 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
410 (llvm::APInt&)N += ArrayIndex;
411 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
412 diagnosePointerArithmetic(Info, E, N);
413 setInvalid();
414 return;
415 }
416
417 ArrayIndex += TruncatedN;
418 assert(ArrayIndex <= ArraySize &&
419 "bounds check succeeded for out-of-bounds index");
420
421 if (IsArray)
422 Entries.back().ArrayIndex = ArrayIndex;
423 else
424 IsOnePastTheEnd = (ArrayIndex != 0);
425 }
Richard Smith96e0c102011-11-04 02:25:55 +0000426 };
427
Richard Smith254a73d2011-10-28 22:34:42 +0000428 /// A stack frame in the constexpr call stack.
429 struct CallStackFrame {
430 EvalInfo &Info;
431
432 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000433 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000434
Richard Smithf6f003a2011-12-16 19:06:07 +0000435 /// Callee - The function which was called.
436 const FunctionDecl *Callee;
437
Richard Smithd62306a2011-11-10 06:34:14 +0000438 /// This - The binding for the this pointer in this call, if any.
439 const LValue *This;
440
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000441 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000442 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000443 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000444
Eli Friedman4830ec82012-06-25 21:21:08 +0000445 // Note that we intentionally use std::map here so that references to
446 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000447 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000448 typedef MapTy::const_iterator temp_iterator;
449 /// Temporaries - Temporary lvalues materialized within this stack frame.
450 MapTy Temporaries;
451
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000452 /// CallLoc - The location of the call expression for this call.
453 SourceLocation CallLoc;
454
455 /// Index - The call index of this call.
456 unsigned Index;
457
Faisal Vali051e3a22017-02-16 04:12:21 +0000458 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
459 // on the overall stack usage of deeply-recursing constexpr evaluataions.
460 // (We should cache this map rather than recomputing it repeatedly.)
461 // But let's try this and see how it goes; we can look into caching the map
462 // as a later change.
463
464 /// LambdaCaptureFields - Mapping from captured variables/this to
465 /// corresponding data members in the closure class.
466 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
467 FieldDecl *LambdaThisCaptureField;
468
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
470 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000471 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000472 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000473
474 APValue *getTemporary(const void *Key) {
475 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000476 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000477 }
478 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000479 };
480
Richard Smith852c9db2013-04-20 22:23:05 +0000481 /// Temporarily override 'this'.
482 class ThisOverrideRAII {
483 public:
484 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
485 : Frame(Frame), OldThis(Frame.This) {
486 if (Enable)
487 Frame.This = NewThis;
488 }
489 ~ThisOverrideRAII() {
490 Frame.This = OldThis;
491 }
492 private:
493 CallStackFrame &Frame;
494 const LValue *OldThis;
495 };
496
Richard Smith92b1ce02011-12-12 09:28:41 +0000497 /// A partial diagnostic which we might know in advance that we are not going
498 /// to emit.
499 class OptionalDiagnostic {
500 PartialDiagnostic *Diag;
501
502 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000503 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
504 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000505
506 template<typename T>
507 OptionalDiagnostic &operator<<(const T &v) {
508 if (Diag)
509 *Diag << v;
510 return *this;
511 }
Richard Smithfe800032012-01-31 04:08:20 +0000512
513 OptionalDiagnostic &operator<<(const APSInt &I) {
514 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000515 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000516 I.toString(Buffer);
517 *Diag << StringRef(Buffer.data(), Buffer.size());
518 }
519 return *this;
520 }
521
522 OptionalDiagnostic &operator<<(const APFloat &F) {
523 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000524 // FIXME: Force the precision of the source value down so we don't
525 // print digits which are usually useless (we don't really care here if
526 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000527 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000528 // representation which rounds to the correct value, but it's a bit
529 // tricky to implement.
530 unsigned precision =
531 llvm::APFloat::semanticsPrecision(F.getSemantics());
532 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000533 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000534 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000535 *Diag << StringRef(Buffer.data(), Buffer.size());
536 }
537 return *this;
538 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000539 };
540
Richard Smith08d6a2c2013-07-24 07:11:57 +0000541 /// A cleanup, and a flag indicating whether it is lifetime-extended.
542 class Cleanup {
543 llvm::PointerIntPair<APValue*, 1, bool> Value;
544
545 public:
546 Cleanup(APValue *Val, bool IsLifetimeExtended)
547 : Value(Val, IsLifetimeExtended) {}
548
549 bool isLifetimeExtended() const { return Value.getInt(); }
550 void endLifetime() {
551 *Value.getPointer() = APValue();
552 }
553 };
554
Richard Smithb228a862012-02-15 02:18:13 +0000555 /// EvalInfo - This is a private struct used by the evaluator to capture
556 /// information about a subexpression as it is folded. It retains information
557 /// about the AST context, but also maintains information about the folded
558 /// expression.
559 ///
560 /// If an expression could be evaluated, it is still possible it is not a C
561 /// "integer constant expression" or constant expression. If not, this struct
562 /// captures information about how and why not.
563 ///
564 /// One bit of information passed *into* the request for constant folding
565 /// indicates whether the subexpression is "evaluated" or not according to C
566 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
567 /// evaluate the expression regardless of what the RHS is, but C only allows
568 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000569 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000570 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000571
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572 /// EvalStatus - Contains information about the evaluation.
573 Expr::EvalStatus &EvalStatus;
574
575 /// CurrentCall - The top of the constexpr call stack.
576 CallStackFrame *CurrentCall;
577
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000578 /// CallStackDepth - The number of calls in the call stack right now.
579 unsigned CallStackDepth;
580
Richard Smithb228a862012-02-15 02:18:13 +0000581 /// NextCallIndex - The next call index to assign.
582 unsigned NextCallIndex;
583
Richard Smitha3d3bd22013-05-08 02:12:03 +0000584 /// StepsLeft - The remaining number of evaluation steps we're permitted
585 /// to perform. This is essentially a limit for the number of statements
586 /// we will evaluate.
587 unsigned StepsLeft;
588
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000589 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000590 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000591 CallStackFrame BottomFrame;
592
Richard Smith08d6a2c2013-07-24 07:11:57 +0000593 /// A stack of values whose lifetimes end at the end of some surrounding
594 /// evaluation frame.
595 llvm::SmallVector<Cleanup, 16> CleanupStack;
596
Richard Smithd62306a2011-11-10 06:34:14 +0000597 /// EvaluatingDecl - This is the declaration whose initializer is being
598 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000599 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000600
601 /// EvaluatingDeclValue - This is the value being constructed for the
602 /// declaration whose initializer is being evaluated, if any.
603 APValue *EvaluatingDeclValue;
604
Erik Pilkington42925492017-10-04 00:18:55 +0000605 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
606 /// the call index that that lvalue was allocated in.
607 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
608
609 /// EvaluatingConstructors - Set of objects that are currently being
610 /// constructed.
611 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
612
613 struct EvaluatingConstructorRAII {
614 EvalInfo &EI;
615 EvaluatingObject Object;
616 bool DidInsert;
617 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
618 : EI(EI), Object(Object) {
619 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
620 }
621 ~EvaluatingConstructorRAII() {
622 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
623 }
624 };
625
626 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
627 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
628 }
629
Richard Smith410306b2016-12-12 02:53:20 +0000630 /// The current array initialization index, if we're performing array
631 /// initialization.
632 uint64_t ArrayInitIndex = -1;
633
Richard Smith357362d2011-12-13 06:39:58 +0000634 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
635 /// notes attached to it will also be stored, otherwise they will not be.
636 bool HasActiveDiagnostic;
637
Richard Smith0c6124b2015-12-03 01:36:22 +0000638 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
639 /// fold (not just why it's not strictly a constant expression)?
640 bool HasFoldFailureDiagnostic;
641
George Burgess IV8c892b52016-05-25 22:31:54 +0000642 /// \brief Whether or not we're currently speculatively evaluating.
643 bool IsSpeculativelyEvaluating;
644
Richard Smith6d4c6582013-11-05 22:18:15 +0000645 enum EvaluationMode {
646 /// Evaluate as a constant expression. Stop if we find that the expression
647 /// is not a constant expression.
648 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000649
Richard Smith6d4c6582013-11-05 22:18:15 +0000650 /// Evaluate as a potential constant expression. Keep going if we hit a
651 /// construct that we can't evaluate yet (because we don't yet know the
652 /// value of something) but stop if we hit something that could never be
653 /// a constant expression.
654 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000655
Richard Smith6d4c6582013-11-05 22:18:15 +0000656 /// Fold the expression to a constant. Stop if we hit a side-effect that
657 /// we can't model.
658 EM_ConstantFold,
659
660 /// Evaluate the expression looking for integer overflow and similar
661 /// issues. Don't worry about side-effects, and try to visit all
662 /// subexpressions.
663 EM_EvaluateForOverflow,
664
665 /// Evaluate in any way we know how. Don't worry about side-effects that
666 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000667 EM_IgnoreSideEffects,
668
669 /// Evaluate as a constant expression. Stop if we find that the expression
670 /// is not a constant expression. Some expressions can be retried in the
671 /// optimizer if we don't constant fold them here, but in an unevaluated
672 /// context we try to fold them immediately since the optimizer never
673 /// gets a chance to look at it.
674 EM_ConstantExpressionUnevaluated,
675
676 /// Evaluate as a potential constant expression. Keep going if we hit a
677 /// construct that we can't evaluate yet (because we don't yet know the
678 /// value of something) but stop if we hit something that could never be
679 /// a constant expression. Some expressions can be retried in the
680 /// optimizer if we don't constant fold them here, but in an unevaluated
681 /// context we try to fold them immediately since the optimizer never
682 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000683 EM_PotentialConstantExpressionUnevaluated,
684
George Burgess IVf9013bf2017-02-10 22:52:29 +0000685 /// Evaluate as a constant expression. In certain scenarios, if:
686 /// - we find a MemberExpr with a base that can't be evaluated, or
687 /// - we find a variable initialized with a call to a function that has
688 /// the alloc_size attribute on it
689 /// then we may consider evaluation to have succeeded.
690 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000691 /// In either case, the LValue returned shall have an invalid base; in the
692 /// former, the base will be the invalid MemberExpr, in the latter, the
693 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
694 /// said CallExpr.
695 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000696 } EvalMode;
697
698 /// Are we checking whether the expression is a potential constant
699 /// expression?
700 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000701 return EvalMode == EM_PotentialConstantExpression ||
702 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 }
704
705 /// Are we checking an expression for overflow?
706 // FIXME: We should check for any kind of undefined or suspicious behavior
707 // in such constructs, not just overflow.
708 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
709
710 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000711 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000712 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000713 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000714 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
715 EvaluatingDecl((const ValueDecl *)nullptr),
716 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000717 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
718 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000719
Richard Smith7525ff62013-05-09 07:14:00 +0000720 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
721 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000722 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000723 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000724 }
725
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000727
Richard Smith357362d2011-12-13 06:39:58 +0000728 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000729 // Don't perform any constexpr calls (other than the call we're checking)
730 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000731 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000732 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000733 if (NextCallIndex == 0) {
734 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000735 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000736 return false;
737 }
Richard Smith357362d2011-12-13 06:39:58 +0000738 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
739 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000740 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000741 << getLangOpts().ConstexprCallDepth;
742 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000743 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000744
Richard Smithb228a862012-02-15 02:18:13 +0000745 CallStackFrame *getCallFrame(unsigned CallIndex) {
746 assert(CallIndex && "no call index in getCallFrame");
747 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
748 // be null in this loop.
749 CallStackFrame *Frame = CurrentCall;
750 while (Frame->Index > CallIndex)
751 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000752 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000753 }
754
Richard Smitha3d3bd22013-05-08 02:12:03 +0000755 bool nextStep(const Stmt *S) {
756 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000757 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000758 return false;
759 }
760 --StepsLeft;
761 return true;
762 }
763
Richard Smith357362d2011-12-13 06:39:58 +0000764 private:
765 /// Add a diagnostic to the diagnostics list.
766 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
767 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
768 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
769 return EvalStatus.Diag->back().second;
770 }
771
Richard Smithf6f003a2011-12-16 19:06:07 +0000772 /// Add notes containing a call stack to the current point of evaluation.
773 void addCallStack(unsigned Limit);
774
Faisal Valie690b7a2016-07-02 22:34:24 +0000775 private:
776 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
777 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000778
Richard Smith92b1ce02011-12-12 09:28:41 +0000779 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000780 // If we have a prior diagnostic, it will be noting that the expression
781 // isn't a constant expression. This diagnostic is more important,
782 // unless we require this evaluation to produce a constant expression.
783 //
784 // FIXME: We might want to show both diagnostics to the user in
785 // EM_ConstantFold mode.
786 if (!EvalStatus.Diag->empty()) {
787 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000788 case EM_ConstantFold:
789 case EM_IgnoreSideEffects:
790 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000791 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000792 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000793 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000794 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000795 case EM_ConstantExpression:
796 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000797 case EM_ConstantExpressionUnevaluated:
798 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000799 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000800 HasActiveDiagnostic = false;
801 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000802 }
803 }
804
Richard Smithf6f003a2011-12-16 19:06:07 +0000805 unsigned CallStackNotes = CallStackDepth - 1;
806 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
807 if (Limit)
808 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000809 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000810 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000811
Richard Smith357362d2011-12-13 06:39:58 +0000812 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000813 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000814 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000815 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
816 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000817 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000818 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000819 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000820 }
Richard Smith357362d2011-12-13 06:39:58 +0000821 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000822 return OptionalDiagnostic();
823 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000824 public:
825 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
826 OptionalDiagnostic
827 FFDiag(SourceLocation Loc,
828 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
829 unsigned ExtraNotes = 0) {
830 return Diag(Loc, DiagId, ExtraNotes, false);
831 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000832
Faisal Valie690b7a2016-07-02 22:34:24 +0000833 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000834 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000835 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000836 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000837 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000838 HasActiveDiagnostic = false;
839 return OptionalDiagnostic();
840 }
841
Richard Smith92b1ce02011-12-12 09:28:41 +0000842 /// Diagnose that the evaluation does not produce a C++11 core constant
843 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000844 ///
845 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
846 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000847 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000848 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000849 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 // Don't override a previous diagnostic. Don't bother collecting
851 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000852 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000853 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000854 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000855 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000856 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000857 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000858 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
859 = diag::note_invalid_subexpr_in_const_expr,
860 unsigned ExtraNotes = 0) {
861 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
862 }
Richard Smith357362d2011-12-13 06:39:58 +0000863 /// Add a note to a prior diagnostic.
864 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
865 if (!HasActiveDiagnostic)
866 return OptionalDiagnostic();
867 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000868 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000869
870 /// Add a stack of notes to a prior diagnostic.
871 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
872 if (HasActiveDiagnostic) {
873 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
874 Diags.begin(), Diags.end());
875 }
876 }
Richard Smith253c2a32012-01-27 01:14:48 +0000877
Richard Smith6d4c6582013-11-05 22:18:15 +0000878 /// Should we continue evaluation after encountering a side-effect that we
879 /// couldn't model?
880 bool keepEvaluatingAfterSideEffect() {
881 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000882 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000883 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 case EM_EvaluateForOverflow:
885 case EM_IgnoreSideEffects:
886 return true;
887
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000889 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000890 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000891 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000892 return false;
893 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000894 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 }
896
897 /// Note that we have had a side-effect, and determine whether we should
898 /// keep evaluating.
899 bool noteSideEffect() {
900 EvalStatus.HasSideEffects = true;
901 return keepEvaluatingAfterSideEffect();
902 }
903
Richard Smithce8eca52015-12-08 03:21:47 +0000904 /// Should we continue evaluation after encountering undefined behavior?
905 bool keepEvaluatingAfterUndefinedBehavior() {
906 switch (EvalMode) {
907 case EM_EvaluateForOverflow:
908 case EM_IgnoreSideEffects:
909 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000910 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000911 return true;
912
913 case EM_PotentialConstantExpression:
914 case EM_PotentialConstantExpressionUnevaluated:
915 case EM_ConstantExpression:
916 case EM_ConstantExpressionUnevaluated:
917 return false;
918 }
919 llvm_unreachable("Missed EvalMode case");
920 }
921
922 /// Note that we hit something that was technically undefined behavior, but
923 /// that we can evaluate past it (such as signed overflow or floating-point
924 /// division by zero.)
925 bool noteUndefinedBehavior() {
926 EvalStatus.HasUndefinedBehavior = true;
927 return keepEvaluatingAfterUndefinedBehavior();
928 }
929
Richard Smith253c2a32012-01-27 01:14:48 +0000930 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000932 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000933 if (!StepsLeft)
934 return false;
935
936 switch (EvalMode) {
937 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000938 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 case EM_EvaluateForOverflow:
940 return true;
941
942 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000943 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000944 case EM_ConstantFold:
945 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000946 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000947 return false;
948 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000949 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000950 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000951
George Burgess IV8c892b52016-05-25 22:31:54 +0000952 /// Notes that we failed to evaluate an expression that other expressions
953 /// directly depend on, and determine if we should keep evaluating. This
954 /// should only be called if we actually intend to keep evaluating.
955 ///
956 /// Call noteSideEffect() instead if we may be able to ignore the value that
957 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
958 ///
959 /// (Foo(), 1) // use noteSideEffect
960 /// (Foo() || true) // use noteSideEffect
961 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000962 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000963 // Failure when evaluating some expression often means there is some
964 // subexpression whose evaluation was skipped. Therefore, (because we
965 // don't track whether we skipped an expression when unwinding after an
966 // evaluation failure) every evaluation failure that bubbles up from a
967 // subexpression implies that a side-effect has potentially happened. We
968 // skip setting the HasSideEffects flag to true until we decide to
969 // continue evaluating after that point, which happens here.
970 bool KeepGoing = keepEvaluatingAfterFailure();
971 EvalStatus.HasSideEffects |= KeepGoing;
972 return KeepGoing;
973 }
974
Richard Smith410306b2016-12-12 02:53:20 +0000975 class ArrayInitLoopIndex {
976 EvalInfo &Info;
977 uint64_t OuterIndex;
978
979 public:
980 ArrayInitLoopIndex(EvalInfo &Info)
981 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
982 Info.ArrayInitIndex = 0;
983 }
984 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
985
986 operator uint64_t&() { return Info.ArrayInitIndex; }
987 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000988 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000989
990 /// Object used to treat all foldable expressions as constant expressions.
991 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000992 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000993 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000994 bool HadNoPriorDiags;
995 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000996
Richard Smith6d4c6582013-11-05 22:18:15 +0000997 explicit FoldConstant(EvalInfo &Info, bool Enabled)
998 : Info(Info),
999 Enabled(Enabled),
1000 HadNoPriorDiags(Info.EvalStatus.Diag &&
1001 Info.EvalStatus.Diag->empty() &&
1002 !Info.EvalStatus.HasSideEffects),
1003 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001004 if (Enabled &&
1005 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1006 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001007 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001008 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001009 void keepDiagnostics() { Enabled = false; }
1010 ~FoldConstant() {
1011 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001012 !Info.EvalStatus.HasSideEffects)
1013 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001014 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001015 }
1016 };
Richard Smith17100ba2012-02-16 02:46:34 +00001017
George Burgess IV3a03fab2015-09-04 21:28:13 +00001018 /// RAII object used to treat the current evaluation as the correct pointer
1019 /// offset fold for the current EvalMode
1020 struct FoldOffsetRAII {
1021 EvalInfo &Info;
1022 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001023 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001024 : Info(Info), OldMode(Info.EvalMode) {
1025 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001026 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001027 }
1028
1029 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1030 };
1031
George Burgess IV8c892b52016-05-25 22:31:54 +00001032 /// RAII object used to optionally suppress diagnostics and side-effects from
1033 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001034 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001035 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001036 Expr::EvalStatus OldStatus;
1037 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001038
George Burgess IV8c892b52016-05-25 22:31:54 +00001039 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001040 Info = Other.Info;
1041 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001042 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001043 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001044 }
1045
1046 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001047 if (!Info)
1048 return;
1049
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001050 Info->EvalStatus = OldStatus;
1051 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001052 }
1053
Richard Smith17100ba2012-02-16 02:46:34 +00001054 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001055 SpeculativeEvaluationRAII() = default;
1056
1057 SpeculativeEvaluationRAII(
1058 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001059 : Info(&Info), OldStatus(Info.EvalStatus),
1060 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001061 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001062 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001063 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001064
1065 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1066 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1067 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001068 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001069
1070 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1071 maybeRestoreState();
1072 moveFromAndCancel(std::move(Other));
1073 return *this;
1074 }
1075
1076 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001077 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001078
1079 /// RAII object wrapping a full-expression or block scope, and handling
1080 /// the ending of the lifetime of temporaries created within it.
1081 template<bool IsFullExpression>
1082 class ScopeRAII {
1083 EvalInfo &Info;
1084 unsigned OldStackSize;
1085 public:
1086 ScopeRAII(EvalInfo &Info)
1087 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1088 ~ScopeRAII() {
1089 // Body moved to a static method to encourage the compiler to inline away
1090 // instances of this class.
1091 cleanup(Info, OldStackSize);
1092 }
1093 private:
1094 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1095 unsigned NewEnd = OldStackSize;
1096 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1097 I != N; ++I) {
1098 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1099 // Full-expression cleanup of a lifetime-extended temporary: nothing
1100 // to do, just move this cleanup to the right place in the stack.
1101 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1102 ++NewEnd;
1103 } else {
1104 // End the lifetime of the object.
1105 Info.CleanupStack[I].endLifetime();
1106 }
1107 }
1108 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1109 Info.CleanupStack.end());
1110 }
1111 };
1112 typedef ScopeRAII<false> BlockScopeRAII;
1113 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001114}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001115
Richard Smitha8105bc2012-01-06 16:39:00 +00001116bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1117 CheckSubobjectKind CSK) {
1118 if (Invalid)
1119 return false;
1120 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001121 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001122 << CSK;
1123 setInvalid();
1124 return false;
1125 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001126 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1127 // must actually be at least one array element; even a VLA cannot have a
1128 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001129 return true;
1130}
1131
Richard Smith6f4f0f12017-10-20 22:56:25 +00001132void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1133 const Expr *E) {
1134 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1135 // Do not set the designator as invalid: we can represent this situation,
1136 // and correct handling of __builtin_object_size requires us to do so.
1137}
1138
Richard Smitha8105bc2012-01-06 16:39:00 +00001139void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001140 const Expr *E,
1141 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001142 // If we're complaining, we must be able to statically determine the size of
1143 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001144 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001145 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001146 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001147 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001148 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001149 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001150 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001151 setInvalid();
1152}
1153
Richard Smithf6f003a2011-12-16 19:06:07 +00001154CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1155 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001156 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001157 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1158 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001159 Info.CurrentCall = this;
1160 ++Info.CallStackDepth;
1161}
1162
1163CallStackFrame::~CallStackFrame() {
1164 assert(Info.CurrentCall == this && "calls retired out of order");
1165 --Info.CallStackDepth;
1166 Info.CurrentCall = Caller;
1167}
1168
Richard Smith08d6a2c2013-07-24 07:11:57 +00001169APValue &CallStackFrame::createTemporary(const void *Key,
1170 bool IsLifetimeExtended) {
1171 APValue &Result = Temporaries[Key];
1172 assert(Result.isUninit() && "temporary created multiple times");
1173 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1174 return Result;
1175}
1176
Richard Smith84401042013-06-03 05:03:02 +00001177static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001178
1179void EvalInfo::addCallStack(unsigned Limit) {
1180 // Determine which calls to skip, if any.
1181 unsigned ActiveCalls = CallStackDepth - 1;
1182 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1183 if (Limit && Limit < ActiveCalls) {
1184 SkipStart = Limit / 2 + Limit % 2;
1185 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001186 }
1187
Richard Smithf6f003a2011-12-16 19:06:07 +00001188 // Walk the call stack and add the diagnostics.
1189 unsigned CallIdx = 0;
1190 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1191 Frame = Frame->Caller, ++CallIdx) {
1192 // Skip this call?
1193 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1194 if (CallIdx == SkipStart) {
1195 // Note that we're skipping calls.
1196 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1197 << unsigned(ActiveCalls - Limit);
1198 }
1199 continue;
1200 }
1201
Richard Smith5179eb72016-06-28 19:03:57 +00001202 // Use a different note for an inheriting constructor, because from the
1203 // user's perspective it's not really a function at all.
1204 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1205 if (CD->isInheritingConstructor()) {
1206 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1207 << CD->getParent();
1208 continue;
1209 }
1210 }
1211
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001212 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001213 llvm::raw_svector_ostream Out(Buffer);
1214 describeCall(Frame, Out);
1215 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1216 }
1217}
1218
1219namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001220 struct ComplexValue {
1221 private:
1222 bool IsInt;
1223
1224 public:
1225 APSInt IntReal, IntImag;
1226 APFloat FloatReal, FloatImag;
1227
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001228 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001229
1230 void makeComplexFloat() { IsInt = false; }
1231 bool isComplexFloat() const { return !IsInt; }
1232 APFloat &getComplexFloatReal() { return FloatReal; }
1233 APFloat &getComplexFloatImag() { return FloatImag; }
1234
1235 void makeComplexInt() { IsInt = true; }
1236 bool isComplexInt() const { return IsInt; }
1237 APSInt &getComplexIntReal() { return IntReal; }
1238 APSInt &getComplexIntImag() { return IntImag; }
1239
Richard Smith2e312c82012-03-03 22:46:17 +00001240 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001241 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001242 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001243 else
Richard Smith2e312c82012-03-03 22:46:17 +00001244 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001245 }
Richard Smith2e312c82012-03-03 22:46:17 +00001246 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001247 assert(v.isComplexFloat() || v.isComplexInt());
1248 if (v.isComplexFloat()) {
1249 makeComplexFloat();
1250 FloatReal = v.getComplexFloatReal();
1251 FloatImag = v.getComplexFloatImag();
1252 } else {
1253 makeComplexInt();
1254 IntReal = v.getComplexIntReal();
1255 IntImag = v.getComplexIntImag();
1256 }
1257 }
John McCall93d91dc2010-05-07 17:22:02 +00001258 };
John McCall45d55e42010-05-07 21:00:08 +00001259
1260 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001261 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001262 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001263 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001264 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001265 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001266 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001267
Richard Smithce40ad62011-11-12 22:28:03 +00001268 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001269 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001270 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001271 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001272 SubobjectDesignator &getLValueDesignator() { return Designator; }
1273 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001275
Richard Smith2e312c82012-03-03 22:46:17 +00001276 void moveInto(APValue &V) const {
1277 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001278 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1279 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001280 else {
1281 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001282 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001283 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001284 }
John McCall45d55e42010-05-07 21:00:08 +00001285 }
Richard Smith2e312c82012-03-03 22:46:17 +00001286 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001287 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001288 Base = V.getLValueBase();
1289 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001290 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001291 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001292 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001293 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001294 }
1295
Tim Northover01503332017-05-26 02:16:00 +00001296 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001297#ifndef NDEBUG
1298 // We only allow a few types of invalid bases. Enforce that here.
1299 if (BInvalid) {
1300 const auto *E = B.get<const Expr *>();
1301 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1302 "Unexpected type of invalid base");
1303 }
1304#endif
1305
Richard Smithce40ad62011-11-12 22:28:03 +00001306 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001307 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001308 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001309 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001310 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001311 IsNullPtr = false;
1312 }
1313
1314 void setNull(QualType PointerTy, uint64_t TargetVal) {
1315 Base = (Expr *)nullptr;
1316 Offset = CharUnits::fromQuantity(TargetVal);
1317 InvalidBase = false;
1318 CallIndex = 0;
1319 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1320 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001321 }
1322
George Burgess IV3a03fab2015-09-04 21:28:13 +00001323 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1324 set(B, I, true);
1325 }
1326
Richard Smitha8105bc2012-01-06 16:39:00 +00001327 // Check that this LValue is not based on a null pointer. If it is, produce
1328 // a diagnostic and mark the designator as invalid.
1329 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1330 CheckSubobjectKind CSK) {
1331 if (Designator.Invalid)
1332 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001333 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001334 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001335 << CSK;
1336 Designator.setInvalid();
1337 return false;
1338 }
1339 return true;
1340 }
1341
1342 // Check this LValue refers to an object. If not, set the designator to be
1343 // invalid and emit a diagnostic.
1344 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001345 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001346 Designator.checkSubobject(Info, E, CSK);
1347 }
1348
1349 void addDecl(EvalInfo &Info, const Expr *E,
1350 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001351 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1352 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001353 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001354 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1355 if (!Designator.Entries.empty()) {
1356 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1357 Designator.setInvalid();
1358 return;
1359 }
Richard Smithefdb5032017-11-15 03:03:56 +00001360 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1361 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1362 Designator.FirstEntryIsAnUnsizedArray = true;
1363 Designator.addUnsizedArrayUnchecked(ElemTy);
1364 }
George Burgess IVe3763372016-12-22 02:50:20 +00001365 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001366 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001367 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1368 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001369 }
Richard Smith66c96992012-02-18 22:04:06 +00001370 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001371 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1372 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001373 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001374 void clearIsNullPointer() {
1375 IsNullPtr = false;
1376 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001377 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1378 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001379 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1380 // but we're not required to diagnose it and it's valid in C++.)
1381 if (!Index)
1382 return;
1383
1384 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1385 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1386 // offsets.
1387 uint64_t Offset64 = Offset.getQuantity();
1388 uint64_t ElemSize64 = ElementSize.getQuantity();
1389 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1390 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1391
1392 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001393 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001394 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001395 }
1396 void adjustOffset(CharUnits N) {
1397 Offset += N;
1398 if (N.getQuantity())
1399 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001400 }
John McCall45d55e42010-05-07 21:00:08 +00001401 };
Richard Smith027bf112011-11-17 22:56:20 +00001402
1403 struct MemberPtr {
1404 MemberPtr() {}
1405 explicit MemberPtr(const ValueDecl *Decl) :
1406 DeclAndIsDerivedMember(Decl, false), Path() {}
1407
1408 /// The member or (direct or indirect) field referred to by this member
1409 /// pointer, or 0 if this is a null member pointer.
1410 const ValueDecl *getDecl() const {
1411 return DeclAndIsDerivedMember.getPointer();
1412 }
1413 /// Is this actually a member of some type derived from the relevant class?
1414 bool isDerivedMember() const {
1415 return DeclAndIsDerivedMember.getInt();
1416 }
1417 /// Get the class which the declaration actually lives in.
1418 const CXXRecordDecl *getContainingRecord() const {
1419 return cast<CXXRecordDecl>(
1420 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1421 }
1422
Richard Smith2e312c82012-03-03 22:46:17 +00001423 void moveInto(APValue &V) const {
1424 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001425 }
Richard Smith2e312c82012-03-03 22:46:17 +00001426 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001427 assert(V.isMemberPointer());
1428 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1429 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1430 Path.clear();
1431 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1432 Path.insert(Path.end(), P.begin(), P.end());
1433 }
1434
1435 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1436 /// whether the member is a member of some class derived from the class type
1437 /// of the member pointer.
1438 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1439 /// Path - The path of base/derived classes from the member declaration's
1440 /// class (exclusive) to the class type of the member pointer (inclusive).
1441 SmallVector<const CXXRecordDecl*, 4> Path;
1442
1443 /// Perform a cast towards the class of the Decl (either up or down the
1444 /// hierarchy).
1445 bool castBack(const CXXRecordDecl *Class) {
1446 assert(!Path.empty());
1447 const CXXRecordDecl *Expected;
1448 if (Path.size() >= 2)
1449 Expected = Path[Path.size() - 2];
1450 else
1451 Expected = getContainingRecord();
1452 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1453 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1454 // if B does not contain the original member and is not a base or
1455 // derived class of the class containing the original member, the result
1456 // of the cast is undefined.
1457 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1458 // (D::*). We consider that to be a language defect.
1459 return false;
1460 }
1461 Path.pop_back();
1462 return true;
1463 }
1464 /// Perform a base-to-derived member pointer cast.
1465 bool castToDerived(const CXXRecordDecl *Derived) {
1466 if (!getDecl())
1467 return true;
1468 if (!isDerivedMember()) {
1469 Path.push_back(Derived);
1470 return true;
1471 }
1472 if (!castBack(Derived))
1473 return false;
1474 if (Path.empty())
1475 DeclAndIsDerivedMember.setInt(false);
1476 return true;
1477 }
1478 /// Perform a derived-to-base member pointer cast.
1479 bool castToBase(const CXXRecordDecl *Base) {
1480 if (!getDecl())
1481 return true;
1482 if (Path.empty())
1483 DeclAndIsDerivedMember.setInt(true);
1484 if (isDerivedMember()) {
1485 Path.push_back(Base);
1486 return true;
1487 }
1488 return castBack(Base);
1489 }
1490 };
Richard Smith357362d2011-12-13 06:39:58 +00001491
Richard Smith7bb00672012-02-01 01:42:44 +00001492 /// Compare two member pointers, which are assumed to be of the same type.
1493 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1494 if (!LHS.getDecl() || !RHS.getDecl())
1495 return !LHS.getDecl() && !RHS.getDecl();
1496 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1497 return false;
1498 return LHS.Path == RHS.Path;
1499 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001500}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001501
Richard Smith2e312c82012-03-03 22:46:17 +00001502static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001503static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1504 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001505 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001506static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1507 bool InvalidBaseOK = false);
1508static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1509 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001510static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1511 EvalInfo &Info);
1512static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001513static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001514static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001515 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001516static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001517static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001518static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1519 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001520static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001521
1522//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001523// Misc utilities
1524//===----------------------------------------------------------------------===//
1525
Richard Smithd6cc1982017-01-31 02:23:02 +00001526/// Negate an APSInt in place, converting it to a signed form if necessary, and
1527/// preserving its value (by extending by up to one bit as needed).
1528static void negateAsSigned(APSInt &Int) {
1529 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1530 Int = Int.extend(Int.getBitWidth() + 1);
1531 Int.setIsSigned(true);
1532 }
1533 Int = -Int;
1534}
1535
Richard Smith84401042013-06-03 05:03:02 +00001536/// Produce a string describing the given constexpr call.
1537static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1538 unsigned ArgIndex = 0;
1539 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1540 !isa<CXXConstructorDecl>(Frame->Callee) &&
1541 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1542
1543 if (!IsMemberCall)
1544 Out << *Frame->Callee << '(';
1545
1546 if (Frame->This && IsMemberCall) {
1547 APValue Val;
1548 Frame->This->moveInto(Val);
1549 Val.printPretty(Out, Frame->Info.Ctx,
1550 Frame->This->Designator.MostDerivedType);
1551 // FIXME: Add parens around Val if needed.
1552 Out << "->" << *Frame->Callee << '(';
1553 IsMemberCall = false;
1554 }
1555
1556 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1557 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1558 if (ArgIndex > (unsigned)IsMemberCall)
1559 Out << ", ";
1560
1561 const ParmVarDecl *Param = *I;
1562 const APValue &Arg = Frame->Arguments[ArgIndex];
1563 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1564
1565 if (ArgIndex == 0 && IsMemberCall)
1566 Out << "->" << *Frame->Callee << '(';
1567 }
1568
1569 Out << ')';
1570}
1571
Richard Smithd9f663b2013-04-22 15:31:51 +00001572/// Evaluate an expression to see if it had side-effects, and discard its
1573/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001574/// \return \c true if the caller should keep evaluating.
1575static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001576 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001577 if (!Evaluate(Scratch, Info, E))
1578 // We don't need the value, but we might have skipped a side effect here.
1579 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001580 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001581}
1582
Richard Smithd62306a2011-11-10 06:34:14 +00001583/// Should this call expression be treated as a string literal?
1584static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001585 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001586 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1587 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1588}
1589
Richard Smithce40ad62011-11-12 22:28:03 +00001590static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001591 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1592 // constant expression of pointer type that evaluates to...
1593
1594 // ... a null pointer value, or a prvalue core constant expression of type
1595 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001596 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001597
Richard Smithce40ad62011-11-12 22:28:03 +00001598 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1599 // ... the address of an object with static storage duration,
1600 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1601 return VD->hasGlobalStorage();
1602 // ... the address of a function,
1603 return isa<FunctionDecl>(D);
1604 }
1605
1606 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001607 switch (E->getStmtClass()) {
1608 default:
1609 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001610 case Expr::CompoundLiteralExprClass: {
1611 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1612 return CLE->isFileScope() && CLE->isLValue();
1613 }
Richard Smithe6c01442013-06-05 00:46:14 +00001614 case Expr::MaterializeTemporaryExprClass:
1615 // A materialized temporary might have been lifetime-extended to static
1616 // storage duration.
1617 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001618 // A string literal has static storage duration.
1619 case Expr::StringLiteralClass:
1620 case Expr::PredefinedExprClass:
1621 case Expr::ObjCStringLiteralClass:
1622 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001623 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001624 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001625 return true;
1626 case Expr::CallExprClass:
1627 return IsStringLiteralCall(cast<CallExpr>(E));
1628 // For GCC compatibility, &&label has static storage duration.
1629 case Expr::AddrLabelExprClass:
1630 return true;
1631 // A Block literal expression may be used as the initialization value for
1632 // Block variables at global or local static scope.
1633 case Expr::BlockExprClass:
1634 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001635 case Expr::ImplicitValueInitExprClass:
1636 // FIXME:
1637 // We can never form an lvalue with an implicit value initialization as its
1638 // base through expression evaluation, so these only appear in one case: the
1639 // implicit variable declaration we invent when checking whether a constexpr
1640 // constructor can produce a constant expression. We must assume that such
1641 // an expression might be a global lvalue.
1642 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001643 }
John McCall95007602010-05-10 23:27:23 +00001644}
1645
Richard Smithb228a862012-02-15 02:18:13 +00001646static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1647 assert(Base && "no location for a null lvalue");
1648 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1649 if (VD)
1650 Info.Note(VD->getLocation(), diag::note_declared_at);
1651 else
Ted Kremenek28831752012-08-23 20:46:57 +00001652 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001653 diag::note_constexpr_temporary_here);
1654}
1655
Richard Smith80815602011-11-07 05:07:52 +00001656/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001657/// value for an address or reference constant expression. Return true if we
1658/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001659static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1660 QualType Type, const LValue &LVal) {
1661 bool IsReferenceType = Type->isReferenceType();
1662
Richard Smith357362d2011-12-13 06:39:58 +00001663 APValue::LValueBase Base = LVal.getLValueBase();
1664 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1665
Richard Smith0dea49e2012-02-18 04:58:18 +00001666 // Check that the object is a global. Note that the fake 'this' object we
1667 // manufacture when checking potential constant expressions is conservatively
1668 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001669 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001670 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001671 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001672 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001673 << IsReferenceType << !Designator.Entries.empty()
1674 << !!VD << VD;
1675 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001676 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001677 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001678 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001679 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001680 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001681 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001682 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001683 LVal.getLValueCallIndex() == 0) &&
1684 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001685
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001686 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1687 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001688 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001689 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001690 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001691
Hans Wennborg82dd8772014-06-25 22:19:48 +00001692 // A dllimport variable never acts like a constant.
1693 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001694 return false;
1695 }
1696 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1697 // __declspec(dllimport) must be handled very carefully:
1698 // We must never initialize an expression with the thunk in C++.
1699 // Doing otherwise would allow the same id-expression to yield
1700 // different addresses for the same function in different translation
1701 // units. However, this means that we must dynamically initialize the
1702 // expression with the contents of the import address table at runtime.
1703 //
1704 // The C language has no notion of ODR; furthermore, it has no notion of
1705 // dynamic initialization. This means that we are permitted to
1706 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001707 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001708 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001709 }
1710 }
1711
Richard Smitha8105bc2012-01-06 16:39:00 +00001712 // Allow address constant expressions to be past-the-end pointers. This is
1713 // an extension: the standard requires them to point to an object.
1714 if (!IsReferenceType)
1715 return true;
1716
1717 // A reference constant expression must refer to an object.
1718 if (!Base) {
1719 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001720 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001721 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001722 }
1723
Richard Smith357362d2011-12-13 06:39:58 +00001724 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001725 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001726 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001727 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001728 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001729 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001730 }
1731
Richard Smith80815602011-11-07 05:07:52 +00001732 return true;
1733}
1734
Reid Klecknercd016d82017-07-07 22:04:29 +00001735/// Member pointers are constant expressions unless they point to a
1736/// non-virtual dllimport member function.
1737static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1738 SourceLocation Loc,
1739 QualType Type,
1740 const APValue &Value) {
1741 const ValueDecl *Member = Value.getMemberPointerDecl();
1742 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1743 if (!FD)
1744 return true;
1745 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1746}
1747
Richard Smithfddd3842011-12-30 21:15:51 +00001748/// Check that this core constant expression is of literal type, and if not,
1749/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001750static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001751 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001752 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001753 return true;
1754
Richard Smith7525ff62013-05-09 07:14:00 +00001755 // C++1y: A constant initializer for an object o [...] may also invoke
1756 // constexpr constructors for o and its subobjects even if those objects
1757 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001758 //
1759 // C++11 missed this detail for aggregates, so classes like this:
1760 // struct foo_t { union { int i; volatile int j; } u; };
1761 // are not (obviously) initializable like so:
1762 // __attribute__((__require_constant_initialization__))
1763 // static const foo_t x = {{0}};
1764 // because "i" is a subobject with non-literal initialization (due to the
1765 // volatile member of the union). See:
1766 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1767 // Therefore, we use the C++1y behavior.
1768 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001769 return true;
1770
Richard Smithfddd3842011-12-30 21:15:51 +00001771 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001772 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001773 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001774 << E->getType();
1775 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001776 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001777 return false;
1778}
1779
Richard Smith0b0a0b62011-10-29 20:57:55 +00001780/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001781/// constant expression. If not, report an appropriate diagnostic. Does not
1782/// check that the expression is of literal type.
1783static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1784 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001785 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001786 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001787 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001788 return false;
1789 }
1790
Richard Smith77be48a2014-07-31 06:31:19 +00001791 // We allow _Atomic(T) to be initialized from anything that T can be
1792 // initialized from.
1793 if (const AtomicType *AT = Type->getAs<AtomicType>())
1794 Type = AT->getValueType();
1795
Richard Smithb228a862012-02-15 02:18:13 +00001796 // Core issue 1454: For a literal constant expression of array or class type,
1797 // each subobject of its value shall have been initialized by a constant
1798 // expression.
1799 if (Value.isArray()) {
1800 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1801 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1802 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1803 Value.getArrayInitializedElt(I)))
1804 return false;
1805 }
1806 if (!Value.hasArrayFiller())
1807 return true;
1808 return CheckConstantExpression(Info, DiagLoc, EltTy,
1809 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001810 }
Richard Smithb228a862012-02-15 02:18:13 +00001811 if (Value.isUnion() && Value.getUnionField()) {
1812 return CheckConstantExpression(Info, DiagLoc,
1813 Value.getUnionField()->getType(),
1814 Value.getUnionValue());
1815 }
1816 if (Value.isStruct()) {
1817 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1818 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1819 unsigned BaseIndex = 0;
1820 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1821 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1822 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1823 Value.getStructBase(BaseIndex)))
1824 return false;
1825 }
1826 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001827 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001828 if (I->isUnnamedBitfield())
1829 continue;
1830
David Blaikie2d7c57e2012-04-30 02:36:29 +00001831 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1832 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001833 return false;
1834 }
1835 }
1836
1837 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001838 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001839 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001840 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1841 }
1842
Reid Klecknercd016d82017-07-07 22:04:29 +00001843 if (Value.isMemberPointer())
1844 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1845
Richard Smithb228a862012-02-15 02:18:13 +00001846 // Everything else is fine.
1847 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001848}
1849
Benjamin Kramer8407df72015-03-09 16:47:52 +00001850static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001851 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001852}
1853
1854static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001855 if (Value.CallIndex)
1856 return false;
1857 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1858 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001859}
1860
Richard Smithcecf1842011-11-01 21:06:14 +00001861static bool IsWeakLValue(const LValue &Value) {
1862 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001863 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001864}
1865
David Majnemerb5116032014-12-09 23:32:34 +00001866static bool isZeroSized(const LValue &Value) {
1867 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001868 if (Decl && isa<VarDecl>(Decl)) {
1869 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001870 if (Ty->isArrayType())
1871 return Ty->isIncompleteType() ||
1872 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001873 }
1874 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001875}
1876
Richard Smith2e312c82012-03-03 22:46:17 +00001877static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001878 // A null base expression indicates a null pointer. These are always
1879 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001880 if (!Value.getLValueBase()) {
1881 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001882 return true;
1883 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001884
Richard Smith027bf112011-11-17 22:56:20 +00001885 // We have a non-null base. These are generally known to be true, but if it's
1886 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001887 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001888 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001889 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001890}
1891
Richard Smith2e312c82012-03-03 22:46:17 +00001892static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001893 switch (Val.getKind()) {
1894 case APValue::Uninitialized:
1895 return false;
1896 case APValue::Int:
1897 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001898 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001899 case APValue::Float:
1900 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001901 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001902 case APValue::ComplexInt:
1903 Result = Val.getComplexIntReal().getBoolValue() ||
1904 Val.getComplexIntImag().getBoolValue();
1905 return true;
1906 case APValue::ComplexFloat:
1907 Result = !Val.getComplexFloatReal().isZero() ||
1908 !Val.getComplexFloatImag().isZero();
1909 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001910 case APValue::LValue:
1911 return EvalPointerValueAsBool(Val, Result);
1912 case APValue::MemberPointer:
1913 Result = Val.getMemberPointerDecl();
1914 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001915 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001916 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001917 case APValue::Struct:
1918 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001919 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001920 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001921 }
1922
Richard Smith11562c52011-10-28 17:51:58 +00001923 llvm_unreachable("unknown APValue kind");
1924}
1925
1926static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1927 EvalInfo &Info) {
1928 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001929 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001930 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001931 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001932 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001933}
1934
Richard Smith357362d2011-12-13 06:39:58 +00001935template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001936static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001937 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001938 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001939 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001940 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001941}
1942
1943static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1944 QualType SrcType, const APFloat &Value,
1945 QualType DestType, APSInt &Result) {
1946 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001947 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001948 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001949
Richard Smith357362d2011-12-13 06:39:58 +00001950 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001951 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001952 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1953 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001954 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001955 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001956}
1957
Richard Smith357362d2011-12-13 06:39:58 +00001958static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1959 QualType SrcType, QualType DestType,
1960 APFloat &Result) {
1961 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001962 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001963 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1964 APFloat::rmNearestTiesToEven, &ignored)
1965 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001966 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001967 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001968}
1969
Richard Smith911e1422012-01-30 22:27:01 +00001970static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1971 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001972 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001973 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001974 APSInt Result = Value;
1975 // Figure out if this is a truncate, extend or noop cast.
1976 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001977 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001978 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001979 return Result;
1980}
1981
Richard Smith357362d2011-12-13 06:39:58 +00001982static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1983 QualType SrcType, const APSInt &Value,
1984 QualType DestType, APFloat &Result) {
1985 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1986 if (Result.convertFromAPInt(Value, Value.isSigned(),
1987 APFloat::rmNearestTiesToEven)
1988 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001989 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001990 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001991}
1992
Richard Smith49ca8aa2013-08-06 07:09:20 +00001993static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1994 APValue &Value, const FieldDecl *FD) {
1995 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1996
1997 if (!Value.isInt()) {
1998 // Trying to store a pointer-cast-to-integer into a bitfield.
1999 // FIXME: In this case, we should provide the diagnostic for casting
2000 // a pointer to an integer.
2001 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002002 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002003 return false;
2004 }
2005
2006 APSInt &Int = Value.getInt();
2007 unsigned OldBitWidth = Int.getBitWidth();
2008 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2009 if (NewBitWidth < OldBitWidth)
2010 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2011 return true;
2012}
2013
Eli Friedman803acb32011-12-22 03:51:45 +00002014static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2015 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002016 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002017 if (!Evaluate(SVal, Info, E))
2018 return false;
2019 if (SVal.isInt()) {
2020 Res = SVal.getInt();
2021 return true;
2022 }
2023 if (SVal.isFloat()) {
2024 Res = SVal.getFloat().bitcastToAPInt();
2025 return true;
2026 }
2027 if (SVal.isVector()) {
2028 QualType VecTy = E->getType();
2029 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2030 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2031 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2032 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2033 Res = llvm::APInt::getNullValue(VecSize);
2034 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2035 APValue &Elt = SVal.getVectorElt(i);
2036 llvm::APInt EltAsInt;
2037 if (Elt.isInt()) {
2038 EltAsInt = Elt.getInt();
2039 } else if (Elt.isFloat()) {
2040 EltAsInt = Elt.getFloat().bitcastToAPInt();
2041 } else {
2042 // Don't try to handle vectors of anything other than int or float
2043 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002044 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002045 return false;
2046 }
2047 unsigned BaseEltSize = EltAsInt.getBitWidth();
2048 if (BigEndian)
2049 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2050 else
2051 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2052 }
2053 return true;
2054 }
2055 // Give up if the input isn't an int, float, or vector. For example, we
2056 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002057 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002058 return false;
2059}
2060
Richard Smith43e77732013-05-07 04:50:00 +00002061/// Perform the given integer operation, which is known to need at most BitWidth
2062/// bits, and check for overflow in the original type (if that type was not an
2063/// unsigned type).
2064template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002065static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2066 const APSInt &LHS, const APSInt &RHS,
2067 unsigned BitWidth, Operation Op,
2068 APSInt &Result) {
2069 if (LHS.isUnsigned()) {
2070 Result = Op(LHS, RHS);
2071 return true;
2072 }
Richard Smith43e77732013-05-07 04:50:00 +00002073
2074 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002075 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002076 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002077 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002078 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002079 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002080 << Result.toString(10) << E->getType();
2081 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002082 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002083 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002084 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002085}
2086
2087/// Perform the given binary integer operation.
2088static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2089 BinaryOperatorKind Opcode, APSInt RHS,
2090 APSInt &Result) {
2091 switch (Opcode) {
2092 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002093 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002094 return false;
2095 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002096 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2097 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002098 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002099 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2100 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002101 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002102 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2103 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002104 case BO_And: Result = LHS & RHS; return true;
2105 case BO_Xor: Result = LHS ^ RHS; return true;
2106 case BO_Or: Result = LHS | RHS; return true;
2107 case BO_Div:
2108 case BO_Rem:
2109 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002110 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002111 return false;
2112 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002113 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2114 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2115 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002116 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2117 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002118 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2119 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002120 return true;
2121 case BO_Shl: {
2122 if (Info.getLangOpts().OpenCL)
2123 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2124 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2125 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2126 RHS.isUnsigned());
2127 else if (RHS.isSigned() && RHS.isNegative()) {
2128 // During constant-folding, a negative shift is an opposite shift. Such
2129 // a shift is not a constant expression.
2130 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2131 RHS = -RHS;
2132 goto shift_right;
2133 }
2134 shift_left:
2135 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2136 // the shifted type.
2137 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2138 if (SA != RHS) {
2139 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2140 << RHS << E->getType() << LHS.getBitWidth();
2141 } else if (LHS.isSigned()) {
2142 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2143 // operand, and must not overflow the corresponding unsigned type.
2144 if (LHS.isNegative())
2145 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2146 else if (LHS.countLeadingZeros() < SA)
2147 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2148 }
2149 Result = LHS << SA;
2150 return true;
2151 }
2152 case BO_Shr: {
2153 if (Info.getLangOpts().OpenCL)
2154 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2155 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2156 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2157 RHS.isUnsigned());
2158 else if (RHS.isSigned() && RHS.isNegative()) {
2159 // During constant-folding, a negative shift is an opposite shift. Such a
2160 // shift is not a constant expression.
2161 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2162 RHS = -RHS;
2163 goto shift_left;
2164 }
2165 shift_right:
2166 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2167 // shifted type.
2168 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2169 if (SA != RHS)
2170 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2171 << RHS << E->getType() << LHS.getBitWidth();
2172 Result = LHS >> SA;
2173 return true;
2174 }
2175
2176 case BO_LT: Result = LHS < RHS; return true;
2177 case BO_GT: Result = LHS > RHS; return true;
2178 case BO_LE: Result = LHS <= RHS; return true;
2179 case BO_GE: Result = LHS >= RHS; return true;
2180 case BO_EQ: Result = LHS == RHS; return true;
2181 case BO_NE: Result = LHS != RHS; return true;
2182 }
2183}
2184
Richard Smith861b5b52013-05-07 23:34:45 +00002185/// Perform the given binary floating-point operation, in-place, on LHS.
2186static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2187 APFloat &LHS, BinaryOperatorKind Opcode,
2188 const APFloat &RHS) {
2189 switch (Opcode) {
2190 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002191 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002192 return false;
2193 case BO_Mul:
2194 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2195 break;
2196 case BO_Add:
2197 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2198 break;
2199 case BO_Sub:
2200 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2201 break;
2202 case BO_Div:
2203 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2204 break;
2205 }
2206
Richard Smith0c6124b2015-12-03 01:36:22 +00002207 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002208 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002209 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002210 }
Richard Smith861b5b52013-05-07 23:34:45 +00002211 return true;
2212}
2213
Richard Smitha8105bc2012-01-06 16:39:00 +00002214/// Cast an lvalue referring to a base subobject to a derived class, by
2215/// truncating the lvalue's path to the given length.
2216static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2217 const RecordDecl *TruncatedType,
2218 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002219 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002220
2221 // Check we actually point to a derived class object.
2222 if (TruncatedElements == D.Entries.size())
2223 return true;
2224 assert(TruncatedElements >= D.MostDerivedPathLength &&
2225 "not casting to a derived class");
2226 if (!Result.checkSubobject(Info, E, CSK_Derived))
2227 return false;
2228
2229 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002230 const RecordDecl *RD = TruncatedType;
2231 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002232 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2234 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002235 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002236 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002237 else
Richard Smithd62306a2011-11-10 06:34:14 +00002238 Result.Offset -= Layout.getBaseClassOffset(Base);
2239 RD = Base;
2240 }
Richard Smith027bf112011-11-17 22:56:20 +00002241 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002242 return true;
2243}
2244
John McCalld7bca762012-05-01 00:38:49 +00002245static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002246 const CXXRecordDecl *Derived,
2247 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002248 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002249 if (!RL) {
2250 if (Derived->isInvalidDecl()) return false;
2251 RL = &Info.Ctx.getASTRecordLayout(Derived);
2252 }
2253
Richard Smithd62306a2011-11-10 06:34:14 +00002254 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002255 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002256 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002257}
2258
Richard Smitha8105bc2012-01-06 16:39:00 +00002259static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002260 const CXXRecordDecl *DerivedDecl,
2261 const CXXBaseSpecifier *Base) {
2262 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2263
John McCalld7bca762012-05-01 00:38:49 +00002264 if (!Base->isVirtual())
2265 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002266
Richard Smitha8105bc2012-01-06 16:39:00 +00002267 SubobjectDesignator &D = Obj.Designator;
2268 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002269 return false;
2270
Richard Smitha8105bc2012-01-06 16:39:00 +00002271 // Extract most-derived object and corresponding type.
2272 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2273 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2274 return false;
2275
2276 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002277 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002278 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2279 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002280 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002281 return true;
2282}
2283
Richard Smith84401042013-06-03 05:03:02 +00002284static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2285 QualType Type, LValue &Result) {
2286 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2287 PathE = E->path_end();
2288 PathI != PathE; ++PathI) {
2289 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2290 *PathI))
2291 return false;
2292 Type = (*PathI)->getType();
2293 }
2294 return true;
2295}
2296
Richard Smithd62306a2011-11-10 06:34:14 +00002297/// Update LVal to refer to the given field, which must be a member of the type
2298/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002299static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002300 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002301 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002302 if (!RL) {
2303 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002304 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002305 }
Richard Smithd62306a2011-11-10 06:34:14 +00002306
2307 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002308 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002309 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002310 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002311}
2312
Richard Smith1b78b3d2012-01-25 22:15:11 +00002313/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002314static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002315 LValue &LVal,
2316 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002317 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002318 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002319 return false;
2320 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002321}
2322
Richard Smithd62306a2011-11-10 06:34:14 +00002323/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002324static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2325 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002326 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2327 // extension.
2328 if (Type->isVoidType() || Type->isFunctionType()) {
2329 Size = CharUnits::One();
2330 return true;
2331 }
2332
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002333 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002334 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002335 return false;
2336 }
2337
Richard Smithd62306a2011-11-10 06:34:14 +00002338 if (!Type->isConstantSizeType()) {
2339 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002340 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002341 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002342 return false;
2343 }
2344
2345 Size = Info.Ctx.getTypeSizeInChars(Type);
2346 return true;
2347}
2348
2349/// Update a pointer value to model pointer arithmetic.
2350/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002351/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002352/// \param LVal - The pointer value to be updated.
2353/// \param EltTy - The pointee type represented by LVal.
2354/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002355static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2356 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002357 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002358 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002359 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002360 return false;
2361
Yaxun Liu402804b2016-12-15 08:09:08 +00002362 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002363 return true;
2364}
2365
Richard Smithd6cc1982017-01-31 02:23:02 +00002366static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2367 LValue &LVal, QualType EltTy,
2368 int64_t Adjustment) {
2369 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2370 APSInt::get(Adjustment));
2371}
2372
Richard Smith66c96992012-02-18 22:04:06 +00002373/// Update an lvalue to refer to a component of a complex number.
2374/// \param Info - Information about the ongoing evaluation.
2375/// \param LVal - The lvalue to be updated.
2376/// \param EltTy - The complex number's component type.
2377/// \param Imag - False for the real component, true for the imaginary.
2378static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2379 LValue &LVal, QualType EltTy,
2380 bool Imag) {
2381 if (Imag) {
2382 CharUnits SizeOfComponent;
2383 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2384 return false;
2385 LVal.Offset += SizeOfComponent;
2386 }
2387 LVal.addComplex(Info, E, EltTy, Imag);
2388 return true;
2389}
2390
Faisal Vali051e3a22017-02-16 04:12:21 +00002391static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2392 QualType Type, const LValue &LVal,
2393 APValue &RVal);
2394
Richard Smith27908702011-10-24 17:54:18 +00002395/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002396///
2397/// \param Info Information about the ongoing evaluation.
2398/// \param E An expression to be used when printing diagnostics.
2399/// \param VD The variable whose initializer should be obtained.
2400/// \param Frame The frame in which the variable was created. Must be null
2401/// if this variable is not local to the evaluation.
2402/// \param Result Filled in with a pointer to the value of the variable.
2403static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2404 const VarDecl *VD, CallStackFrame *Frame,
2405 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002406
Richard Smith254a73d2011-10-28 22:34:42 +00002407 // If this is a parameter to an active constexpr function call, perform
2408 // argument substitution.
2409 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002410 // Assume arguments of a potential constant expression are unknown
2411 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002412 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002413 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002414 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002415 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002416 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002417 }
Richard Smith3229b742013-05-05 21:17:10 +00002418 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002419 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002420 }
Richard Smith27908702011-10-24 17:54:18 +00002421
Richard Smithd9f663b2013-04-22 15:31:51 +00002422 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002423 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002424 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002425 if (!Result) {
2426 // Assume variables referenced within a lambda's call operator that were
2427 // not declared within the call operator are captures and during checking
2428 // of a potential constant expression, assume they are unknown constant
2429 // expressions.
2430 assert(isLambdaCallOperator(Frame->Callee) &&
2431 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2432 "missing value for local variable");
2433 if (Info.checkingPotentialConstantExpression())
2434 return false;
2435 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002436 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002437 diag::note_unimplemented_constexpr_lambda_feature_ast)
2438 << "captures not currently allowed";
2439 return false;
2440 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002441 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002442 }
2443
Richard Smithd0b4dd62011-12-19 06:19:21 +00002444 // Dig out the initializer, and use the declaration which it's attached to.
2445 const Expr *Init = VD->getAnyInitializer(VD);
2446 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002447 // If we're checking a potential constant expression, the variable could be
2448 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002449 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002450 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002451 return false;
2452 }
2453
Richard Smithd62306a2011-11-10 06:34:14 +00002454 // If we're currently evaluating the initializer of this declaration, use that
2455 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002456 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002457 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002458 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002459 }
2460
Richard Smithcecf1842011-11-01 21:06:14 +00002461 // Never evaluate the initializer of a weak variable. We can't be sure that
2462 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002463 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002464 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002465 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002466 }
Richard Smithcecf1842011-11-01 21:06:14 +00002467
Richard Smithd0b4dd62011-12-19 06:19:21 +00002468 // Check that we can fold the initializer. In C++, we will have already done
2469 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002470 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002471 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002472 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002473 Notes.size() + 1) << VD;
2474 Info.Note(VD->getLocation(), diag::note_declared_at);
2475 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002476 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002477 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002478 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002479 Notes.size() + 1) << VD;
2480 Info.Note(VD->getLocation(), diag::note_declared_at);
2481 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002482 }
Richard Smith27908702011-10-24 17:54:18 +00002483
Richard Smith3229b742013-05-05 21:17:10 +00002484 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002485 return true;
Richard Smith27908702011-10-24 17:54:18 +00002486}
2487
Richard Smith11562c52011-10-28 17:51:58 +00002488static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002489 Qualifiers Quals = T.getQualifiers();
2490 return Quals.hasConst() && !Quals.hasVolatile();
2491}
2492
Richard Smithe97cbd72011-11-11 04:05:33 +00002493/// Get the base index of the given base class within an APValue representing
2494/// the given derived class.
2495static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2496 const CXXRecordDecl *Base) {
2497 Base = Base->getCanonicalDecl();
2498 unsigned Index = 0;
2499 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2500 E = Derived->bases_end(); I != E; ++I, ++Index) {
2501 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2502 return Index;
2503 }
2504
2505 llvm_unreachable("base class missing from derived class's bases list");
2506}
2507
Richard Smith3da88fa2013-04-26 14:36:30 +00002508/// Extract the value of a character from a string literal.
2509static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2510 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002511 // FIXME: Support MakeStringConstant
2512 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2513 std::string Str;
2514 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2515 assert(Index <= Str.size() && "Index too large");
2516 return APSInt::getUnsigned(Str.c_str()[Index]);
2517 }
2518
Alexey Bataevec474782014-10-09 08:45:04 +00002519 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2520 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002521 const StringLiteral *S = cast<StringLiteral>(Lit);
2522 const ConstantArrayType *CAT =
2523 Info.Ctx.getAsConstantArrayType(S->getType());
2524 assert(CAT && "string literal isn't an array");
2525 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002526 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002527
2528 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002529 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002530 if (Index < S->getLength())
2531 Value = S->getCodeUnit(Index);
2532 return Value;
2533}
2534
Richard Smith3da88fa2013-04-26 14:36:30 +00002535// Expand a string literal into an array of characters.
2536static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2537 APValue &Result) {
2538 const StringLiteral *S = cast<StringLiteral>(Lit);
2539 const ConstantArrayType *CAT =
2540 Info.Ctx.getAsConstantArrayType(S->getType());
2541 assert(CAT && "string literal isn't an array");
2542 QualType CharType = CAT->getElementType();
2543 assert(CharType->isIntegerType() && "unexpected character type");
2544
2545 unsigned Elts = CAT->getSize().getZExtValue();
2546 Result = APValue(APValue::UninitArray(),
2547 std::min(S->getLength(), Elts), Elts);
2548 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2549 CharType->isUnsignedIntegerType());
2550 if (Result.hasArrayFiller())
2551 Result.getArrayFiller() = APValue(Value);
2552 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2553 Value = S->getCodeUnit(I);
2554 Result.getArrayInitializedElt(I) = APValue(Value);
2555 }
2556}
2557
2558// Expand an array so that it has more than Index filled elements.
2559static void expandArray(APValue &Array, unsigned Index) {
2560 unsigned Size = Array.getArraySize();
2561 assert(Index < Size);
2562
2563 // Always at least double the number of elements for which we store a value.
2564 unsigned OldElts = Array.getArrayInitializedElts();
2565 unsigned NewElts = std::max(Index+1, OldElts * 2);
2566 NewElts = std::min(Size, std::max(NewElts, 8u));
2567
2568 // Copy the data across.
2569 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2570 for (unsigned I = 0; I != OldElts; ++I)
2571 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2572 for (unsigned I = OldElts; I != NewElts; ++I)
2573 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2574 if (NewValue.hasArrayFiller())
2575 NewValue.getArrayFiller() = Array.getArrayFiller();
2576 Array.swap(NewValue);
2577}
2578
Richard Smithb01fe402014-09-16 01:24:02 +00002579/// Determine whether a type would actually be read by an lvalue-to-rvalue
2580/// conversion. If it's of class type, we may assume that the copy operation
2581/// is trivial. Note that this is never true for a union type with fields
2582/// (because the copy always "reads" the active member) and always true for
2583/// a non-class type.
2584static bool isReadByLvalueToRvalueConversion(QualType T) {
2585 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2586 if (!RD || (RD->isUnion() && !RD->field_empty()))
2587 return true;
2588 if (RD->isEmpty())
2589 return false;
2590
2591 for (auto *Field : RD->fields())
2592 if (isReadByLvalueToRvalueConversion(Field->getType()))
2593 return true;
2594
2595 for (auto &BaseSpec : RD->bases())
2596 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2597 return true;
2598
2599 return false;
2600}
2601
2602/// Diagnose an attempt to read from any unreadable field within the specified
2603/// type, which might be a class type.
2604static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2605 QualType T) {
2606 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2607 if (!RD)
2608 return false;
2609
2610 if (!RD->hasMutableFields())
2611 return false;
2612
2613 for (auto *Field : RD->fields()) {
2614 // If we're actually going to read this field in some way, then it can't
2615 // be mutable. If we're in a union, then assigning to a mutable field
2616 // (even an empty one) can change the active member, so that's not OK.
2617 // FIXME: Add core issue number for the union case.
2618 if (Field->isMutable() &&
2619 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002620 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002621 Info.Note(Field->getLocation(), diag::note_declared_at);
2622 return true;
2623 }
2624
2625 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2626 return true;
2627 }
2628
2629 for (auto &BaseSpec : RD->bases())
2630 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2631 return true;
2632
2633 // All mutable fields were empty, and thus not actually read.
2634 return false;
2635}
2636
Richard Smith861b5b52013-05-07 23:34:45 +00002637/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002638enum AccessKinds {
2639 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002640 AK_Assign,
2641 AK_Increment,
2642 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002643};
2644
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002645namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002646/// A handle to a complete object (an object that is not a subobject of
2647/// another object).
2648struct CompleteObject {
2649 /// The value of the complete object.
2650 APValue *Value;
2651 /// The type of the complete object.
2652 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002653 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002654
Craig Topper36250ad2014-05-12 05:36:57 +00002655 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002656 CompleteObject(APValue *Value, QualType Type,
2657 bool LifetimeStartedInEvaluation)
2658 : Value(Value), Type(Type),
2659 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002660 assert(Value && "missing value for complete object");
2661 }
2662
Aaron Ballman67347662015-02-15 22:00:28 +00002663 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002664};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002665} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002666
Richard Smith3da88fa2013-04-26 14:36:30 +00002667/// Find the designated sub-object of an rvalue.
2668template<typename SubobjectHandler>
2669typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002670findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002671 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002672 if (Sub.Invalid)
2673 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002674 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002675 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002676 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002677 Info.FFDiag(E, Sub.isOnePastTheEnd()
2678 ? diag::note_constexpr_access_past_end
2679 : diag::note_constexpr_access_unsized_array)
2680 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002681 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002682 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002683 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002684 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002685
Richard Smith3229b742013-05-05 21:17:10 +00002686 APValue *O = Obj.Value;
2687 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002688 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002689 const bool MayReadMutableMembers =
2690 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002691
Richard Smithd62306a2011-11-10 06:34:14 +00002692 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002693 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2694 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002695 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002696 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002697 return handler.failed();
2698 }
2699
Richard Smith49ca8aa2013-08-06 07:09:20 +00002700 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002701 // If we are reading an object of class type, there may still be more
2702 // things we need to check: if there are any mutable subobjects, we
2703 // cannot perform this read. (This only happens when performing a trivial
2704 // copy or assignment.)
2705 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002706 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002707 return handler.failed();
2708
Richard Smith49ca8aa2013-08-06 07:09:20 +00002709 if (!handler.found(*O, ObjType))
2710 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002711
Richard Smith49ca8aa2013-08-06 07:09:20 +00002712 // If we modified a bit-field, truncate it to the right width.
2713 if (handler.AccessKind != AK_Read &&
2714 LastField && LastField->isBitField() &&
2715 !truncateBitfieldValue(Info, E, *O, LastField))
2716 return false;
2717
2718 return true;
2719 }
2720
Craig Topper36250ad2014-05-12 05:36:57 +00002721 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002722 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002723 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002724 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002725 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002726 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002727 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002728 // Note, it should not be possible to form a pointer with a valid
2729 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002730 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002731 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002732 << handler.AccessKind;
2733 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002734 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002735 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002736 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002737
2738 ObjType = CAT->getElementType();
2739
Richard Smith14a94132012-02-17 03:35:37 +00002740 // An array object is represented as either an Array APValue or as an
2741 // LValue which refers to a string literal.
2742 if (O->isLValue()) {
2743 assert(I == N - 1 && "extracting subobject of character?");
2744 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002745 if (handler.AccessKind != AK_Read)
2746 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2747 *O);
2748 else
2749 return handler.foundString(*O, ObjType, Index);
2750 }
2751
2752 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002753 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 else if (handler.AccessKind != AK_Read) {
2755 expandArray(*O, Index);
2756 O = &O->getArrayInitializedElt(Index);
2757 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002758 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002759 } else if (ObjType->isAnyComplexType()) {
2760 // Next subobject is a complex number.
2761 uint64_t Index = Sub.Entries[I].ArrayIndex;
2762 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002763 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002764 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002765 << handler.AccessKind;
2766 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002767 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002768 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002769 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002770
2771 bool WasConstQualified = ObjType.isConstQualified();
2772 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2773 if (WasConstQualified)
2774 ObjType.addConst();
2775
Richard Smith66c96992012-02-18 22:04:06 +00002776 assert(I == N - 1 && "extracting subobject of scalar?");
2777 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 return handler.found(Index ? O->getComplexIntImag()
2779 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002780 } else {
2781 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002782 return handler.found(Index ? O->getComplexFloatImag()
2783 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002784 }
Richard Smithd62306a2011-11-10 06:34:14 +00002785 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002786 // In C++14 onwards, it is permitted to read a mutable member whose
2787 // lifetime began within the evaluation.
2788 // FIXME: Should we also allow this in C++11?
2789 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2790 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002791 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002792 << Field;
2793 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002794 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002795 }
2796
Richard Smithd62306a2011-11-10 06:34:14 +00002797 // Next subobject is a class, struct or union field.
2798 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2799 if (RD->isUnion()) {
2800 const FieldDecl *UnionField = O->getUnionField();
2801 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002802 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002803 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002804 << handler.AccessKind << Field << !UnionField << UnionField;
2805 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002806 }
Richard Smithd62306a2011-11-10 06:34:14 +00002807 O = &O->getUnionValue();
2808 } else
2809 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002810
2811 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002812 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002813 if (WasConstQualified && !Field->isMutable())
2814 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002815
2816 if (ObjType.isVolatileQualified()) {
2817 if (Info.getLangOpts().CPlusPlus) {
2818 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002819 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002820 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002821 Info.Note(Field->getLocation(), diag::note_declared_at);
2822 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002823 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002824 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002825 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002826 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002827
2828 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002829 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002830 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002831 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2832 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2833 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002834
2835 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002836 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002837 if (WasConstQualified)
2838 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002839 }
2840 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002841}
2842
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002843namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002844struct ExtractSubobjectHandler {
2845 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002846 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002847
2848 static const AccessKinds AccessKind = AK_Read;
2849
2850 typedef bool result_type;
2851 bool failed() { return false; }
2852 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002853 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002854 return true;
2855 }
2856 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002857 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002858 return true;
2859 }
2860 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002861 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 return true;
2863 }
2864 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002865 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002866 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2867 return true;
2868 }
2869};
Richard Smith3229b742013-05-05 21:17:10 +00002870} // end anonymous namespace
2871
Richard Smith3da88fa2013-04-26 14:36:30 +00002872const AccessKinds ExtractSubobjectHandler::AccessKind;
2873
2874/// Extract the designated sub-object of an rvalue.
2875static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002876 const CompleteObject &Obj,
2877 const SubobjectDesignator &Sub,
2878 APValue &Result) {
2879 ExtractSubobjectHandler Handler = { Info, Result };
2880 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002881}
2882
Richard Smith3229b742013-05-05 21:17:10 +00002883namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002884struct ModifySubobjectHandler {
2885 EvalInfo &Info;
2886 APValue &NewVal;
2887 const Expr *E;
2888
2889 typedef bool result_type;
2890 static const AccessKinds AccessKind = AK_Assign;
2891
2892 bool checkConst(QualType QT) {
2893 // Assigning to a const object has undefined behavior.
2894 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002895 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002896 return false;
2897 }
2898 return true;
2899 }
2900
2901 bool failed() { return false; }
2902 bool found(APValue &Subobj, QualType SubobjType) {
2903 if (!checkConst(SubobjType))
2904 return false;
2905 // We've been given ownership of NewVal, so just swap it in.
2906 Subobj.swap(NewVal);
2907 return true;
2908 }
2909 bool found(APSInt &Value, QualType SubobjType) {
2910 if (!checkConst(SubobjType))
2911 return false;
2912 if (!NewVal.isInt()) {
2913 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002914 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002915 return false;
2916 }
2917 Value = NewVal.getInt();
2918 return true;
2919 }
2920 bool found(APFloat &Value, QualType SubobjType) {
2921 if (!checkConst(SubobjType))
2922 return false;
2923 Value = NewVal.getFloat();
2924 return true;
2925 }
2926 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2927 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2928 }
2929};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002930} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002931
Richard Smith3229b742013-05-05 21:17:10 +00002932const AccessKinds ModifySubobjectHandler::AccessKind;
2933
Richard Smith3da88fa2013-04-26 14:36:30 +00002934/// Update the designated sub-object of an rvalue to the given value.
2935static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002936 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 const SubobjectDesignator &Sub,
2938 APValue &NewVal) {
2939 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002940 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002941}
2942
Richard Smith84f6dcf2012-02-02 01:16:57 +00002943/// Find the position where two subobject designators diverge, or equivalently
2944/// the length of the common initial subsequence.
2945static unsigned FindDesignatorMismatch(QualType ObjType,
2946 const SubobjectDesignator &A,
2947 const SubobjectDesignator &B,
2948 bool &WasArrayIndex) {
2949 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2950 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002951 if (!ObjType.isNull() &&
2952 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002953 // Next subobject is an array element.
2954 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2955 WasArrayIndex = true;
2956 return I;
2957 }
Richard Smith66c96992012-02-18 22:04:06 +00002958 if (ObjType->isAnyComplexType())
2959 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2960 else
2961 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002962 } else {
2963 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2964 WasArrayIndex = false;
2965 return I;
2966 }
2967 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2968 // Next subobject is a field.
2969 ObjType = FD->getType();
2970 else
2971 // Next subobject is a base class.
2972 ObjType = QualType();
2973 }
2974 }
2975 WasArrayIndex = false;
2976 return I;
2977}
2978
2979/// Determine whether the given subobject designators refer to elements of the
2980/// same array object.
2981static bool AreElementsOfSameArray(QualType ObjType,
2982 const SubobjectDesignator &A,
2983 const SubobjectDesignator &B) {
2984 if (A.Entries.size() != B.Entries.size())
2985 return false;
2986
George Burgess IVa51c4072015-10-16 01:49:01 +00002987 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002988 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2989 // A is a subobject of the array element.
2990 return false;
2991
2992 // If A (and B) designates an array element, the last entry will be the array
2993 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2994 // of length 1' case, and the entire path must match.
2995 bool WasArrayIndex;
2996 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2997 return CommonLength >= A.Entries.size() - IsArray;
2998}
2999
Richard Smith3229b742013-05-05 21:17:10 +00003000/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003001static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3002 AccessKinds AK, const LValue &LVal,
3003 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003004 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003005 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003006 return CompleteObject();
3007 }
3008
Craig Topper36250ad2014-05-12 05:36:57 +00003009 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00003010 if (LVal.CallIndex) {
3011 Frame = Info.getCallFrame(LVal.CallIndex);
3012 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003013 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003014 << AK << LVal.Base.is<const ValueDecl*>();
3015 NoteLValueLocation(Info, LVal.Base);
3016 return CompleteObject();
3017 }
Richard Smith3229b742013-05-05 21:17:10 +00003018 }
3019
3020 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3021 // is not a constant expression (even if the object is non-volatile). We also
3022 // apply this rule to C++98, in order to conform to the expected 'volatile'
3023 // semantics.
3024 if (LValType.isVolatileQualified()) {
3025 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003026 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003027 << AK << LValType;
3028 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003029 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003030 return CompleteObject();
3031 }
3032
3033 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003034 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003035 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003036 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003037
3038 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3039 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3040 // In C++11, constexpr, non-volatile variables initialized with constant
3041 // expressions are constant expressions too. Inside constexpr functions,
3042 // parameters are constant expressions even if they're non-const.
3043 // In C++1y, objects local to a constant expression (those with a Frame) are
3044 // both readable and writable inside constant expressions.
3045 // In C, such things can also be folded, although they are not ICEs.
3046 const VarDecl *VD = dyn_cast<VarDecl>(D);
3047 if (VD) {
3048 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3049 VD = VDef;
3050 }
3051 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003052 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003053 return CompleteObject();
3054 }
3055
3056 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003057 if (BaseType.isVolatileQualified()) {
3058 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003059 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003060 << AK << 1 << VD;
3061 Info.Note(VD->getLocation(), diag::note_declared_at);
3062 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003063 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003064 }
3065 return CompleteObject();
3066 }
3067
3068 // Unless we're looking at a local variable or argument in a constexpr call,
3069 // the variable we're reading must be const.
3070 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003071 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003072 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3073 // OK, we can read and modify an object if we're in the process of
3074 // evaluating its initializer, because its lifetime began in this
3075 // evaluation.
3076 } else if (AK != AK_Read) {
3077 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003078 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003079 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003080 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003081 // OK, we can read this variable.
3082 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003083 // In OpenCL if a variable is in constant address space it is a const value.
3084 if (!(BaseType.isConstQualified() ||
3085 (Info.getLangOpts().OpenCL &&
3086 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003087 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003088 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003089 Info.Note(VD->getLocation(), diag::note_declared_at);
3090 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003091 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003092 }
3093 return CompleteObject();
3094 }
3095 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3096 // We support folding of const floating-point types, in order to make
3097 // static const data members of such types (supported as an extension)
3098 // more useful.
3099 if (Info.getLangOpts().CPlusPlus11) {
3100 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3101 Info.Note(VD->getLocation(), diag::note_declared_at);
3102 } else {
3103 Info.CCEDiag(E);
3104 }
George Burgess IVb5316982016-12-27 05:33:20 +00003105 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3106 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3107 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003108 } else {
3109 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003110 if (Info.checkingPotentialConstantExpression() &&
3111 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3112 // The definition of this variable could be constexpr. We can't
3113 // access it right now, but may be able to in future.
3114 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003115 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003116 Info.Note(VD->getLocation(), diag::note_declared_at);
3117 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003118 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003119 }
3120 return CompleteObject();
3121 }
3122 }
3123
3124 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3125 return CompleteObject();
3126 } else {
3127 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3128
3129 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003130 if (const MaterializeTemporaryExpr *MTE =
3131 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3132 assert(MTE->getStorageDuration() == SD_Static &&
3133 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003134
Richard Smithe6c01442013-06-05 00:46:14 +00003135 // Per C++1y [expr.const]p2:
3136 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3137 // - a [...] glvalue of integral or enumeration type that refers to
3138 // a non-volatile const object [...]
3139 // [...]
3140 // - a [...] glvalue of literal type that refers to a non-volatile
3141 // object whose lifetime began within the evaluation of e.
3142 //
3143 // C++11 misses the 'began within the evaluation of e' check and
3144 // instead allows all temporaries, including things like:
3145 // int &&r = 1;
3146 // int x = ++r;
3147 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003148 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003149 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3150 const ValueDecl *ED = MTE->getExtendingDecl();
3151 if (!(BaseType.isConstQualified() &&
3152 BaseType->isIntegralOrEnumerationType()) &&
3153 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003154 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003155 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3156 return CompleteObject();
3157 }
3158
3159 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3160 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003161 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003162 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003163 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003164 return CompleteObject();
3165 }
3166 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003167 BaseVal = Frame->getTemporary(Base);
3168 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003169 }
Richard Smith3229b742013-05-05 21:17:10 +00003170
3171 // Volatile temporary objects cannot be accessed in constant expressions.
3172 if (BaseType.isVolatileQualified()) {
3173 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003174 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003175 << AK << 0;
3176 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3177 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003178 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003179 }
3180 return CompleteObject();
3181 }
3182 }
3183
Richard Smith7525ff62013-05-09 07:14:00 +00003184 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003185 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003186 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003187 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003188 BaseType = Info.Ctx.getCanonicalType(BaseType);
3189 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003190 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003191 }
3192
Richard Smith9defb7d2018-02-21 03:38:30 +00003193 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003194 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003195 //
3196 // FIXME: Not all local state is mutable. Allow local constant subobjects
3197 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003198 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3199 Info.EvalStatus.HasSideEffects) ||
3200 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003201 return CompleteObject();
3202
Richard Smith9defb7d2018-02-21 03:38:30 +00003203 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003204}
3205
Richard Smith243ef902013-05-05 23:31:59 +00003206/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3207/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3208/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003209///
3210/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003211/// \param Conv - The expression for which we are performing the conversion.
3212/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003213/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3214/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003215/// \param LVal - The glvalue on which we are attempting to perform this action.
3216/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003217static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003218 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003219 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003220 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003221 return false;
3222
Richard Smith3229b742013-05-05 21:17:10 +00003223 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003224 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003225 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003226 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3227 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3228 // initializer until now for such expressions. Such an expression can't be
3229 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003230 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003231 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003232 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003233 }
Richard Smith3229b742013-05-05 21:17:10 +00003234 APValue Lit;
3235 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3236 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003237 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003238 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003239 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003240 // We represent a string literal array as an lvalue pointing at the
3241 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003242 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003243 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003244 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003245 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003246 }
Richard Smith11562c52011-10-28 17:51:58 +00003247 }
3248
Richard Smith3229b742013-05-05 21:17:10 +00003249 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3250 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003251}
3252
3253/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003254static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003255 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003256 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003257 return false;
3258
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003259 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003260 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003261 return false;
3262 }
3263
Richard Smith3229b742013-05-05 21:17:10 +00003264 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003265 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3266}
3267
3268namespace {
3269struct CompoundAssignSubobjectHandler {
3270 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003271 const Expr *E;
3272 QualType PromotedLHSType;
3273 BinaryOperatorKind Opcode;
3274 const APValue &RHS;
3275
3276 static const AccessKinds AccessKind = AK_Assign;
3277
3278 typedef bool result_type;
3279
3280 bool checkConst(QualType QT) {
3281 // Assigning to a const object has undefined behavior.
3282 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003283 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003284 return false;
3285 }
3286 return true;
3287 }
3288
3289 bool failed() { return false; }
3290 bool found(APValue &Subobj, QualType SubobjType) {
3291 switch (Subobj.getKind()) {
3292 case APValue::Int:
3293 return found(Subobj.getInt(), SubobjType);
3294 case APValue::Float:
3295 return found(Subobj.getFloat(), SubobjType);
3296 case APValue::ComplexInt:
3297 case APValue::ComplexFloat:
3298 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003299 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003300 return false;
3301 case APValue::LValue:
3302 return foundPointer(Subobj, SubobjType);
3303 default:
3304 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003305 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003306 return false;
3307 }
3308 }
3309 bool found(APSInt &Value, QualType SubobjType) {
3310 if (!checkConst(SubobjType))
3311 return false;
3312
3313 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3314 // We don't support compound assignment on integer-cast-to-pointer
3315 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003316 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003317 return false;
3318 }
3319
3320 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3321 SubobjType, Value);
3322 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3323 return false;
3324 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3325 return true;
3326 }
3327 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003328 return checkConst(SubobjType) &&
3329 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3330 Value) &&
3331 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3332 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003333 }
3334 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3335 if (!checkConst(SubobjType))
3336 return false;
3337
3338 QualType PointeeType;
3339 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3340 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003341
3342 if (PointeeType.isNull() || !RHS.isInt() ||
3343 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003344 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003345 return false;
3346 }
3347
Richard Smithd6cc1982017-01-31 02:23:02 +00003348 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003349 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003350 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003351
3352 LValue LVal;
3353 LVal.setFrom(Info.Ctx, Subobj);
3354 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3355 return false;
3356 LVal.moveInto(Subobj);
3357 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003358 }
3359 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3360 llvm_unreachable("shouldn't encounter string elements here");
3361 }
3362};
3363} // end anonymous namespace
3364
3365const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3366
3367/// Perform a compound assignment of LVal <op>= RVal.
3368static bool handleCompoundAssignment(
3369 EvalInfo &Info, const Expr *E,
3370 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3371 BinaryOperatorKind Opcode, const APValue &RVal) {
3372 if (LVal.Designator.Invalid)
3373 return false;
3374
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003375 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003376 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003377 return false;
3378 }
3379
3380 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3381 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3382 RVal };
3383 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3384}
3385
Aaron Ballmana5038552018-01-09 13:07:03 +00003386namespace {
3387struct IncDecSubobjectHandler {
3388 EvalInfo &Info;
3389 const UnaryOperator *E;
3390 AccessKinds AccessKind;
3391 APValue *Old;
3392
Richard Smith243ef902013-05-05 23:31:59 +00003393 typedef bool result_type;
3394
3395 bool checkConst(QualType QT) {
3396 // Assigning to a const object has undefined behavior.
3397 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003398 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003399 return false;
3400 }
3401 return true;
3402 }
3403
3404 bool failed() { return false; }
3405 bool found(APValue &Subobj, QualType SubobjType) {
3406 // Stash the old value. Also clear Old, so we don't clobber it later
3407 // if we're post-incrementing a complex.
3408 if (Old) {
3409 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003410 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003411 }
3412
3413 switch (Subobj.getKind()) {
3414 case APValue::Int:
3415 return found(Subobj.getInt(), SubobjType);
3416 case APValue::Float:
3417 return found(Subobj.getFloat(), SubobjType);
3418 case APValue::ComplexInt:
3419 return found(Subobj.getComplexIntReal(),
3420 SubobjType->castAs<ComplexType>()->getElementType()
3421 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3422 case APValue::ComplexFloat:
3423 return found(Subobj.getComplexFloatReal(),
3424 SubobjType->castAs<ComplexType>()->getElementType()
3425 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3426 case APValue::LValue:
3427 return foundPointer(Subobj, SubobjType);
3428 default:
3429 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003430 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003431 return false;
3432 }
3433 }
3434 bool found(APSInt &Value, QualType SubobjType) {
3435 if (!checkConst(SubobjType))
3436 return false;
3437
3438 if (!SubobjType->isIntegerType()) {
3439 // We don't support increment / decrement on integer-cast-to-pointer
3440 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003441 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003442 return false;
3443 }
3444
3445 if (Old) *Old = APValue(Value);
3446
3447 // bool arithmetic promotes to int, and the conversion back to bool
3448 // doesn't reduce mod 2^n, so special-case it.
3449 if (SubobjType->isBooleanType()) {
3450 if (AccessKind == AK_Increment)
3451 Value = 1;
3452 else
3453 Value = !Value;
3454 return true;
3455 }
3456
3457 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003458 if (AccessKind == AK_Increment) {
3459 ++Value;
3460
3461 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3462 APSInt ActualValue(Value, /*IsUnsigned*/true);
3463 return HandleOverflow(Info, E, ActualValue, SubobjType);
3464 }
3465 } else {
3466 --Value;
3467
3468 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3469 unsigned BitWidth = Value.getBitWidth();
3470 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3471 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003472 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003473 }
3474 }
3475 return true;
3476 }
3477 bool found(APFloat &Value, QualType SubobjType) {
3478 if (!checkConst(SubobjType))
3479 return false;
3480
3481 if (Old) *Old = APValue(Value);
3482
3483 APFloat One(Value.getSemantics(), 1);
3484 if (AccessKind == AK_Increment)
3485 Value.add(One, APFloat::rmNearestTiesToEven);
3486 else
3487 Value.subtract(One, APFloat::rmNearestTiesToEven);
3488 return true;
3489 }
3490 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3491 if (!checkConst(SubobjType))
3492 return false;
3493
3494 QualType PointeeType;
3495 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3496 PointeeType = PT->getPointeeType();
3497 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003498 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003499 return false;
3500 }
3501
3502 LValue LVal;
3503 LVal.setFrom(Info.Ctx, Subobj);
3504 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3505 AccessKind == AK_Increment ? 1 : -1))
3506 return false;
3507 LVal.moveInto(Subobj);
3508 return true;
3509 }
3510 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3511 llvm_unreachable("shouldn't encounter string elements here");
3512 }
3513};
3514} // end anonymous namespace
3515
3516/// Perform an increment or decrement on LVal.
3517static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3518 QualType LValType, bool IsIncrement, APValue *Old) {
3519 if (LVal.Designator.Invalid)
3520 return false;
3521
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003522 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003523 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003524 return false;
3525 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003526
3527 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3528 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3529 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3530 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3531}
3532
Richard Smithe97cbd72011-11-11 04:05:33 +00003533/// Build an lvalue for the object argument of a member function call.
3534static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3535 LValue &This) {
3536 if (Object->getType()->isPointerType())
3537 return EvaluatePointer(Object, This, Info);
3538
3539 if (Object->isGLValue())
3540 return EvaluateLValue(Object, This, Info);
3541
Richard Smithd9f663b2013-04-22 15:31:51 +00003542 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003543 return EvaluateTemporary(Object, This, Info);
3544
Faisal Valie690b7a2016-07-02 22:34:24 +00003545 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003546 return false;
3547}
3548
3549/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3550/// lvalue referring to the result.
3551///
3552/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003553/// \param LV - An lvalue referring to the base of the member pointer.
3554/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003555/// \param IncludeMember - Specifies whether the member itself is included in
3556/// the resulting LValue subobject designator. This is not possible when
3557/// creating a bound member function.
3558/// \return The field or method declaration to which the member pointer refers,
3559/// or 0 if evaluation fails.
3560static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003561 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003562 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003563 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003564 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003565 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003566 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003567 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003568
3569 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3570 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003571 if (!MemPtr.getDecl()) {
3572 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003573 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003574 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003575 }
Richard Smith253c2a32012-01-27 01:14:48 +00003576
Richard Smith027bf112011-11-17 22:56:20 +00003577 if (MemPtr.isDerivedMember()) {
3578 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003579 // The end of the derived-to-base path for the base object must match the
3580 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003581 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003582 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003583 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003584 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003585 }
Richard Smith027bf112011-11-17 22:56:20 +00003586 unsigned PathLengthToMember =
3587 LV.Designator.Entries.size() - MemPtr.Path.size();
3588 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3589 const CXXRecordDecl *LVDecl = getAsBaseClass(
3590 LV.Designator.Entries[PathLengthToMember + I]);
3591 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003592 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003593 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003594 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003595 }
Richard Smith027bf112011-11-17 22:56:20 +00003596 }
3597
3598 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003599 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003600 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003601 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003602 } else if (!MemPtr.Path.empty()) {
3603 // Extend the LValue path with the member pointer's path.
3604 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3605 MemPtr.Path.size() + IncludeMember);
3606
3607 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003608 if (const PointerType *PT = LVType->getAs<PointerType>())
3609 LVType = PT->getPointeeType();
3610 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3611 assert(RD && "member pointer access on non-class-type expression");
3612 // The first class in the path is that of the lvalue.
3613 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3614 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003615 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003616 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003617 RD = Base;
3618 }
3619 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003620 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3621 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003622 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003623 }
3624
3625 // Add the member. Note that we cannot build bound member functions here.
3626 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003627 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003628 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003629 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003630 } else if (const IndirectFieldDecl *IFD =
3631 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003632 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003633 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003634 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003635 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003636 }
Richard Smith027bf112011-11-17 22:56:20 +00003637 }
3638
3639 return MemPtr.getDecl();
3640}
3641
Richard Smith84401042013-06-03 05:03:02 +00003642static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3643 const BinaryOperator *BO,
3644 LValue &LV,
3645 bool IncludeMember = true) {
3646 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3647
3648 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003649 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003650 MemberPtr MemPtr;
3651 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3652 }
Craig Topper36250ad2014-05-12 05:36:57 +00003653 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003654 }
3655
3656 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3657 BO->getRHS(), IncludeMember);
3658}
3659
Richard Smith027bf112011-11-17 22:56:20 +00003660/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3661/// the provided lvalue, which currently refers to the base object.
3662static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3663 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003664 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003665 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003666 return false;
3667
Richard Smitha8105bc2012-01-06 16:39:00 +00003668 QualType TargetQT = E->getType();
3669 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3670 TargetQT = PT->getPointeeType();
3671
3672 // Check this cast lands within the final derived-to-base subobject path.
3673 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003674 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003675 << D.MostDerivedType << TargetQT;
3676 return false;
3677 }
3678
Richard Smith027bf112011-11-17 22:56:20 +00003679 // Check the type of the final cast. We don't need to check the path,
3680 // since a cast can only be formed if the path is unique.
3681 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003682 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3683 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003684 if (NewEntriesSize == D.MostDerivedPathLength)
3685 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3686 else
Richard Smith027bf112011-11-17 22:56:20 +00003687 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003688 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003689 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003690 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003691 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003692 }
Richard Smith027bf112011-11-17 22:56:20 +00003693
3694 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003695 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003696}
3697
Mike Stump876387b2009-10-27 22:09:17 +00003698namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003699enum EvalStmtResult {
3700 /// Evaluation failed.
3701 ESR_Failed,
3702 /// Hit a 'return' statement.
3703 ESR_Returned,
3704 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003705 ESR_Succeeded,
3706 /// Hit a 'continue' statement.
3707 ESR_Continue,
3708 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003709 ESR_Break,
3710 /// Still scanning for 'case' or 'default' statement.
3711 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003712};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003713}
Richard Smith254a73d2011-10-28 22:34:42 +00003714
Richard Smith97fcf4b2016-08-14 23:15:52 +00003715static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3716 // We don't need to evaluate the initializer for a static local.
3717 if (!VD->hasLocalStorage())
3718 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003719
Richard Smith97fcf4b2016-08-14 23:15:52 +00003720 LValue Result;
3721 Result.set(VD, Info.CurrentCall->Index);
3722 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003723
Richard Smith97fcf4b2016-08-14 23:15:52 +00003724 const Expr *InitE = VD->getInit();
3725 if (!InitE) {
3726 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3727 << false << VD->getType();
3728 Val = APValue();
3729 return false;
3730 }
Richard Smith51f03172013-06-20 03:00:05 +00003731
Richard Smith97fcf4b2016-08-14 23:15:52 +00003732 if (InitE->isValueDependent())
3733 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003734
Richard Smith97fcf4b2016-08-14 23:15:52 +00003735 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3736 // Wipe out any partially-computed value, to allow tracking that this
3737 // evaluation failed.
3738 Val = APValue();
3739 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003740 }
3741
3742 return true;
3743}
3744
Richard Smith97fcf4b2016-08-14 23:15:52 +00003745static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3746 bool OK = true;
3747
3748 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3749 OK &= EvaluateVarDecl(Info, VD);
3750
3751 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3752 for (auto *BD : DD->bindings())
3753 if (auto *VD = BD->getHoldingVar())
3754 OK &= EvaluateDecl(Info, VD);
3755
3756 return OK;
3757}
3758
3759
Richard Smith4e18ca52013-05-06 05:56:11 +00003760/// Evaluate a condition (either a variable declaration or an expression).
3761static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3762 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003763 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003764 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3765 return false;
3766 return EvaluateAsBooleanCondition(Cond, Result, Info);
3767}
3768
Richard Smith89210072016-04-04 23:29:43 +00003769namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003770/// \brief A location where the result (returned value) of evaluating a
3771/// statement should be stored.
3772struct StmtResult {
3773 /// The APValue that should be filled in with the returned value.
3774 APValue &Value;
3775 /// The location containing the result, if any (used to support RVO).
3776 const LValue *Slot;
3777};
Richard Smith89210072016-04-04 23:29:43 +00003778}
Richard Smith52a980a2015-08-28 02:43:42 +00003779
3780static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003781 const Stmt *S,
3782 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003783
3784/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003785static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003786 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003787 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003788 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003789 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003790 case ESR_Break:
3791 return ESR_Succeeded;
3792 case ESR_Succeeded:
3793 case ESR_Continue:
3794 return ESR_Continue;
3795 case ESR_Failed:
3796 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003797 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003798 return ESR;
3799 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003800 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003801}
3802
Richard Smith496ddcf2013-05-12 17:32:42 +00003803/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003804static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003805 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806 BlockScopeRAII Scope(Info);
3807
Richard Smith496ddcf2013-05-12 17:32:42 +00003808 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003809 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003810 {
3811 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003812 if (const Stmt *Init = SS->getInit()) {
3813 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3814 if (ESR != ESR_Succeeded)
3815 return ESR;
3816 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003817 if (SS->getConditionVariable() &&
3818 !EvaluateDecl(Info, SS->getConditionVariable()))
3819 return ESR_Failed;
3820 if (!EvaluateInteger(SS->getCond(), Value, Info))
3821 return ESR_Failed;
3822 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003823
3824 // Find the switch case corresponding to the value of the condition.
3825 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003826 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003827 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3828 SC = SC->getNextSwitchCase()) {
3829 if (isa<DefaultStmt>(SC)) {
3830 Found = SC;
3831 continue;
3832 }
3833
3834 const CaseStmt *CS = cast<CaseStmt>(SC);
3835 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3836 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3837 : LHS;
3838 if (LHS <= Value && Value <= RHS) {
3839 Found = SC;
3840 break;
3841 }
3842 }
3843
3844 if (!Found)
3845 return ESR_Succeeded;
3846
3847 // Search the switch body for the switch case and evaluate it from there.
3848 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3849 case ESR_Break:
3850 return ESR_Succeeded;
3851 case ESR_Succeeded:
3852 case ESR_Continue:
3853 case ESR_Failed:
3854 case ESR_Returned:
3855 return ESR;
3856 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003857 // This can only happen if the switch case is nested within a statement
3858 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003859 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003860 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003861 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003862 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003863}
3864
Richard Smith254a73d2011-10-28 22:34:42 +00003865// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003866static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003867 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003868 if (!Info.nextStep(S))
3869 return ESR_Failed;
3870
Richard Smith496ddcf2013-05-12 17:32:42 +00003871 // If we're hunting down a 'case' or 'default' label, recurse through
3872 // substatements until we hit the label.
3873 if (Case) {
3874 // FIXME: We don't start the lifetime of objects whose initialization we
3875 // jump over. However, such objects must be of class type with a trivial
3876 // default constructor that initialize all subobjects, so must be empty,
3877 // so this almost never matters.
3878 switch (S->getStmtClass()) {
3879 case Stmt::CompoundStmtClass:
3880 // FIXME: Precompute which substatement of a compound statement we
3881 // would jump to, and go straight there rather than performing a
3882 // linear scan each time.
3883 case Stmt::LabelStmtClass:
3884 case Stmt::AttributedStmtClass:
3885 case Stmt::DoStmtClass:
3886 break;
3887
3888 case Stmt::CaseStmtClass:
3889 case Stmt::DefaultStmtClass:
3890 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003891 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003892 break;
3893
3894 case Stmt::IfStmtClass: {
3895 // FIXME: Precompute which side of an 'if' we would jump to, and go
3896 // straight there rather than scanning both sides.
3897 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003898
3899 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3900 // preceded by our switch label.
3901 BlockScopeRAII Scope(Info);
3902
Richard Smith496ddcf2013-05-12 17:32:42 +00003903 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3904 if (ESR != ESR_CaseNotFound || !IS->getElse())
3905 return ESR;
3906 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3907 }
3908
3909 case Stmt::WhileStmtClass: {
3910 EvalStmtResult ESR =
3911 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3912 if (ESR != ESR_Continue)
3913 return ESR;
3914 break;
3915 }
3916
3917 case Stmt::ForStmtClass: {
3918 const ForStmt *FS = cast<ForStmt>(S);
3919 EvalStmtResult ESR =
3920 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3921 if (ESR != ESR_Continue)
3922 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003923 if (FS->getInc()) {
3924 FullExpressionRAII IncScope(Info);
3925 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3926 return ESR_Failed;
3927 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003928 break;
3929 }
3930
3931 case Stmt::DeclStmtClass:
3932 // FIXME: If the variable has initialization that can't be jumped over,
3933 // bail out of any immediately-surrounding compound-statement too.
3934 default:
3935 return ESR_CaseNotFound;
3936 }
3937 }
3938
Richard Smith254a73d2011-10-28 22:34:42 +00003939 switch (S->getStmtClass()) {
3940 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003941 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003942 // Don't bother evaluating beyond an expression-statement which couldn't
3943 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003944 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003945 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003946 return ESR_Failed;
3947 return ESR_Succeeded;
3948 }
3949
Faisal Valie690b7a2016-07-02 22:34:24 +00003950 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003951 return ESR_Failed;
3952
3953 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003954 return ESR_Succeeded;
3955
Richard Smithd9f663b2013-04-22 15:31:51 +00003956 case Stmt::DeclStmtClass: {
3957 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003958 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003959 // Each declaration initialization is its own full-expression.
3960 // FIXME: This isn't quite right; if we're performing aggregate
3961 // initialization, each braced subexpression is its own full-expression.
3962 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003963 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003964 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003965 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003966 return ESR_Succeeded;
3967 }
3968
Richard Smith357362d2011-12-13 06:39:58 +00003969 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003970 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003971 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003972 if (RetExpr &&
3973 !(Result.Slot
3974 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3975 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003976 return ESR_Failed;
3977 return ESR_Returned;
3978 }
Richard Smith254a73d2011-10-28 22:34:42 +00003979
3980 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003981 BlockScopeRAII Scope(Info);
3982
Richard Smith254a73d2011-10-28 22:34:42 +00003983 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003984 for (const auto *BI : CS->body()) {
3985 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003986 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003987 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003988 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003989 return ESR;
3990 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003991 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003992 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003993
3994 case Stmt::IfStmtClass: {
3995 const IfStmt *IS = cast<IfStmt>(S);
3996
3997 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003998 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003999 if (const Stmt *Init = IS->getInit()) {
4000 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4001 if (ESR != ESR_Succeeded)
4002 return ESR;
4003 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004004 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004005 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004006 return ESR_Failed;
4007
4008 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4009 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4010 if (ESR != ESR_Succeeded)
4011 return ESR;
4012 }
4013 return ESR_Succeeded;
4014 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004015
4016 case Stmt::WhileStmtClass: {
4017 const WhileStmt *WS = cast<WhileStmt>(S);
4018 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004019 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004020 bool Continue;
4021 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4022 Continue))
4023 return ESR_Failed;
4024 if (!Continue)
4025 break;
4026
4027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4028 if (ESR != ESR_Continue)
4029 return ESR;
4030 }
4031 return ESR_Succeeded;
4032 }
4033
4034 case Stmt::DoStmtClass: {
4035 const DoStmt *DS = cast<DoStmt>(S);
4036 bool Continue;
4037 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004038 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004039 if (ESR != ESR_Continue)
4040 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004041 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004042
Richard Smith08d6a2c2013-07-24 07:11:57 +00004043 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004044 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4045 return ESR_Failed;
4046 } while (Continue);
4047 return ESR_Succeeded;
4048 }
4049
4050 case Stmt::ForStmtClass: {
4051 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004052 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004053 if (FS->getInit()) {
4054 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4055 if (ESR != ESR_Succeeded)
4056 return ESR;
4057 }
4058 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004059 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004060 bool Continue = true;
4061 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4062 FS->getCond(), Continue))
4063 return ESR_Failed;
4064 if (!Continue)
4065 break;
4066
4067 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4068 if (ESR != ESR_Continue)
4069 return ESR;
4070
Richard Smith08d6a2c2013-07-24 07:11:57 +00004071 if (FS->getInc()) {
4072 FullExpressionRAII IncScope(Info);
4073 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4074 return ESR_Failed;
4075 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004076 }
4077 return ESR_Succeeded;
4078 }
4079
Richard Smith896e0d72013-05-06 06:51:17 +00004080 case Stmt::CXXForRangeStmtClass: {
4081 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004082 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004083
4084 // Initialize the __range variable.
4085 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4086 if (ESR != ESR_Succeeded)
4087 return ESR;
4088
4089 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004090 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4091 if (ESR != ESR_Succeeded)
4092 return ESR;
4093 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004094 if (ESR != ESR_Succeeded)
4095 return ESR;
4096
4097 while (true) {
4098 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004099 {
4100 bool Continue = true;
4101 FullExpressionRAII CondExpr(Info);
4102 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4103 return ESR_Failed;
4104 if (!Continue)
4105 break;
4106 }
Richard Smith896e0d72013-05-06 06:51:17 +00004107
4108 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004109 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004110 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4111 if (ESR != ESR_Succeeded)
4112 return ESR;
4113
4114 // Loop body.
4115 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4116 if (ESR != ESR_Continue)
4117 return ESR;
4118
4119 // Increment: ++__begin
4120 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4121 return ESR_Failed;
4122 }
4123
4124 return ESR_Succeeded;
4125 }
4126
Richard Smith496ddcf2013-05-12 17:32:42 +00004127 case Stmt::SwitchStmtClass:
4128 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4129
Richard Smith4e18ca52013-05-06 05:56:11 +00004130 case Stmt::ContinueStmtClass:
4131 return ESR_Continue;
4132
4133 case Stmt::BreakStmtClass:
4134 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004135
4136 case Stmt::LabelStmtClass:
4137 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4138
4139 case Stmt::AttributedStmtClass:
4140 // As a general principle, C++11 attributes can be ignored without
4141 // any semantic impact.
4142 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4143 Case);
4144
4145 case Stmt::CaseStmtClass:
4146 case Stmt::DefaultStmtClass:
4147 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004148 }
4149}
4150
Richard Smithcc36f692011-12-22 02:22:31 +00004151/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4152/// default constructor. If so, we'll fold it whether or not it's marked as
4153/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4154/// so we need special handling.
4155static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004156 const CXXConstructorDecl *CD,
4157 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004158 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4159 return false;
4160
Richard Smith66e05fe2012-01-18 05:21:49 +00004161 // Value-initialization does not call a trivial default constructor, so such a
4162 // call is a core constant expression whether or not the constructor is
4163 // constexpr.
4164 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004165 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004166 // FIXME: If DiagDecl is an implicitly-declared special member function,
4167 // we should be much more explicit about why it's not constexpr.
4168 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4169 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4170 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004171 } else {
4172 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4173 }
4174 }
4175 return true;
4176}
4177
Richard Smith357362d2011-12-13 06:39:58 +00004178/// CheckConstexprFunction - Check that a function can be called in a constant
4179/// expression.
4180static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4181 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004182 const FunctionDecl *Definition,
4183 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004184 // Potential constant expressions can contain calls to declared, but not yet
4185 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004186 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004187 Declaration->isConstexpr())
4188 return false;
4189
Richard Smith0838f3a2013-05-14 05:18:44 +00004190 // Bail out with no diagnostic if the function declaration itself is invalid.
4191 // We will have produced a relevant diagnostic while parsing it.
4192 if (Declaration->isInvalidDecl())
4193 return false;
4194
Richard Smith357362d2011-12-13 06:39:58 +00004195 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004196 if (Definition && Definition->isConstexpr() &&
4197 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004198 return true;
4199
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004200 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004201 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004202
Richard Smith5179eb72016-06-28 19:03:57 +00004203 // If this function is not constexpr because it is an inherited
4204 // non-constexpr constructor, diagnose that directly.
4205 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4206 if (CD && CD->isInheritingConstructor()) {
4207 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004208 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004209 DiagDecl = CD = Inherited;
4210 }
4211
4212 // FIXME: If DiagDecl is an implicitly-declared special member function
4213 // or an inheriting constructor, we should be much more explicit about why
4214 // it's not constexpr.
4215 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004216 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004217 << CD->getInheritedConstructor().getConstructor()->getParent();
4218 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004219 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004220 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004221 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4222 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004223 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004224 }
4225 return false;
4226}
4227
Richard Smithbe6dd812014-11-19 21:27:17 +00004228/// Determine if a class has any fields that might need to be copied by a
4229/// trivial copy or move operation.
4230static bool hasFields(const CXXRecordDecl *RD) {
4231 if (!RD || RD->isEmpty())
4232 return false;
4233 for (auto *FD : RD->fields()) {
4234 if (FD->isUnnamedBitfield())
4235 continue;
4236 return true;
4237 }
4238 for (auto &Base : RD->bases())
4239 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4240 return true;
4241 return false;
4242}
4243
Richard Smithd62306a2011-11-10 06:34:14 +00004244namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004245typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004246}
4247
4248/// EvaluateArgs - Evaluate the arguments to a function call.
4249static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4250 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004251 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004252 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004253 I != E; ++I) {
4254 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4255 // If we're checking for a potential constant expression, evaluate all
4256 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004257 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004258 return false;
4259 Success = false;
4260 }
4261 }
4262 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004263}
4264
Richard Smith254a73d2011-10-28 22:34:42 +00004265/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004266static bool HandleFunctionCall(SourceLocation CallLoc,
4267 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004268 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004269 EvalInfo &Info, APValue &Result,
4270 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004271 ArgVector ArgValues(Args.size());
4272 if (!EvaluateArgs(Args, ArgValues, Info))
4273 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004274
Richard Smith253c2a32012-01-27 01:14:48 +00004275 if (!Info.CheckCallLimit(CallLoc))
4276 return false;
4277
4278 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004279
4280 // For a trivial copy or move assignment, perform an APValue copy. This is
4281 // essential for unions, where the operations performed by the assignment
4282 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004283 //
4284 // Skip this for non-union classes with no fields; in that case, the defaulted
4285 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004286 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004287 if (MD && MD->isDefaulted() &&
4288 (MD->getParent()->isUnion() ||
4289 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004290 assert(This &&
4291 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4292 LValue RHS;
4293 RHS.setFrom(Info.Ctx, ArgValues[0]);
4294 APValue RHSValue;
4295 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4296 RHS, RHSValue))
4297 return false;
4298 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4299 RHSValue))
4300 return false;
4301 This->moveInto(Result);
4302 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004303 } else if (MD && isLambdaCallOperator(MD)) {
4304 // We're in a lambda; determine the lambda capture field maps.
4305 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4306 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004307 }
4308
Richard Smith52a980a2015-08-28 02:43:42 +00004309 StmtResult Ret = {Result, ResultSlot};
4310 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004311 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004312 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004313 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004314 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004315 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004316 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004317}
4318
Richard Smithd62306a2011-11-10 06:34:14 +00004319/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004320static bool HandleConstructorCall(const Expr *E, const LValue &This,
4321 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004322 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004323 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004324 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004325 if (!Info.CheckCallLimit(CallLoc))
4326 return false;
4327
Richard Smith3607ffe2012-02-13 03:54:03 +00004328 const CXXRecordDecl *RD = Definition->getParent();
4329 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004330 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004331 return false;
4332 }
4333
Erik Pilkington42925492017-10-04 00:18:55 +00004334 EvalInfo::EvaluatingConstructorRAII EvalObj(
4335 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004336 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004337
Richard Smith52a980a2015-08-28 02:43:42 +00004338 // FIXME: Creating an APValue just to hold a nonexistent return value is
4339 // wasteful.
4340 APValue RetVal;
4341 StmtResult Ret = {RetVal, nullptr};
4342
Richard Smith5179eb72016-06-28 19:03:57 +00004343 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004344 if (Definition->isDelegatingConstructor()) {
4345 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004346 {
4347 FullExpressionRAII InitScope(Info);
4348 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4349 return false;
4350 }
Richard Smith52a980a2015-08-28 02:43:42 +00004351 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004352 }
4353
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004354 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004355 // essential for unions (or classes with anonymous union members), where the
4356 // operations performed by the constructor cannot be represented by
4357 // ctor-initializers.
4358 //
4359 // Skip this for empty non-union classes; we should not perform an
4360 // lvalue-to-rvalue conversion on them because their copy constructor does not
4361 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004362 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004363 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004364 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004365 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004366 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004367 return handleLValueToRValueConversion(
4368 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4369 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004370 }
4371
4372 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004373 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004374 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004375 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004376
John McCalld7bca762012-05-01 00:38:49 +00004377 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004378 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4379
Richard Smith08d6a2c2013-07-24 07:11:57 +00004380 // A scope for temporaries lifetime-extended by reference members.
4381 BlockScopeRAII LifetimeExtendedScope(Info);
4382
Richard Smith253c2a32012-01-27 01:14:48 +00004383 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004384 unsigned BasesSeen = 0;
4385#ifndef NDEBUG
4386 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4387#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004388 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004389 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004390 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004391 APValue *Value = &Result;
4392
4393 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004394 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004395 if (I->isBaseInitializer()) {
4396 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004397#ifndef NDEBUG
4398 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004399 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004400 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4401 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4402 "base class initializers not in expected order");
4403 ++BaseIt;
4404#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004405 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004406 BaseType->getAsCXXRecordDecl(), &Layout))
4407 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004408 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004409 } else if ((FD = I->getMember())) {
4410 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004411 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004412 if (RD->isUnion()) {
4413 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004414 Value = &Result.getUnionValue();
4415 } else {
4416 Value = &Result.getStructField(FD->getFieldIndex());
4417 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004418 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004419 // Walk the indirect field decl's chain to find the object to initialize,
4420 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004421 auto IndirectFieldChain = IFD->chain();
4422 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004423 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004424 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4425 // Switch the union field if it differs. This happens if we had
4426 // preceding zero-initialization, and we're now initializing a union
4427 // subobject other than the first.
4428 // FIXME: In this case, the values of the other subobjects are
4429 // specified, since zero-initialization sets all padding bits to zero.
4430 if (Value->isUninit() ||
4431 (Value->isUnion() && Value->getUnionField() != FD)) {
4432 if (CD->isUnion())
4433 *Value = APValue(FD);
4434 else
4435 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004436 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004437 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004438 // Store Subobject as its parent before updating it for the last element
4439 // in the chain.
4440 if (C == IndirectFieldChain.back())
4441 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004442 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004443 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004444 if (CD->isUnion())
4445 Value = &Value->getUnionValue();
4446 else
4447 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004448 }
Richard Smithd62306a2011-11-10 06:34:14 +00004449 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004450 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004451 }
Richard Smith253c2a32012-01-27 01:14:48 +00004452
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004453 // Need to override This for implicit field initializers as in this case
4454 // This refers to innermost anonymous struct/union containing initializer,
4455 // not to currently constructed class.
4456 const Expr *Init = I->getInit();
4457 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4458 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004459 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004460 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4461 (FD && FD->isBitField() &&
4462 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004463 // If we're checking for a potential constant expression, evaluate all
4464 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004465 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004466 return false;
4467 Success = false;
4468 }
Richard Smithd62306a2011-11-10 06:34:14 +00004469 }
4470
Richard Smithd9f663b2013-04-22 15:31:51 +00004471 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004472 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004473}
4474
Richard Smith5179eb72016-06-28 19:03:57 +00004475static bool HandleConstructorCall(const Expr *E, const LValue &This,
4476 ArrayRef<const Expr*> Args,
4477 const CXXConstructorDecl *Definition,
4478 EvalInfo &Info, APValue &Result) {
4479 ArgVector ArgValues(Args.size());
4480 if (!EvaluateArgs(Args, ArgValues, Info))
4481 return false;
4482
4483 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4484 Info, Result);
4485}
4486
Eli Friedman9a156e52008-11-12 09:44:48 +00004487//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004488// Generic Evaluation
4489//===----------------------------------------------------------------------===//
4490namespace {
4491
Aaron Ballman68af21c2014-01-03 19:26:43 +00004492template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004493class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004494 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004495private:
Richard Smith52a980a2015-08-28 02:43:42 +00004496 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004497 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004498 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004499 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004501 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004502 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004503
Richard Smith17100ba2012-02-16 02:46:34 +00004504 // Check whether a conditional operator with a non-constant condition is a
4505 // potential constant expression. If neither arm is a potential constant
4506 // expression, then the conditional operator is not either.
4507 template<typename ConditionalOperator>
4508 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004509 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004510
4511 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004512 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004513 {
Richard Smith17100ba2012-02-16 02:46:34 +00004514 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004515 StmtVisitorTy::Visit(E->getFalseExpr());
4516 if (Diag.empty())
4517 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004518 }
Richard Smith17100ba2012-02-16 02:46:34 +00004519
George Burgess IV8c892b52016-05-25 22:31:54 +00004520 {
4521 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004522 Diag.clear();
4523 StmtVisitorTy::Visit(E->getTrueExpr());
4524 if (Diag.empty())
4525 return;
4526 }
4527
4528 Error(E, diag::note_constexpr_conditional_never_const);
4529 }
4530
4531
4532 template<typename ConditionalOperator>
4533 bool HandleConditionalOperator(const ConditionalOperator *E) {
4534 bool BoolResult;
4535 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004536 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004537 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004538 return false;
4539 }
4540 if (Info.noteFailure()) {
4541 StmtVisitorTy::Visit(E->getTrueExpr());
4542 StmtVisitorTy::Visit(E->getFalseExpr());
4543 }
Richard Smith17100ba2012-02-16 02:46:34 +00004544 return false;
4545 }
4546
4547 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4548 return StmtVisitorTy::Visit(EvalExpr);
4549 }
4550
Peter Collingbournee9200682011-05-13 03:29:01 +00004551protected:
4552 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004553 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004554 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4555
Richard Smith92b1ce02011-12-12 09:28:41 +00004556 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004557 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004558 }
4559
Aaron Ballman68af21c2014-01-03 19:26:43 +00004560 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004561
4562public:
4563 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4564
4565 EvalInfo &getEvalInfo() { return Info; }
4566
Richard Smithf57d8cb2011-12-09 22:58:01 +00004567 /// Report an evaluation error. This should only be called when an error is
4568 /// first discovered. When propagating an error, just return false.
4569 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004570 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004571 return false;
4572 }
4573 bool Error(const Expr *E) {
4574 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4575 }
4576
Aaron Ballman68af21c2014-01-03 19:26:43 +00004577 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004578 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004579 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004580 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004581 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004582 }
4583
Aaron Ballman68af21c2014-01-03 19:26:43 +00004584 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004585 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004586 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004587 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004588 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004589 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004591 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004592 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004593 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004595 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004596 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004597 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004599 // The initializer may not have been parsed yet, or might be erroneous.
4600 if (!E->getExpr())
4601 return Error(E);
4602 return StmtVisitorTy::Visit(E->getExpr());
4603 }
Richard Smith5894a912011-12-19 22:12:41 +00004604 // We cannot create any objects for which cleanups are required, so there is
4605 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004606 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004607 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004608
Aaron Ballman68af21c2014-01-03 19:26:43 +00004609 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004610 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4611 return static_cast<Derived*>(this)->VisitCastExpr(E);
4612 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004613 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004614 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4615 return static_cast<Derived*>(this)->VisitCastExpr(E);
4616 }
4617
Aaron Ballman68af21c2014-01-03 19:26:43 +00004618 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004619 switch (E->getOpcode()) {
4620 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004621 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004622
4623 case BO_Comma:
4624 VisitIgnoredValue(E->getLHS());
4625 return StmtVisitorTy::Visit(E->getRHS());
4626
4627 case BO_PtrMemD:
4628 case BO_PtrMemI: {
4629 LValue Obj;
4630 if (!HandleMemberPointerAccess(Info, E, Obj))
4631 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004632 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004633 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004634 return false;
4635 return DerivedSuccess(Result, E);
4636 }
4637 }
4638 }
4639
Aaron Ballman68af21c2014-01-03 19:26:43 +00004640 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004641 // Evaluate and cache the common expression. We treat it as a temporary,
4642 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004643 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004644 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004645 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004646
Richard Smith17100ba2012-02-16 02:46:34 +00004647 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004648 }
4649
Aaron Ballman68af21c2014-01-03 19:26:43 +00004650 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004651 bool IsBcpCall = false;
4652 // If the condition (ignoring parens) is a __builtin_constant_p call,
4653 // the result is a constant expression if it can be folded without
4654 // side-effects. This is an important GNU extension. See GCC PR38377
4655 // for discussion.
4656 if (const CallExpr *CallCE =
4657 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004658 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004659 IsBcpCall = true;
4660
4661 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4662 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004663 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004664 return false;
4665
Richard Smith6d4c6582013-11-05 22:18:15 +00004666 FoldConstant Fold(Info, IsBcpCall);
4667 if (!HandleConditionalOperator(E)) {
4668 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004669 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004670 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004671
4672 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004673 }
4674
Aaron Ballman68af21c2014-01-03 19:26:43 +00004675 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004676 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4677 return DerivedSuccess(*Value, E);
4678
4679 const Expr *Source = E->getSourceExpr();
4680 if (!Source)
4681 return Error(E);
4682 if (Source == E) { // sanity checking.
4683 assert(0 && "OpaqueValueExpr recursively refers to itself");
4684 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004685 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004686 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004687 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004688
Aaron Ballman68af21c2014-01-03 19:26:43 +00004689 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004690 APValue Result;
4691 if (!handleCallExpr(E, Result, nullptr))
4692 return false;
4693 return DerivedSuccess(Result, E);
4694 }
4695
4696 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004697 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004698 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004699 QualType CalleeType = Callee->getType();
4700
Craig Topper36250ad2014-05-12 05:36:57 +00004701 const FunctionDecl *FD = nullptr;
4702 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004703 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004704 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004705
Richard Smithe97cbd72011-11-11 04:05:33 +00004706 // Extract function decl and 'this' pointer from the callee.
4707 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004708 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004709 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4710 // Explicit bound member calls, such as x.f() or p->g();
4711 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004712 return false;
4713 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004714 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004715 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004716 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4717 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004718 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4719 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004720 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004721 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004722 return Error(Callee);
4723
4724 FD = dyn_cast<FunctionDecl>(Member);
4725 if (!FD)
4726 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004727 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004728 LValue Call;
4729 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004731
Richard Smitha8105bc2012-01-06 16:39:00 +00004732 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004733 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004734 FD = dyn_cast_or_null<FunctionDecl>(
4735 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004736 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004737 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004738 // Don't call function pointers which have been cast to some other type.
4739 // Per DR (no number yet), the caller and callee can differ in noexcept.
4740 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4741 CalleeType->getPointeeType(), FD->getType())) {
4742 return Error(E);
4743 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004744
4745 // Overloaded operator calls to member functions are represented as normal
4746 // calls with '*this' as the first argument.
4747 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4748 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004749 // FIXME: When selecting an implicit conversion for an overloaded
4750 // operator delete, we sometimes try to evaluate calls to conversion
4751 // operators without a 'this' parameter!
4752 if (Args.empty())
4753 return Error(E);
4754
Nick Lewycky13073a62017-06-12 21:15:44 +00004755 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004756 return false;
4757 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004758 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004759 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004760 // Map the static invoker for the lambda back to the call operator.
4761 // Conveniently, we don't have to slice out the 'this' argument (as is
4762 // being done for the non-static case), since a static member function
4763 // doesn't have an implicit argument passed in.
4764 const CXXRecordDecl *ClosureClass = MD->getParent();
4765 assert(
4766 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4767 "Number of captures must be zero for conversion to function-ptr");
4768
4769 const CXXMethodDecl *LambdaCallOp =
4770 ClosureClass->getLambdaCallOperator();
4771
4772 // Set 'FD', the function that will be called below, to the call
4773 // operator. If the closure object represents a generic lambda, find
4774 // the corresponding specialization of the call operator.
4775
4776 if (ClosureClass->isGenericLambda()) {
4777 assert(MD->isFunctionTemplateSpecialization() &&
4778 "A generic lambda's static-invoker function must be a "
4779 "template specialization");
4780 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4781 FunctionTemplateDecl *CallOpTemplate =
4782 LambdaCallOp->getDescribedFunctionTemplate();
4783 void *InsertPos = nullptr;
4784 FunctionDecl *CorrespondingCallOpSpecialization =
4785 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4786 assert(CorrespondingCallOpSpecialization &&
4787 "We must always have a function call operator specialization "
4788 "that corresponds to our static invoker specialization");
4789 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4790 } else
4791 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004792 }
4793
Daniel Jasperffdee092017-05-02 19:21:42 +00004794
Richard Smithe97cbd72011-11-11 04:05:33 +00004795 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004796 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004797
Richard Smith47b34932012-02-01 02:39:43 +00004798 if (This && !This->checkSubobject(Info, E, CSK_This))
4799 return false;
4800
Richard Smith3607ffe2012-02-13 03:54:03 +00004801 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4802 // calls to such functions in constant expressions.
4803 if (This && !HasQualifier &&
4804 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4805 return Error(E, diag::note_constexpr_virtual_call);
4806
Craig Topper36250ad2014-05-12 05:36:57 +00004807 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004808 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004809
Nick Lewycky13073a62017-06-12 21:15:44 +00004810 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4811 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004812 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004813 return false;
4814
Richard Smith52a980a2015-08-28 02:43:42 +00004815 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004816 }
4817
Aaron Ballman68af21c2014-01-03 19:26:43 +00004818 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004819 return StmtVisitorTy::Visit(E->getInitializer());
4820 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004821 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004822 if (E->getNumInits() == 0)
4823 return DerivedZeroInitialization(E);
4824 if (E->getNumInits() == 1)
4825 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004826 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004827 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004828 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004829 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004830 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004831 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004832 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004833 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004834 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004835 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004836 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004837
Richard Smithd62306a2011-11-10 06:34:14 +00004838 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004839 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004840 assert(!E->isArrow() && "missing call to bound member function?");
4841
Richard Smith2e312c82012-03-03 22:46:17 +00004842 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004843 if (!Evaluate(Val, Info, E->getBase()))
4844 return false;
4845
4846 QualType BaseTy = E->getBase()->getType();
4847
4848 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004849 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004850 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004851 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004852 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4853
Richard Smith9defb7d2018-02-21 03:38:30 +00004854 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004855 SubobjectDesignator Designator(BaseTy);
4856 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004857
Richard Smith3229b742013-05-05 21:17:10 +00004858 APValue Result;
4859 return extractSubobject(Info, E, Obj, Designator, Result) &&
4860 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004861 }
4862
Aaron Ballman68af21c2014-01-03 19:26:43 +00004863 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004864 switch (E->getCastKind()) {
4865 default:
4866 break;
4867
Richard Smitha23ab512013-05-23 00:30:41 +00004868 case CK_AtomicToNonAtomic: {
4869 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004870 // This does not need to be done in place even for class/array types:
4871 // atomic-to-non-atomic conversion implies copying the object
4872 // representation.
4873 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004874 return false;
4875 return DerivedSuccess(AtomicVal, E);
4876 }
4877
Richard Smith11562c52011-10-28 17:51:58 +00004878 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004879 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004880 return StmtVisitorTy::Visit(E->getSubExpr());
4881
4882 case CK_LValueToRValue: {
4883 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004884 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4885 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004886 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004887 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004888 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004889 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004890 return false;
4891 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004892 }
4893 }
4894
Richard Smithf57d8cb2011-12-09 22:58:01 +00004895 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004896 }
4897
Aaron Ballman68af21c2014-01-03 19:26:43 +00004898 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004899 return VisitUnaryPostIncDec(UO);
4900 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004901 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004902 return VisitUnaryPostIncDec(UO);
4903 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004904 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004905 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004906 return Error(UO);
4907
4908 LValue LVal;
4909 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4910 return false;
4911 APValue RVal;
4912 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4913 UO->isIncrementOp(), &RVal))
4914 return false;
4915 return DerivedSuccess(RVal, UO);
4916 }
4917
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004919 // We will have checked the full-expressions inside the statement expression
4920 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004921 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004922 return Error(E);
4923
Richard Smith08d6a2c2013-07-24 07:11:57 +00004924 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004925 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004926 if (CS->body_empty())
4927 return true;
4928
Richard Smith51f03172013-06-20 03:00:05 +00004929 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4930 BE = CS->body_end();
4931 /**/; ++BI) {
4932 if (BI + 1 == BE) {
4933 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4934 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004935 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004936 diag::note_constexpr_stmt_expr_unsupported);
4937 return false;
4938 }
4939 return this->Visit(FinalExpr);
4940 }
4941
4942 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004943 StmtResult Result = { ReturnValue, nullptr };
4944 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004945 if (ESR != ESR_Succeeded) {
4946 // FIXME: If the statement-expression terminated due to 'return',
4947 // 'break', or 'continue', it would be nice to propagate that to
4948 // the outer statement evaluation rather than bailing out.
4949 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004950 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004951 diag::note_constexpr_stmt_expr_unsupported);
4952 return false;
4953 }
4954 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004955
4956 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004957 }
4958
Richard Smith4a678122011-10-24 18:44:57 +00004959 /// Visit a value which is evaluated, but whose value is ignored.
4960 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004961 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004962 }
David Majnemere9807b22016-02-26 04:23:19 +00004963
4964 /// Potentially visit a MemberExpr's base expression.
4965 void VisitIgnoredBaseExpression(const Expr *E) {
4966 // While MSVC doesn't evaluate the base expression, it does diagnose the
4967 // presence of side-effecting behavior.
4968 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4969 return;
4970 VisitIgnoredValue(E);
4971 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004972};
4973
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004974}
Peter Collingbournee9200682011-05-13 03:29:01 +00004975
4976//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004977// Common base class for lvalue and temporary evaluation.
4978//===----------------------------------------------------------------------===//
4979namespace {
4980template<class Derived>
4981class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004982 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004983protected:
4984 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004985 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004986 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004987 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004988
4989 bool Success(APValue::LValueBase B) {
4990 Result.set(B);
4991 return true;
4992 }
4993
George Burgess IVf9013bf2017-02-10 22:52:29 +00004994 bool evaluatePointer(const Expr *E, LValue &Result) {
4995 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4996 }
4997
Richard Smith027bf112011-11-17 22:56:20 +00004998public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004999 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5000 : ExprEvaluatorBaseTy(Info), Result(Result),
5001 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005002
Richard Smith2e312c82012-03-03 22:46:17 +00005003 bool Success(const APValue &V, const Expr *E) {
5004 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005005 return true;
5006 }
Richard Smith027bf112011-11-17 22:56:20 +00005007
Richard Smith027bf112011-11-17 22:56:20 +00005008 bool VisitMemberExpr(const MemberExpr *E) {
5009 // Handle non-static data members.
5010 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005011 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005012 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005013 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005014 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005015 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005016 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005017 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005018 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005019 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005020 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005021 BaseTy = E->getBase()->getType();
5022 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005023 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005024 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005025 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005026 Result.setInvalid(E);
5027 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005028 }
Richard Smith027bf112011-11-17 22:56:20 +00005029
Richard Smith1b78b3d2012-01-25 22:15:11 +00005030 const ValueDecl *MD = E->getMemberDecl();
5031 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5032 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5033 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5034 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005035 if (!HandleLValueMember(this->Info, E, Result, FD))
5036 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005037 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005038 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5039 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005040 } else
5041 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005042
Richard Smith1b78b3d2012-01-25 22:15:11 +00005043 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005044 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005045 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005046 RefValue))
5047 return false;
5048 return Success(RefValue, E);
5049 }
5050 return true;
5051 }
5052
5053 bool VisitBinaryOperator(const BinaryOperator *E) {
5054 switch (E->getOpcode()) {
5055 default:
5056 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5057
5058 case BO_PtrMemD:
5059 case BO_PtrMemI:
5060 return HandleMemberPointerAccess(this->Info, E, Result);
5061 }
5062 }
5063
5064 bool VisitCastExpr(const CastExpr *E) {
5065 switch (E->getCastKind()) {
5066 default:
5067 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5068
5069 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005070 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005071 if (!this->Visit(E->getSubExpr()))
5072 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005073
5074 // Now figure out the necessary offset to add to the base LV to get from
5075 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005076 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5077 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005078 }
5079 }
5080};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005081}
Richard Smith027bf112011-11-17 22:56:20 +00005082
5083//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005084// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005085//
5086// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5087// function designators (in C), decl references to void objects (in C), and
5088// temporaries (if building with -Wno-address-of-temporary).
5089//
5090// LValue evaluation produces values comprising a base expression of one of the
5091// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005092// - Declarations
5093// * VarDecl
5094// * FunctionDecl
5095// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005096// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005097// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005098// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005099// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005100// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005101// * ObjCEncodeExpr
5102// * AddrLabelExpr
5103// * BlockExpr
5104// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005105// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005106// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005107// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005108// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5109// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005110// * A MaterializeTemporaryExpr that has static storage duration, with no
5111// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005112// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005113//===----------------------------------------------------------------------===//
5114namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005115class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005116 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005117public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005118 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5119 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005120
Richard Smith11562c52011-10-28 17:51:58 +00005121 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005122 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005123
Peter Collingbournee9200682011-05-13 03:29:01 +00005124 bool VisitDeclRefExpr(const DeclRefExpr *E);
5125 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005126 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005127 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5128 bool VisitMemberExpr(const MemberExpr *E);
5129 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5130 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005131 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005132 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005133 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5134 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005135 bool VisitUnaryReal(const UnaryOperator *E);
5136 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005137 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5138 return VisitUnaryPreIncDec(UO);
5139 }
5140 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5141 return VisitUnaryPreIncDec(UO);
5142 }
Richard Smith3229b742013-05-05 21:17:10 +00005143 bool VisitBinAssign(const BinaryOperator *BO);
5144 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005145
Peter Collingbournee9200682011-05-13 03:29:01 +00005146 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005147 switch (E->getCastKind()) {
5148 default:
Richard Smith027bf112011-11-17 22:56:20 +00005149 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005150
Eli Friedmance3e02a2011-10-11 00:13:24 +00005151 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005152 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005153 if (!Visit(E->getSubExpr()))
5154 return false;
5155 Result.Designator.setInvalid();
5156 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005157
Richard Smith027bf112011-11-17 22:56:20 +00005158 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005159 if (!Visit(E->getSubExpr()))
5160 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005161 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005162 }
5163 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005164};
5165} // end anonymous namespace
5166
Richard Smith11562c52011-10-28 17:51:58 +00005167/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005168/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005169/// * function designators in C, and
5170/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005171/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005172static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5173 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005174 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005175 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005176 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005177}
5178
Peter Collingbournee9200682011-05-13 03:29:01 +00005179bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005180 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005181 return Success(FD);
5182 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005183 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005184 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005185 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005186 return Error(E);
5187}
Richard Smith733237d2011-10-24 23:14:33 +00005188
Faisal Vali0528a312016-11-13 06:09:16 +00005189
Richard Smith11562c52011-10-28 17:51:58 +00005190bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005191
5192 // If we are within a lambda's call operator, check whether the 'VD' referred
5193 // to within 'E' actually represents a lambda-capture that maps to a
5194 // data-member/field within the closure object, and if so, evaluate to the
5195 // field or what the field refers to.
5196 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5197 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5198 if (Info.checkingPotentialConstantExpression())
5199 return false;
5200 // Start with 'Result' referring to the complete closure object...
5201 Result = *Info.CurrentCall->This;
5202 // ... then update it to refer to the field of the closure object
5203 // that represents the capture.
5204 if (!HandleLValueMember(Info, E, Result, FD))
5205 return false;
5206 // And if the field is of reference type, update 'Result' to refer to what
5207 // the field refers to.
5208 if (FD->getType()->isReferenceType()) {
5209 APValue RVal;
5210 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5211 RVal))
5212 return false;
5213 Result.setFrom(Info.Ctx, RVal);
5214 }
5215 return true;
5216 }
5217 }
Craig Topper36250ad2014-05-12 05:36:57 +00005218 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005219 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5220 // Only if a local variable was declared in the function currently being
5221 // evaluated, do we expect to be able to find its value in the current
5222 // frame. (Otherwise it was likely declared in an enclosing context and
5223 // could either have a valid evaluatable value (for e.g. a constexpr
5224 // variable) or be ill-formed (and trigger an appropriate evaluation
5225 // diagnostic)).
5226 if (Info.CurrentCall->Callee &&
5227 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5228 Frame = Info.CurrentCall;
5229 }
5230 }
Richard Smith3229b742013-05-05 21:17:10 +00005231
Richard Smithfec09922011-11-01 16:57:24 +00005232 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005233 if (Frame) {
5234 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005235 return true;
5236 }
Richard Smithce40ad62011-11-12 22:28:03 +00005237 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005238 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005239
Richard Smith3229b742013-05-05 21:17:10 +00005240 APValue *V;
5241 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005242 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005243 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005244 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005245 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005246 return false;
5247 }
Richard Smith3229b742013-05-05 21:17:10 +00005248 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005249}
5250
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005251bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5252 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005253 // Walk through the expression to find the materialized temporary itself.
5254 SmallVector<const Expr *, 2> CommaLHSs;
5255 SmallVector<SubobjectAdjustment, 2> Adjustments;
5256 const Expr *Inner = E->GetTemporaryExpr()->
5257 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005258
Richard Smith84401042013-06-03 05:03:02 +00005259 // If we passed any comma operators, evaluate their LHSs.
5260 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5261 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5262 return false;
5263
Richard Smithe6c01442013-06-05 00:46:14 +00005264 // A materialized temporary with static storage duration can appear within the
5265 // result of a constant expression evaluation, so we need to preserve its
5266 // value for use outside this evaluation.
5267 APValue *Value;
5268 if (E->getStorageDuration() == SD_Static) {
5269 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005270 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005271 Result.set(E);
5272 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005273 Value = &Info.CurrentCall->
5274 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005275 Result.set(E, Info.CurrentCall->Index);
5276 }
5277
Richard Smithea4ad5d2013-06-06 08:19:16 +00005278 QualType Type = Inner->getType();
5279
Richard Smith84401042013-06-03 05:03:02 +00005280 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005281 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5282 (E->getStorageDuration() == SD_Static &&
5283 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5284 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005285 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005286 }
Richard Smith84401042013-06-03 05:03:02 +00005287
5288 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005289 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5290 --I;
5291 switch (Adjustments[I].Kind) {
5292 case SubobjectAdjustment::DerivedToBaseAdjustment:
5293 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5294 Type, Result))
5295 return false;
5296 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5297 break;
5298
5299 case SubobjectAdjustment::FieldAdjustment:
5300 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5301 return false;
5302 Type = Adjustments[I].Field->getType();
5303 break;
5304
5305 case SubobjectAdjustment::MemberPointerAdjustment:
5306 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5307 Adjustments[I].Ptr.RHS))
5308 return false;
5309 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5310 break;
5311 }
5312 }
5313
5314 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005315}
5316
Peter Collingbournee9200682011-05-13 03:29:01 +00005317bool
5318LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005319 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5320 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005321 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5322 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005323 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005324}
5325
Richard Smith6e525142011-12-27 12:18:28 +00005326bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005327 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005328 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005329
Faisal Valie690b7a2016-07-02 22:34:24 +00005330 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005331 << E->getExprOperand()->getType()
5332 << E->getExprOperand()->getSourceRange();
5333 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005334}
5335
Francois Pichet0066db92012-04-16 04:08:35 +00005336bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5337 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005338}
Francois Pichet0066db92012-04-16 04:08:35 +00005339
Peter Collingbournee9200682011-05-13 03:29:01 +00005340bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005341 // Handle static data members.
5342 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005343 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005344 return VisitVarDecl(E, VD);
5345 }
5346
Richard Smith254a73d2011-10-28 22:34:42 +00005347 // Handle static member functions.
5348 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5349 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005350 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005351 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005352 }
5353 }
5354
Richard Smithd62306a2011-11-10 06:34:14 +00005355 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005356 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005357}
5358
Peter Collingbournee9200682011-05-13 03:29:01 +00005359bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005360 // FIXME: Deal with vectors as array subscript bases.
5361 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005362 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005363
Nick Lewyckyad888682017-04-27 07:27:36 +00005364 bool Success = true;
5365 if (!evaluatePointer(E->getBase(), Result)) {
5366 if (!Info.noteFailure())
5367 return false;
5368 Success = false;
5369 }
Mike Stump11289f42009-09-09 15:08:12 +00005370
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005371 APSInt Index;
5372 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005373 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005374
Nick Lewyckyad888682017-04-27 07:27:36 +00005375 return Success &&
5376 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005377}
Eli Friedman9a156e52008-11-12 09:44:48 +00005378
Peter Collingbournee9200682011-05-13 03:29:01 +00005379bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005380 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005381}
5382
Richard Smith66c96992012-02-18 22:04:06 +00005383bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5384 if (!Visit(E->getSubExpr()))
5385 return false;
5386 // __real is a no-op on scalar lvalues.
5387 if (E->getSubExpr()->getType()->isAnyComplexType())
5388 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5389 return true;
5390}
5391
5392bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5393 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5394 "lvalue __imag__ on scalar?");
5395 if (!Visit(E->getSubExpr()))
5396 return false;
5397 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5398 return true;
5399}
5400
Richard Smith243ef902013-05-05 23:31:59 +00005401bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005402 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005403 return Error(UO);
5404
5405 if (!this->Visit(UO->getSubExpr()))
5406 return false;
5407
Richard Smith243ef902013-05-05 23:31:59 +00005408 return handleIncDec(
5409 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005410 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005411}
5412
5413bool LValueExprEvaluator::VisitCompoundAssignOperator(
5414 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005415 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005416 return Error(CAO);
5417
Richard Smith3229b742013-05-05 21:17:10 +00005418 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005419
5420 // The overall lvalue result is the result of evaluating the LHS.
5421 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005422 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005423 Evaluate(RHS, this->Info, CAO->getRHS());
5424 return false;
5425 }
5426
Richard Smith3229b742013-05-05 21:17:10 +00005427 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5428 return false;
5429
Richard Smith43e77732013-05-07 04:50:00 +00005430 return handleCompoundAssignment(
5431 this->Info, CAO,
5432 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5433 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005434}
5435
5436bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005437 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005438 return Error(E);
5439
Richard Smith3229b742013-05-05 21:17:10 +00005440 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005441
5442 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005443 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005444 Evaluate(NewVal, this->Info, E->getRHS());
5445 return false;
5446 }
5447
Richard Smith3229b742013-05-05 21:17:10 +00005448 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5449 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005450
5451 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005452 NewVal);
5453}
5454
Eli Friedman9a156e52008-11-12 09:44:48 +00005455//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005456// Pointer Evaluation
5457//===----------------------------------------------------------------------===//
5458
George Burgess IVe3763372016-12-22 02:50:20 +00005459/// \brief Attempts to compute the number of bytes available at the pointer
5460/// returned by a function with the alloc_size attribute. Returns true if we
5461/// were successful. Places an unsigned number into `Result`.
5462///
5463/// This expects the given CallExpr to be a call to a function with an
5464/// alloc_size attribute.
5465static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5466 const CallExpr *Call,
5467 llvm::APInt &Result) {
5468 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5469
Joel E. Denny49254452018-03-02 19:03:22 +00005470 assert(AllocSize && AllocSize->elemSizeParam().isValid());
5471 unsigned SizeArgNo = AllocSize->elemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005472 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5473 if (Call->getNumArgs() <= SizeArgNo)
5474 return false;
5475
5476 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5477 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5478 return false;
5479 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5480 return false;
5481 Into = Into.zextOrSelf(BitsInSizeT);
5482 return true;
5483 };
5484
5485 APSInt SizeOfElem;
5486 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5487 return false;
5488
Joel E. Denny49254452018-03-02 19:03:22 +00005489 if (!AllocSize->numElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005490 Result = std::move(SizeOfElem);
5491 return true;
5492 }
5493
5494 APSInt NumberOfElems;
Joel E. Denny49254452018-03-02 19:03:22 +00005495 unsigned NumArgNo = AllocSize->numElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005496 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5497 return false;
5498
5499 bool Overflow;
5500 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5501 if (Overflow)
5502 return false;
5503
5504 Result = std::move(BytesAvailable);
5505 return true;
5506}
5507
5508/// \brief Convenience function. LVal's base must be a call to an alloc_size
5509/// function.
5510static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5511 const LValue &LVal,
5512 llvm::APInt &Result) {
5513 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5514 "Can't get the size of a non alloc_size function");
5515 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5516 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5517 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5518}
5519
5520/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5521/// a function with the alloc_size attribute. If it was possible to do so, this
5522/// function will return true, make Result's Base point to said function call,
5523/// and mark Result's Base as invalid.
5524static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5525 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005526 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005527 return false;
5528
5529 // Because we do no form of static analysis, we only support const variables.
5530 //
5531 // Additionally, we can't support parameters, nor can we support static
5532 // variables (in the latter case, use-before-assign isn't UB; in the former,
5533 // we have no clue what they'll be assigned to).
5534 const auto *VD =
5535 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5536 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5537 return false;
5538
5539 const Expr *Init = VD->getAnyInitializer();
5540 if (!Init)
5541 return false;
5542
5543 const Expr *E = Init->IgnoreParens();
5544 if (!tryUnwrapAllocSizeCall(E))
5545 return false;
5546
5547 // Store E instead of E unwrapped so that the type of the LValue's base is
5548 // what the user wanted.
5549 Result.setInvalid(E);
5550
5551 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005552 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005553 return true;
5554}
5555
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005556namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005557class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005558 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005559 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005560 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005561
Peter Collingbournee9200682011-05-13 03:29:01 +00005562 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005563 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005564 return true;
5565 }
George Burgess IVe3763372016-12-22 02:50:20 +00005566
George Burgess IVf9013bf2017-02-10 22:52:29 +00005567 bool evaluateLValue(const Expr *E, LValue &Result) {
5568 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5569 }
5570
5571 bool evaluatePointer(const Expr *E, LValue &Result) {
5572 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5573 }
5574
George Burgess IVe3763372016-12-22 02:50:20 +00005575 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005576public:
Mike Stump11289f42009-09-09 15:08:12 +00005577
George Burgess IVf9013bf2017-02-10 22:52:29 +00005578 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5579 : ExprEvaluatorBaseTy(info), Result(Result),
5580 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005581
Richard Smith2e312c82012-03-03 22:46:17 +00005582 bool Success(const APValue &V, const Expr *E) {
5583 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005584 return true;
5585 }
Richard Smithfddd3842011-12-30 21:15:51 +00005586 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005587 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5588 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005589 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005590 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005591
John McCall45d55e42010-05-07 21:00:08 +00005592 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005593 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005594 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005595 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005596 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005597 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5598 if (Info.noteFailure())
5599 EvaluateIgnoredValue(Info, E->getSubExpr());
5600 return Error(E);
5601 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005602 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005603 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005604 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005605 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005606 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005607 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005608 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005609 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005610 }
Richard Smithd62306a2011-11-10 06:34:14 +00005611 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005612 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005613 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005614 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005615 if (!Info.CurrentCall->This) {
5616 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005617 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005618 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005619 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005620 return false;
5621 }
Richard Smithd62306a2011-11-10 06:34:14 +00005622 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005623 // If we are inside a lambda's call operator, the 'this' expression refers
5624 // to the enclosing '*this' object (either by value or reference) which is
5625 // either copied into the closure object's field that represents the '*this'
5626 // or refers to '*this'.
5627 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5628 // Update 'Result' to refer to the data member/field of the closure object
5629 // that represents the '*this' capture.
5630 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005631 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005632 return false;
5633 // If we captured '*this' by reference, replace the field with its referent.
5634 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5635 ->isPointerType()) {
5636 APValue RVal;
5637 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5638 RVal))
5639 return false;
5640
5641 Result.setFrom(Info.Ctx, RVal);
5642 }
5643 }
Richard Smithd62306a2011-11-10 06:34:14 +00005644 return true;
5645 }
John McCallc07a0c72011-02-17 10:25:35 +00005646
Eli Friedman449fe542009-03-23 04:56:01 +00005647 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005648};
Chris Lattner05706e882008-07-11 18:11:29 +00005649} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005650
George Burgess IVf9013bf2017-02-10 22:52:29 +00005651static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5652 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005653 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005654 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005655}
5656
John McCall45d55e42010-05-07 21:00:08 +00005657bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005658 if (E->getOpcode() != BO_Add &&
5659 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005660 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005661
Chris Lattner05706e882008-07-11 18:11:29 +00005662 const Expr *PExp = E->getLHS();
5663 const Expr *IExp = E->getRHS();
5664 if (IExp->getType()->isPointerType())
5665 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005666
George Burgess IVf9013bf2017-02-10 22:52:29 +00005667 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005668 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005669 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005670
John McCall45d55e42010-05-07 21:00:08 +00005671 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005672 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005673 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005674
Richard Smith96e0c102011-11-04 02:25:55 +00005675 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005676 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005677
Ted Kremenek28831752012-08-23 20:46:57 +00005678 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005679 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005680}
Eli Friedman9a156e52008-11-12 09:44:48 +00005681
John McCall45d55e42010-05-07 21:00:08 +00005682bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005683 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005684}
Mike Stump11289f42009-09-09 15:08:12 +00005685
Peter Collingbournee9200682011-05-13 03:29:01 +00005686bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5687 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005688
Eli Friedman847a2bc2009-12-27 05:43:15 +00005689 switch (E->getCastKind()) {
5690 default:
5691 break;
5692
John McCalle3027922010-08-25 11:45:40 +00005693 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005694 case CK_CPointerToObjCPointerCast:
5695 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005696 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005697 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005698 if (!Visit(SubExpr))
5699 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005700 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5701 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5702 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005703 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005704 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005705 if (SubExpr->getType()->isVoidPointerType())
5706 CCEDiag(E, diag::note_constexpr_invalid_cast)
5707 << 3 << SubExpr->getType();
5708 else
5709 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5710 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005711 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5712 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005713 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005714
Anders Carlsson18275092010-10-31 20:41:46 +00005715 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005716 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005717 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005718 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005719 if (!Result.Base && Result.Offset.isZero())
5720 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005721
Richard Smithd62306a2011-11-10 06:34:14 +00005722 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005723 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005724 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5725 castAs<PointerType>()->getPointeeType(),
5726 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005727
Richard Smith027bf112011-11-17 22:56:20 +00005728 case CK_BaseToDerived:
5729 if (!Visit(E->getSubExpr()))
5730 return false;
5731 if (!Result.Base && Result.Offset.isZero())
5732 return true;
5733 return HandleBaseToDerivedCast(Info, E, Result);
5734
Richard Smith0b0a0b62011-10-29 20:57:55 +00005735 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005736 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005737 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005738
John McCalle3027922010-08-25 11:45:40 +00005739 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005740 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5741
Richard Smith2e312c82012-03-03 22:46:17 +00005742 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005743 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005744 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005745
John McCall45d55e42010-05-07 21:00:08 +00005746 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005747 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5748 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005749 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005750 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005751 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005752 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005753 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005754 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005755 return true;
5756 } else {
5757 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005758 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005759 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005760 }
5761 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005762
5763 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005764 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005765 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005766 return false;
5767 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005768 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005769 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005770 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005771 return false;
5772 }
Richard Smith96e0c102011-11-04 02:25:55 +00005773 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005774 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5775 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005776 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005777 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005778 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005779 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005780 }
Richard Smithdd785442011-10-31 20:57:44 +00005781
John McCalle3027922010-08-25 11:45:40 +00005782 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005783 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005784
5785 case CK_LValueToRValue: {
5786 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005787 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005788 return false;
5789
5790 APValue RVal;
5791 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5792 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5793 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005794 return InvalidBaseOK &&
5795 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005796 return Success(RVal, E);
5797 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005798 }
5799
Richard Smith11562c52011-10-28 17:51:58 +00005800 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005801}
Chris Lattner05706e882008-07-11 18:11:29 +00005802
Hal Finkel0dd05d42014-10-03 17:18:37 +00005803static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5804 // C++ [expr.alignof]p3:
5805 // When alignof is applied to a reference type, the result is the
5806 // alignment of the referenced type.
5807 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5808 T = Ref->getPointeeType();
5809
5810 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005811 if (T.getQualifiers().hasUnaligned())
5812 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005813 return Info.Ctx.toCharUnitsFromBits(
5814 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5815}
5816
5817static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5818 E = E->IgnoreParens();
5819
5820 // The kinds of expressions that we have special-case logic here for
5821 // should be kept up to date with the special checks for those
5822 // expressions in Sema.
5823
5824 // alignof decl is always accepted, even if it doesn't make sense: we default
5825 // to 1 in those cases.
5826 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5827 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5828 /*RefAsPointee*/true);
5829
5830 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5831 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5832 /*RefAsPointee*/true);
5833
5834 return GetAlignOfType(Info, E->getType());
5835}
5836
George Burgess IVe3763372016-12-22 02:50:20 +00005837// To be clear: this happily visits unsupported builtins. Better name welcomed.
5838bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5839 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5840 return true;
5841
George Burgess IVf9013bf2017-02-10 22:52:29 +00005842 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005843 return false;
5844
5845 Result.setInvalid(E);
5846 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005847 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005848 return true;
5849}
5850
Peter Collingbournee9200682011-05-13 03:29:01 +00005851bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005852 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005853 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005854
Richard Smith6328cbd2016-11-16 00:57:23 +00005855 if (unsigned BuiltinOp = E->getBuiltinCallee())
5856 return VisitBuiltinCallExpr(E, BuiltinOp);
5857
George Burgess IVe3763372016-12-22 02:50:20 +00005858 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005859}
5860
5861bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5862 unsigned BuiltinOp) {
5863 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005864 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005865 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005866 case Builtin::BI__builtin_assume_aligned: {
5867 // We need to be very careful here because: if the pointer does not have the
5868 // asserted alignment, then the behavior is undefined, and undefined
5869 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005870 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005871 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005872
Hal Finkel0dd05d42014-10-03 17:18:37 +00005873 LValue OffsetResult(Result);
5874 APSInt Alignment;
5875 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5876 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005877 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005878
5879 if (E->getNumArgs() > 2) {
5880 APSInt Offset;
5881 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5882 return false;
5883
Richard Smith642a2362017-01-30 23:30:26 +00005884 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005885 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5886 }
5887
5888 // If there is a base object, then it must have the correct alignment.
5889 if (OffsetResult.Base) {
5890 CharUnits BaseAlignment;
5891 if (const ValueDecl *VD =
5892 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5893 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5894 } else {
5895 BaseAlignment =
5896 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5897 }
5898
5899 if (BaseAlignment < Align) {
5900 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005901 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005902 CCEDiag(E->getArg(0),
5903 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005904 << (unsigned)BaseAlignment.getQuantity()
5905 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005906 return false;
5907 }
5908 }
5909
5910 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005911 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005912 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005913
Richard Smith642a2362017-01-30 23:30:26 +00005914 (OffsetResult.Base
5915 ? CCEDiag(E->getArg(0),
5916 diag::note_constexpr_baa_insufficient_alignment) << 1
5917 : CCEDiag(E->getArg(0),
5918 diag::note_constexpr_baa_value_insufficient_alignment))
5919 << (int)OffsetResult.Offset.getQuantity()
5920 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005921 return false;
5922 }
5923
5924 return true;
5925 }
Richard Smithe9507952016-11-12 01:39:56 +00005926
5927 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005928 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005929 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005930 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005931 if (Info.getLangOpts().CPlusPlus11)
5932 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5933 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005934 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005935 else
5936 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005937 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005938 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005939 case Builtin::BI__builtin_wcschr:
5940 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005941 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005942 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005943 if (!Visit(E->getArg(0)))
5944 return false;
5945 APSInt Desired;
5946 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5947 return false;
5948 uint64_t MaxLength = uint64_t(-1);
5949 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005950 BuiltinOp != Builtin::BIwcschr &&
5951 BuiltinOp != Builtin::BI__builtin_strchr &&
5952 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005953 APSInt N;
5954 if (!EvaluateInteger(E->getArg(2), N, Info))
5955 return false;
5956 MaxLength = N.getExtValue();
5957 }
5958
Richard Smith8110c9d2016-11-29 19:45:17 +00005959 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005960
Richard Smith8110c9d2016-11-29 19:45:17 +00005961 // Figure out what value we're actually looking for (after converting to
5962 // the corresponding unsigned type if necessary).
5963 uint64_t DesiredVal;
5964 bool StopAtNull = false;
5965 switch (BuiltinOp) {
5966 case Builtin::BIstrchr:
5967 case Builtin::BI__builtin_strchr:
5968 // strchr compares directly to the passed integer, and therefore
5969 // always fails if given an int that is not a char.
5970 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5971 E->getArg(1)->getType(),
5972 Desired),
5973 Desired))
5974 return ZeroInitialization(E);
5975 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005976 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005977 case Builtin::BImemchr:
5978 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005979 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005980 // memchr compares by converting both sides to unsigned char. That's also
5981 // correct for strchr if we get this far (to cope with plain char being
5982 // unsigned in the strchr case).
5983 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5984 break;
Richard Smithe9507952016-11-12 01:39:56 +00005985
Richard Smith8110c9d2016-11-29 19:45:17 +00005986 case Builtin::BIwcschr:
5987 case Builtin::BI__builtin_wcschr:
5988 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005989 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005990 case Builtin::BIwmemchr:
5991 case Builtin::BI__builtin_wmemchr:
5992 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5993 DesiredVal = Desired.getZExtValue();
5994 break;
5995 }
Richard Smithe9507952016-11-12 01:39:56 +00005996
5997 for (; MaxLength; --MaxLength) {
5998 APValue Char;
5999 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6000 !Char.isInt())
6001 return false;
6002 if (Char.getInt().getZExtValue() == DesiredVal)
6003 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006004 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006005 break;
6006 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6007 return false;
6008 }
6009 // Not found: return nullptr.
6010 return ZeroInitialization(E);
6011 }
6012
Richard Smith6cbd65d2013-07-11 02:27:57 +00006013 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006014 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006015 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006016}
Chris Lattner05706e882008-07-11 18:11:29 +00006017
6018//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006019// Member Pointer Evaluation
6020//===----------------------------------------------------------------------===//
6021
6022namespace {
6023class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006024 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006025 MemberPtr &Result;
6026
6027 bool Success(const ValueDecl *D) {
6028 Result = MemberPtr(D);
6029 return true;
6030 }
6031public:
6032
6033 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6034 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6035
Richard Smith2e312c82012-03-03 22:46:17 +00006036 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006037 Result.setFrom(V);
6038 return true;
6039 }
Richard Smithfddd3842011-12-30 21:15:51 +00006040 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006041 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006042 }
6043
6044 bool VisitCastExpr(const CastExpr *E);
6045 bool VisitUnaryAddrOf(const UnaryOperator *E);
6046};
6047} // end anonymous namespace
6048
6049static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6050 EvalInfo &Info) {
6051 assert(E->isRValue() && E->getType()->isMemberPointerType());
6052 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6053}
6054
6055bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6056 switch (E->getCastKind()) {
6057 default:
6058 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6059
6060 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006061 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006062 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006063
6064 case CK_BaseToDerivedMemberPointer: {
6065 if (!Visit(E->getSubExpr()))
6066 return false;
6067 if (E->path_empty())
6068 return true;
6069 // Base-to-derived member pointer casts store the path in derived-to-base
6070 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6071 // the wrong end of the derived->base arc, so stagger the path by one class.
6072 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6073 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6074 PathI != PathE; ++PathI) {
6075 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6076 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6077 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006078 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006079 }
6080 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6081 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006082 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006083 return true;
6084 }
6085
6086 case CK_DerivedToBaseMemberPointer:
6087 if (!Visit(E->getSubExpr()))
6088 return false;
6089 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6090 PathE = E->path_end(); PathI != PathE; ++PathI) {
6091 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6092 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6093 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006094 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006095 }
6096 return true;
6097 }
6098}
6099
6100bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6101 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6102 // member can be formed.
6103 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6104}
6105
6106//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006107// Record Evaluation
6108//===----------------------------------------------------------------------===//
6109
6110namespace {
6111 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006112 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006113 const LValue &This;
6114 APValue &Result;
6115 public:
6116
6117 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6118 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6119
Richard Smith2e312c82012-03-03 22:46:17 +00006120 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006121 Result = V;
6122 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006123 }
Richard Smithb8348f52016-05-12 22:16:28 +00006124 bool ZeroInitialization(const Expr *E) {
6125 return ZeroInitialization(E, E->getType());
6126 }
6127 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006128
Richard Smith52a980a2015-08-28 02:43:42 +00006129 bool VisitCallExpr(const CallExpr *E) {
6130 return handleCallExpr(E, Result, &This);
6131 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006132 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006133 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006134 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6135 return VisitCXXConstructExpr(E, E->getType());
6136 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006137 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006138 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006139 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006140 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006141 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006142}
Richard Smithd62306a2011-11-10 06:34:14 +00006143
Richard Smithfddd3842011-12-30 21:15:51 +00006144/// Perform zero-initialization on an object of non-union class type.
6145/// C++11 [dcl.init]p5:
6146/// To zero-initialize an object or reference of type T means:
6147/// [...]
6148/// -- if T is a (possibly cv-qualified) non-union class type,
6149/// each non-static data member and each base-class subobject is
6150/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006151static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6152 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006153 const LValue &This, APValue &Result) {
6154 assert(!RD->isUnion() && "Expected non-union class type");
6155 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6156 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006157 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006158
John McCalld7bca762012-05-01 00:38:49 +00006159 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006160 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6161
6162 if (CD) {
6163 unsigned Index = 0;
6164 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006165 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006166 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6167 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006168 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6169 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006170 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006171 Result.getStructBase(Index)))
6172 return false;
6173 }
6174 }
6175
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006176 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006177 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006178 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006179 continue;
6180
6181 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006182 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006183 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006184
David Blaikie2d7c57e2012-04-30 02:36:29 +00006185 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006186 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006187 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006188 return false;
6189 }
6190
6191 return true;
6192}
6193
Richard Smithb8348f52016-05-12 22:16:28 +00006194bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6195 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006196 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006197 if (RD->isUnion()) {
6198 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6199 // object's first non-static named data member is zero-initialized
6200 RecordDecl::field_iterator I = RD->field_begin();
6201 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006202 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006203 return true;
6204 }
6205
6206 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006207 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006208 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006209 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006210 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006211 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006212 }
6213
Richard Smith5d108602012-02-17 00:44:16 +00006214 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006215 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006216 return false;
6217 }
6218
Richard Smitha8105bc2012-01-06 16:39:00 +00006219 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006220}
6221
Richard Smithe97cbd72011-11-11 04:05:33 +00006222bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6223 switch (E->getCastKind()) {
6224 default:
6225 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6226
6227 case CK_ConstructorConversion:
6228 return Visit(E->getSubExpr());
6229
6230 case CK_DerivedToBase:
6231 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006232 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006233 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006234 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006235 if (!DerivedObject.isStruct())
6236 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006237
6238 // Derived-to-base rvalue conversion: just slice off the derived part.
6239 APValue *Value = &DerivedObject;
6240 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6241 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6242 PathE = E->path_end(); PathI != PathE; ++PathI) {
6243 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6244 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6245 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6246 RD = Base;
6247 }
6248 Result = *Value;
6249 return true;
6250 }
6251 }
6252}
6253
Richard Smithd62306a2011-11-10 06:34:14 +00006254bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006255 if (E->isTransparent())
6256 return Visit(E->getInit(0));
6257
Richard Smithd62306a2011-11-10 06:34:14 +00006258 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006259 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006260 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6261
6262 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006263 const FieldDecl *Field = E->getInitializedFieldInUnion();
6264 Result = APValue(Field);
6265 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006266 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006267
6268 // If the initializer list for a union does not contain any elements, the
6269 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006270 // FIXME: The element should be initialized from an initializer list.
6271 // Is this difference ever observable for initializer lists which
6272 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006273 ImplicitValueInitExpr VIE(Field->getType());
6274 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6275
Richard Smithd62306a2011-11-10 06:34:14 +00006276 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006277 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6278 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006279
6280 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6281 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6282 isa<CXXDefaultInitExpr>(InitExpr));
6283
Richard Smithb228a862012-02-15 02:18:13 +00006284 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006285 }
6286
Richard Smith872307e2016-03-08 22:17:41 +00006287 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006288 if (Result.isUninit())
6289 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6290 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006291 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006292 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006293
6294 // Initialize base classes.
6295 if (CXXRD) {
6296 for (const auto &Base : CXXRD->bases()) {
6297 assert(ElementNo < E->getNumInits() && "missing init for base class");
6298 const Expr *Init = E->getInit(ElementNo);
6299
6300 LValue Subobject = This;
6301 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6302 return false;
6303
6304 APValue &FieldVal = Result.getStructBase(ElementNo);
6305 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006306 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006307 return false;
6308 Success = false;
6309 }
6310 ++ElementNo;
6311 }
6312 }
6313
6314 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006315 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006316 // Anonymous bit-fields are not considered members of the class for
6317 // purposes of aggregate initialization.
6318 if (Field->isUnnamedBitfield())
6319 continue;
6320
6321 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006322
Richard Smith253c2a32012-01-27 01:14:48 +00006323 bool HaveInit = ElementNo < E->getNumInits();
6324
6325 // FIXME: Diagnostics here should point to the end of the initializer
6326 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006327 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006328 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006329 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006330
6331 // Perform an implicit value-initialization for members beyond the end of
6332 // the initializer list.
6333 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006334 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006335
Richard Smith852c9db2013-04-20 22:23:05 +00006336 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6337 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6338 isa<CXXDefaultInitExpr>(Init));
6339
Richard Smith49ca8aa2013-08-06 07:09:20 +00006340 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6341 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6342 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006343 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006344 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006345 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006346 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006347 }
6348 }
6349
Richard Smith253c2a32012-01-27 01:14:48 +00006350 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006351}
6352
Richard Smithb8348f52016-05-12 22:16:28 +00006353bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6354 QualType T) {
6355 // Note that E's type is not necessarily the type of our class here; we might
6356 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006357 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006358 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6359
Richard Smithfddd3842011-12-30 21:15:51 +00006360 bool ZeroInit = E->requiresZeroInitialization();
6361 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006362 // If we've already performed zero-initialization, we're already done.
6363 if (!Result.isUninit())
6364 return true;
6365
Richard Smithda3f4fd2014-03-05 23:32:50 +00006366 // We can get here in two different ways:
6367 // 1) We're performing value-initialization, and should zero-initialize
6368 // the object, or
6369 // 2) We're performing default-initialization of an object with a trivial
6370 // constexpr default constructor, in which case we should start the
6371 // lifetimes of all the base subobjects (there can be no data member
6372 // subobjects in this case) per [basic.life]p1.
6373 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006374 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006375 }
6376
Craig Topper36250ad2014-05-12 05:36:57 +00006377 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006378 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006379
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006380 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006381 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006382
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006383 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006384 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006385 if (const MaterializeTemporaryExpr *ME
6386 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6387 return Visit(ME->GetTemporaryExpr());
6388
Richard Smithb8348f52016-05-12 22:16:28 +00006389 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006390 return false;
6391
Craig Topper5fc8fc22014-08-27 06:28:36 +00006392 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006393 return HandleConstructorCall(E, This, Args,
6394 cast<CXXConstructorDecl>(Definition), Info,
6395 Result);
6396}
6397
6398bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6399 const CXXInheritedCtorInitExpr *E) {
6400 if (!Info.CurrentCall) {
6401 assert(Info.checkingPotentialConstantExpression());
6402 return false;
6403 }
6404
6405 const CXXConstructorDecl *FD = E->getConstructor();
6406 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6407 return false;
6408
6409 const FunctionDecl *Definition = nullptr;
6410 auto Body = FD->getBody(Definition);
6411
6412 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6413 return false;
6414
6415 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006416 cast<CXXConstructorDecl>(Definition), Info,
6417 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006418}
6419
Richard Smithcc1b96d2013-06-12 22:31:48 +00006420bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6421 const CXXStdInitializerListExpr *E) {
6422 const ConstantArrayType *ArrayType =
6423 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6424
6425 LValue Array;
6426 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6427 return false;
6428
6429 // Get a pointer to the first element of the array.
6430 Array.addArray(Info, E, ArrayType);
6431
6432 // FIXME: Perform the checks on the field types in SemaInit.
6433 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6434 RecordDecl::field_iterator Field = Record->field_begin();
6435 if (Field == Record->field_end())
6436 return Error(E);
6437
6438 // Start pointer.
6439 if (!Field->getType()->isPointerType() ||
6440 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6441 ArrayType->getElementType()))
6442 return Error(E);
6443
6444 // FIXME: What if the initializer_list type has base classes, etc?
6445 Result = APValue(APValue::UninitStruct(), 0, 2);
6446 Array.moveInto(Result.getStructField(0));
6447
6448 if (++Field == Record->field_end())
6449 return Error(E);
6450
6451 if (Field->getType()->isPointerType() &&
6452 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6453 ArrayType->getElementType())) {
6454 // End pointer.
6455 if (!HandleLValueArrayAdjustment(Info, E, Array,
6456 ArrayType->getElementType(),
6457 ArrayType->getSize().getZExtValue()))
6458 return false;
6459 Array.moveInto(Result.getStructField(1));
6460 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6461 // Length.
6462 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6463 else
6464 return Error(E);
6465
6466 if (++Field != Record->field_end())
6467 return Error(E);
6468
6469 return true;
6470}
6471
Faisal Valic72a08c2017-01-09 03:02:53 +00006472bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6473 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6474 if (ClosureClass->isInvalidDecl()) return false;
6475
6476 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006477
Faisal Vali051e3a22017-02-16 04:12:21 +00006478 const size_t NumFields =
6479 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006480
6481 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6482 E->capture_init_end()) &&
6483 "The number of lambda capture initializers should equal the number of "
6484 "fields within the closure type");
6485
Faisal Vali051e3a22017-02-16 04:12:21 +00006486 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6487 // Iterate through all the lambda's closure object's fields and initialize
6488 // them.
6489 auto *CaptureInitIt = E->capture_init_begin();
6490 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6491 bool Success = true;
6492 for (const auto *Field : ClosureClass->fields()) {
6493 assert(CaptureInitIt != E->capture_init_end());
6494 // Get the initializer for this field
6495 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006496
Faisal Vali051e3a22017-02-16 04:12:21 +00006497 // If there is no initializer, either this is a VLA or an error has
6498 // occurred.
6499 if (!CurFieldInit)
6500 return Error(E);
6501
6502 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6503 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6504 if (!Info.keepEvaluatingAfterFailure())
6505 return false;
6506 Success = false;
6507 }
6508 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006509 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006510 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006511}
6512
Richard Smithd62306a2011-11-10 06:34:14 +00006513static bool EvaluateRecord(const Expr *E, const LValue &This,
6514 APValue &Result, EvalInfo &Info) {
6515 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006516 "can't evaluate expression as a record rvalue");
6517 return RecordExprEvaluator(Info, This, Result).Visit(E);
6518}
6519
6520//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006521// Temporary Evaluation
6522//
6523// Temporaries are represented in the AST as rvalues, but generally behave like
6524// lvalues. The full-object of which the temporary is a subobject is implicitly
6525// materialized so that a reference can bind to it.
6526//===----------------------------------------------------------------------===//
6527namespace {
6528class TemporaryExprEvaluator
6529 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6530public:
6531 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006532 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006533
6534 /// Visit an expression which constructs the value of this temporary.
6535 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006536 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006537 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6538 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006539 }
6540
6541 bool VisitCastExpr(const CastExpr *E) {
6542 switch (E->getCastKind()) {
6543 default:
6544 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6545
6546 case CK_ConstructorConversion:
6547 return VisitConstructExpr(E->getSubExpr());
6548 }
6549 }
6550 bool VisitInitListExpr(const InitListExpr *E) {
6551 return VisitConstructExpr(E);
6552 }
6553 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6554 return VisitConstructExpr(E);
6555 }
6556 bool VisitCallExpr(const CallExpr *E) {
6557 return VisitConstructExpr(E);
6558 }
Richard Smith513955c2014-12-17 19:24:30 +00006559 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6560 return VisitConstructExpr(E);
6561 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006562 bool VisitLambdaExpr(const LambdaExpr *E) {
6563 return VisitConstructExpr(E);
6564 }
Richard Smith027bf112011-11-17 22:56:20 +00006565};
6566} // end anonymous namespace
6567
6568/// Evaluate an expression of record type as a temporary.
6569static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006570 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006571 return TemporaryExprEvaluator(Info, Result).Visit(E);
6572}
6573
6574//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006575// Vector Evaluation
6576//===----------------------------------------------------------------------===//
6577
6578namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006579 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006580 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006581 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006582 public:
Mike Stump11289f42009-09-09 15:08:12 +00006583
Richard Smith2d406342011-10-22 21:10:00 +00006584 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6585 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006586
Craig Topper9798b932015-09-29 04:30:05 +00006587 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006588 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6589 // FIXME: remove this APValue copy.
6590 Result = APValue(V.data(), V.size());
6591 return true;
6592 }
Richard Smith2e312c82012-03-03 22:46:17 +00006593 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006594 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006595 Result = V;
6596 return true;
6597 }
Richard Smithfddd3842011-12-30 21:15:51 +00006598 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006599
Richard Smith2d406342011-10-22 21:10:00 +00006600 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006601 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006602 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006603 bool VisitInitListExpr(const InitListExpr *E);
6604 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006605 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006606 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006607 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006608 };
6609} // end anonymous namespace
6610
6611static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006612 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006613 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006614}
6615
George Burgess IV533ff002015-12-11 00:23:35 +00006616bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006617 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006618 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006619
Richard Smith161f09a2011-12-06 22:44:34 +00006620 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006621 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006622
Eli Friedmanc757de22011-03-25 00:43:55 +00006623 switch (E->getCastKind()) {
6624 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006625 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006626 if (SETy->isIntegerType()) {
6627 APSInt IntResult;
6628 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006629 return false;
6630 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006631 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006632 APFloat FloatResult(0.0);
6633 if (!EvaluateFloat(SE, FloatResult, Info))
6634 return false;
6635 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006636 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006637 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006638 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006639
6640 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006641 SmallVector<APValue, 4> Elts(NElts, Val);
6642 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006643 }
Eli Friedman803acb32011-12-22 03:51:45 +00006644 case CK_BitCast: {
6645 // Evaluate the operand into an APInt we can extract from.
6646 llvm::APInt SValInt;
6647 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6648 return false;
6649 // Extract the elements
6650 QualType EltTy = VTy->getElementType();
6651 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6652 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6653 SmallVector<APValue, 4> Elts;
6654 if (EltTy->isRealFloatingType()) {
6655 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006656 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006657 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006658 FloatEltSize = 80;
6659 for (unsigned i = 0; i < NElts; i++) {
6660 llvm::APInt Elt;
6661 if (BigEndian)
6662 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6663 else
6664 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006665 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006666 }
6667 } else if (EltTy->isIntegerType()) {
6668 for (unsigned i = 0; i < NElts; i++) {
6669 llvm::APInt Elt;
6670 if (BigEndian)
6671 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6672 else
6673 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6674 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6675 }
6676 } else {
6677 return Error(E);
6678 }
6679 return Success(Elts, E);
6680 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006681 default:
Richard Smith11562c52011-10-28 17:51:58 +00006682 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006683 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006684}
6685
Richard Smith2d406342011-10-22 21:10:00 +00006686bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006687VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006688 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006689 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006690 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006691
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006692 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006693 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006694
Eli Friedmanb9c71292012-01-03 23:24:20 +00006695 // The number of initializers can be less than the number of
6696 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006697 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006698 // should be initialized with zeroes.
6699 unsigned CountInits = 0, CountElts = 0;
6700 while (CountElts < NumElements) {
6701 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006702 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006703 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006704 APValue v;
6705 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6706 return Error(E);
6707 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006708 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006709 Elements.push_back(v.getVectorElt(j));
6710 CountElts += vlen;
6711 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006712 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006713 if (CountInits < NumInits) {
6714 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006715 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006716 } else // trailing integer zero.
6717 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6718 Elements.push_back(APValue(sInt));
6719 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006720 } else {
6721 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006722 if (CountInits < NumInits) {
6723 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006724 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006725 } else // trailing float zero.
6726 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6727 Elements.push_back(APValue(f));
6728 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006729 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006730 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006731 }
Richard Smith2d406342011-10-22 21:10:00 +00006732 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006733}
6734
Richard Smith2d406342011-10-22 21:10:00 +00006735bool
Richard Smithfddd3842011-12-30 21:15:51 +00006736VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006737 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006738 QualType EltTy = VT->getElementType();
6739 APValue ZeroElement;
6740 if (EltTy->isIntegerType())
6741 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6742 else
6743 ZeroElement =
6744 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6745
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006746 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006747 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006748}
6749
Richard Smith2d406342011-10-22 21:10:00 +00006750bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006751 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006752 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006753}
6754
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006755//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006756// Array Evaluation
6757//===----------------------------------------------------------------------===//
6758
6759namespace {
6760 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006761 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006762 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006763 APValue &Result;
6764 public:
6765
Richard Smithd62306a2011-11-10 06:34:14 +00006766 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6767 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006768
6769 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006770 assert((V.isArray() || V.isLValue()) &&
6771 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006772 Result = V;
6773 return true;
6774 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006775
Richard Smithfddd3842011-12-30 21:15:51 +00006776 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006777 const ConstantArrayType *CAT =
6778 Info.Ctx.getAsConstantArrayType(E->getType());
6779 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006780 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006781
6782 Result = APValue(APValue::UninitArray(), 0,
6783 CAT->getSize().getZExtValue());
6784 if (!Result.hasArrayFiller()) return true;
6785
Richard Smithfddd3842011-12-30 21:15:51 +00006786 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006787 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006788 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006789 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006790 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006791 }
6792
Richard Smith52a980a2015-08-28 02:43:42 +00006793 bool VisitCallExpr(const CallExpr *E) {
6794 return handleCallExpr(E, Result, &This);
6795 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006796 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006797 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006798 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006799 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6800 const LValue &Subobject,
6801 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006802 };
6803} // end anonymous namespace
6804
Richard Smithd62306a2011-11-10 06:34:14 +00006805static bool EvaluateArray(const Expr *E, const LValue &This,
6806 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006807 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006808 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006809}
6810
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006811// Return true iff the given array filler may depend on the element index.
6812static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6813 // For now, just whitelist non-class value-initialization and initialization
6814 // lists comprised of them.
6815 if (isa<ImplicitValueInitExpr>(FillerExpr))
6816 return false;
6817 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6818 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6819 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6820 return true;
6821 }
6822 return false;
6823 }
6824 return true;
6825}
6826
Richard Smithf3e9e432011-11-07 09:22:26 +00006827bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6828 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6829 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006830 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006831
Richard Smithca2cfbf2011-12-22 01:07:19 +00006832 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6833 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006834 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006835 LValue LV;
6836 if (!EvaluateLValue(E->getInit(0), LV, Info))
6837 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006838 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006839 LV.moveInto(Val);
6840 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006841 }
6842
Richard Smith253c2a32012-01-27 01:14:48 +00006843 bool Success = true;
6844
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006845 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6846 "zero-initialized array shouldn't have any initialized elts");
6847 APValue Filler;
6848 if (Result.isArray() && Result.hasArrayFiller())
6849 Filler = Result.getArrayFiller();
6850
Richard Smith9543c5e2013-04-22 14:44:29 +00006851 unsigned NumEltsToInit = E->getNumInits();
6852 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006853 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006854
6855 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006856 // array element.
6857 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006858 NumEltsToInit = NumElts;
6859
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006860 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6861 NumEltsToInit << ".\n");
6862
Richard Smith9543c5e2013-04-22 14:44:29 +00006863 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006864
6865 // If the array was previously zero-initialized, preserve the
6866 // zero-initialized values.
6867 if (!Filler.isUninit()) {
6868 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6869 Result.getArrayInitializedElt(I) = Filler;
6870 if (Result.hasArrayFiller())
6871 Result.getArrayFiller() = Filler;
6872 }
6873
Richard Smithd62306a2011-11-10 06:34:14 +00006874 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006875 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006876 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6877 const Expr *Init =
6878 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006879 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006880 Info, Subobject, Init) ||
6881 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006882 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006883 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006884 return false;
6885 Success = false;
6886 }
Richard Smithd62306a2011-11-10 06:34:14 +00006887 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006888
Richard Smith9543c5e2013-04-22 14:44:29 +00006889 if (!Result.hasArrayFiller())
6890 return Success;
6891
6892 // If we get here, we have a trivial filler, which we can just evaluate
6893 // once and splat over the rest of the array elements.
6894 assert(FillerExpr && "no array filler for incomplete init list");
6895 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6896 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006897}
6898
Richard Smith410306b2016-12-12 02:53:20 +00006899bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6900 if (E->getCommonExpr() &&
6901 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6902 Info, E->getCommonExpr()->getSourceExpr()))
6903 return false;
6904
6905 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6906
6907 uint64_t Elements = CAT->getSize().getZExtValue();
6908 Result = APValue(APValue::UninitArray(), Elements, Elements);
6909
6910 LValue Subobject = This;
6911 Subobject.addArray(Info, E, CAT);
6912
6913 bool Success = true;
6914 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6915 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6916 Info, Subobject, E->getSubExpr()) ||
6917 !HandleLValueArrayAdjustment(Info, E, Subobject,
6918 CAT->getElementType(), 1)) {
6919 if (!Info.noteFailure())
6920 return false;
6921 Success = false;
6922 }
6923 }
6924
6925 return Success;
6926}
6927
Richard Smith027bf112011-11-17 22:56:20 +00006928bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006929 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6930}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006931
Richard Smith9543c5e2013-04-22 14:44:29 +00006932bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6933 const LValue &Subobject,
6934 APValue *Value,
6935 QualType Type) {
6936 bool HadZeroInit = !Value->isUninit();
6937
6938 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6939 unsigned N = CAT->getSize().getZExtValue();
6940
6941 // Preserve the array filler if we had prior zero-initialization.
6942 APValue Filler =
6943 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6944 : APValue();
6945
6946 *Value = APValue(APValue::UninitArray(), N, N);
6947
6948 if (HadZeroInit)
6949 for (unsigned I = 0; I != N; ++I)
6950 Value->getArrayInitializedElt(I) = Filler;
6951
6952 // Initialize the elements.
6953 LValue ArrayElt = Subobject;
6954 ArrayElt.addArray(Info, E, CAT);
6955 for (unsigned I = 0; I != N; ++I)
6956 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6957 CAT->getElementType()) ||
6958 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6959 CAT->getElementType(), 1))
6960 return false;
6961
6962 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006963 }
Richard Smith027bf112011-11-17 22:56:20 +00006964
Richard Smith9543c5e2013-04-22 14:44:29 +00006965 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006966 return Error(E);
6967
Richard Smithb8348f52016-05-12 22:16:28 +00006968 return RecordExprEvaluator(Info, Subobject, *Value)
6969 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006970}
6971
Richard Smithf3e9e432011-11-07 09:22:26 +00006972//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006973// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006974//
6975// As a GNU extension, we support casting pointers to sufficiently-wide integer
6976// types and back in constant folding. Integer values are thus represented
6977// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006978//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006979
6980namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006981class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006982 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006983 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006984public:
Richard Smith2e312c82012-03-03 22:46:17 +00006985 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006986 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006987
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006988 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006989 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006990 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006991 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006992 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006993 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006994 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006995 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006996 return true;
6997 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006998 bool Success(const llvm::APSInt &SI, const Expr *E) {
6999 return Success(SI, E, Result);
7000 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007001
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007002 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007003 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007004 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007005 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007006 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007007 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007008 Result.getInt().setIsUnsigned(
7009 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007010 return true;
7011 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007012 bool Success(const llvm::APInt &I, const Expr *E) {
7013 return Success(I, E, Result);
7014 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007015
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007016 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007017 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007018 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007019 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007020 return true;
7021 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007022 bool Success(uint64_t Value, const Expr *E) {
7023 return Success(Value, E, Result);
7024 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007025
Ken Dyckdbc01912011-03-11 02:13:43 +00007026 bool Success(CharUnits Size, const Expr *E) {
7027 return Success(Size.getQuantity(), E);
7028 }
7029
Richard Smith2e312c82012-03-03 22:46:17 +00007030 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007031 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007032 Result = V;
7033 return true;
7034 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007035 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007036 }
Mike Stump11289f42009-09-09 15:08:12 +00007037
Richard Smithfddd3842011-12-30 21:15:51 +00007038 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007039
Peter Collingbournee9200682011-05-13 03:29:01 +00007040 //===--------------------------------------------------------------------===//
7041 // Visitor Methods
7042 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007043
Chris Lattner7174bf32008-07-12 00:38:25 +00007044 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007045 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007046 }
7047 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007048 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007049 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007050
7051 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7052 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007053 if (CheckReferencedDecl(E, E->getDecl()))
7054 return true;
7055
7056 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007057 }
7058 bool VisitMemberExpr(const MemberExpr *E) {
7059 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007060 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007061 return true;
7062 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007063
7064 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007065 }
7066
Peter Collingbournee9200682011-05-13 03:29:01 +00007067 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007068 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007069 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007070 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007071 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007072
Peter Collingbournee9200682011-05-13 03:29:01 +00007073 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007074 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007075
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007076 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007077 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007078 }
Mike Stump11289f42009-09-09 15:08:12 +00007079
Ted Kremeneke65b0862012-03-06 20:05:56 +00007080 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7081 return Success(E->getValue(), E);
7082 }
Richard Smith410306b2016-12-12 02:53:20 +00007083
7084 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7085 if (Info.ArrayInitIndex == uint64_t(-1)) {
7086 // We were asked to evaluate this subexpression independent of the
7087 // enclosing ArrayInitLoopExpr. We can't do that.
7088 Info.FFDiag(E);
7089 return false;
7090 }
7091 return Success(Info.ArrayInitIndex, E);
7092 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007093
Richard Smith4ce706a2011-10-11 21:43:33 +00007094 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007095 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007096 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007097 }
7098
Douglas Gregor29c42f22012-02-24 07:38:34 +00007099 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7100 return Success(E->getValue(), E);
7101 }
7102
John Wiegley6242b6a2011-04-28 00:16:57 +00007103 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7104 return Success(E->getValue(), E);
7105 }
7106
John Wiegleyf9f65842011-04-25 06:54:41 +00007107 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7108 return Success(E->getValue(), E);
7109 }
7110
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007111 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007112 bool VisitUnaryImag(const UnaryOperator *E);
7113
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007114 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007115 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007116
Eli Friedman4e7a2412009-02-27 04:45:43 +00007117 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007118};
Chris Lattner05706e882008-07-11 18:11:29 +00007119} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007120
Richard Smith11562c52011-10-28 17:51:58 +00007121/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7122/// produce either the integer value or a pointer.
7123///
7124/// GCC has a heinous extension which folds casts between pointer types and
7125/// pointer-sized integral types. We support this by allowing the evaluation of
7126/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7127/// Some simple arithmetic on such values is supported (they are treated much
7128/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007129static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007130 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007131 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007132 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007133}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007134
Richard Smithf57d8cb2011-12-09 22:58:01 +00007135static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007136 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007137 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007138 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007139 if (!Val.isInt()) {
7140 // FIXME: It would be better to produce the diagnostic for casting
7141 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007142 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007143 return false;
7144 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007145 Result = Val.getInt();
7146 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007147}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007148
Richard Smithf57d8cb2011-12-09 22:58:01 +00007149/// Check whether the given declaration can be directly converted to an integral
7150/// rvalue. If not, no diagnostic is produced; there are other things we can
7151/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007152bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007153 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007154 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007155 // Check for signedness/width mismatches between E type and ECD value.
7156 bool SameSign = (ECD->getInitVal().isSigned()
7157 == E->getType()->isSignedIntegerOrEnumerationType());
7158 bool SameWidth = (ECD->getInitVal().getBitWidth()
7159 == Info.Ctx.getIntWidth(E->getType()));
7160 if (SameSign && SameWidth)
7161 return Success(ECD->getInitVal(), E);
7162 else {
7163 // Get rid of mismatch (otherwise Success assertions will fail)
7164 // by computing a new value matching the type of E.
7165 llvm::APSInt Val = ECD->getInitVal();
7166 if (!SameSign)
7167 Val.setIsSigned(!ECD->getInitVal().isSigned());
7168 if (!SameWidth)
7169 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7170 return Success(Val, E);
7171 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007172 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007173 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007174}
7175
Chris Lattner86ee2862008-10-06 06:40:35 +00007176/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7177/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007178static int EvaluateBuiltinClassifyType(const CallExpr *E,
7179 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007180 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007181 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007182 enum gcc_type_class {
7183 no_type_class = -1,
7184 void_type_class, integer_type_class, char_type_class,
7185 enumeral_type_class, boolean_type_class,
7186 pointer_type_class, reference_type_class, offset_type_class,
7187 real_type_class, complex_type_class,
7188 function_type_class, method_type_class,
7189 record_type_class, union_type_class,
7190 array_type_class, string_type_class,
7191 lang_type_class
7192 };
Mike Stump11289f42009-09-09 15:08:12 +00007193
7194 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007195 // ideal, however it is what gcc does.
7196 if (E->getNumArgs() == 0)
7197 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007198
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007199 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7200 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7201
7202 switch (CanTy->getTypeClass()) {
7203#define TYPE(ID, BASE)
7204#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7205#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7206#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7207#include "clang/AST/TypeNodes.def"
7208 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7209
7210 case Type::Builtin:
7211 switch (BT->getKind()) {
7212#define BUILTIN_TYPE(ID, SINGLETON_ID)
7213#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7214#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7215#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7216#include "clang/AST/BuiltinTypes.def"
7217 case BuiltinType::Void:
7218 return void_type_class;
7219
7220 case BuiltinType::Bool:
7221 return boolean_type_class;
7222
7223 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7224 case BuiltinType::UChar:
7225 case BuiltinType::UShort:
7226 case BuiltinType::UInt:
7227 case BuiltinType::ULong:
7228 case BuiltinType::ULongLong:
7229 case BuiltinType::UInt128:
7230 return integer_type_class;
7231
7232 case BuiltinType::NullPtr:
7233 return pointer_type_class;
7234
7235 case BuiltinType::WChar_U:
7236 case BuiltinType::Char16:
7237 case BuiltinType::Char32:
7238 case BuiltinType::ObjCId:
7239 case BuiltinType::ObjCClass:
7240 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007241#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7242 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007243#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007244 case BuiltinType::OCLSampler:
7245 case BuiltinType::OCLEvent:
7246 case BuiltinType::OCLClkEvent:
7247 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007248 case BuiltinType::OCLReserveID:
7249 case BuiltinType::Dependent:
7250 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7251 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007252 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007253
7254 case Type::Enum:
7255 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7256 break;
7257
7258 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007259 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007260 break;
7261
7262 case Type::MemberPointer:
7263 if (CanTy->isMemberDataPointerType())
7264 return offset_type_class;
7265 else {
7266 // We expect member pointers to be either data or function pointers,
7267 // nothing else.
7268 assert(CanTy->isMemberFunctionPointerType());
7269 return method_type_class;
7270 }
7271
7272 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007273 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007274
7275 case Type::FunctionNoProto:
7276 case Type::FunctionProto:
7277 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7278
7279 case Type::Record:
7280 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7281 switch (RT->getDecl()->getTagKind()) {
7282 case TagTypeKind::TTK_Struct:
7283 case TagTypeKind::TTK_Class:
7284 case TagTypeKind::TTK_Interface:
7285 return record_type_class;
7286
7287 case TagTypeKind::TTK_Enum:
7288 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7289
7290 case TagTypeKind::TTK_Union:
7291 return union_type_class;
7292 }
7293 }
David Blaikie83d382b2011-09-23 05:06:16 +00007294 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007295
7296 case Type::ConstantArray:
7297 case Type::VariableArray:
7298 case Type::IncompleteArray:
7299 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7300
7301 case Type::BlockPointer:
7302 case Type::LValueReference:
7303 case Type::RValueReference:
7304 case Type::Vector:
7305 case Type::ExtVector:
7306 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007307 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007308 case Type::ObjCObject:
7309 case Type::ObjCInterface:
7310 case Type::ObjCObjectPointer:
7311 case Type::Pipe:
7312 case Type::Atomic:
7313 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7314 }
7315
7316 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007317}
7318
Richard Smith5fab0c92011-12-28 19:48:30 +00007319/// EvaluateBuiltinConstantPForLValue - Determine the result of
7320/// __builtin_constant_p when applied to the given lvalue.
7321///
7322/// An lvalue is only "constant" if it is a pointer or reference to the first
7323/// character of a string literal.
7324template<typename LValue>
7325static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007326 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007327 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7328}
7329
7330/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7331/// GCC as we can manage.
7332static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7333 QualType ArgType = Arg->getType();
7334
7335 // __builtin_constant_p always has one operand. The rules which gcc follows
7336 // are not precisely documented, but are as follows:
7337 //
7338 // - If the operand is of integral, floating, complex or enumeration type,
7339 // and can be folded to a known value of that type, it returns 1.
7340 // - If the operand and can be folded to a pointer to the first character
7341 // of a string literal (or such a pointer cast to an integral type), it
7342 // returns 1.
7343 //
7344 // Otherwise, it returns 0.
7345 //
7346 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7347 // its support for this does not currently work.
7348 if (ArgType->isIntegralOrEnumerationType()) {
7349 Expr::EvalResult Result;
7350 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7351 return false;
7352
7353 APValue &V = Result.Val;
7354 if (V.getKind() == APValue::Int)
7355 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007356 if (V.getKind() == APValue::LValue)
7357 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007358 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7359 return Arg->isEvaluatable(Ctx);
7360 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7361 LValue LV;
7362 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007363 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007364 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7365 : EvaluatePointer(Arg, LV, Info)) &&
7366 !Status.HasSideEffects)
7367 return EvaluateBuiltinConstantPForLValue(LV);
7368 }
7369
7370 // Anything else isn't considered to be sufficiently constant.
7371 return false;
7372}
7373
John McCall95007602010-05-10 23:27:23 +00007374/// Retrieves the "underlying object type" of the given expression,
7375/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007376static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007377 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7378 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007379 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007380 } else if (const Expr *E = B.get<const Expr*>()) {
7381 if (isa<CompoundLiteralExpr>(E))
7382 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007383 }
7384
7385 return QualType();
7386}
7387
George Burgess IV3a03fab2015-09-04 21:28:13 +00007388/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007389/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007390/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007391/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7392///
7393/// Always returns an RValue with a pointer representation.
7394static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7395 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7396
7397 auto *NoParens = E->IgnoreParens();
7398 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007399 if (Cast == nullptr)
7400 return NoParens;
7401
7402 // We only conservatively allow a few kinds of casts, because this code is
7403 // inherently a simple solution that seeks to support the common case.
7404 auto CastKind = Cast->getCastKind();
7405 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7406 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007407 return NoParens;
7408
7409 auto *SubExpr = Cast->getSubExpr();
7410 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7411 return NoParens;
7412 return ignorePointerCastsAndParens(SubExpr);
7413}
7414
George Burgess IVa51c4072015-10-16 01:49:01 +00007415/// Checks to see if the given LValue's Designator is at the end of the LValue's
7416/// record layout. e.g.
7417/// struct { struct { int a, b; } fst, snd; } obj;
7418/// obj.fst // no
7419/// obj.snd // yes
7420/// obj.fst.a // no
7421/// obj.fst.b // no
7422/// obj.snd.a // no
7423/// obj.snd.b // yes
7424///
7425/// Please note: this function is specialized for how __builtin_object_size
7426/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007427///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007428/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7429/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007430static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7431 assert(!LVal.Designator.Invalid);
7432
George Burgess IV4168d752016-06-27 19:40:41 +00007433 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7434 const RecordDecl *Parent = FD->getParent();
7435 Invalid = Parent->isInvalidDecl();
7436 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007437 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007438 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007439 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7440 };
7441
7442 auto &Base = LVal.getLValueBase();
7443 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7444 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007445 bool Invalid;
7446 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7447 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007448 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007449 for (auto *FD : IFD->chain()) {
7450 bool Invalid;
7451 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7452 return Invalid;
7453 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007454 }
7455 }
7456
George Burgess IVe3763372016-12-22 02:50:20 +00007457 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007458 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007459 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007460 // If we don't know the array bound, conservatively assume we're looking at
7461 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007462 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007463 if (BaseType->isIncompleteArrayType())
7464 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7465 else
7466 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007467 }
7468
7469 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7470 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007471 if (BaseType->isArrayType()) {
7472 // Because __builtin_object_size treats arrays as objects, we can ignore
7473 // the index iff this is the last array in the Designator.
7474 if (I + 1 == E)
7475 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007476 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7477 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007478 if (Index + 1 != CAT->getSize())
7479 return false;
7480 BaseType = CAT->getElementType();
7481 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007482 const auto *CT = BaseType->castAs<ComplexType>();
7483 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007484 if (Index != 1)
7485 return false;
7486 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007487 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007488 bool Invalid;
7489 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7490 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007491 BaseType = FD->getType();
7492 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007493 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007494 return false;
7495 }
7496 }
7497 return true;
7498}
7499
George Burgess IVe3763372016-12-22 02:50:20 +00007500/// Tests to see if the LValue has a user-specified designator (that isn't
7501/// necessarily valid). Note that this always returns 'true' if the LValue has
7502/// an unsized array as its first designator entry, because there's currently no
7503/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007504static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007505 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007506 return false;
7507
George Burgess IVe3763372016-12-22 02:50:20 +00007508 if (!LVal.Designator.Entries.empty())
7509 return LVal.Designator.isMostDerivedAnUnsizedArray();
7510
George Burgess IVa51c4072015-10-16 01:49:01 +00007511 if (!LVal.InvalidBase)
7512 return true;
7513
George Burgess IVe3763372016-12-22 02:50:20 +00007514 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7515 // the LValueBase.
7516 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7517 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007518}
7519
George Burgess IVe3763372016-12-22 02:50:20 +00007520/// Attempts to detect a user writing into a piece of memory that's impossible
7521/// to figure out the size of by just using types.
7522static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7523 const SubobjectDesignator &Designator = LVal.Designator;
7524 // Notes:
7525 // - Users can only write off of the end when we have an invalid base. Invalid
7526 // bases imply we don't know where the memory came from.
7527 // - We used to be a bit more aggressive here; we'd only be conservative if
7528 // the array at the end was flexible, or if it had 0 or 1 elements. This
7529 // broke some common standard library extensions (PR30346), but was
7530 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7531 // with some sort of whitelist. OTOH, it seems that GCC is always
7532 // conservative with the last element in structs (if it's an array), so our
7533 // current behavior is more compatible than a whitelisting approach would
7534 // be.
7535 return LVal.InvalidBase &&
7536 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7537 Designator.MostDerivedIsArrayElement &&
7538 isDesignatorAtObjectEnd(Ctx, LVal);
7539}
7540
7541/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7542/// Fails if the conversion would cause loss of precision.
7543static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7544 CharUnits &Result) {
7545 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7546 if (Int.ugt(CharUnitsMax))
7547 return false;
7548 Result = CharUnits::fromQuantity(Int.getZExtValue());
7549 return true;
7550}
7551
7552/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7553/// determine how many bytes exist from the beginning of the object to either
7554/// the end of the current subobject, or the end of the object itself, depending
7555/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007556///
George Burgess IVe3763372016-12-22 02:50:20 +00007557/// If this returns false, the value of Result is undefined.
7558static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7559 unsigned Type, const LValue &LVal,
7560 CharUnits &EndOffset) {
7561 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007562
George Burgess IV7fb7e362017-01-03 23:35:19 +00007563 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7564 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7565 return false;
7566 return HandleSizeof(Info, ExprLoc, Ty, Result);
7567 };
7568
George Burgess IVe3763372016-12-22 02:50:20 +00007569 // We want to evaluate the size of the entire object. This is a valid fallback
7570 // for when Type=1 and the designator is invalid, because we're asked for an
7571 // upper-bound.
7572 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7573 // Type=3 wants a lower bound, so we can't fall back to this.
7574 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007575 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007576
7577 llvm::APInt APEndOffset;
7578 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7579 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7580 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7581
7582 if (LVal.InvalidBase)
7583 return false;
7584
7585 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007586 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007587 }
7588
George Burgess IVe3763372016-12-22 02:50:20 +00007589 // We want to evaluate the size of a subobject.
7590 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007591
7592 // The following is a moderately common idiom in C:
7593 //
7594 // struct Foo { int a; char c[1]; };
7595 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7596 // strcpy(&F->c[0], Bar);
7597 //
George Burgess IVe3763372016-12-22 02:50:20 +00007598 // In order to not break too much legacy code, we need to support it.
7599 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7600 // If we can resolve this to an alloc_size call, we can hand that back,
7601 // because we know for certain how many bytes there are to write to.
7602 llvm::APInt APEndOffset;
7603 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7604 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7605 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7606
7607 // If we cannot determine the size of the initial allocation, then we can't
7608 // given an accurate upper-bound. However, we are still able to give
7609 // conservative lower-bounds for Type=3.
7610 if (Type == 1)
7611 return false;
7612 }
7613
7614 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007615 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007616 return false;
7617
George Burgess IVe3763372016-12-22 02:50:20 +00007618 // According to the GCC documentation, we want the size of the subobject
7619 // denoted by the pointer. But that's not quite right -- what we actually
7620 // want is the size of the immediately-enclosing array, if there is one.
7621 int64_t ElemsRemaining;
7622 if (Designator.MostDerivedIsArrayElement &&
7623 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7624 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7625 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7626 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7627 } else {
7628 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7629 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007630
George Burgess IVe3763372016-12-22 02:50:20 +00007631 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7632 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007633}
7634
George Burgess IVe3763372016-12-22 02:50:20 +00007635/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7636/// returns true and stores the result in @p Size.
7637///
7638/// If @p WasError is non-null, this will report whether the failure to evaluate
7639/// is to be treated as an Error in IntExprEvaluator.
7640static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7641 EvalInfo &Info, uint64_t &Size) {
7642 // Determine the denoted object.
7643 LValue LVal;
7644 {
7645 // The operand of __builtin_object_size is never evaluated for side-effects.
7646 // If there are any, but we can determine the pointed-to object anyway, then
7647 // ignore the side-effects.
7648 SpeculativeEvaluationRAII SpeculativeEval(Info);
7649 FoldOffsetRAII Fold(Info);
7650
7651 if (E->isGLValue()) {
7652 // It's possible for us to be given GLValues if we're called via
7653 // Expr::tryEvaluateObjectSize.
7654 APValue RVal;
7655 if (!EvaluateAsRValue(Info, E, RVal))
7656 return false;
7657 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007658 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7659 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007660 return false;
7661 }
7662
7663 // If we point to before the start of the object, there are no accessible
7664 // bytes.
7665 if (LVal.getLValueOffset().isNegative()) {
7666 Size = 0;
7667 return true;
7668 }
7669
7670 CharUnits EndOffset;
7671 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7672 return false;
7673
7674 // If we've fallen outside of the end offset, just pretend there's nothing to
7675 // write to/read from.
7676 if (EndOffset <= LVal.getLValueOffset())
7677 Size = 0;
7678 else
7679 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7680 return true;
John McCall95007602010-05-10 23:27:23 +00007681}
7682
Peter Collingbournee9200682011-05-13 03:29:01 +00007683bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007684 if (unsigned BuiltinOp = E->getBuiltinCallee())
7685 return VisitBuiltinCallExpr(E, BuiltinOp);
7686
7687 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7688}
7689
7690bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7691 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007692 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007693 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007694 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007695
7696 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007697 // The type was checked when we built the expression.
7698 unsigned Type =
7699 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7700 assert(Type <= 3 && "unexpected type");
7701
George Burgess IVe3763372016-12-22 02:50:20 +00007702 uint64_t Size;
7703 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7704 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007705
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007706 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007707 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007708
Richard Smith01ade172012-05-23 04:13:20 +00007709 // Expression had no side effects, but we couldn't statically determine the
7710 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007711 switch (Info.EvalMode) {
7712 case EvalInfo::EM_ConstantExpression:
7713 case EvalInfo::EM_PotentialConstantExpression:
7714 case EvalInfo::EM_ConstantFold:
7715 case EvalInfo::EM_EvaluateForOverflow:
7716 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007717 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007718 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007719 return Error(E);
7720 case EvalInfo::EM_ConstantExpressionUnevaluated:
7721 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007722 // Reduce it to a constant now.
7723 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007724 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007725
7726 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007727 }
7728
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007729 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007730 case Builtin::BI__builtin_bswap32:
7731 case Builtin::BI__builtin_bswap64: {
7732 APSInt Val;
7733 if (!EvaluateInteger(E->getArg(0), Val, Info))
7734 return false;
7735
7736 return Success(Val.byteSwap(), E);
7737 }
7738
Richard Smith8889a3d2013-06-13 06:26:32 +00007739 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007740 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007741
7742 // FIXME: BI__builtin_clrsb
7743 // FIXME: BI__builtin_clrsbl
7744 // FIXME: BI__builtin_clrsbll
7745
Richard Smith80b3c8e2013-06-13 05:04:16 +00007746 case Builtin::BI__builtin_clz:
7747 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007748 case Builtin::BI__builtin_clzll:
7749 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007750 APSInt Val;
7751 if (!EvaluateInteger(E->getArg(0), Val, Info))
7752 return false;
7753 if (!Val)
7754 return Error(E);
7755
7756 return Success(Val.countLeadingZeros(), E);
7757 }
7758
Richard Smith8889a3d2013-06-13 06:26:32 +00007759 case Builtin::BI__builtin_constant_p:
7760 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7761
Richard Smith80b3c8e2013-06-13 05:04:16 +00007762 case Builtin::BI__builtin_ctz:
7763 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007764 case Builtin::BI__builtin_ctzll:
7765 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007766 APSInt Val;
7767 if (!EvaluateInteger(E->getArg(0), Val, Info))
7768 return false;
7769 if (!Val)
7770 return Error(E);
7771
7772 return Success(Val.countTrailingZeros(), E);
7773 }
7774
Richard Smith8889a3d2013-06-13 06:26:32 +00007775 case Builtin::BI__builtin_eh_return_data_regno: {
7776 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7777 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7778 return Success(Operand, E);
7779 }
7780
7781 case Builtin::BI__builtin_expect:
7782 return Visit(E->getArg(0));
7783
7784 case Builtin::BI__builtin_ffs:
7785 case Builtin::BI__builtin_ffsl:
7786 case Builtin::BI__builtin_ffsll: {
7787 APSInt Val;
7788 if (!EvaluateInteger(E->getArg(0), Val, Info))
7789 return false;
7790
7791 unsigned N = Val.countTrailingZeros();
7792 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7793 }
7794
7795 case Builtin::BI__builtin_fpclassify: {
7796 APFloat Val(0.0);
7797 if (!EvaluateFloat(E->getArg(5), Val, Info))
7798 return false;
7799 unsigned Arg;
7800 switch (Val.getCategory()) {
7801 case APFloat::fcNaN: Arg = 0; break;
7802 case APFloat::fcInfinity: Arg = 1; break;
7803 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7804 case APFloat::fcZero: Arg = 4; break;
7805 }
7806 return Visit(E->getArg(Arg));
7807 }
7808
7809 case Builtin::BI__builtin_isinf_sign: {
7810 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007811 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007812 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7813 }
7814
Richard Smithea3019d2013-10-15 19:07:14 +00007815 case Builtin::BI__builtin_isinf: {
7816 APFloat Val(0.0);
7817 return EvaluateFloat(E->getArg(0), Val, Info) &&
7818 Success(Val.isInfinity() ? 1 : 0, E);
7819 }
7820
7821 case Builtin::BI__builtin_isfinite: {
7822 APFloat Val(0.0);
7823 return EvaluateFloat(E->getArg(0), Val, Info) &&
7824 Success(Val.isFinite() ? 1 : 0, E);
7825 }
7826
7827 case Builtin::BI__builtin_isnan: {
7828 APFloat Val(0.0);
7829 return EvaluateFloat(E->getArg(0), Val, Info) &&
7830 Success(Val.isNaN() ? 1 : 0, E);
7831 }
7832
7833 case Builtin::BI__builtin_isnormal: {
7834 APFloat Val(0.0);
7835 return EvaluateFloat(E->getArg(0), Val, Info) &&
7836 Success(Val.isNormal() ? 1 : 0, E);
7837 }
7838
Richard Smith8889a3d2013-06-13 06:26:32 +00007839 case Builtin::BI__builtin_parity:
7840 case Builtin::BI__builtin_parityl:
7841 case Builtin::BI__builtin_parityll: {
7842 APSInt Val;
7843 if (!EvaluateInteger(E->getArg(0), Val, Info))
7844 return false;
7845
7846 return Success(Val.countPopulation() % 2, E);
7847 }
7848
Richard Smith80b3c8e2013-06-13 05:04:16 +00007849 case Builtin::BI__builtin_popcount:
7850 case Builtin::BI__builtin_popcountl:
7851 case Builtin::BI__builtin_popcountll: {
7852 APSInt Val;
7853 if (!EvaluateInteger(E->getArg(0), Val, Info))
7854 return false;
7855
7856 return Success(Val.countPopulation(), E);
7857 }
7858
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007859 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007860 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007861 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007862 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007863 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007864 << /*isConstexpr*/0 << /*isConstructor*/0
7865 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007866 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007867 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007868 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007869 case Builtin::BI__builtin_strlen:
7870 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007871 // As an extension, we support __builtin_strlen() as a constant expression,
7872 // and support folding strlen() to a constant.
7873 LValue String;
7874 if (!EvaluatePointer(E->getArg(0), String, Info))
7875 return false;
7876
Richard Smith8110c9d2016-11-29 19:45:17 +00007877 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7878
Richard Smithe6c19f22013-11-15 02:10:04 +00007879 // Fast path: if it's a string literal, search the string value.
7880 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7881 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007882 // The string literal may have embedded null characters. Find the first
7883 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007884 StringRef Str = S->getBytes();
7885 int64_t Off = String.Offset.getQuantity();
7886 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007887 S->getCharByteWidth() == 1 &&
7888 // FIXME: Add fast-path for wchar_t too.
7889 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007890 Str = Str.substr(Off);
7891
7892 StringRef::size_type Pos = Str.find(0);
7893 if (Pos != StringRef::npos)
7894 Str = Str.substr(0, Pos);
7895
7896 return Success(Str.size(), E);
7897 }
7898
7899 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007900 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007901
7902 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007903 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7904 APValue Char;
7905 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7906 !Char.isInt())
7907 return false;
7908 if (!Char.getInt())
7909 return Success(Strlen, E);
7910 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7911 return false;
7912 }
7913 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007914
Richard Smithe151bab2016-11-11 23:43:35 +00007915 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007916 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007917 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007918 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007919 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007920 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007921 // A call to strlen is not a constant expression.
7922 if (Info.getLangOpts().CPlusPlus11)
7923 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7924 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007925 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007926 else
7927 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007928 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007929 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007930 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007931 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007932 case Builtin::BI__builtin_wcsncmp:
7933 case Builtin::BI__builtin_memcmp:
7934 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007935 LValue String1, String2;
7936 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7937 !EvaluatePointer(E->getArg(1), String2, Info))
7938 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007939
7940 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7941
Richard Smithe151bab2016-11-11 23:43:35 +00007942 uint64_t MaxLength = uint64_t(-1);
7943 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007944 BuiltinOp != Builtin::BIwcscmp &&
7945 BuiltinOp != Builtin::BI__builtin_strcmp &&
7946 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007947 APSInt N;
7948 if (!EvaluateInteger(E->getArg(2), N, Info))
7949 return false;
7950 MaxLength = N.getExtValue();
7951 }
7952 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007953 BuiltinOp != Builtin::BIwmemcmp &&
7954 BuiltinOp != Builtin::BI__builtin_memcmp &&
7955 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007956 for (; MaxLength; --MaxLength) {
7957 APValue Char1, Char2;
7958 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7959 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7960 !Char1.isInt() || !Char2.isInt())
7961 return false;
7962 if (Char1.getInt() != Char2.getInt())
7963 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7964 if (StopAtNull && !Char1.getInt())
7965 return Success(0, E);
7966 assert(!(StopAtNull && !Char2.getInt()));
7967 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7968 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7969 return false;
7970 }
7971 // We hit the strncmp / memcmp limit.
7972 return Success(0, E);
7973 }
7974
Richard Smith01ba47d2012-04-13 00:45:38 +00007975 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007976 case Builtin::BI__atomic_is_lock_free:
7977 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007978 APSInt SizeVal;
7979 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7980 return false;
7981
7982 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7983 // of two less than the maximum inline atomic width, we know it is
7984 // lock-free. If the size isn't a power of two, or greater than the
7985 // maximum alignment where we promote atomics, we know it is not lock-free
7986 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7987 // the answer can only be determined at runtime; for example, 16-byte
7988 // atomics have lock-free implementations on some, but not all,
7989 // x86-64 processors.
7990
7991 // Check power-of-two.
7992 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007993 if (Size.isPowerOfTwo()) {
7994 // Check against inlining width.
7995 unsigned InlineWidthBits =
7996 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7997 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7998 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7999 Size == CharUnits::One() ||
8000 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8001 Expr::NPC_NeverValueDependent))
8002 // OK, we will inline appropriately-aligned operations of this size,
8003 // and _Atomic(T) is appropriately-aligned.
8004 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008005
Richard Smith01ba47d2012-04-13 00:45:38 +00008006 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8007 castAs<PointerType>()->getPointeeType();
8008 if (!PointeeType->isIncompleteType() &&
8009 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8010 // OK, we will inline operations on this object.
8011 return Success(1, E);
8012 }
8013 }
8014 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008015
Richard Smith01ba47d2012-04-13 00:45:38 +00008016 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8017 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008018 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008019 case Builtin::BIomp_is_initial_device:
8020 // We can decide statically which value the runtime would return if called.
8021 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008022 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008023}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008024
Richard Smith8b3497e2011-10-31 01:37:14 +00008025static bool HasSameBase(const LValue &A, const LValue &B) {
8026 if (!A.getLValueBase())
8027 return !B.getLValueBase();
8028 if (!B.getLValueBase())
8029 return false;
8030
Richard Smithce40ad62011-11-12 22:28:03 +00008031 if (A.getLValueBase().getOpaqueValue() !=
8032 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008033 const Decl *ADecl = GetLValueBaseDecl(A);
8034 if (!ADecl)
8035 return false;
8036 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008037 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008038 return false;
8039 }
8040
8041 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008042 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008043}
8044
Richard Smithd20f1e62014-10-21 23:01:04 +00008045/// \brief Determine whether this is a pointer past the end of the complete
8046/// object referred to by the lvalue.
8047static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8048 const LValue &LV) {
8049 // A null pointer can be viewed as being "past the end" but we don't
8050 // choose to look at it that way here.
8051 if (!LV.getLValueBase())
8052 return false;
8053
8054 // If the designator is valid and refers to a subobject, we're not pointing
8055 // past the end.
8056 if (!LV.getLValueDesignator().Invalid &&
8057 !LV.getLValueDesignator().isOnePastTheEnd())
8058 return false;
8059
David Majnemerc378ca52015-08-29 08:32:55 +00008060 // A pointer to an incomplete type might be past-the-end if the type's size is
8061 // zero. We cannot tell because the type is incomplete.
8062 QualType Ty = getType(LV.getLValueBase());
8063 if (Ty->isIncompleteType())
8064 return true;
8065
Richard Smithd20f1e62014-10-21 23:01:04 +00008066 // We're a past-the-end pointer if we point to the byte after the object,
8067 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008068 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008069 return LV.getLValueOffset() == Size;
8070}
8071
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008072namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008073
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008074/// \brief Data recursive integer evaluator of certain binary operators.
8075///
8076/// We use a data recursive algorithm for binary operators so that we are able
8077/// to handle extreme cases of chained binary operators without causing stack
8078/// overflow.
8079class DataRecursiveIntBinOpEvaluator {
8080 struct EvalResult {
8081 APValue Val;
8082 bool Failed;
8083
8084 EvalResult() : Failed(false) { }
8085
8086 void swap(EvalResult &RHS) {
8087 Val.swap(RHS.Val);
8088 Failed = RHS.Failed;
8089 RHS.Failed = false;
8090 }
8091 };
8092
8093 struct Job {
8094 const Expr *E;
8095 EvalResult LHSResult; // meaningful only for binary operator expression.
8096 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008097
David Blaikie73726062015-08-12 23:09:24 +00008098 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008099 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008100
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008101 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008102 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008103 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008104
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008105 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008106 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008107 };
8108
8109 SmallVector<Job, 16> Queue;
8110
8111 IntExprEvaluator &IntEval;
8112 EvalInfo &Info;
8113 APValue &FinalResult;
8114
8115public:
8116 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8117 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8118
8119 /// \brief True if \param E is a binary operator that we are going to handle
8120 /// data recursively.
8121 /// We handle binary operators that are comma, logical, or that have operands
8122 /// with integral or enumeration type.
8123 static bool shouldEnqueue(const BinaryOperator *E) {
8124 return E->getOpcode() == BO_Comma ||
8125 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008126 (E->isRValue() &&
8127 E->getType()->isIntegralOrEnumerationType() &&
8128 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008129 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008130 }
8131
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008132 bool Traverse(const BinaryOperator *E) {
8133 enqueue(E);
8134 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008135 while (!Queue.empty())
8136 process(PrevResult);
8137
8138 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008139
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008140 FinalResult.swap(PrevResult.Val);
8141 return true;
8142 }
8143
8144private:
8145 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8146 return IntEval.Success(Value, E, Result);
8147 }
8148 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8149 return IntEval.Success(Value, E, Result);
8150 }
8151 bool Error(const Expr *E) {
8152 return IntEval.Error(E);
8153 }
8154 bool Error(const Expr *E, diag::kind D) {
8155 return IntEval.Error(E, D);
8156 }
8157
8158 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8159 return Info.CCEDiag(E, D);
8160 }
8161
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008162 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8163 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008164 bool &SuppressRHSDiags);
8165
8166 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8167 const BinaryOperator *E, APValue &Result);
8168
8169 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8170 Result.Failed = !Evaluate(Result.Val, Info, E);
8171 if (Result.Failed)
8172 Result.Val = APValue();
8173 }
8174
Richard Trieuba4d0872012-03-21 23:30:30 +00008175 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176
8177 void enqueue(const Expr *E) {
8178 E = E->IgnoreParens();
8179 Queue.resize(Queue.size()+1);
8180 Queue.back().E = E;
8181 Queue.back().Kind = Job::AnyExprKind;
8182 }
8183};
8184
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008185}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008186
8187bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008188 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008189 bool &SuppressRHSDiags) {
8190 if (E->getOpcode() == BO_Comma) {
8191 // Ignore LHS but note if we could not evaluate it.
8192 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008193 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008194 return true;
8195 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008196
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008197 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008198 bool LHSAsBool;
8199 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008200 // We were able to evaluate the LHS, see if we can get away with not
8201 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008202 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8203 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008204 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008205 }
8206 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008207 LHSResult.Failed = true;
8208
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008209 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008210 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008211 if (!Info.noteSideEffect())
8212 return false;
8213
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008214 // We can't evaluate the LHS; however, sometimes the result
8215 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8216 // Don't ignore RHS and suppress diagnostics from this arm.
8217 SuppressRHSDiags = true;
8218 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008219
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008220 return true;
8221 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008222
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008223 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8224 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008225
George Burgess IVa145e252016-05-25 22:38:36 +00008226 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008227 return false; // Ignore RHS;
8228
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008229 return true;
8230}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008231
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008232static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8233 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008234 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8235 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8236 // offsets.
8237 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8238 CharUnits &Offset = LVal.getLValueOffset();
8239 uint64_t Offset64 = Offset.getQuantity();
8240 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8241 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8242 : Offset64 + Index64);
8243}
8244
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008245bool DataRecursiveIntBinOpEvaluator::
8246 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8247 const BinaryOperator *E, APValue &Result) {
8248 if (E->getOpcode() == BO_Comma) {
8249 if (RHSResult.Failed)
8250 return false;
8251 Result = RHSResult.Val;
8252 return true;
8253 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008254
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008255 if (E->isLogicalOp()) {
8256 bool lhsResult, rhsResult;
8257 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8258 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008259
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008260 if (LHSIsOK) {
8261 if (RHSIsOK) {
8262 if (E->getOpcode() == BO_LOr)
8263 return Success(lhsResult || rhsResult, E, Result);
8264 else
8265 return Success(lhsResult && rhsResult, E, Result);
8266 }
8267 } else {
8268 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008269 // We can't evaluate the LHS; however, sometimes the result
8270 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8271 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008272 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008273 }
8274 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008275
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008276 return false;
8277 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008278
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008279 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8280 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008281
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008282 if (LHSResult.Failed || RHSResult.Failed)
8283 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008284
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008285 const APValue &LHSVal = LHSResult.Val;
8286 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008287
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008288 // Handle cases like (unsigned long)&a + 4.
8289 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8290 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008291 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008292 return true;
8293 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008294
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008295 // Handle cases like 4 + (unsigned long)&a
8296 if (E->getOpcode() == BO_Add &&
8297 RHSVal.isLValue() && LHSVal.isInt()) {
8298 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008299 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008300 return true;
8301 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008302
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008303 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8304 // Handle (intptr_t)&&A - (intptr_t)&&B.
8305 if (!LHSVal.getLValueOffset().isZero() ||
8306 !RHSVal.getLValueOffset().isZero())
8307 return false;
8308 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8309 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8310 if (!LHSExpr || !RHSExpr)
8311 return false;
8312 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8313 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8314 if (!LHSAddrExpr || !RHSAddrExpr)
8315 return false;
8316 // Make sure both labels come from the same function.
8317 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8318 RHSAddrExpr->getLabel()->getDeclContext())
8319 return false;
8320 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8321 return true;
8322 }
Richard Smith43e77732013-05-07 04:50:00 +00008323
8324 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008325 if (!LHSVal.isInt() || !RHSVal.isInt())
8326 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008327
8328 // Set up the width and signedness manually, in case it can't be deduced
8329 // from the operation we're performing.
8330 // FIXME: Don't do this in the cases where we can deduce it.
8331 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8332 E->getType()->isUnsignedIntegerOrEnumerationType());
8333 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8334 RHSVal.getInt(), Value))
8335 return false;
8336 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008337}
8338
Richard Trieuba4d0872012-03-21 23:30:30 +00008339void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008340 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008341
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008342 switch (job.Kind) {
8343 case Job::AnyExprKind: {
8344 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8345 if (shouldEnqueue(Bop)) {
8346 job.Kind = Job::BinOpKind;
8347 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008348 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008349 }
8350 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008351
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008352 EvaluateExpr(job.E, Result);
8353 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008354 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008355 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008356
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008357 case Job::BinOpKind: {
8358 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008359 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008360 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008361 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008362 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008363 }
8364 if (SuppressRHSDiags)
8365 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008366 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008367 job.Kind = Job::BinOpVisitedLHSKind;
8368 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008369 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008370 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008371
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008372 case Job::BinOpVisitedLHSKind: {
8373 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8374 EvalResult RHS;
8375 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008376 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008377 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008378 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008379 }
8380 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008381
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008382 llvm_unreachable("Invalid Job::Kind!");
8383}
8384
George Burgess IV8c892b52016-05-25 22:31:54 +00008385namespace {
8386/// Used when we determine that we should fail, but can keep evaluating prior to
8387/// noting that we had a failure.
8388class DelayedNoteFailureRAII {
8389 EvalInfo &Info;
8390 bool NoteFailure;
8391
8392public:
8393 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8394 : Info(Info), NoteFailure(NoteFailure) {}
8395 ~DelayedNoteFailureRAII() {
8396 if (NoteFailure) {
8397 bool ContinueAfterFailure = Info.noteFailure();
8398 (void)ContinueAfterFailure;
8399 assert(ContinueAfterFailure &&
8400 "Shouldn't have kept evaluating on failure.");
8401 }
8402 }
8403};
8404}
8405
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008406bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008407 // We don't call noteFailure immediately because the assignment happens after
8408 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008409 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008410 return Error(E);
8411
George Burgess IV8c892b52016-05-25 22:31:54 +00008412 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008413 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8414 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008415
Anders Carlssonacc79812008-11-16 07:17:21 +00008416 QualType LHSTy = E->getLHS()->getType();
8417 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008418
Chandler Carruthb29a7432014-10-11 11:03:30 +00008419 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008420 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008421 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008422 if (E->isAssignmentOp()) {
8423 LValue LV;
8424 EvaluateLValue(E->getLHS(), LV, Info);
8425 LHSOK = false;
8426 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008427 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8428 if (LHSOK) {
8429 LHS.makeComplexFloat();
8430 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8431 }
8432 } else {
8433 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8434 }
George Burgess IVa145e252016-05-25 22:38:36 +00008435 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008436 return false;
8437
Chandler Carruthb29a7432014-10-11 11:03:30 +00008438 if (E->getRHS()->getType()->isRealFloatingType()) {
8439 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8440 return false;
8441 RHS.makeComplexFloat();
8442 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8443 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008444 return false;
8445
8446 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008447 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008448 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008449 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008450 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8451
John McCalle3027922010-08-25 11:45:40 +00008452 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008453 return Success((CR_r == APFloat::cmpEqual &&
8454 CR_i == APFloat::cmpEqual), E);
8455 else {
John McCalle3027922010-08-25 11:45:40 +00008456 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008457 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008458 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008459 CR_r == APFloat::cmpLessThan ||
8460 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008461 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008462 CR_i == APFloat::cmpLessThan ||
8463 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008464 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008465 } else {
John McCalle3027922010-08-25 11:45:40 +00008466 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008467 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8468 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8469 else {
John McCalle3027922010-08-25 11:45:40 +00008470 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008471 "Invalid compex comparison.");
8472 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8473 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8474 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008475 }
8476 }
Mike Stump11289f42009-09-09 15:08:12 +00008477
Anders Carlssonacc79812008-11-16 07:17:21 +00008478 if (LHSTy->isRealFloatingType() &&
8479 RHSTy->isRealFloatingType()) {
8480 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008481
Richard Smith253c2a32012-01-27 01:14:48 +00008482 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008483 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008484 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008485
Richard Smith253c2a32012-01-27 01:14:48 +00008486 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008487 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008488
Anders Carlssonacc79812008-11-16 07:17:21 +00008489 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008490
Anders Carlssonacc79812008-11-16 07:17:21 +00008491 switch (E->getOpcode()) {
8492 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008493 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008494 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008495 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008496 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008497 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008498 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008499 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008500 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008501 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008502 E);
John McCalle3027922010-08-25 11:45:40 +00008503 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008504 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008505 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008506 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008507 || CR == APFloat::cmpLessThan
8508 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008509 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008510 }
Mike Stump11289f42009-09-09 15:08:12 +00008511
Eli Friedmana38da572009-04-28 19:17:36 +00008512 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008513 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008514 LValue LHSValue, RHSValue;
8515
8516 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008517 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008518 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008519
Richard Smith253c2a32012-01-27 01:14:48 +00008520 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008521 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008522
Richard Smith8b3497e2011-10-31 01:37:14 +00008523 // Reject differing bases from the normal codepath; we special-case
8524 // comparisons to null.
8525 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008526 if (E->getOpcode() == BO_Sub) {
8527 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008528 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008529 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008530 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008531 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008532 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008533 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008534 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8535 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8536 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008537 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008538 // Make sure both labels come from the same function.
8539 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8540 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008541 return Error(E);
8542 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008543 }
Richard Smith83c68212011-10-31 05:11:32 +00008544 // Inequalities and subtractions between unrelated pointers have
8545 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008546 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008547 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008548 // A constant address may compare equal to the address of a symbol.
8549 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008550 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008551 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8552 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008553 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008554 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008555 // distinct addresses. In clang, the result of such a comparison is
8556 // unspecified, so it is not a constant expression. However, we do know
8557 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008558 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8559 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008560 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008561 // We can't tell whether weak symbols will end up pointing to the same
8562 // object.
8563 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008564 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008565 // We can't compare the address of the start of one object with the
8566 // past-the-end address of another object, per C++ DR1652.
8567 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8568 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8569 (RHSValue.Base && RHSValue.Offset.isZero() &&
8570 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8571 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008572 // We can't tell whether an object is at the same address as another
8573 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008574 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8575 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008576 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008577 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008578 // (Note that clang defaults to -fmerge-all-constants, which can
8579 // lead to inconsistent results for comparisons involving the address
8580 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008581 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008582 }
Eli Friedman64004332009-03-23 04:38:34 +00008583
Richard Smith1b470412012-02-01 08:10:20 +00008584 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8585 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8586
Richard Smith84f6dcf2012-02-02 01:16:57 +00008587 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8588 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8589
John McCalle3027922010-08-25 11:45:40 +00008590 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008591 // C++11 [expr.add]p6:
8592 // Unless both pointers point to elements of the same array object, or
8593 // one past the last element of the array object, the behavior is
8594 // undefined.
8595 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8596 !AreElementsOfSameArray(getType(LHSValue.Base),
8597 LHSDesignator, RHSDesignator))
8598 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8599
Chris Lattner882bdf22010-04-20 17:13:14 +00008600 QualType Type = E->getLHS()->getType();
8601 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008602
Richard Smithd62306a2011-11-10 06:34:14 +00008603 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008604 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008605 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008606
Richard Smith84c6b3d2013-09-10 21:34:14 +00008607 // As an extension, a type may have zero size (empty struct or union in
8608 // C, array of zero length). Pointer subtraction in such cases has
8609 // undefined behavior, so is not constant.
8610 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008611 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008612 << ElementType;
8613 return false;
8614 }
8615
Richard Smith1b470412012-02-01 08:10:20 +00008616 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8617 // and produce incorrect results when it overflows. Such behavior
8618 // appears to be non-conforming, but is common, so perhaps we should
8619 // assume the standard intended for such cases to be undefined behavior
8620 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008621
Richard Smith1b470412012-02-01 08:10:20 +00008622 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8623 // overflow in the final conversion to ptrdiff_t.
8624 APSInt LHS(
8625 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8626 APSInt RHS(
8627 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8628 APSInt ElemSize(
8629 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8630 APSInt TrueResult = (LHS - RHS) / ElemSize;
8631 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8632
Richard Smith0c6124b2015-12-03 01:36:22 +00008633 if (Result.extend(65) != TrueResult &&
8634 !HandleOverflow(Info, E, TrueResult, E->getType()))
8635 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008636 return Success(Result, E);
8637 }
Richard Smithde21b242012-01-31 06:41:30 +00008638
8639 // C++11 [expr.rel]p3:
8640 // Pointers to void (after pointer conversions) can be compared, with a
8641 // result defined as follows: If both pointers represent the same
8642 // address or are both the null pointer value, the result is true if the
8643 // operator is <= or >= and false otherwise; otherwise the result is
8644 // unspecified.
8645 // We interpret this as applying to pointers to *cv* void.
8646 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008647 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008648 CCEDiag(E, diag::note_constexpr_void_comparison);
8649
Richard Smith84f6dcf2012-02-02 01:16:57 +00008650 // C++11 [expr.rel]p2:
8651 // - If two pointers point to non-static data members of the same object,
8652 // or to subobjects or array elements fo such members, recursively, the
8653 // pointer to the later declared member compares greater provided the
8654 // two members have the same access control and provided their class is
8655 // not a union.
8656 // [...]
8657 // - Otherwise pointer comparisons are unspecified.
8658 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8659 E->isRelationalOp()) {
8660 bool WasArrayIndex;
8661 unsigned Mismatch =
8662 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8663 RHSDesignator, WasArrayIndex);
8664 // At the point where the designators diverge, the comparison has a
8665 // specified value if:
8666 // - we are comparing array indices
8667 // - we are comparing fields of a union, or fields with the same access
8668 // Otherwise, the result is unspecified and thus the comparison is not a
8669 // constant expression.
8670 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8671 Mismatch < RHSDesignator.Entries.size()) {
8672 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8673 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8674 if (!LF && !RF)
8675 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8676 else if (!LF)
8677 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8678 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8679 << RF->getParent() << RF;
8680 else if (!RF)
8681 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8682 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8683 << LF->getParent() << LF;
8684 else if (!LF->getParent()->isUnion() &&
8685 LF->getAccess() != RF->getAccess())
8686 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8687 << LF << LF->getAccess() << RF << RF->getAccess()
8688 << LF->getParent();
8689 }
8690 }
8691
Eli Friedman6c31cb42012-04-16 04:30:08 +00008692 // The comparison here must be unsigned, and performed with the same
8693 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008694 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8695 uint64_t CompareLHS = LHSOffset.getQuantity();
8696 uint64_t CompareRHS = RHSOffset.getQuantity();
8697 assert(PtrSize <= 64 && "Unexpected pointer width");
8698 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8699 CompareLHS &= Mask;
8700 CompareRHS &= Mask;
8701
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008702 // If there is a base and this is a relational operator, we can only
8703 // compare pointers within the object in question; otherwise, the result
8704 // depends on where the object is located in memory.
8705 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8706 QualType BaseTy = getType(LHSValue.Base);
8707 if (BaseTy->isIncompleteType())
8708 return Error(E);
8709 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8710 uint64_t OffsetLimit = Size.getQuantity();
8711 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8712 return Error(E);
8713 }
8714
Richard Smith8b3497e2011-10-31 01:37:14 +00008715 switch (E->getOpcode()) {
8716 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008717 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8718 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8719 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8720 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8721 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8722 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008723 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008724 }
8725 }
Richard Smith7bb00672012-02-01 01:42:44 +00008726
8727 if (LHSTy->isMemberPointerType()) {
8728 assert(E->isEqualityOp() && "unexpected member pointer operation");
8729 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8730
8731 MemberPtr LHSValue, RHSValue;
8732
8733 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008734 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008735 return false;
8736
8737 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8738 return false;
8739
8740 // C++11 [expr.eq]p2:
8741 // If both operands are null, they compare equal. Otherwise if only one is
8742 // null, they compare unequal.
8743 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8744 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8745 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8746 }
8747
8748 // Otherwise if either is a pointer to a virtual member function, the
8749 // result is unspecified.
8750 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8751 if (MD->isVirtual())
8752 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8753 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8754 if (MD->isVirtual())
8755 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8756
8757 // Otherwise they compare equal if and only if they would refer to the
8758 // same member of the same most derived object or the same subobject if
8759 // they were dereferenced with a hypothetical object of the associated
8760 // class type.
8761 bool Equal = LHSValue == RHSValue;
8762 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8763 }
8764
Richard Smithab44d9b2012-02-14 22:35:28 +00008765 if (LHSTy->isNullPtrType()) {
8766 assert(E->isComparisonOp() && "unexpected nullptr operation");
8767 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8768 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8769 // are compared, the result is true of the operator is <=, >= or ==, and
8770 // false otherwise.
8771 BinaryOperator::Opcode Opcode = E->getOpcode();
8772 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8773 }
8774
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008775 assert((!LHSTy->isIntegralOrEnumerationType() ||
8776 !RHSTy->isIntegralOrEnumerationType()) &&
8777 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8778 // We can't continue from here for non-integral types.
8779 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008780}
8781
Peter Collingbournee190dee2011-03-11 19:24:49 +00008782/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8783/// a result as the expression's type.
8784bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8785 const UnaryExprOrTypeTraitExpr *E) {
8786 switch(E->getKind()) {
8787 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008788 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008789 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008790 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008791 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008792 }
Eli Friedman64004332009-03-23 04:38:34 +00008793
Peter Collingbournee190dee2011-03-11 19:24:49 +00008794 case UETT_VecStep: {
8795 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008796
Peter Collingbournee190dee2011-03-11 19:24:49 +00008797 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008798 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008799
Peter Collingbournee190dee2011-03-11 19:24:49 +00008800 // The vec_step built-in functions that take a 3-component
8801 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8802 if (n == 3)
8803 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008804
Peter Collingbournee190dee2011-03-11 19:24:49 +00008805 return Success(n, E);
8806 } else
8807 return Success(1, E);
8808 }
8809
8810 case UETT_SizeOf: {
8811 QualType SrcTy = E->getTypeOfArgument();
8812 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8813 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008814 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8815 SrcTy = Ref->getPointeeType();
8816
Richard Smithd62306a2011-11-10 06:34:14 +00008817 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008818 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008819 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008820 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008821 }
Alexey Bataev00396512015-07-02 03:40:19 +00008822 case UETT_OpenMPRequiredSimdAlign:
8823 assert(E->isArgumentType());
8824 return Success(
8825 Info.Ctx.toCharUnitsFromBits(
8826 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8827 .getQuantity(),
8828 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008829 }
8830
8831 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008832}
8833
Peter Collingbournee9200682011-05-13 03:29:01 +00008834bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008835 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008836 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008837 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008838 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008839 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008840 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008841 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008842 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008843 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008844 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008845 APSInt IdxResult;
8846 if (!EvaluateInteger(Idx, IdxResult, Info))
8847 return false;
8848 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8849 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008850 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008851 CurrentType = AT->getElementType();
8852 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8853 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008854 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008855 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008856
James Y Knight7281c352015-12-29 22:31:18 +00008857 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008858 FieldDecl *MemberDecl = ON.getField();
8859 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008860 if (!RT)
8861 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008862 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008863 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008864 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008865 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008866 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008867 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008868 CurrentType = MemberDecl->getType().getNonReferenceType();
8869 break;
8870 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008871
James Y Knight7281c352015-12-29 22:31:18 +00008872 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008873 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008874
James Y Knight7281c352015-12-29 22:31:18 +00008875 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008876 CXXBaseSpecifier *BaseSpec = ON.getBase();
8877 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008878 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008879
8880 // Find the layout of the class whose base we are looking into.
8881 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008882 if (!RT)
8883 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008884 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008885 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008886 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8887
8888 // Find the base class itself.
8889 CurrentType = BaseSpec->getType();
8890 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8891 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008892 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008893
Douglas Gregord1702062010-04-29 00:18:15 +00008894 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008895 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008896 break;
8897 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008898 }
8899 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008900 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008901}
8902
Chris Lattnere13042c2008-07-11 19:10:17 +00008903bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008904 switch (E->getOpcode()) {
8905 default:
8906 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8907 // See C99 6.6p3.
8908 return Error(E);
8909 case UO_Extension:
8910 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8911 // If so, we could clear the diagnostic ID.
8912 return Visit(E->getSubExpr());
8913 case UO_Plus:
8914 // The result is just the value.
8915 return Visit(E->getSubExpr());
8916 case UO_Minus: {
8917 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008918 return false;
8919 if (!Result.isInt()) return Error(E);
8920 const APSInt &Value = Result.getInt();
8921 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8922 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8923 E->getType()))
8924 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008925 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008926 }
8927 case UO_Not: {
8928 if (!Visit(E->getSubExpr()))
8929 return false;
8930 if (!Result.isInt()) return Error(E);
8931 return Success(~Result.getInt(), E);
8932 }
8933 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008934 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008935 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008936 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008937 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008938 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008939 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008940}
Mike Stump11289f42009-09-09 15:08:12 +00008941
Chris Lattner477c4be2008-07-12 01:15:53 +00008942/// HandleCast - This is used to evaluate implicit or explicit casts where the
8943/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008944bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8945 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008946 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008947 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008948
Eli Friedmanc757de22011-03-25 00:43:55 +00008949 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008950 case CK_BaseToDerived:
8951 case CK_DerivedToBase:
8952 case CK_UncheckedDerivedToBase:
8953 case CK_Dynamic:
8954 case CK_ToUnion:
8955 case CK_ArrayToPointerDecay:
8956 case CK_FunctionToPointerDecay:
8957 case CK_NullToPointer:
8958 case CK_NullToMemberPointer:
8959 case CK_BaseToDerivedMemberPointer:
8960 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008961 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008962 case CK_ConstructorConversion:
8963 case CK_IntegralToPointer:
8964 case CK_ToVoid:
8965 case CK_VectorSplat:
8966 case CK_IntegralToFloating:
8967 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008968 case CK_CPointerToObjCPointerCast:
8969 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008970 case CK_AnyPointerToBlockPointerCast:
8971 case CK_ObjCObjectLValueCast:
8972 case CK_FloatingRealToComplex:
8973 case CK_FloatingComplexToReal:
8974 case CK_FloatingComplexCast:
8975 case CK_FloatingComplexToIntegralComplex:
8976 case CK_IntegralRealToComplex:
8977 case CK_IntegralComplexCast:
8978 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008979 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008980 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008981 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008982 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008983 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008984 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008985 llvm_unreachable("invalid cast kind for integral value");
8986
Eli Friedman9faf2f92011-03-25 19:07:11 +00008987 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008988 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008989 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008990 case CK_ARCProduceObject:
8991 case CK_ARCConsumeObject:
8992 case CK_ARCReclaimReturnedObject:
8993 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008994 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008995 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008996
Richard Smith4ef685b2012-01-17 21:17:26 +00008997 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008998 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008999 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009000 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009001 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009002
9003 case CK_MemberPointerToBoolean:
9004 case CK_PointerToBoolean:
9005 case CK_IntegralToBoolean:
9006 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009007 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009008 case CK_FloatingComplexToBoolean:
9009 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009010 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009011 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009012 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009013 uint64_t IntResult = BoolResult;
9014 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9015 IntResult = (uint64_t)-1;
9016 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009017 }
9018
Eli Friedmanc757de22011-03-25 00:43:55 +00009019 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009020 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009021 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009022
Eli Friedman742421e2009-02-20 01:15:07 +00009023 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009024 // Allow casts of address-of-label differences if they are no-ops
9025 // or narrowing. (The narrowing case isn't actually guaranteed to
9026 // be constant-evaluatable except in some narrow cases which are hard
9027 // to detect here. We let it through on the assumption the user knows
9028 // what they are doing.)
9029 if (Result.isAddrLabelDiff())
9030 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009031 // Only allow casts of lvalues if they are lossless.
9032 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9033 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009034
Richard Smith911e1422012-01-30 22:27:01 +00009035 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9036 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009037 }
Mike Stump11289f42009-09-09 15:08:12 +00009038
Eli Friedmanc757de22011-03-25 00:43:55 +00009039 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009040 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9041
John McCall45d55e42010-05-07 21:00:08 +00009042 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009043 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009044 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009045
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009046 if (LV.getLValueBase()) {
9047 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009048 // FIXME: Allow a larger integer size than the pointer size, and allow
9049 // narrowing back down to pointer width in subsequent integral casts.
9050 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009051 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009052 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009053
Richard Smithcf74da72011-11-16 07:18:12 +00009054 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009055 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009056 return true;
9057 }
9058
Yaxun Liu402804b2016-12-15 08:09:08 +00009059 uint64_t V;
9060 if (LV.isNullPointer())
9061 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9062 else
9063 V = LV.getLValueOffset().getQuantity();
9064
9065 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009066 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009067 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009068
Eli Friedmanc757de22011-03-25 00:43:55 +00009069 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009070 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009071 if (!EvaluateComplex(SubExpr, C, Info))
9072 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009073 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009074 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009075
Eli Friedmanc757de22011-03-25 00:43:55 +00009076 case CK_FloatingToIntegral: {
9077 APFloat F(0.0);
9078 if (!EvaluateFloat(SubExpr, F, Info))
9079 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009080
Richard Smith357362d2011-12-13 06:39:58 +00009081 APSInt Value;
9082 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9083 return false;
9084 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009085 }
9086 }
Mike Stump11289f42009-09-09 15:08:12 +00009087
Eli Friedmanc757de22011-03-25 00:43:55 +00009088 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009089}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009090
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009091bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9092 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009093 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009094 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9095 return false;
9096 if (!LV.isComplexInt())
9097 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009098 return Success(LV.getComplexIntReal(), E);
9099 }
9100
9101 return Visit(E->getSubExpr());
9102}
9103
Eli Friedman4e7a2412009-02-27 04:45:43 +00009104bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009105 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009106 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009107 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9108 return false;
9109 if (!LV.isComplexInt())
9110 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009111 return Success(LV.getComplexIntImag(), E);
9112 }
9113
Richard Smith4a678122011-10-24 18:44:57 +00009114 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009115 return Success(0, E);
9116}
9117
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009118bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9119 return Success(E->getPackLength(), E);
9120}
9121
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009122bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9123 return Success(E->getValue(), E);
9124}
9125
Chris Lattner05706e882008-07-11 18:11:29 +00009126//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009127// Float Evaluation
9128//===----------------------------------------------------------------------===//
9129
9130namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009131class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009132 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009133 APFloat &Result;
9134public:
9135 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009136 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009137
Richard Smith2e312c82012-03-03 22:46:17 +00009138 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009139 Result = V.getFloat();
9140 return true;
9141 }
Eli Friedman24c01542008-08-22 00:06:13 +00009142
Richard Smithfddd3842011-12-30 21:15:51 +00009143 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009144 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9145 return true;
9146 }
9147
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009148 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009149
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009150 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009151 bool VisitBinaryOperator(const BinaryOperator *E);
9152 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009153 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009154
John McCallb1fb0d32010-05-07 22:08:54 +00009155 bool VisitUnaryReal(const UnaryOperator *E);
9156 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009157
Richard Smithfddd3842011-12-30 21:15:51 +00009158 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009159};
9160} // end anonymous namespace
9161
9162static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009163 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009164 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009165}
9166
Jay Foad39c79802011-01-12 09:06:06 +00009167static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009168 QualType ResultTy,
9169 const Expr *Arg,
9170 bool SNaN,
9171 llvm::APFloat &Result) {
9172 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9173 if (!S) return false;
9174
9175 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9176
9177 llvm::APInt fill;
9178
9179 // Treat empty strings as if they were zero.
9180 if (S->getString().empty())
9181 fill = llvm::APInt(32, 0);
9182 else if (S->getString().getAsInteger(0, fill))
9183 return false;
9184
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009185 if (Context.getTargetInfo().isNan2008()) {
9186 if (SNaN)
9187 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9188 else
9189 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9190 } else {
9191 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9192 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9193 // a different encoding to what became a standard in 2008, and for pre-
9194 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9195 // sNaN. This is now known as "legacy NaN" encoding.
9196 if (SNaN)
9197 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9198 else
9199 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9200 }
9201
John McCall16291492010-02-28 13:00:19 +00009202 return true;
9203}
9204
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009205bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009206 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009207 default:
9208 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9209
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009210 case Builtin::BI__builtin_huge_val:
9211 case Builtin::BI__builtin_huge_valf:
9212 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009213 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009214 case Builtin::BI__builtin_inf:
9215 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009216 case Builtin::BI__builtin_infl:
9217 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009218 const llvm::fltSemantics &Sem =
9219 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009220 Result = llvm::APFloat::getInf(Sem);
9221 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009222 }
Mike Stump11289f42009-09-09 15:08:12 +00009223
John McCall16291492010-02-28 13:00:19 +00009224 case Builtin::BI__builtin_nans:
9225 case Builtin::BI__builtin_nansf:
9226 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009227 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009228 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9229 true, Result))
9230 return Error(E);
9231 return true;
John McCall16291492010-02-28 13:00:19 +00009232
Chris Lattner0b7282e2008-10-06 06:31:58 +00009233 case Builtin::BI__builtin_nan:
9234 case Builtin::BI__builtin_nanf:
9235 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009236 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009237 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009238 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009239 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9240 false, Result))
9241 return Error(E);
9242 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009243
9244 case Builtin::BI__builtin_fabs:
9245 case Builtin::BI__builtin_fabsf:
9246 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009247 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009248 if (!EvaluateFloat(E->getArg(0), Result, Info))
9249 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009250
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009251 if (Result.isNegative())
9252 Result.changeSign();
9253 return true;
9254
Richard Smith8889a3d2013-06-13 06:26:32 +00009255 // FIXME: Builtin::BI__builtin_powi
9256 // FIXME: Builtin::BI__builtin_powif
9257 // FIXME: Builtin::BI__builtin_powil
9258
Mike Stump11289f42009-09-09 15:08:12 +00009259 case Builtin::BI__builtin_copysign:
9260 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009261 case Builtin::BI__builtin_copysignl:
9262 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009263 APFloat RHS(0.);
9264 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9265 !EvaluateFloat(E->getArg(1), RHS, Info))
9266 return false;
9267 Result.copySign(RHS);
9268 return true;
9269 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009270 }
9271}
9272
John McCallb1fb0d32010-05-07 22:08:54 +00009273bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009274 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9275 ComplexValue CV;
9276 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9277 return false;
9278 Result = CV.FloatReal;
9279 return true;
9280 }
9281
9282 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009283}
9284
9285bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009286 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9287 ComplexValue CV;
9288 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9289 return false;
9290 Result = CV.FloatImag;
9291 return true;
9292 }
9293
Richard Smith4a678122011-10-24 18:44:57 +00009294 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009295 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9296 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009297 return true;
9298}
9299
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009300bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009301 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009302 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009303 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009304 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009305 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009306 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9307 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009308 Result.changeSign();
9309 return true;
9310 }
9311}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009312
Eli Friedman24c01542008-08-22 00:06:13 +00009313bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009314 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9315 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009316
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009317 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009318 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009319 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009320 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009321 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9322 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009323}
9324
9325bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9326 Result = E->getValue();
9327 return true;
9328}
9329
Peter Collingbournee9200682011-05-13 03:29:01 +00009330bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9331 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009332
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009333 switch (E->getCastKind()) {
9334 default:
Richard Smith11562c52011-10-28 17:51:58 +00009335 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009336
9337 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009338 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009339 return EvaluateInteger(SubExpr, IntResult, Info) &&
9340 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9341 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009342 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009343
9344 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009345 if (!Visit(SubExpr))
9346 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009347 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9348 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009349 }
John McCalld7646252010-11-14 08:17:51 +00009350
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009351 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009352 ComplexValue V;
9353 if (!EvaluateComplex(SubExpr, V, Info))
9354 return false;
9355 Result = V.getComplexFloatReal();
9356 return true;
9357 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009358 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009359}
9360
Eli Friedman24c01542008-08-22 00:06:13 +00009361//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009362// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009363//===----------------------------------------------------------------------===//
9364
9365namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009366class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009367 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009368 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009369
Anders Carlsson537969c2008-11-16 20:27:53 +00009370public:
John McCall93d91dc2010-05-07 17:22:02 +00009371 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009372 : ExprEvaluatorBaseTy(info), Result(Result) {}
9373
Richard Smith2e312c82012-03-03 22:46:17 +00009374 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009375 Result.setFrom(V);
9376 return true;
9377 }
Mike Stump11289f42009-09-09 15:08:12 +00009378
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009379 bool ZeroInitialization(const Expr *E);
9380
Anders Carlsson537969c2008-11-16 20:27:53 +00009381 //===--------------------------------------------------------------------===//
9382 // Visitor Methods
9383 //===--------------------------------------------------------------------===//
9384
Peter Collingbournee9200682011-05-13 03:29:01 +00009385 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009386 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009387 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009388 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009389 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009390};
9391} // end anonymous namespace
9392
John McCall93d91dc2010-05-07 17:22:02 +00009393static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9394 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009395 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009396 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009397}
9398
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009399bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009400 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009401 if (ElemTy->isRealFloatingType()) {
9402 Result.makeComplexFloat();
9403 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9404 Result.FloatReal = Zero;
9405 Result.FloatImag = Zero;
9406 } else {
9407 Result.makeComplexInt();
9408 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9409 Result.IntReal = Zero;
9410 Result.IntImag = Zero;
9411 }
9412 return true;
9413}
9414
Peter Collingbournee9200682011-05-13 03:29:01 +00009415bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9416 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009417
9418 if (SubExpr->getType()->isRealFloatingType()) {
9419 Result.makeComplexFloat();
9420 APFloat &Imag = Result.FloatImag;
9421 if (!EvaluateFloat(SubExpr, Imag, Info))
9422 return false;
9423
9424 Result.FloatReal = APFloat(Imag.getSemantics());
9425 return true;
9426 } else {
9427 assert(SubExpr->getType()->isIntegerType() &&
9428 "Unexpected imaginary literal.");
9429
9430 Result.makeComplexInt();
9431 APSInt &Imag = Result.IntImag;
9432 if (!EvaluateInteger(SubExpr, Imag, Info))
9433 return false;
9434
9435 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9436 return true;
9437 }
9438}
9439
Peter Collingbournee9200682011-05-13 03:29:01 +00009440bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009441
John McCallfcef3cf2010-12-14 17:51:41 +00009442 switch (E->getCastKind()) {
9443 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009444 case CK_BaseToDerived:
9445 case CK_DerivedToBase:
9446 case CK_UncheckedDerivedToBase:
9447 case CK_Dynamic:
9448 case CK_ToUnion:
9449 case CK_ArrayToPointerDecay:
9450 case CK_FunctionToPointerDecay:
9451 case CK_NullToPointer:
9452 case CK_NullToMemberPointer:
9453 case CK_BaseToDerivedMemberPointer:
9454 case CK_DerivedToBaseMemberPointer:
9455 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009456 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009457 case CK_ConstructorConversion:
9458 case CK_IntegralToPointer:
9459 case CK_PointerToIntegral:
9460 case CK_PointerToBoolean:
9461 case CK_ToVoid:
9462 case CK_VectorSplat:
9463 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009464 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009465 case CK_IntegralToBoolean:
9466 case CK_IntegralToFloating:
9467 case CK_FloatingToIntegral:
9468 case CK_FloatingToBoolean:
9469 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009470 case CK_CPointerToObjCPointerCast:
9471 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009472 case CK_AnyPointerToBlockPointerCast:
9473 case CK_ObjCObjectLValueCast:
9474 case CK_FloatingComplexToReal:
9475 case CK_FloatingComplexToBoolean:
9476 case CK_IntegralComplexToReal:
9477 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009478 case CK_ARCProduceObject:
9479 case CK_ARCConsumeObject:
9480 case CK_ARCReclaimReturnedObject:
9481 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009482 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009483 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009484 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009485 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009486 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009487 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009488 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009489 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009490
John McCallfcef3cf2010-12-14 17:51:41 +00009491 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009492 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009493 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009494 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009495
9496 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009497 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009498 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009499 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009500
9501 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009502 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009503 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009504 return false;
9505
John McCallfcef3cf2010-12-14 17:51:41 +00009506 Result.makeComplexFloat();
9507 Result.FloatImag = APFloat(Real.getSemantics());
9508 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009509 }
9510
John McCallfcef3cf2010-12-14 17:51:41 +00009511 case CK_FloatingComplexCast: {
9512 if (!Visit(E->getSubExpr()))
9513 return false;
9514
9515 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9516 QualType From
9517 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9518
Richard Smith357362d2011-12-13 06:39:58 +00009519 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9520 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009521 }
9522
9523 case CK_FloatingComplexToIntegralComplex: {
9524 if (!Visit(E->getSubExpr()))
9525 return false;
9526
9527 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9528 QualType From
9529 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9530 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009531 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9532 To, Result.IntReal) &&
9533 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9534 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009535 }
9536
9537 case CK_IntegralRealToComplex: {
9538 APSInt &Real = Result.IntReal;
9539 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9540 return false;
9541
9542 Result.makeComplexInt();
9543 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9544 return true;
9545 }
9546
9547 case CK_IntegralComplexCast: {
9548 if (!Visit(E->getSubExpr()))
9549 return false;
9550
9551 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9552 QualType From
9553 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9554
Richard Smith911e1422012-01-30 22:27:01 +00009555 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9556 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009557 return true;
9558 }
9559
9560 case CK_IntegralComplexToFloatingComplex: {
9561 if (!Visit(E->getSubExpr()))
9562 return false;
9563
Ted Kremenek28831752012-08-23 20:46:57 +00009564 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009565 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009566 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009567 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009568 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9569 To, Result.FloatReal) &&
9570 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9571 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009572 }
9573 }
9574
9575 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009576}
9577
John McCall93d91dc2010-05-07 17:22:02 +00009578bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009579 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009580 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9581
Chandler Carrutha216cad2014-10-11 00:57:18 +00009582 // Track whether the LHS or RHS is real at the type system level. When this is
9583 // the case we can simplify our evaluation strategy.
9584 bool LHSReal = false, RHSReal = false;
9585
9586 bool LHSOK;
9587 if (E->getLHS()->getType()->isRealFloatingType()) {
9588 LHSReal = true;
9589 APFloat &Real = Result.FloatReal;
9590 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9591 if (LHSOK) {
9592 Result.makeComplexFloat();
9593 Result.FloatImag = APFloat(Real.getSemantics());
9594 }
9595 } else {
9596 LHSOK = Visit(E->getLHS());
9597 }
George Burgess IVa145e252016-05-25 22:38:36 +00009598 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009599 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009600
John McCall93d91dc2010-05-07 17:22:02 +00009601 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009602 if (E->getRHS()->getType()->isRealFloatingType()) {
9603 RHSReal = true;
9604 APFloat &Real = RHS.FloatReal;
9605 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9606 return false;
9607 RHS.makeComplexFloat();
9608 RHS.FloatImag = APFloat(Real.getSemantics());
9609 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009610 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009611
Chandler Carrutha216cad2014-10-11 00:57:18 +00009612 assert(!(LHSReal && RHSReal) &&
9613 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009614 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009615 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009616 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009617 if (Result.isComplexFloat()) {
9618 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9619 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009620 if (LHSReal)
9621 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9622 else if (!RHSReal)
9623 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9624 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009625 } else {
9626 Result.getComplexIntReal() += RHS.getComplexIntReal();
9627 Result.getComplexIntImag() += RHS.getComplexIntImag();
9628 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009629 break;
John McCalle3027922010-08-25 11:45:40 +00009630 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009631 if (Result.isComplexFloat()) {
9632 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9633 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009634 if (LHSReal) {
9635 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9636 Result.getComplexFloatImag().changeSign();
9637 } else if (!RHSReal) {
9638 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9639 APFloat::rmNearestTiesToEven);
9640 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009641 } else {
9642 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9643 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9644 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009645 break;
John McCalle3027922010-08-25 11:45:40 +00009646 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009647 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009648 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009649 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009650 // following naming scheme:
9651 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009652 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009653 APFloat &A = LHS.getComplexFloatReal();
9654 APFloat &B = LHS.getComplexFloatImag();
9655 APFloat &C = RHS.getComplexFloatReal();
9656 APFloat &D = RHS.getComplexFloatImag();
9657 APFloat &ResR = Result.getComplexFloatReal();
9658 APFloat &ResI = Result.getComplexFloatImag();
9659 if (LHSReal) {
9660 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9661 ResR = A * C;
9662 ResI = A * D;
9663 } else if (RHSReal) {
9664 ResR = C * A;
9665 ResI = C * B;
9666 } else {
9667 // In the fully general case, we need to handle NaNs and infinities
9668 // robustly.
9669 APFloat AC = A * C;
9670 APFloat BD = B * D;
9671 APFloat AD = A * D;
9672 APFloat BC = B * C;
9673 ResR = AC - BD;
9674 ResI = AD + BC;
9675 if (ResR.isNaN() && ResI.isNaN()) {
9676 bool Recalc = false;
9677 if (A.isInfinity() || B.isInfinity()) {
9678 A = APFloat::copySign(
9679 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9680 B = APFloat::copySign(
9681 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9682 if (C.isNaN())
9683 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9684 if (D.isNaN())
9685 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9686 Recalc = true;
9687 }
9688 if (C.isInfinity() || D.isInfinity()) {
9689 C = APFloat::copySign(
9690 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9691 D = APFloat::copySign(
9692 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9693 if (A.isNaN())
9694 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9695 if (B.isNaN())
9696 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9697 Recalc = true;
9698 }
9699 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9700 AD.isInfinity() || BC.isInfinity())) {
9701 if (A.isNaN())
9702 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9703 if (B.isNaN())
9704 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9705 if (C.isNaN())
9706 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9707 if (D.isNaN())
9708 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9709 Recalc = true;
9710 }
9711 if (Recalc) {
9712 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9713 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9714 }
9715 }
9716 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009717 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009718 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009719 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009720 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9721 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009722 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009723 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9724 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9725 }
9726 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009727 case BO_Div:
9728 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009729 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009730 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009731 // following naming scheme:
9732 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009733 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009734 APFloat &A = LHS.getComplexFloatReal();
9735 APFloat &B = LHS.getComplexFloatImag();
9736 APFloat &C = RHS.getComplexFloatReal();
9737 APFloat &D = RHS.getComplexFloatImag();
9738 APFloat &ResR = Result.getComplexFloatReal();
9739 APFloat &ResI = Result.getComplexFloatImag();
9740 if (RHSReal) {
9741 ResR = A / C;
9742 ResI = B / C;
9743 } else {
9744 if (LHSReal) {
9745 // No real optimizations we can do here, stub out with zero.
9746 B = APFloat::getZero(A.getSemantics());
9747 }
9748 int DenomLogB = 0;
9749 APFloat MaxCD = maxnum(abs(C), abs(D));
9750 if (MaxCD.isFinite()) {
9751 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009752 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9753 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009754 }
9755 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009756 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9757 APFloat::rmNearestTiesToEven);
9758 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9759 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009760 if (ResR.isNaN() && ResI.isNaN()) {
9761 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9762 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9763 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9764 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9765 D.isFinite()) {
9766 A = APFloat::copySign(
9767 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9768 B = APFloat::copySign(
9769 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9770 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9771 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9772 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9773 C = APFloat::copySign(
9774 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9775 D = APFloat::copySign(
9776 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9777 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9778 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9779 }
9780 }
9781 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009782 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009783 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9784 return Error(E, diag::note_expr_divide_by_zero);
9785
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009786 ComplexValue LHS = Result;
9787 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9788 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9789 Result.getComplexIntReal() =
9790 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9791 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9792 Result.getComplexIntImag() =
9793 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9794 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9795 }
9796 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009797 }
9798
John McCall93d91dc2010-05-07 17:22:02 +00009799 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009800}
9801
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009802bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9803 // Get the operand value into 'Result'.
9804 if (!Visit(E->getSubExpr()))
9805 return false;
9806
9807 switch (E->getOpcode()) {
9808 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009809 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009810 case UO_Extension:
9811 return true;
9812 case UO_Plus:
9813 // The result is always just the subexpr.
9814 return true;
9815 case UO_Minus:
9816 if (Result.isComplexFloat()) {
9817 Result.getComplexFloatReal().changeSign();
9818 Result.getComplexFloatImag().changeSign();
9819 }
9820 else {
9821 Result.getComplexIntReal() = -Result.getComplexIntReal();
9822 Result.getComplexIntImag() = -Result.getComplexIntImag();
9823 }
9824 return true;
9825 case UO_Not:
9826 if (Result.isComplexFloat())
9827 Result.getComplexFloatImag().changeSign();
9828 else
9829 Result.getComplexIntImag() = -Result.getComplexIntImag();
9830 return true;
9831 }
9832}
9833
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009834bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9835 if (E->getNumInits() == 2) {
9836 if (E->getType()->isComplexType()) {
9837 Result.makeComplexFloat();
9838 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9839 return false;
9840 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9841 return false;
9842 } else {
9843 Result.makeComplexInt();
9844 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9845 return false;
9846 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9847 return false;
9848 }
9849 return true;
9850 }
9851 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9852}
9853
Anders Carlsson537969c2008-11-16 20:27:53 +00009854//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009855// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9856// implicit conversion.
9857//===----------------------------------------------------------------------===//
9858
9859namespace {
9860class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009861 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009862 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009863 APValue &Result;
9864public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009865 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9866 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009867
9868 bool Success(const APValue &V, const Expr *E) {
9869 Result = V;
9870 return true;
9871 }
9872
9873 bool ZeroInitialization(const Expr *E) {
9874 ImplicitValueInitExpr VIE(
9875 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009876 // For atomic-qualified class (and array) types in C++, initialize the
9877 // _Atomic-wrapped subobject directly, in-place.
9878 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9879 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009880 }
9881
9882 bool VisitCastExpr(const CastExpr *E) {
9883 switch (E->getCastKind()) {
9884 default:
9885 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9886 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009887 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9888 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009889 }
9890 }
9891};
9892} // end anonymous namespace
9893
Richard Smith64cb9ca2017-02-22 22:09:50 +00009894static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9895 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009896 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009897 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009898}
9899
9900//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009901// Void expression evaluation, primarily for a cast to void on the LHS of a
9902// comma operator
9903//===----------------------------------------------------------------------===//
9904
9905namespace {
9906class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009907 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009908public:
9909 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9910
Richard Smith2e312c82012-03-03 22:46:17 +00009911 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009912
Richard Smith7cd577b2017-08-17 19:35:50 +00009913 bool ZeroInitialization(const Expr *E) { return true; }
9914
Richard Smith42d3af92011-12-07 00:43:50 +00009915 bool VisitCastExpr(const CastExpr *E) {
9916 switch (E->getCastKind()) {
9917 default:
9918 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9919 case CK_ToVoid:
9920 VisitIgnoredValue(E->getSubExpr());
9921 return true;
9922 }
9923 }
Hal Finkela8443c32014-07-17 14:49:58 +00009924
9925 bool VisitCallExpr(const CallExpr *E) {
9926 switch (E->getBuiltinCallee()) {
9927 default:
9928 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9929 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009930 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009931 // The argument is not evaluated!
9932 return true;
9933 }
9934 }
Richard Smith42d3af92011-12-07 00:43:50 +00009935};
9936} // end anonymous namespace
9937
9938static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9939 assert(E->isRValue() && E->getType()->isVoidType());
9940 return VoidExprEvaluator(Info).Visit(E);
9941}
9942
9943//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009944// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009945//===----------------------------------------------------------------------===//
9946
Richard Smith2e312c82012-03-03 22:46:17 +00009947static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009948 // In C, function designators are not lvalues, but we evaluate them as if they
9949 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009950 QualType T = E->getType();
9951 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009952 LValue LV;
9953 if (!EvaluateLValue(E, LV, Info))
9954 return false;
9955 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009956 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009957 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009958 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009959 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009960 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009961 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009962 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009963 LValue LV;
9964 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009965 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009966 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009967 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009968 llvm::APFloat F(0.0);
9969 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009970 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009971 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009972 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009973 ComplexValue C;
9974 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009975 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009976 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009977 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009978 MemberPtr P;
9979 if (!EvaluateMemberPointer(E, P, Info))
9980 return false;
9981 P.moveInto(Result);
9982 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009983 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009984 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009985 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009986 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9987 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009988 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009989 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009990 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009991 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009992 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009993 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9994 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009995 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009996 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009997 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009998 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009999 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010000 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010001 if (!EvaluateVoid(E, Info))
10002 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010003 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010004 QualType Unqual = T.getAtomicUnqualifiedType();
10005 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10006 LValue LV;
10007 LV.set(E, Info.CurrentCall->Index);
10008 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10009 if (!EvaluateAtomic(E, &LV, Value, Info))
10010 return false;
10011 } else {
10012 if (!EvaluateAtomic(E, nullptr, Result, Info))
10013 return false;
10014 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010015 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010016 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010017 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010018 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010019 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010020 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010021 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010022
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010023 return true;
10024}
10025
Richard Smithb228a862012-02-15 02:18:13 +000010026/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10027/// cases, the in-place evaluation is essential, since later initializers for
10028/// an object can indirectly refer to subobjects which were initialized earlier.
10029static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010030 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010031 assert(!E->isValueDependent());
10032
Richard Smith7525ff62013-05-09 07:14:00 +000010033 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010034 return false;
10035
10036 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010037 // Evaluate arrays and record types in-place, so that later initializers can
10038 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010039 QualType T = E->getType();
10040 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010041 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010042 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010043 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010044 else if (T->isAtomicType()) {
10045 QualType Unqual = T.getAtomicUnqualifiedType();
10046 if (Unqual->isArrayType() || Unqual->isRecordType())
10047 return EvaluateAtomic(E, &This, Result, Info);
10048 }
Richard Smithed5165f2011-11-04 05:33:44 +000010049 }
10050
10051 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010052 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010053}
10054
Richard Smithf57d8cb2011-12-09 22:58:01 +000010055/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10056/// lvalue-to-rvalue cast if it is an lvalue.
10057static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010058 if (E->getType().isNull())
10059 return false;
10060
Nick Lewyckyc190f962017-05-02 01:06:16 +000010061 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010062 return false;
10063
Richard Smith2e312c82012-03-03 22:46:17 +000010064 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010065 return false;
10066
10067 if (E->isGLValue()) {
10068 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010069 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010070 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010071 return false;
10072 }
10073
Richard Smith2e312c82012-03-03 22:46:17 +000010074 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010075 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010076}
Richard Smith11562c52011-10-28 17:51:58 +000010077
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010078static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010079 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010080 // Fast-path evaluations of integer literals, since we sometimes see files
10081 // containing vast quantities of these.
10082 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10083 Result.Val = APValue(APSInt(L->getValue(),
10084 L->getType()->isUnsignedIntegerType()));
10085 IsConst = true;
10086 return true;
10087 }
James Dennett0492ef02014-03-14 17:44:10 +000010088
10089 // This case should be rare, but we need to check it before we check on
10090 // the type below.
10091 if (Exp->getType().isNull()) {
10092 IsConst = false;
10093 return true;
10094 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010095
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010096 // FIXME: Evaluating values of large array and record types can cause
10097 // performance problems. Only do so in C++11 for now.
10098 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10099 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010100 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010101 IsConst = false;
10102 return true;
10103 }
10104 return false;
10105}
10106
10107
Richard Smith7b553f12011-10-29 00:50:52 +000010108/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010109/// any crazy technique (that has nothing to do with language standards) that
10110/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010111/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10112/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010113bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010114 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010115 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010116 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010117
Richard Smith6d4c6582013-11-05 22:18:15 +000010118 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010119 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010120}
10121
Jay Foad39c79802011-01-12 09:06:06 +000010122bool Expr::EvaluateAsBooleanCondition(bool &Result,
10123 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010124 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010125 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010126 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010127}
10128
Richard Smithce8eca52015-12-08 03:21:47 +000010129static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10130 Expr::SideEffectsKind SEK) {
10131 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10132 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10133}
10134
Richard Smith5fab0c92011-12-28 19:48:30 +000010135bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10136 SideEffectsKind AllowSideEffects) const {
10137 if (!getType()->isIntegralOrEnumerationType())
10138 return false;
10139
Richard Smith11562c52011-10-28 17:51:58 +000010140 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010141 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010142 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010143 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010144
Richard Smith11562c52011-10-28 17:51:58 +000010145 Result = ExprResult.Val.getInt();
10146 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010147}
10148
Richard Trieube234c32016-04-21 21:04:55 +000010149bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10150 SideEffectsKind AllowSideEffects) const {
10151 if (!getType()->isRealFloatingType())
10152 return false;
10153
10154 EvalResult ExprResult;
10155 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10156 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10157 return false;
10158
10159 Result = ExprResult.Val.getFloat();
10160 return true;
10161}
10162
Jay Foad39c79802011-01-12 09:06:06 +000010163bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010164 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010165
John McCall45d55e42010-05-07 21:00:08 +000010166 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010167 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10168 !CheckLValueConstantExpression(Info, getExprLoc(),
10169 Ctx.getLValueReferenceType(getType()), LV))
10170 return false;
10171
Richard Smith2e312c82012-03-03 22:46:17 +000010172 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010173 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010174}
10175
Richard Smithd0b4dd62011-12-19 06:19:21 +000010176bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10177 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010178 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010179 // FIXME: Evaluating initializers for large array and record types can cause
10180 // performance problems. Only do so in C++11 for now.
10181 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010182 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010183 return false;
10184
Richard Smithd0b4dd62011-12-19 06:19:21 +000010185 Expr::EvalStatus EStatus;
10186 EStatus.Diag = &Notes;
10187
Richard Smith0c6124b2015-12-03 01:36:22 +000010188 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10189 ? EvalInfo::EM_ConstantExpression
10190 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010191 InitInfo.setEvaluatingDecl(VD, Value);
10192
10193 LValue LVal;
10194 LVal.set(VD);
10195
Richard Smithfddd3842011-12-30 21:15:51 +000010196 // C++11 [basic.start.init]p2:
10197 // Variables with static storage duration or thread storage duration shall be
10198 // zero-initialized before any other initialization takes place.
10199 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010200 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010201 !VD->getType()->isReferenceType()) {
10202 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010203 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010204 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010205 return false;
10206 }
10207
Richard Smith7525ff62013-05-09 07:14:00 +000010208 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10209 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010210 EStatus.HasSideEffects)
10211 return false;
10212
10213 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10214 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010215}
10216
Richard Smith7b553f12011-10-29 00:50:52 +000010217/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10218/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010219bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010220 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010221 return EvaluateAsRValue(Result, Ctx) &&
10222 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010223}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010224
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010225APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010226 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010227 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010228 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010229 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010230 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010231 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010232 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010233
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010234 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010235}
John McCall864e3962010-05-07 05:32:02 +000010236
Richard Smithe9ff7702013-11-05 22:23:30 +000010237void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010238 bool IsConst;
10239 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010240 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010241 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010242 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10243 }
10244}
10245
Richard Smithe6c01442013-06-05 00:46:14 +000010246bool Expr::EvalResult::isGlobalLValue() const {
10247 assert(Val.isLValue());
10248 return IsGlobalLValue(Val.getLValueBase());
10249}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010250
10251
John McCall864e3962010-05-07 05:32:02 +000010252/// isIntegerConstantExpr - this recursive routine will test if an expression is
10253/// an integer constant expression.
10254
10255/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10256/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010257
10258// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010259// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10260// and a (possibly null) SourceLocation indicating the location of the problem.
10261//
John McCall864e3962010-05-07 05:32:02 +000010262// Note that to reduce code duplication, this helper does no evaluation
10263// itself; the caller checks whether the expression is evaluatable, and
10264// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010265// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010266
Dan Gohman28ade552010-07-26 21:25:24 +000010267namespace {
10268
Richard Smith9e575da2012-12-28 13:25:52 +000010269enum ICEKind {
10270 /// This expression is an ICE.
10271 IK_ICE,
10272 /// This expression is not an ICE, but if it isn't evaluated, it's
10273 /// a legal subexpression for an ICE. This return value is used to handle
10274 /// the comma operator in C99 mode, and non-constant subexpressions.
10275 IK_ICEIfUnevaluated,
10276 /// This expression is not an ICE, and is not a legal subexpression for one.
10277 IK_NotICE
10278};
10279
John McCall864e3962010-05-07 05:32:02 +000010280struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010281 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010282 SourceLocation Loc;
10283
Richard Smith9e575da2012-12-28 13:25:52 +000010284 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010285};
10286
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010287}
Dan Gohman28ade552010-07-26 21:25:24 +000010288
Richard Smith9e575da2012-12-28 13:25:52 +000010289static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10290
10291static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010292
Craig Toppera31a8822013-08-22 07:09:37 +000010293static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010294 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010295 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010296 !EVResult.Val.isInt())
10297 return ICEDiag(IK_NotICE, E->getLocStart());
10298
John McCall864e3962010-05-07 05:32:02 +000010299 return NoDiag();
10300}
10301
Craig Toppera31a8822013-08-22 07:09:37 +000010302static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010303 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010304 if (!E->getType()->isIntegralOrEnumerationType())
10305 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010306
10307 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010308#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010309#define STMT(Node, Base) case Expr::Node##Class:
10310#define EXPR(Node, Base)
10311#include "clang/AST/StmtNodes.inc"
10312 case Expr::PredefinedExprClass:
10313 case Expr::FloatingLiteralClass:
10314 case Expr::ImaginaryLiteralClass:
10315 case Expr::StringLiteralClass:
10316 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010317 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010318 case Expr::MemberExprClass:
10319 case Expr::CompoundAssignOperatorClass:
10320 case Expr::CompoundLiteralExprClass:
10321 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010322 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010323 case Expr::ArrayInitLoopExprClass:
10324 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010325 case Expr::NoInitExprClass:
10326 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010327 case Expr::ImplicitValueInitExprClass:
10328 case Expr::ParenListExprClass:
10329 case Expr::VAArgExprClass:
10330 case Expr::AddrLabelExprClass:
10331 case Expr::StmtExprClass:
10332 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010333 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010334 case Expr::CXXDynamicCastExprClass:
10335 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010336 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010337 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010338 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010339 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010340 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010341 case Expr::CXXThisExprClass:
10342 case Expr::CXXThrowExprClass:
10343 case Expr::CXXNewExprClass:
10344 case Expr::CXXDeleteExprClass:
10345 case Expr::CXXPseudoDestructorExprClass:
10346 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010347 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010348 case Expr::DependentScopeDeclRefExprClass:
10349 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010350 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010351 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010352 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010353 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010354 case Expr::CXXTemporaryObjectExprClass:
10355 case Expr::CXXUnresolvedConstructExprClass:
10356 case Expr::CXXDependentScopeMemberExprClass:
10357 case Expr::UnresolvedMemberExprClass:
10358 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010359 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010360 case Expr::ObjCArrayLiteralClass:
10361 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010362 case Expr::ObjCEncodeExprClass:
10363 case Expr::ObjCMessageExprClass:
10364 case Expr::ObjCSelectorExprClass:
10365 case Expr::ObjCProtocolExprClass:
10366 case Expr::ObjCIvarRefExprClass:
10367 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010368 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010369 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010370 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010371 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010372 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010373 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010374 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010375 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010376 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010377 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010378 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010379 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010380 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010381 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010382 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010383 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010384 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010385 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010386 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010387 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010388 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010389 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010390
Richard Smithf137f932014-01-25 20:50:08 +000010391 case Expr::InitListExprClass: {
10392 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10393 // form "T x = { a };" is equivalent to "T x = a;".
10394 // Unless we're initializing a reference, T is a scalar as it is known to be
10395 // of integral or enumeration type.
10396 if (E->isRValue())
10397 if (cast<InitListExpr>(E)->getNumInits() == 1)
10398 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10399 return ICEDiag(IK_NotICE, E->getLocStart());
10400 }
10401
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010402 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010403 case Expr::GNUNullExprClass:
10404 // GCC considers the GNU __null value to be an integral constant expression.
10405 return NoDiag();
10406
John McCall7c454bb2011-07-15 05:09:51 +000010407 case Expr::SubstNonTypeTemplateParmExprClass:
10408 return
10409 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10410
John McCall864e3962010-05-07 05:32:02 +000010411 case Expr::ParenExprClass:
10412 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010413 case Expr::GenericSelectionExprClass:
10414 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010415 case Expr::IntegerLiteralClass:
10416 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010417 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010418 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010419 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010420 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010421 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010422 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010423 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010424 return NoDiag();
10425 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010426 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010427 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10428 // constant expressions, but they can never be ICEs because an ICE cannot
10429 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010430 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010431 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010432 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010433 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010434 }
Richard Smith6365c912012-02-24 22:12:32 +000010435 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010436 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10437 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010438 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010439 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010440 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010441 // Parameter variables are never constants. Without this check,
10442 // getAnyInitializer() can find a default argument, which leads
10443 // to chaos.
10444 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010445 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010446
10447 // C++ 7.1.5.1p2
10448 // A variable of non-volatile const-qualified integral or enumeration
10449 // type initialized by an ICE can be used in ICEs.
10450 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010451 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010452 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010453
Richard Smithd0b4dd62011-12-19 06:19:21 +000010454 const VarDecl *VD;
10455 // Look for a declaration of this variable that has an initializer, and
10456 // check whether it is an ICE.
10457 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10458 return NoDiag();
10459 else
Richard Smith9e575da2012-12-28 13:25:52 +000010460 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010461 }
10462 }
Richard Smith9e575da2012-12-28 13:25:52 +000010463 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010464 }
John McCall864e3962010-05-07 05:32:02 +000010465 case Expr::UnaryOperatorClass: {
10466 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10467 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010468 case UO_PostInc:
10469 case UO_PostDec:
10470 case UO_PreInc:
10471 case UO_PreDec:
10472 case UO_AddrOf:
10473 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010474 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010475 // C99 6.6/3 allows increment and decrement within unevaluated
10476 // subexpressions of constant expressions, but they can never be ICEs
10477 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010478 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010479 case UO_Extension:
10480 case UO_LNot:
10481 case UO_Plus:
10482 case UO_Minus:
10483 case UO_Not:
10484 case UO_Real:
10485 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010486 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010487 }
Richard Smith9e575da2012-12-28 13:25:52 +000010488
John McCall864e3962010-05-07 05:32:02 +000010489 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010490 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010491 }
10492 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010493 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10494 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10495 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10496 // compliance: we should warn earlier for offsetof expressions with
10497 // array subscripts that aren't ICEs, and if the array subscripts
10498 // are ICEs, the value of the offsetof must be an integer constant.
10499 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010500 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010501 case Expr::UnaryExprOrTypeTraitExprClass: {
10502 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10503 if ((Exp->getKind() == UETT_SizeOf) &&
10504 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010505 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010506 return NoDiag();
10507 }
10508 case Expr::BinaryOperatorClass: {
10509 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10510 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010511 case BO_PtrMemD:
10512 case BO_PtrMemI:
10513 case BO_Assign:
10514 case BO_MulAssign:
10515 case BO_DivAssign:
10516 case BO_RemAssign:
10517 case BO_AddAssign:
10518 case BO_SubAssign:
10519 case BO_ShlAssign:
10520 case BO_ShrAssign:
10521 case BO_AndAssign:
10522 case BO_XorAssign:
10523 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010524 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010525 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10526 // constant expressions, but they can never be ICEs because an ICE cannot
10527 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010528 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010529
John McCalle3027922010-08-25 11:45:40 +000010530 case BO_Mul:
10531 case BO_Div:
10532 case BO_Rem:
10533 case BO_Add:
10534 case BO_Sub:
10535 case BO_Shl:
10536 case BO_Shr:
10537 case BO_LT:
10538 case BO_GT:
10539 case BO_LE:
10540 case BO_GE:
10541 case BO_EQ:
10542 case BO_NE:
10543 case BO_And:
10544 case BO_Xor:
10545 case BO_Or:
10546 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010547 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10548 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010549 if (Exp->getOpcode() == BO_Div ||
10550 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010551 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010552 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010553 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010554 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010555 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010556 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010557 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010558 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010559 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010560 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010561 }
10562 }
10563 }
John McCalle3027922010-08-25 11:45:40 +000010564 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010565 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010566 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10567 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010568 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10569 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010570 } else {
10571 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010572 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010573 }
10574 }
Richard Smith9e575da2012-12-28 13:25:52 +000010575 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010576 }
John McCalle3027922010-08-25 11:45:40 +000010577 case BO_LAnd:
10578 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010579 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10580 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010581 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010582 // Rare case where the RHS has a comma "side-effect"; we need
10583 // to actually check the condition to see whether the side
10584 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010585 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010586 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010587 return RHSResult;
10588 return NoDiag();
10589 }
10590
Richard Smith9e575da2012-12-28 13:25:52 +000010591 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010592 }
10593 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010594 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010595 }
10596 case Expr::ImplicitCastExprClass:
10597 case Expr::CStyleCastExprClass:
10598 case Expr::CXXFunctionalCastExprClass:
10599 case Expr::CXXStaticCastExprClass:
10600 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010601 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010602 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010603 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010604 if (isa<ExplicitCastExpr>(E)) {
10605 if (const FloatingLiteral *FL
10606 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10607 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10608 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10609 APSInt IgnoredVal(DestWidth, !DestSigned);
10610 bool Ignored;
10611 // If the value does not fit in the destination type, the behavior is
10612 // undefined, so we are not required to treat it as a constant
10613 // expression.
10614 if (FL->getValue().convertToInteger(IgnoredVal,
10615 llvm::APFloat::rmTowardZero,
10616 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010617 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010618 return NoDiag();
10619 }
10620 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010621 switch (cast<CastExpr>(E)->getCastKind()) {
10622 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010623 case CK_AtomicToNonAtomic:
10624 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010625 case CK_NoOp:
10626 case CK_IntegralToBoolean:
10627 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010628 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010629 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010630 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010631 }
John McCall864e3962010-05-07 05:32:02 +000010632 }
John McCallc07a0c72011-02-17 10:25:35 +000010633 case Expr::BinaryConditionalOperatorClass: {
10634 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10635 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010636 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010637 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010638 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10639 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10640 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010641 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010642 return FalseResult;
10643 }
John McCall864e3962010-05-07 05:32:02 +000010644 case Expr::ConditionalOperatorClass: {
10645 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10646 // If the condition (ignoring parens) is a __builtin_constant_p call,
10647 // then only the true side is actually considered in an integer constant
10648 // expression, and it is fully evaluated. This is an important GNU
10649 // extension. See GCC PR38377 for discussion.
10650 if (const CallExpr *CallCE
10651 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010652 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010653 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010654 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010655 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010656 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010657
Richard Smithf57d8cb2011-12-09 22:58:01 +000010658 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10659 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010660
Richard Smith9e575da2012-12-28 13:25:52 +000010661 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010662 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010663 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010664 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010665 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010666 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010667 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010668 return NoDiag();
10669 // Rare case where the diagnostics depend on which side is evaluated
10670 // Note that if we get here, CondResult is 0, and at least one of
10671 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010672 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010673 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010674 return TrueResult;
10675 }
10676 case Expr::CXXDefaultArgExprClass:
10677 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010678 case Expr::CXXDefaultInitExprClass:
10679 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010680 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010681 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010682 }
10683 }
10684
David Blaikiee4d798f2012-01-20 21:50:17 +000010685 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010686}
10687
Richard Smithf57d8cb2011-12-09 22:58:01 +000010688/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010689static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010690 const Expr *E,
10691 llvm::APSInt *Value,
10692 SourceLocation *Loc) {
10693 if (!E->getType()->isIntegralOrEnumerationType()) {
10694 if (Loc) *Loc = E->getExprLoc();
10695 return false;
10696 }
10697
Richard Smith66e05fe2012-01-18 05:21:49 +000010698 APValue Result;
10699 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010700 return false;
10701
Richard Smith98710fc2014-11-13 23:03:19 +000010702 if (!Result.isInt()) {
10703 if (Loc) *Loc = E->getExprLoc();
10704 return false;
10705 }
10706
Richard Smith66e05fe2012-01-18 05:21:49 +000010707 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010708 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010709}
10710
Craig Toppera31a8822013-08-22 07:09:37 +000010711bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10712 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010713 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010714 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010715
Richard Smith9e575da2012-12-28 13:25:52 +000010716 ICEDiag D = CheckICE(this, Ctx);
10717 if (D.Kind != IK_ICE) {
10718 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010719 return false;
10720 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010721 return true;
10722}
10723
Craig Toppera31a8822013-08-22 07:09:37 +000010724bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010725 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010726 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010727 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10728
10729 if (!isIntegerConstantExpr(Ctx, Loc))
10730 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010731 // The only possible side-effects here are due to UB discovered in the
10732 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10733 // required to treat the expression as an ICE, so we produce the folded
10734 // value.
10735 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010736 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010737 return true;
10738}
Richard Smith66e05fe2012-01-18 05:21:49 +000010739
Craig Toppera31a8822013-08-22 07:09:37 +000010740bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010741 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010742}
10743
Craig Toppera31a8822013-08-22 07:09:37 +000010744bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010745 SourceLocation *Loc) const {
10746 // We support this checking in C++98 mode in order to diagnose compatibility
10747 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010748 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010749
Richard Smith98a0a492012-02-14 21:38:30 +000010750 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010751 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010752 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010753 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010754 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010755
10756 APValue Scratch;
10757 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10758
10759 if (!Diags.empty()) {
10760 IsConstExpr = false;
10761 if (Loc) *Loc = Diags[0].first;
10762 } else if (!IsConstExpr) {
10763 // FIXME: This shouldn't happen.
10764 if (Loc) *Loc = getExprLoc();
10765 }
10766
10767 return IsConstExpr;
10768}
Richard Smith253c2a32012-01-27 01:14:48 +000010769
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010770bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10771 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010772 ArrayRef<const Expr*> Args,
10773 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010774 Expr::EvalStatus Status;
10775 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10776
George Burgess IV177399e2017-01-09 04:12:14 +000010777 LValue ThisVal;
10778 const LValue *ThisPtr = nullptr;
10779 if (This) {
10780#ifndef NDEBUG
10781 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10782 assert(MD && "Don't provide `this` for non-methods.");
10783 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10784#endif
10785 if (EvaluateObjectArgument(Info, This, ThisVal))
10786 ThisPtr = &ThisVal;
10787 if (Info.EvalStatus.HasSideEffects)
10788 return false;
10789 }
10790
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010791 ArgVector ArgValues(Args.size());
10792 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10793 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010794 if ((*I)->isValueDependent() ||
10795 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010796 // If evaluation fails, throw away the argument entirely.
10797 ArgValues[I - Args.begin()] = APValue();
10798 if (Info.EvalStatus.HasSideEffects)
10799 return false;
10800 }
10801
10802 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010803 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010804 ArgValues.data());
10805 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10806}
10807
Richard Smith253c2a32012-01-27 01:14:48 +000010808bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010809 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010810 PartialDiagnosticAt> &Diags) {
10811 // FIXME: It would be useful to check constexpr function templates, but at the
10812 // moment the constant expression evaluator cannot cope with the non-rigorous
10813 // ASTs which we build for dependent expressions.
10814 if (FD->isDependentContext())
10815 return true;
10816
10817 Expr::EvalStatus Status;
10818 Status.Diag = &Diags;
10819
Richard Smith6d4c6582013-11-05 22:18:15 +000010820 EvalInfo Info(FD->getASTContext(), Status,
10821 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010822
10823 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010824 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010825
Richard Smith7525ff62013-05-09 07:14:00 +000010826 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010827 // is a temporary being used as the 'this' pointer.
10828 LValue This;
10829 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010830 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010831
Richard Smith253c2a32012-01-27 01:14:48 +000010832 ArrayRef<const Expr*> Args;
10833
Richard Smith2e312c82012-03-03 22:46:17 +000010834 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010835 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10836 // Evaluate the call as a constant initializer, to allow the construction
10837 // of objects of non-literal types.
10838 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010839 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10840 } else {
10841 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010842 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010843 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010844 }
Richard Smith253c2a32012-01-27 01:14:48 +000010845
10846 return Diags.empty();
10847}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010848
10849bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10850 const FunctionDecl *FD,
10851 SmallVectorImpl<
10852 PartialDiagnosticAt> &Diags) {
10853 Expr::EvalStatus Status;
10854 Status.Diag = &Diags;
10855
10856 EvalInfo Info(FD->getASTContext(), Status,
10857 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10858
10859 // Fabricate a call stack frame to give the arguments a plausible cover story.
10860 ArrayRef<const Expr*> Args;
10861 ArgVector ArgValues(0);
10862 bool Success = EvaluateArgs(Args, ArgValues, Info);
10863 (void)Success;
10864 assert(Success &&
10865 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010866 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010867
10868 APValue ResultScratch;
10869 Evaluate(ResultScratch, Info, E);
10870 return Diags.empty();
10871}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010872
10873bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10874 unsigned Type) const {
10875 if (!getType()->isPointerType())
10876 return false;
10877
10878 Expr::EvalStatus Status;
10879 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010880 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010881}