Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 5397, column 57
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ExprConstant.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp

1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include <cstring>
36#include <functional>
37#include "Interp/Context.h"
38#include "Interp/Frame.h"
39#include "Interp/State.h"
40#include "clang/AST/APValue.h"
41#include "clang/AST/ASTContext.h"
42#include "clang/AST/ASTDiagnostic.h"
43#include "clang/AST/ASTLambda.h"
44#include "clang/AST/CXXInheritance.h"
45#include "clang/AST/CharUnits.h"
46#include "clang/AST/CurrentSourceLocExprScope.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
49#include "clang/AST/OptionalDiagnostic.h"
50#include "clang/AST/RecordLayout.h"
51#include "clang/AST/StmtVisitor.h"
52#include "clang/AST/TypeLoc.h"
53#include "clang/Basic/Builtins.h"
54#include "clang/Basic/FixedPoint.h"
55#include "clang/Basic/TargetInfo.h"
56#include "llvm/ADT/Optional.h"
57#include "llvm/ADT/SmallBitVector.h"
58#include "llvm/Support/SaveAndRestore.h"
59#include "llvm/Support/raw_ostream.h"
60
61#define DEBUG_TYPE"exprconstant" "exprconstant"
62
63using namespace clang;
64using llvm::APInt;
65using llvm::APSInt;
66using llvm::APFloat;
67using llvm::Optional;
68
69namespace {
70 struct LValue;
71 class CallStackFrame;
72 class EvalInfo;
73
74 using SourceLocExprScopeGuard =
75 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
76
77 static QualType getType(APValue::LValueBase B) {
78 if (!B) return QualType();
79 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
80 // FIXME: It's unclear where we're supposed to take the type from, and
81 // this actually matters for arrays of unknown bound. Eg:
82 //
83 // extern int arr[]; void f() { extern int arr[3]; };
84 // constexpr int *p = &arr[1]; // valid?
85 //
86 // For now, we take the array bound from the most recent declaration.
87 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
88 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
89 QualType T = Redecl->getType();
90 if (!T->isIncompleteArrayType())
91 return T;
92 }
93 return D->getType();
94 }
95
96 if (B.is<TypeInfoLValue>())
97 return B.getTypeInfoType();
98
99 if (B.is<DynamicAllocLValue>())
100 return B.getDynamicAllocType();
101
102 const Expr *Base = B.get<const Expr*>();
103
104 // For a materialized temporary, the type of the temporary we materialized
105 // may not be the type of the expression.
106 if (const MaterializeTemporaryExpr *MTE =
107 dyn_cast<MaterializeTemporaryExpr>(Base)) {
108 SmallVector<const Expr *, 2> CommaLHSs;
109 SmallVector<SubobjectAdjustment, 2> Adjustments;
110 const Expr *Temp = MTE->GetTemporaryExpr();
111 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
112 Adjustments);
113 // Keep any cv-qualifiers from the reference if we generated a temporary
114 // for it directly. Otherwise use the type after adjustment.
115 if (!Adjustments.empty())
116 return Inner->getType();
117 }
118
119 return Base->getType();
120 }
121
122 /// Get an LValue path entry, which is known to not be an array index, as a
123 /// field declaration.
124 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
125 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
126 }
127 /// Get an LValue path entry, which is known to not be an array index, as a
128 /// base class declaration.
129 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
130 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
131 }
132 /// Determine whether this LValue path entry for a base class names a virtual
133 /// base class.
134 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
135 return E.getAsBaseOrMember().getInt();
136 }
137
138 /// Given an expression, determine the type used to store the result of
139 /// evaluating that expression.
140 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
141 if (E->isRValue())
142 return E->getType();
143 return Ctx.getLValueReferenceType(E->getType());
144 }
145
146 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
147 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
148 const FunctionDecl *Callee = CE->getDirectCallee();
149 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
150 }
151
152 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
153 /// This will look through a single cast.
154 ///
155 /// Returns null if we couldn't unwrap a function with alloc_size.
156 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
157 if (!E->getType()->isPointerType())
158 return nullptr;
159
160 E = E->IgnoreParens();
161 // If we're doing a variable assignment from e.g. malloc(N), there will
162 // probably be a cast of some kind. In exotic cases, we might also see a
163 // top-level ExprWithCleanups. Ignore them either way.
164 if (const auto *FE = dyn_cast<FullExpr>(E))
165 E = FE->getSubExpr()->IgnoreParens();
166
167 if (const auto *Cast = dyn_cast<CastExpr>(E))
168 E = Cast->getSubExpr()->IgnoreParens();
169
170 if (const auto *CE = dyn_cast<CallExpr>(E))
171 return getAllocSizeAttr(CE) ? CE : nullptr;
172 return nullptr;
173 }
174
175 /// Determines whether or not the given Base contains a call to a function
176 /// with the alloc_size attribute.
177 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
178 const auto *E = Base.dyn_cast<const Expr *>();
179 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
180 }
181
182 /// The bound to claim that an array of unknown bound has.
183 /// The value in MostDerivedArraySize is undefined in this case. So, set it
184 /// to an arbitrary value that's likely to loudly break things if it's used.
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
187
188 /// Determines if an LValue with the given LValueBase will have an unsized
189 /// array in its designator.
190 /// Find the path length and type of the most-derived subobject in the given
191 /// path, and find the size of the containing array, if any.
192 static unsigned
193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
194 ArrayRef<APValue::LValuePathEntry> Path,
195 uint64_t &ArraySize, QualType &Type, bool &IsArray,
196 bool &FirstEntryIsUnsizedArray) {
197 // This only accepts LValueBases from APValues, and APValues don't support
198 // arrays that lack size info.
199 assert(!isBaseAnAllocSizeCall(Base) &&((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here"
) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 200, __PRETTY_FUNCTION__))
200 "Unsized arrays shouldn't appear here")((!isBaseAnAllocSizeCall(Base) && "Unsized arrays shouldn't appear here"
) ? static_cast<void> (0) : __assert_fail ("!isBaseAnAllocSizeCall(Base) && \"Unsized arrays shouldn't appear here\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 200, __PRETTY_FUNCTION__))
;
201 unsigned MostDerivedLength = 0;
202 Type = getType(Base);
203
204 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
205 if (Type->isArrayType()) {
206 const ArrayType *AT = Ctx.getAsArrayType(Type);
207 Type = AT->getElementType();
208 MostDerivedLength = I + 1;
209 IsArray = true;
210
211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getSize().getZExtValue();
213 } else {
214 assert(I == 0 && "unexpected unsized array designator")((I == 0 && "unexpected unsized array designator") ? static_cast
<void> (0) : __assert_fail ("I == 0 && \"unexpected unsized array designator\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 214, __PRETTY_FUNCTION__))
;
215 FirstEntryIsUnsizedArray = true;
216 ArraySize = AssumedSizeForUnsizedArray;
217 }
218 } else if (Type->isAnyComplexType()) {
219 const ComplexType *CT = Type->castAs<ComplexType>();
220 Type = CT->getElementType();
221 ArraySize = 2;
222 MostDerivedLength = I + 1;
223 IsArray = true;
224 } else if (const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
226 ArraySize = 0;
227 MostDerivedLength = I + 1;
228 IsArray = false;
229 } else {
230 // Path[I] describes a base class.
231 ArraySize = 0;
232 IsArray = false;
233 }
234 }
235 return MostDerivedLength;
236 }
237
238 /// A path from a glvalue to a subobject of that glvalue.
239 struct SubobjectDesignator {
240 /// True if the subobject was named in a manner not supported by C++11. Such
241 /// lvalues can still be folded, but they are not core constant expressions
242 /// and we cannot perform lvalue-to-rvalue conversions on them.
243 unsigned Invalid : 1;
244
245 /// Is this a pointer one past the end of an object?
246 unsigned IsOnePastTheEnd : 1;
247
248 /// Indicator of whether the first entry is an unsized array.
249 unsigned FirstEntryIsAnUnsizedArray : 1;
250
251 /// Indicator of whether the most-derived object is an array element.
252 unsigned MostDerivedIsArrayElement : 1;
253
254 /// The length of the path to the most-derived object of which this is a
255 /// subobject.
256 unsigned MostDerivedPathLength : 28;
257
258 /// The size of the array of which the most-derived object is an element.
259 /// This will always be 0 if the most-derived object is not an array
260 /// element. 0 is not an indicator of whether or not the most-derived object
261 /// is an array, however, because 0-length arrays are allowed.
262 ///
263 /// If the current array is an unsized array, the value of this is
264 /// undefined.
265 uint64_t MostDerivedArraySize;
266
267 /// The type of the most derived object referred to by this address.
268 QualType MostDerivedType;
269
270 typedef APValue::LValuePathEntry PathEntry;
271
272 /// The entries on the path from the glvalue to the designated subobject.
273 SmallVector<PathEntry, 8> Entries;
274
275 SubobjectDesignator() : Invalid(true) {}
276
277 explicit SubobjectDesignator(QualType T)
278 : Invalid(false), IsOnePastTheEnd(false),
279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280 MostDerivedPathLength(0), MostDerivedArraySize(0),
281 MostDerivedType(T) {}
282
283 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286 MostDerivedPathLength(0), MostDerivedArraySize(0) {
287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?")((V.isLValue() && "Non-LValue used to make an LValue designator?"
) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Non-LValue used to make an LValue designator?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 287, __PRETTY_FUNCTION__))
;
288 if (!Invalid) {
289 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
290 ArrayRef<PathEntry> VEntries = V.getLValuePath();
291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
292 if (V.getLValueBase()) {
293 bool IsArray = false;
294 bool FirstIsUnsizedArray = false;
295 MostDerivedPathLength = findMostDerivedSubobject(
296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
297 MostDerivedType, IsArray, FirstIsUnsizedArray);
298 MostDerivedIsArrayElement = IsArray;
299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
300 }
301 }
302 }
303
304 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305 unsigned NewLength) {
306 if (Invalid)
307 return;
308
309 assert(Base && "cannot truncate path for null pointer")((Base && "cannot truncate path for null pointer") ? static_cast
<void> (0) : __assert_fail ("Base && \"cannot truncate path for null pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 309, __PRETTY_FUNCTION__))
;
310 assert(NewLength <= Entries.size() && "not a truncation")((NewLength <= Entries.size() && "not a truncation"
) ? static_cast<void> (0) : __assert_fail ("NewLength <= Entries.size() && \"not a truncation\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 310, __PRETTY_FUNCTION__))
;
311
312 if (NewLength == Entries.size())
313 return;
314 Entries.resize(NewLength);
315
316 bool IsArray = false;
317 bool FirstIsUnsizedArray = false;
318 MostDerivedPathLength = findMostDerivedSubobject(
319 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320 FirstIsUnsizedArray);
321 MostDerivedIsArrayElement = IsArray;
322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323 }
324
325 void setInvalid() {
326 Invalid = true;
327 Entries.clear();
328 }
329
330 /// Determine whether the most derived subobject is an array without a
331 /// known bound.
332 bool isMostDerivedAnUnsizedArray() const {
333 assert(!Invalid && "Calling this makes no sense on invalid designators")((!Invalid && "Calling this makes no sense on invalid designators"
) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"Calling this makes no sense on invalid designators\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 333, __PRETTY_FUNCTION__))
;
334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
335 }
336
337 /// Determine what the most derived array's size is. Results in an assertion
338 /// failure if the most derived array lacks a size.
339 uint64_t getMostDerivedArraySize() const {
340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size")((!isMostDerivedAnUnsizedArray() && "Unsized array has no size"
) ? static_cast<void> (0) : __assert_fail ("!isMostDerivedAnUnsizedArray() && \"Unsized array has no size\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 340, __PRETTY_FUNCTION__))
;
341 return MostDerivedArraySize;
342 }
343
344 /// Determine whether this is a one-past-the-end pointer.
345 bool isOnePastTheEnd() const {
346 assert(!Invalid)((!Invalid) ? static_cast<void> (0) : __assert_fail ("!Invalid"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 346, __PRETTY_FUNCTION__))
;
347 if (IsOnePastTheEnd)
348 return true;
349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351 MostDerivedArraySize)
352 return true;
353 return false;
354 }
355
356 /// Get the range of valid index adjustments in the form
357 /// {maximum value that can be subtracted from this pointer,
358 /// maximum value that can be added to this pointer}
359 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360 if (Invalid || isMostDerivedAnUnsizedArray())
361 return {0, 0};
362
363 // [expr.add]p4: For the purposes of these operators, a pointer to a
364 // nonarray object behaves the same as a pointer to the first element of
365 // an array of length one with the type of the object as its element type.
366 bool IsArray = MostDerivedPathLength == Entries.size() &&
367 MostDerivedIsArrayElement;
368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369 : (uint64_t)IsOnePastTheEnd;
370 uint64_t ArraySize =
371 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372 return {ArrayIndex, ArraySize - ArrayIndex};
373 }
374
375 /// Check that this refers to a valid subobject.
376 bool isValidSubobject() const {
377 if (Invalid)
378 return false;
379 return !isOnePastTheEnd();
380 }
381 /// Check that this refers to a valid subobject, and if not, produce a
382 /// relevant diagnostic and set the designator as invalid.
383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
384
385 /// Get the type of the designated object.
386 QualType getType(ASTContext &Ctx) const {
387 assert(!Invalid && "invalid designator has no subobject type")((!Invalid && "invalid designator has no subobject type"
) ? static_cast<void> (0) : __assert_fail ("!Invalid && \"invalid designator has no subobject type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 387, __PRETTY_FUNCTION__))
;
388 return MostDerivedPathLength == Entries.size()
389 ? MostDerivedType
390 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391 }
392
393 /// Update this designator to refer to the first element within this array.
394 void addArrayUnchecked(const ConstantArrayType *CAT) {
395 Entries.push_back(PathEntry::ArrayIndex(0));
396
397 // This is a most-derived object.
398 MostDerivedType = CAT->getElementType();
399 MostDerivedIsArrayElement = true;
400 MostDerivedArraySize = CAT->getSize().getZExtValue();
401 MostDerivedPathLength = Entries.size();
402 }
403 /// Update this designator to refer to the first element within the array of
404 /// elements of type T. This is an array of unknown size.
405 void addUnsizedArrayUnchecked(QualType ElemTy) {
406 Entries.push_back(PathEntry::ArrayIndex(0));
407
408 MostDerivedType = ElemTy;
409 MostDerivedIsArrayElement = true;
410 // The value in MostDerivedArraySize is undefined in this case. So, set it
411 // to an arbitrary value that's likely to loudly break things if it's
412 // used.
413 MostDerivedArraySize = AssumedSizeForUnsizedArray;
414 MostDerivedPathLength = Entries.size();
415 }
416 /// Update this designator to refer to the given base or member of this
417 /// object.
418 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
420
421 // If this isn't a base class, it's a new most-derived object.
422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423 MostDerivedType = FD->getType();
424 MostDerivedIsArrayElement = false;
425 MostDerivedArraySize = 0;
426 MostDerivedPathLength = Entries.size();
427 }
428 }
429 /// Update this designator to refer to the given complex component.
430 void addComplexUnchecked(QualType EltTy, bool Imag) {
431 Entries.push_back(PathEntry::ArrayIndex(Imag));
432
433 // This is technically a most-derived object, though in practice this
434 // is unlikely to matter.
435 MostDerivedType = EltTy;
436 MostDerivedIsArrayElement = true;
437 MostDerivedArraySize = 2;
438 MostDerivedPathLength = Entries.size();
439 }
440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
442 const APSInt &N);
443 /// Add N to the address of this subobject.
444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445 if (Invalid || !N) return;
446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447 if (isMostDerivedAnUnsizedArray()) {
448 diagnoseUnsizedArrayPointerArithmetic(Info, E);
449 // Can't verify -- trust that the user is doing the right thing (or if
450 // not, trust that the caller will catch the bad behavior).
451 // FIXME: Should we reject if this overflows, at least?
452 Entries.back() = PathEntry::ArrayIndex(
453 Entries.back().getAsArrayIndex() + TruncatedN);
454 return;
455 }
456
457 // [expr.add]p4: For the purposes of these operators, a pointer to a
458 // nonarray object behaves the same as a pointer to the first element of
459 // an array of length one with the type of the object as its element type.
460 bool IsArray = MostDerivedPathLength == Entries.size() &&
461 MostDerivedIsArrayElement;
462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463 : (uint64_t)IsOnePastTheEnd;
464 uint64_t ArraySize =
465 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
466
467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468 // Calculate the actual index in a wide enough type, so we can include
469 // it in the note.
470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471 (llvm::APInt&)N += ArrayIndex;
472 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index")((N.ugt(ArraySize) && "bounds check failed for in-bounds index"
) ? static_cast<void> (0) : __assert_fail ("N.ugt(ArraySize) && \"bounds check failed for in-bounds index\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 472, __PRETTY_FUNCTION__))
;
473 diagnosePointerArithmetic(Info, E, N);
474 setInvalid();
475 return;
476 }
477
478 ArrayIndex += TruncatedN;
479 assert(ArrayIndex <= ArraySize &&((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index"
) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 480, __PRETTY_FUNCTION__))
480 "bounds check succeeded for out-of-bounds index")((ArrayIndex <= ArraySize && "bounds check succeeded for out-of-bounds index"
) ? static_cast<void> (0) : __assert_fail ("ArrayIndex <= ArraySize && \"bounds check succeeded for out-of-bounds index\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 480, __PRETTY_FUNCTION__))
;
481
482 if (IsArray)
483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
484 else
485 IsOnePastTheEnd = (ArrayIndex != 0);
486 }
487 };
488
489 /// A stack frame in the constexpr call stack.
490 class CallStackFrame : public interp::Frame {
491 public:
492 EvalInfo &Info;
493
494 /// Parent - The caller of this stack frame.
495 CallStackFrame *Caller;
496
497 /// Callee - The function which was called.
498 const FunctionDecl *Callee;
499
500 /// This - The binding for the this pointer in this call, if any.
501 const LValue *This;
502
503 /// Arguments - Parameter bindings for this function call, indexed by
504 /// parameters' function scope indices.
505 APValue *Arguments;
506
507 /// Source location information about the default argument or default
508 /// initializer expression we're evaluating, if any.
509 CurrentSourceLocExprScope CurSourceLocExprScope;
510
511 // Note that we intentionally use std::map here so that references to
512 // values are stable.
513 typedef std::pair<const void *, unsigned> MapKeyTy;
514 typedef std::map<MapKeyTy, APValue> MapTy;
515 /// Temporaries - Temporary lvalues materialized within this stack frame.
516 MapTy Temporaries;
517
518 /// CallLoc - The location of the call expression for this call.
519 SourceLocation CallLoc;
520
521 /// Index - The call index of this call.
522 unsigned Index;
523
524 /// The stack of integers for tracking version numbers for temporaries.
525 SmallVector<unsigned, 2> TempVersionStack = {1};
526 unsigned CurTempVersion = TempVersionStack.back();
527
528 unsigned getTempVersion() const { return TempVersionStack.back(); }
529
530 void pushTempVersion() {
531 TempVersionStack.push_back(++CurTempVersion);
532 }
533
534 void popTempVersion() {
535 TempVersionStack.pop_back();
536 }
537
538 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
539 // on the overall stack usage of deeply-recursing constexpr evaluations.
540 // (We should cache this map rather than recomputing it repeatedly.)
541 // But let's try this and see how it goes; we can look into caching the map
542 // as a later change.
543
544 /// LambdaCaptureFields - Mapping from captured variables/this to
545 /// corresponding data members in the closure class.
546 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
547 FieldDecl *LambdaThisCaptureField;
548
549 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
550 const FunctionDecl *Callee, const LValue *This,
551 APValue *Arguments);
552 ~CallStackFrame();
553
554 // Return the temporary for Key whose version number is Version.
555 APValue *getTemporary(const void *Key, unsigned Version) {
556 MapKeyTy KV(Key, Version);
557 auto LB = Temporaries.lower_bound(KV);
558 if (LB != Temporaries.end() && LB->first == KV)
559 return &LB->second;
560 // Pair (Key,Version) wasn't found in the map. Check that no elements
561 // in the map have 'Key' as their key.
562 assert((LB == Temporaries.end() || LB->first.first != Key) &&(((LB == Temporaries.end() || LB->first.first != Key) &&
(LB == Temporaries.begin() || std::prev(LB)->first.first !=
Key) && "Element with key 'Key' found in map") ? static_cast
<void> (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 564, __PRETTY_FUNCTION__))
563 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&(((LB == Temporaries.end() || LB->first.first != Key) &&
(LB == Temporaries.begin() || std::prev(LB)->first.first !=
Key) && "Element with key 'Key' found in map") ? static_cast
<void> (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 564, __PRETTY_FUNCTION__))
564 "Element with key 'Key' found in map")(((LB == Temporaries.end() || LB->first.first != Key) &&
(LB == Temporaries.begin() || std::prev(LB)->first.first !=
Key) && "Element with key 'Key' found in map") ? static_cast
<void> (0) : __assert_fail ("(LB == Temporaries.end() || LB->first.first != Key) && (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && \"Element with key 'Key' found in map\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 564, __PRETTY_FUNCTION__))
;
565 return nullptr;
566 }
567
568 // Return the current temporary for Key in the map.
569 APValue *getCurrentTemporary(const void *Key) {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return &std::prev(UB)->second;
573 return nullptr;
574 }
575
576 // Return the version number of the current temporary for Key.
577 unsigned getCurrentTemporaryVersion(const void *Key) const {
578 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX(2147483647 *2U +1U)));
579 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
580 return std::prev(UB)->first.second;
581 return 0;
582 }
583
584 /// Allocate storage for an object of type T in this stack frame.
585 /// Populates LV with a handle to the created object. Key identifies
586 /// the temporary within the stack frame, and must not be reused without
587 /// bumping the temporary version number.
588 template<typename KeyT>
589 APValue &createTemporary(const KeyT *Key, QualType T,
590 bool IsLifetimeExtended, LValue &LV);
591
592 void describe(llvm::raw_ostream &OS) override;
593
594 Frame *getCaller() const override { return Caller; }
595 SourceLocation getCallLocation() const override { return CallLoc; }
596 const FunctionDecl *getCallee() const override { return Callee; }
597
598 bool isStdFunction() const {
599 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
600 if (DC->isStdNamespace())
601 return true;
602 return false;
603 }
604 };
605
606 /// Temporarily override 'this'.
607 class ThisOverrideRAII {
608 public:
609 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
610 : Frame(Frame), OldThis(Frame.This) {
611 if (Enable)
612 Frame.This = NewThis;
613 }
614 ~ThisOverrideRAII() {
615 Frame.This = OldThis;
616 }
617 private:
618 CallStackFrame &Frame;
619 const LValue *OldThis;
620 };
621}
622
623static bool HandleDestruction(EvalInfo &Info, const Expr *E,
624 const LValue &This, QualType ThisType);
625static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
626 APValue::LValueBase LVBase, APValue &Value,
627 QualType T);
628
629namespace {
630 /// A cleanup, and a flag indicating whether it is lifetime-extended.
631 class Cleanup {
632 llvm::PointerIntPair<APValue*, 1, bool> Value;
633 APValue::LValueBase Base;
634 QualType T;
635
636 public:
637 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
638 bool IsLifetimeExtended)
639 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
640
641 bool isLifetimeExtended() const { return Value.getInt(); }
642 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
643 if (RunDestructors) {
644 SourceLocation Loc;
645 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
646 Loc = VD->getLocation();
647 else if (const Expr *E = Base.dyn_cast<const Expr*>())
648 Loc = E->getExprLoc();
649 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
650 }
651 *Value.getPointer() = APValue();
652 return true;
653 }
654
655 bool hasSideEffect() {
656 return T.isDestructedType();
657 }
658 };
659
660 /// A reference to an object whose construction we are currently evaluating.
661 struct ObjectUnderConstruction {
662 APValue::LValueBase Base;
663 ArrayRef<APValue::LValuePathEntry> Path;
664 friend bool operator==(const ObjectUnderConstruction &LHS,
665 const ObjectUnderConstruction &RHS) {
666 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
667 }
668 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
669 return llvm::hash_combine(Obj.Base, Obj.Path);
670 }
671 };
672 enum class ConstructionPhase {
673 None,
674 Bases,
675 AfterBases,
676 Destroying,
677 DestroyingBases
678 };
679}
680
681namespace llvm {
682template<> struct DenseMapInfo<ObjectUnderConstruction> {
683 using Base = DenseMapInfo<APValue::LValueBase>;
684 static ObjectUnderConstruction getEmptyKey() {
685 return {Base::getEmptyKey(), {}}; }
686 static ObjectUnderConstruction getTombstoneKey() {
687 return {Base::getTombstoneKey(), {}};
688 }
689 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
690 return hash_value(Object);
691 }
692 static bool isEqual(const ObjectUnderConstruction &LHS,
693 const ObjectUnderConstruction &RHS) {
694 return LHS == RHS;
695 }
696};
697}
698
699namespace {
700 /// A dynamically-allocated heap object.
701 struct DynAlloc {
702 /// The value of this heap-allocated object.
703 APValue Value;
704 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
705 /// or a CallExpr (the latter is for direct calls to operator new inside
706 /// std::allocator<T>::allocate).
707 const Expr *AllocExpr = nullptr;
708
709 enum Kind {
710 New,
711 ArrayNew,
712 StdAllocator
713 };
714
715 /// Get the kind of the allocation. This must match between allocation
716 /// and deallocation.
717 Kind getKind() const {
718 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
719 return NE->isArray() ? ArrayNew : New;
720 assert(isa<CallExpr>(AllocExpr))((isa<CallExpr>(AllocExpr)) ? static_cast<void> (
0) : __assert_fail ("isa<CallExpr>(AllocExpr)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 720, __PRETTY_FUNCTION__))
;
721 return StdAllocator;
722 }
723 };
724
725 struct DynAllocOrder {
726 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
727 return L.getIndex() < R.getIndex();
728 }
729 };
730
731 /// EvalInfo - This is a private struct used by the evaluator to capture
732 /// information about a subexpression as it is folded. It retains information
733 /// about the AST context, but also maintains information about the folded
734 /// expression.
735 ///
736 /// If an expression could be evaluated, it is still possible it is not a C
737 /// "integer constant expression" or constant expression. If not, this struct
738 /// captures information about how and why not.
739 ///
740 /// One bit of information passed *into* the request for constant folding
741 /// indicates whether the subexpression is "evaluated" or not according to C
742 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
743 /// evaluate the expression regardless of what the RHS is, but C only allows
744 /// certain things in certain situations.
745 class EvalInfo : public interp::State {
746 public:
747 ASTContext &Ctx;
748
749 /// EvalStatus - Contains information about the evaluation.
750 Expr::EvalStatus &EvalStatus;
751
752 /// CurrentCall - The top of the constexpr call stack.
753 CallStackFrame *CurrentCall;
754
755 /// CallStackDepth - The number of calls in the call stack right now.
756 unsigned CallStackDepth;
757
758 /// NextCallIndex - The next call index to assign.
759 unsigned NextCallIndex;
760
761 /// StepsLeft - The remaining number of evaluation steps we're permitted
762 /// to perform. This is essentially a limit for the number of statements
763 /// we will evaluate.
764 unsigned StepsLeft;
765
766 /// Force the use of the experimental new constant interpreter, bailing out
767 /// with an error if a feature is not supported.
768 bool ForceNewConstInterp;
769
770 /// Enable the experimental new constant interpreter.
771 bool EnableNewConstInterp;
772
773 /// BottomFrame - The frame in which evaluation started. This must be
774 /// initialized after CurrentCall and CallStackDepth.
775 CallStackFrame BottomFrame;
776
777 /// A stack of values whose lifetimes end at the end of some surrounding
778 /// evaluation frame.
779 llvm::SmallVector<Cleanup, 16> CleanupStack;
780
781 /// EvaluatingDecl - This is the declaration whose initializer is being
782 /// evaluated, if any.
783 APValue::LValueBase EvaluatingDecl;
784
785 enum class EvaluatingDeclKind {
786 None,
787 /// We're evaluating the construction of EvaluatingDecl.
788 Ctor,
789 /// We're evaluating the destruction of EvaluatingDecl.
790 Dtor,
791 };
792 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
793
794 /// EvaluatingDeclValue - This is the value being constructed for the
795 /// declaration whose initializer is being evaluated, if any.
796 APValue *EvaluatingDeclValue;
797
798 /// Set of objects that are currently being constructed.
799 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
800 ObjectsUnderConstruction;
801
802 /// Current heap allocations, along with the location where each was
803 /// allocated. We use std::map here because we need stable addresses
804 /// for the stored APValues.
805 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
806
807 /// The number of heap allocations performed so far in this evaluation.
808 unsigned NumHeapAllocs = 0;
809
810 struct EvaluatingConstructorRAII {
811 EvalInfo &EI;
812 ObjectUnderConstruction Object;
813 bool DidInsert;
814 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
815 bool HasBases)
816 : EI(EI), Object(Object) {
817 DidInsert =
818 EI.ObjectsUnderConstruction
819 .insert({Object, HasBases ? ConstructionPhase::Bases
820 : ConstructionPhase::AfterBases})
821 .second;
822 }
823 void finishedConstructingBases() {
824 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
825 }
826 ~EvaluatingConstructorRAII() {
827 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
828 }
829 };
830
831 struct EvaluatingDestructorRAII {
832 EvalInfo &EI;
833 ObjectUnderConstruction Object;
834 bool DidInsert;
835 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
836 : EI(EI), Object(Object) {
837 DidInsert = EI.ObjectsUnderConstruction
838 .insert({Object, ConstructionPhase::Destroying})
839 .second;
840 }
841 void startedDestroyingBases() {
842 EI.ObjectsUnderConstruction[Object] =
843 ConstructionPhase::DestroyingBases;
844 }
845 ~EvaluatingDestructorRAII() {
846 if (DidInsert)
847 EI.ObjectsUnderConstruction.erase(Object);
848 }
849 };
850
851 ConstructionPhase
852 isEvaluatingCtorDtor(APValue::LValueBase Base,
853 ArrayRef<APValue::LValuePathEntry> Path) {
854 return ObjectsUnderConstruction.lookup({Base, Path});
855 }
856
857 /// If we're currently speculatively evaluating, the outermost call stack
858 /// depth at which we can mutate state, otherwise 0.
859 unsigned SpeculativeEvaluationDepth = 0;
860
861 /// The current array initialization index, if we're performing array
862 /// initialization.
863 uint64_t ArrayInitIndex = -1;
864
865 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
866 /// notes attached to it will also be stored, otherwise they will not be.
867 bool HasActiveDiagnostic;
868
869 /// Have we emitted a diagnostic explaining why we couldn't constant
870 /// fold (not just why it's not strictly a constant expression)?
871 bool HasFoldFailureDiagnostic;
872
873 /// Whether or not we're in a context where the front end requires a
874 /// constant value.
875 bool InConstantContext;
876
877 /// Whether we're checking that an expression is a potential constant
878 /// expression. If so, do not fail on constructs that could become constant
879 /// later on (such as a use of an undefined global).
880 bool CheckingPotentialConstantExpression = false;
881
882 /// Whether we're checking for an expression that has undefined behavior.
883 /// If so, we will produce warnings if we encounter an operation that is
884 /// always undefined.
885 bool CheckingForUndefinedBehavior = false;
886
887 enum EvaluationMode {
888 /// Evaluate as a constant expression. Stop if we find that the expression
889 /// is not a constant expression.
890 EM_ConstantExpression,
891
892 /// Evaluate as a constant expression. Stop if we find that the expression
893 /// is not a constant expression. Some expressions can be retried in the
894 /// optimizer if we don't constant fold them here, but in an unevaluated
895 /// context we try to fold them immediately since the optimizer never
896 /// gets a chance to look at it.
897 EM_ConstantExpressionUnevaluated,
898
899 /// Fold the expression to a constant. Stop if we hit a side-effect that
900 /// we can't model.
901 EM_ConstantFold,
902
903 /// Evaluate in any way we know how. Don't worry about side-effects that
904 /// can't be modeled.
905 EM_IgnoreSideEffects,
906 } EvalMode;
907
908 /// Are we checking whether the expression is a potential constant
909 /// expression?
910 bool checkingPotentialConstantExpression() const override {
911 return CheckingPotentialConstantExpression;
912 }
913
914 /// Are we checking an expression for overflow?
915 // FIXME: We should check for any kind of undefined or suspicious behavior
916 // in such constructs, not just overflow.
917 bool checkingForUndefinedBehavior() const override {
918 return CheckingForUndefinedBehavior;
919 }
920
921 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
922 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
923 CallStackDepth(0), NextCallIndex(1),
924 StepsLeft(getLangOpts().ConstexprStepLimit),
925 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
926 EnableNewConstInterp(ForceNewConstInterp ||
927 getLangOpts().EnableNewConstInterp),
928 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
929 EvaluatingDecl((const ValueDecl *)nullptr),
930 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
931 HasFoldFailureDiagnostic(false), InConstantContext(false),
932 EvalMode(Mode) {}
933
934 ~EvalInfo() {
935 discardCleanups();
936 }
937
938 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
939 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
940 EvaluatingDecl = Base;
941 IsEvaluatingDecl = EDK;
942 EvaluatingDeclValue = &Value;
943 }
944
945 bool CheckCallLimit(SourceLocation Loc) {
946 // Don't perform any constexpr calls (other than the call we're checking)
947 // when checking a potential constant expression.
948 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
37
Assuming the condition is false
949 return false;
950 if (NextCallIndex == 0) {
38
Assuming field 'NextCallIndex' is not equal to 0
39
Taking false branch
951 // NextCallIndex has wrapped around.
952 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
953 return false;
954 }
955 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
40
Assuming field 'CallStackDepth' is <= field 'ConstexprCallDepth'
41
Taking true branch
956 return true;
42
Returning the value 1, which participates in a condition later
957 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
958 << getLangOpts().ConstexprCallDepth;
959 return false;
960 }
961
962 std::pair<CallStackFrame *, unsigned>
963 getCallFrameAndDepth(unsigned CallIndex) {
964 assert(CallIndex && "no call index in getCallFrameAndDepth")((CallIndex && "no call index in getCallFrameAndDepth"
) ? static_cast<void> (0) : __assert_fail ("CallIndex && \"no call index in getCallFrameAndDepth\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 964, __PRETTY_FUNCTION__))
;
965 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
966 // be null in this loop.
967 unsigned Depth = CallStackDepth;
968 CallStackFrame *Frame = CurrentCall;
969 while (Frame->Index > CallIndex) {
970 Frame = Frame->Caller;
971 --Depth;
972 }
973 if (Frame->Index == CallIndex)
974 return {Frame, Depth};
975 return {nullptr, 0};
976 }
977
978 bool nextStep(const Stmt *S) {
979 if (!StepsLeft) {
980 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
981 return false;
982 }
983 --StepsLeft;
984 return true;
985 }
986
987 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
988
989 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
990 Optional<DynAlloc*> Result;
991 auto It = HeapAllocs.find(DA);
992 if (It != HeapAllocs.end())
993 Result = &It->second;
994 return Result;
995 }
996
997 /// Information about a stack frame for std::allocator<T>::[de]allocate.
998 struct StdAllocatorCaller {
999 unsigned FrameIndex;
1000 QualType ElemType;
1001 explicit operator bool() const { return FrameIndex != 0; };
1002 };
1003
1004 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1005 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1006 Call = Call->Caller) {
1007 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1008 if (!MD)
1009 continue;
1010 const IdentifierInfo *FnII = MD->getIdentifier();
1011 if (!FnII || !FnII->isStr(FnName))
1012 continue;
1013
1014 const auto *CTSD =
1015 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1016 if (!CTSD)
1017 continue;
1018
1019 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1020 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1021 if (CTSD->isInStdNamespace() && ClassII &&
1022 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1023 TAL[0].getKind() == TemplateArgument::Type)
1024 return {Call->Index, TAL[0].getAsType()};
1025 }
1026
1027 return {};
1028 }
1029
1030 void performLifetimeExtension() {
1031 // Disable the cleanups for lifetime-extended temporaries.
1032 CleanupStack.erase(
1033 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1034 [](Cleanup &C) { return C.isLifetimeExtended(); }),
1035 CleanupStack.end());
1036 }
1037
1038 /// Throw away any remaining cleanups at the end of evaluation. If any
1039 /// cleanups would have had a side-effect, note that as an unmodeled
1040 /// side-effect and return false. Otherwise, return true.
1041 bool discardCleanups() {
1042 for (Cleanup &C : CleanupStack) {
1043 if (C.hasSideEffect() && !noteSideEffect()) {
1044 CleanupStack.clear();
1045 return false;
1046 }
1047 }
1048 CleanupStack.clear();
1049 return true;
1050 }
1051
1052 private:
1053 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1054 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1055
1056 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1057 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1058
1059 void setFoldFailureDiagnostic(bool Flag) override {
1060 HasFoldFailureDiagnostic = Flag;
1061 }
1062
1063 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1064
1065 ASTContext &getCtx() const override { return Ctx; }
1066
1067 // If we have a prior diagnostic, it will be noting that the expression
1068 // isn't a constant expression. This diagnostic is more important,
1069 // unless we require this evaluation to produce a constant expression.
1070 //
1071 // FIXME: We might want to show both diagnostics to the user in
1072 // EM_ConstantFold mode.
1073 bool hasPriorDiagnostic() override {
1074 if (!EvalStatus.Diag->empty()) {
1075 switch (EvalMode) {
1076 case EM_ConstantFold:
1077 case EM_IgnoreSideEffects:
1078 if (!HasFoldFailureDiagnostic)
1079 break;
1080 // We've already failed to fold something. Keep that diagnostic.
1081 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1082 case EM_ConstantExpression:
1083 case EM_ConstantExpressionUnevaluated:
1084 setActiveDiagnostic(false);
1085 return true;
1086 }
1087 }
1088 return false;
1089 }
1090
1091 unsigned getCallStackDepth() override { return CallStackDepth; }
1092
1093 public:
1094 /// Should we continue evaluation after encountering a side-effect that we
1095 /// couldn't model?
1096 bool keepEvaluatingAfterSideEffect() {
1097 switch (EvalMode) {
1098 case EM_IgnoreSideEffects:
1099 return true;
1100
1101 case EM_ConstantExpression:
1102 case EM_ConstantExpressionUnevaluated:
1103 case EM_ConstantFold:
1104 // By default, assume any side effect might be valid in some other
1105 // evaluation of this expression from a different context.
1106 return checkingPotentialConstantExpression() ||
1107 checkingForUndefinedBehavior();
1108 }
1109 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1109)
;
1110 }
1111
1112 /// Note that we have had a side-effect, and determine whether we should
1113 /// keep evaluating.
1114 bool noteSideEffect() {
1115 EvalStatus.HasSideEffects = true;
1116 return keepEvaluatingAfterSideEffect();
1117 }
1118
1119 /// Should we continue evaluation after encountering undefined behavior?
1120 bool keepEvaluatingAfterUndefinedBehavior() {
1121 switch (EvalMode) {
1122 case EM_IgnoreSideEffects:
1123 case EM_ConstantFold:
1124 return true;
1125
1126 case EM_ConstantExpression:
1127 case EM_ConstantExpressionUnevaluated:
1128 return checkingForUndefinedBehavior();
1129 }
1130 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1130)
;
1131 }
1132
1133 /// Note that we hit something that was technically undefined behavior, but
1134 /// that we can evaluate past it (such as signed overflow or floating-point
1135 /// division by zero.)
1136 bool noteUndefinedBehavior() override {
1137 EvalStatus.HasUndefinedBehavior = true;
1138 return keepEvaluatingAfterUndefinedBehavior();
1139 }
1140
1141 /// Should we continue evaluation as much as possible after encountering a
1142 /// construct which can't be reduced to a value?
1143 bool keepEvaluatingAfterFailure() const override {
1144 if (!StepsLeft)
1145 return false;
1146
1147 switch (EvalMode) {
1148 case EM_ConstantExpression:
1149 case EM_ConstantExpressionUnevaluated:
1150 case EM_ConstantFold:
1151 case EM_IgnoreSideEffects:
1152 return checkingPotentialConstantExpression() ||
1153 checkingForUndefinedBehavior();
1154 }
1155 llvm_unreachable("Missed EvalMode case")::llvm::llvm_unreachable_internal("Missed EvalMode case", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1155)
;
1156 }
1157
1158 /// Notes that we failed to evaluate an expression that other expressions
1159 /// directly depend on, and determine if we should keep evaluating. This
1160 /// should only be called if we actually intend to keep evaluating.
1161 ///
1162 /// Call noteSideEffect() instead if we may be able to ignore the value that
1163 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1164 ///
1165 /// (Foo(), 1) // use noteSideEffect
1166 /// (Foo() || true) // use noteSideEffect
1167 /// Foo() + 1 // use noteFailure
1168 LLVM_NODISCARD[[clang::warn_unused_result]] bool noteFailure() {
1169 // Failure when evaluating some expression often means there is some
1170 // subexpression whose evaluation was skipped. Therefore, (because we
1171 // don't track whether we skipped an expression when unwinding after an
1172 // evaluation failure) every evaluation failure that bubbles up from a
1173 // subexpression implies that a side-effect has potentially happened. We
1174 // skip setting the HasSideEffects flag to true until we decide to
1175 // continue evaluating after that point, which happens here.
1176 bool KeepGoing = keepEvaluatingAfterFailure();
1177 EvalStatus.HasSideEffects |= KeepGoing;
1178 return KeepGoing;
1179 }
1180
1181 class ArrayInitLoopIndex {
1182 EvalInfo &Info;
1183 uint64_t OuterIndex;
1184
1185 public:
1186 ArrayInitLoopIndex(EvalInfo &Info)
1187 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1188 Info.ArrayInitIndex = 0;
1189 }
1190 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1191
1192 operator uint64_t&() { return Info.ArrayInitIndex; }
1193 };
1194 };
1195
1196 /// Object used to treat all foldable expressions as constant expressions.
1197 struct FoldConstant {
1198 EvalInfo &Info;
1199 bool Enabled;
1200 bool HadNoPriorDiags;
1201 EvalInfo::EvaluationMode OldMode;
1202
1203 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1204 : Info(Info),
1205 Enabled(Enabled),
1206 HadNoPriorDiags(Info.EvalStatus.Diag &&
1207 Info.EvalStatus.Diag->empty() &&
1208 !Info.EvalStatus.HasSideEffects),
1209 OldMode(Info.EvalMode) {
1210 if (Enabled)
1211 Info.EvalMode = EvalInfo::EM_ConstantFold;
1212 }
1213 void keepDiagnostics() { Enabled = false; }
1214 ~FoldConstant() {
1215 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1216 !Info.EvalStatus.HasSideEffects)
1217 Info.EvalStatus.Diag->clear();
1218 Info.EvalMode = OldMode;
1219 }
1220 };
1221
1222 /// RAII object used to set the current evaluation mode to ignore
1223 /// side-effects.
1224 struct IgnoreSideEffectsRAII {
1225 EvalInfo &Info;
1226 EvalInfo::EvaluationMode OldMode;
1227 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1228 : Info(Info), OldMode(Info.EvalMode) {
1229 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1230 }
1231
1232 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1233 };
1234
1235 /// RAII object used to optionally suppress diagnostics and side-effects from
1236 /// a speculative evaluation.
1237 class SpeculativeEvaluationRAII {
1238 EvalInfo *Info = nullptr;
1239 Expr::EvalStatus OldStatus;
1240 unsigned OldSpeculativeEvaluationDepth;
1241
1242 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1243 Info = Other.Info;
1244 OldStatus = Other.OldStatus;
1245 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1246 Other.Info = nullptr;
1247 }
1248
1249 void maybeRestoreState() {
1250 if (!Info)
1251 return;
1252
1253 Info->EvalStatus = OldStatus;
1254 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1255 }
1256
1257 public:
1258 SpeculativeEvaluationRAII() = default;
1259
1260 SpeculativeEvaluationRAII(
1261 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1262 : Info(&Info), OldStatus(Info.EvalStatus),
1263 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1264 Info.EvalStatus.Diag = NewDiag;
1265 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1266 }
1267
1268 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1269 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1270 moveFromAndCancel(std::move(Other));
1271 }
1272
1273 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1274 maybeRestoreState();
1275 moveFromAndCancel(std::move(Other));
1276 return *this;
1277 }
1278
1279 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1280 };
1281
1282 /// RAII object wrapping a full-expression or block scope, and handling
1283 /// the ending of the lifetime of temporaries created within it.
1284 template<bool IsFullExpression>
1285 class ScopeRAII {
1286 EvalInfo &Info;
1287 unsigned OldStackSize;
1288 public:
1289 ScopeRAII(EvalInfo &Info)
1290 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1291 // Push a new temporary version. This is needed to distinguish between
1292 // temporaries created in different iterations of a loop.
1293 Info.CurrentCall->pushTempVersion();
1294 }
1295 bool destroy(bool RunDestructors = true) {
1296 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1297 OldStackSize = -1U;
1298 return OK;
1299 }
1300 ~ScopeRAII() {
1301 if (OldStackSize != -1U)
1302 destroy(false);
1303 // Body moved to a static method to encourage the compiler to inline away
1304 // instances of this class.
1305 Info.CurrentCall->popTempVersion();
1306 }
1307 private:
1308 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1309 unsigned OldStackSize) {
1310 assert(OldStackSize <= Info.CleanupStack.size() &&((OldStackSize <= Info.CleanupStack.size() && "running cleanups out of order?"
) ? static_cast<void> (0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1311, __PRETTY_FUNCTION__))
1311 "running cleanups out of order?")((OldStackSize <= Info.CleanupStack.size() && "running cleanups out of order?"
) ? static_cast<void> (0) : __assert_fail ("OldStackSize <= Info.CleanupStack.size() && \"running cleanups out of order?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1311, __PRETTY_FUNCTION__))
;
1312
1313 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1314 // for a full-expression scope.
1315 bool Success = true;
1316 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1317 if (!(IsFullExpression &&
1318 Info.CleanupStack[I - 1].isLifetimeExtended())) {
1319 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1320 Success = false;
1321 break;
1322 }
1323 }
1324 }
1325
1326 // Compact lifetime-extended cleanups.
1327 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1328 if (IsFullExpression)
1329 NewEnd =
1330 std::remove_if(NewEnd, Info.CleanupStack.end(),
1331 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1332 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1333 return Success;
1334 }
1335 };
1336 typedef ScopeRAII<false> BlockScopeRAII;
1337 typedef ScopeRAII<true> FullExpressionRAII;
1338}
1339
1340bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1341 CheckSubobjectKind CSK) {
1342 if (Invalid)
1343 return false;
1344 if (isOnePastTheEnd()) {
1345 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1346 << CSK;
1347 setInvalid();
1348 return false;
1349 }
1350 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1351 // must actually be at least one array element; even a VLA cannot have a
1352 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1353 return true;
1354}
1355
1356void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1357 const Expr *E) {
1358 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1359 // Do not set the designator as invalid: we can represent this situation,
1360 // and correct handling of __builtin_object_size requires us to do so.
1361}
1362
1363void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1364 const Expr *E,
1365 const APSInt &N) {
1366 // If we're complaining, we must be able to statically determine the size of
1367 // the most derived array.
1368 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1369 Info.CCEDiag(E, diag::note_constexpr_array_index)
1370 << N << /*array*/ 0
1371 << static_cast<unsigned>(getMostDerivedArraySize());
1372 else
1373 Info.CCEDiag(E, diag::note_constexpr_array_index)
1374 << N << /*non-array*/ 1;
1375 setInvalid();
1376}
1377
1378CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1379 const FunctionDecl *Callee, const LValue *This,
1380 APValue *Arguments)
1381 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1382 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1383 Info.CurrentCall = this;
1384 ++Info.CallStackDepth;
1385}
1386
1387CallStackFrame::~CallStackFrame() {
1388 assert(Info.CurrentCall == this && "calls retired out of order")((Info.CurrentCall == this && "calls retired out of order"
) ? static_cast<void> (0) : __assert_fail ("Info.CurrentCall == this && \"calls retired out of order\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1388, __PRETTY_FUNCTION__))
;
1389 --Info.CallStackDepth;
1390 Info.CurrentCall = Caller;
1391}
1392
1393static bool isRead(AccessKinds AK) {
1394 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1395}
1396
1397static bool isModification(AccessKinds AK) {
1398 switch (AK) {
1399 case AK_Read:
1400 case AK_ReadObjectRepresentation:
1401 case AK_MemberCall:
1402 case AK_DynamicCast:
1403 case AK_TypeId:
1404 return false;
1405 case AK_Assign:
1406 case AK_Increment:
1407 case AK_Decrement:
1408 case AK_Construct:
1409 case AK_Destroy:
1410 return true;
1411 }
1412 llvm_unreachable("unknown access kind")::llvm::llvm_unreachable_internal("unknown access kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1412)
;
1413}
1414
1415static bool isAnyAccess(AccessKinds AK) {
1416 return isRead(AK) || isModification(AK);
1417}
1418
1419/// Is this an access per the C++ definition?
1420static bool isFormalAccess(AccessKinds AK) {
1421 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1422}
1423
1424namespace {
1425 struct ComplexValue {
1426 private:
1427 bool IsInt;
1428
1429 public:
1430 APSInt IntReal, IntImag;
1431 APFloat FloatReal, FloatImag;
1432
1433 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1434
1435 void makeComplexFloat() { IsInt = false; }
1436 bool isComplexFloat() const { return !IsInt; }
1437 APFloat &getComplexFloatReal() { return FloatReal; }
1438 APFloat &getComplexFloatImag() { return FloatImag; }
1439
1440 void makeComplexInt() { IsInt = true; }
1441 bool isComplexInt() const { return IsInt; }
1442 APSInt &getComplexIntReal() { return IntReal; }
1443 APSInt &getComplexIntImag() { return IntImag; }
1444
1445 void moveInto(APValue &v) const {
1446 if (isComplexFloat())
1447 v = APValue(FloatReal, FloatImag);
1448 else
1449 v = APValue(IntReal, IntImag);
1450 }
1451 void setFrom(const APValue &v) {
1452 assert(v.isComplexFloat() || v.isComplexInt())((v.isComplexFloat() || v.isComplexInt()) ? static_cast<void
> (0) : __assert_fail ("v.isComplexFloat() || v.isComplexInt()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1452, __PRETTY_FUNCTION__))
;
1453 if (v.isComplexFloat()) {
1454 makeComplexFloat();
1455 FloatReal = v.getComplexFloatReal();
1456 FloatImag = v.getComplexFloatImag();
1457 } else {
1458 makeComplexInt();
1459 IntReal = v.getComplexIntReal();
1460 IntImag = v.getComplexIntImag();
1461 }
1462 }
1463 };
1464
1465 struct LValue {
1466 APValue::LValueBase Base;
1467 CharUnits Offset;
1468 SubobjectDesignator Designator;
1469 bool IsNullPtr : 1;
1470 bool InvalidBase : 1;
1471
1472 const APValue::LValueBase getLValueBase() const { return Base; }
1473 CharUnits &getLValueOffset() { return Offset; }
1474 const CharUnits &getLValueOffset() const { return Offset; }
1475 SubobjectDesignator &getLValueDesignator() { return Designator; }
1476 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1477 bool isNullPointer() const { return IsNullPtr;}
1478
1479 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1480 unsigned getLValueVersion() const { return Base.getVersion(); }
1481
1482 void moveInto(APValue &V) const {
1483 if (Designator.Invalid)
1484 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1485 else {
1486 assert(!InvalidBase && "APValues can't handle invalid LValue bases")((!InvalidBase && "APValues can't handle invalid LValue bases"
) ? static_cast<void> (0) : __assert_fail ("!InvalidBase && \"APValues can't handle invalid LValue bases\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1486, __PRETTY_FUNCTION__))
;
1487 V = APValue(Base, Offset, Designator.Entries,
1488 Designator.IsOnePastTheEnd, IsNullPtr);
1489 }
1490 }
1491 void setFrom(ASTContext &Ctx, const APValue &V) {
1492 assert(V.isLValue() && "Setting LValue from a non-LValue?")((V.isLValue() && "Setting LValue from a non-LValue?"
) ? static_cast<void> (0) : __assert_fail ("V.isLValue() && \"Setting LValue from a non-LValue?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1492, __PRETTY_FUNCTION__))
;
1493 Base = V.getLValueBase();
1494 Offset = V.getLValueOffset();
1495 InvalidBase = false;
1496 Designator = SubobjectDesignator(Ctx, V);
1497 IsNullPtr = V.isNullPointer();
1498 }
1499
1500 void set(APValue::LValueBase B, bool BInvalid = false) {
1501#ifndef NDEBUG
1502 // We only allow a few types of invalid bases. Enforce that here.
1503 if (BInvalid) {
1504 const auto *E = B.get<const Expr *>();
1505 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
"Unexpected type of invalid base") ? static_cast<void>
(0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1506, __PRETTY_FUNCTION__))
1506 "Unexpected type of invalid base")(((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
"Unexpected type of invalid base") ? static_cast<void>
(0) : __assert_fail ("(isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && \"Unexpected type of invalid base\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1506, __PRETTY_FUNCTION__))
;
1507 }
1508#endif
1509
1510 Base = B;
1511 Offset = CharUnits::fromQuantity(0);
1512 InvalidBase = BInvalid;
1513 Designator = SubobjectDesignator(getType(B));
1514 IsNullPtr = false;
1515 }
1516
1517 void setNull(ASTContext &Ctx, QualType PointerTy) {
1518 Base = (Expr *)nullptr;
1519 Offset =
1520 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1521 InvalidBase = false;
1522 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1523 IsNullPtr = true;
1524 }
1525
1526 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1527 set(B, true);
1528 }
1529
1530 std::string toString(ASTContext &Ctx, QualType T) const {
1531 APValue Printable;
1532 moveInto(Printable);
1533 return Printable.getAsString(Ctx, T);
1534 }
1535
1536 private:
1537 // Check that this LValue is not based on a null pointer. If it is, produce
1538 // a diagnostic and mark the designator as invalid.
1539 template <typename GenDiagType>
1540 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1541 if (Designator.Invalid)
1542 return false;
1543 if (IsNullPtr) {
1544 GenDiag();
1545 Designator.setInvalid();
1546 return false;
1547 }
1548 return true;
1549 }
1550
1551 public:
1552 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1553 CheckSubobjectKind CSK) {
1554 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1555 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1556 });
1557 }
1558
1559 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1560 AccessKinds AK) {
1561 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1562 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1563 });
1564 }
1565
1566 // Check this LValue refers to an object. If not, set the designator to be
1567 // invalid and emit a diagnostic.
1568 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1569 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1570 Designator.checkSubobject(Info, E, CSK);
1571 }
1572
1573 void addDecl(EvalInfo &Info, const Expr *E,
1574 const Decl *D, bool Virtual = false) {
1575 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1576 Designator.addDeclUnchecked(D, Virtual);
1577 }
1578 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1579 if (!Designator.Entries.empty()) {
1580 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1581 Designator.setInvalid();
1582 return;
1583 }
1584 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1585 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType())((getType(Base)->isPointerType() || getType(Base)->isArrayType
()) ? static_cast<void> (0) : __assert_fail ("getType(Base)->isPointerType() || getType(Base)->isArrayType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1585, __PRETTY_FUNCTION__))
;
1586 Designator.FirstEntryIsAnUnsizedArray = true;
1587 Designator.addUnsizedArrayUnchecked(ElemTy);
1588 }
1589 }
1590 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1591 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1592 Designator.addArrayUnchecked(CAT);
1593 }
1594 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1595 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1596 Designator.addComplexUnchecked(EltTy, Imag);
1597 }
1598 void clearIsNullPointer() {
1599 IsNullPtr = false;
1600 }
1601 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1602 const APSInt &Index, CharUnits ElementSize) {
1603 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1604 // but we're not required to diagnose it and it's valid in C++.)
1605 if (!Index)
1606 return;
1607
1608 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1609 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1610 // offsets.
1611 uint64_t Offset64 = Offset.getQuantity();
1612 uint64_t ElemSize64 = ElementSize.getQuantity();
1613 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1614 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1615
1616 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1617 Designator.adjustIndex(Info, E, Index);
1618 clearIsNullPointer();
1619 }
1620 void adjustOffset(CharUnits N) {
1621 Offset += N;
1622 if (N.getQuantity())
1623 clearIsNullPointer();
1624 }
1625 };
1626
1627 struct MemberPtr {
1628 MemberPtr() {}
1629 explicit MemberPtr(const ValueDecl *Decl) :
1630 DeclAndIsDerivedMember(Decl, false), Path() {}
1631
1632 /// The member or (direct or indirect) field referred to by this member
1633 /// pointer, or 0 if this is a null member pointer.
1634 const ValueDecl *getDecl() const {
1635 return DeclAndIsDerivedMember.getPointer();
1636 }
1637 /// Is this actually a member of some type derived from the relevant class?
1638 bool isDerivedMember() const {
1639 return DeclAndIsDerivedMember.getInt();
1640 }
1641 /// Get the class which the declaration actually lives in.
1642 const CXXRecordDecl *getContainingRecord() const {
1643 return cast<CXXRecordDecl>(
1644 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1645 }
1646
1647 void moveInto(APValue &V) const {
1648 V = APValue(getDecl(), isDerivedMember(), Path);
1649 }
1650 void setFrom(const APValue &V) {
1651 assert(V.isMemberPointer())((V.isMemberPointer()) ? static_cast<void> (0) : __assert_fail
("V.isMemberPointer()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1651, __PRETTY_FUNCTION__))
;
1652 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1653 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1654 Path.clear();
1655 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1656 Path.insert(Path.end(), P.begin(), P.end());
1657 }
1658
1659 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1660 /// whether the member is a member of some class derived from the class type
1661 /// of the member pointer.
1662 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1663 /// Path - The path of base/derived classes from the member declaration's
1664 /// class (exclusive) to the class type of the member pointer (inclusive).
1665 SmallVector<const CXXRecordDecl*, 4> Path;
1666
1667 /// Perform a cast towards the class of the Decl (either up or down the
1668 /// hierarchy).
1669 bool castBack(const CXXRecordDecl *Class) {
1670 assert(!Path.empty())((!Path.empty()) ? static_cast<void> (0) : __assert_fail
("!Path.empty()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1670, __PRETTY_FUNCTION__))
;
1671 const CXXRecordDecl *Expected;
1672 if (Path.size() >= 2)
1673 Expected = Path[Path.size() - 2];
1674 else
1675 Expected = getContainingRecord();
1676 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1677 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1678 // if B does not contain the original member and is not a base or
1679 // derived class of the class containing the original member, the result
1680 // of the cast is undefined.
1681 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1682 // (D::*). We consider that to be a language defect.
1683 return false;
1684 }
1685 Path.pop_back();
1686 return true;
1687 }
1688 /// Perform a base-to-derived member pointer cast.
1689 bool castToDerived(const CXXRecordDecl *Derived) {
1690 if (!getDecl())
1691 return true;
1692 if (!isDerivedMember()) {
1693 Path.push_back(Derived);
1694 return true;
1695 }
1696 if (!castBack(Derived))
1697 return false;
1698 if (Path.empty())
1699 DeclAndIsDerivedMember.setInt(false);
1700 return true;
1701 }
1702 /// Perform a derived-to-base member pointer cast.
1703 bool castToBase(const CXXRecordDecl *Base) {
1704 if (!getDecl())
1705 return true;
1706 if (Path.empty())
1707 DeclAndIsDerivedMember.setInt(true);
1708 if (isDerivedMember()) {
1709 Path.push_back(Base);
1710 return true;
1711 }
1712 return castBack(Base);
1713 }
1714 };
1715
1716 /// Compare two member pointers, which are assumed to be of the same type.
1717 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1718 if (!LHS.getDecl() || !RHS.getDecl())
1719 return !LHS.getDecl() && !RHS.getDecl();
1720 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1721 return false;
1722 return LHS.Path == RHS.Path;
1723 }
1724}
1725
1726static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1727static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1728 const LValue &This, const Expr *E,
1729 bool AllowNonLiteralTypes = false);
1730static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1731 bool InvalidBaseOK = false);
1732static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1733 bool InvalidBaseOK = false);
1734static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1735 EvalInfo &Info);
1736static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1737static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1738static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1739 EvalInfo &Info);
1740static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1741static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1742static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1743 EvalInfo &Info);
1744static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1745
1746/// Evaluate an integer or fixed point expression into an APResult.
1747static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1748 EvalInfo &Info);
1749
1750/// Evaluate only a fixed point expression into an APResult.
1751static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1752 EvalInfo &Info);
1753
1754//===----------------------------------------------------------------------===//
1755// Misc utilities
1756//===----------------------------------------------------------------------===//
1757
1758/// Negate an APSInt in place, converting it to a signed form if necessary, and
1759/// preserving its value (by extending by up to one bit as needed).
1760static void negateAsSigned(APSInt &Int) {
1761 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1762 Int = Int.extend(Int.getBitWidth() + 1);
1763 Int.setIsSigned(true);
1764 }
1765 Int = -Int;
1766}
1767
1768template<typename KeyT>
1769APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1770 bool IsLifetimeExtended, LValue &LV) {
1771 unsigned Version = getTempVersion();
1772 APValue::LValueBase Base(Key, Index, Version);
1773 LV.set(Base);
1774 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1775 assert(Result.isAbsent() && "temporary created multiple times")((Result.isAbsent() && "temporary created multiple times"
) ? static_cast<void> (0) : __assert_fail ("Result.isAbsent() && \"temporary created multiple times\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1775, __PRETTY_FUNCTION__))
;
1776
1777 // If we're creating a temporary immediately in the operand of a speculative
1778 // evaluation, don't register a cleanup to be run outside the speculative
1779 // evaluation context, since we won't actually be able to initialize this
1780 // object.
1781 if (Index <= Info.SpeculativeEvaluationDepth) {
1782 if (T.isDestructedType())
1783 Info.noteSideEffect();
1784 } else {
1785 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1786 }
1787 return Result;
1788}
1789
1790APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1791 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1792 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1793 return nullptr;
1794 }
1795
1796 DynamicAllocLValue DA(NumHeapAllocs++);
1797 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1798 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1799 std::forward_as_tuple(DA), std::tuple<>());
1800 assert(Result.second && "reused a heap alloc index?")((Result.second && "reused a heap alloc index?") ? static_cast
<void> (0) : __assert_fail ("Result.second && \"reused a heap alloc index?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1800, __PRETTY_FUNCTION__))
;
1801 Result.first->second.AllocExpr = E;
1802 return &Result.first->second.Value;
1803}
1804
1805/// Produce a string describing the given constexpr call.
1806void CallStackFrame::describe(raw_ostream &Out) {
1807 unsigned ArgIndex = 0;
1808 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1809 !isa<CXXConstructorDecl>(Callee) &&
1810 cast<CXXMethodDecl>(Callee)->isInstance();
1811
1812 if (!IsMemberCall)
1813 Out << *Callee << '(';
1814
1815 if (This && IsMemberCall) {
1816 APValue Val;
1817 This->moveInto(Val);
1818 Val.printPretty(Out, Info.Ctx,
1819 This->Designator.MostDerivedType);
1820 // FIXME: Add parens around Val if needed.
1821 Out << "->" << *Callee << '(';
1822 IsMemberCall = false;
1823 }
1824
1825 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1826 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1827 if (ArgIndex > (unsigned)IsMemberCall)
1828 Out << ", ";
1829
1830 const ParmVarDecl *Param = *I;
1831 const APValue &Arg = Arguments[ArgIndex];
1832 Arg.printPretty(Out, Info.Ctx, Param->getType());
1833
1834 if (ArgIndex == 0 && IsMemberCall)
1835 Out << "->" << *Callee << '(';
1836 }
1837
1838 Out << ')';
1839}
1840
1841/// Evaluate an expression to see if it had side-effects, and discard its
1842/// result.
1843/// \return \c true if the caller should keep evaluating.
1844static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1845 APValue Scratch;
1846 if (!Evaluate(Scratch, Info, E))
1847 // We don't need the value, but we might have skipped a side effect here.
1848 return Info.noteSideEffect();
1849 return true;
1850}
1851
1852/// Should this call expression be treated as a string literal?
1853static bool IsStringLiteralCall(const CallExpr *E) {
1854 unsigned Builtin = E->getBuiltinCallee();
1855 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1856 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1857}
1858
1859static bool IsGlobalLValue(APValue::LValueBase B) {
1860 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1861 // constant expression of pointer type that evaluates to...
1862
1863 // ... a null pointer value, or a prvalue core constant expression of type
1864 // std::nullptr_t.
1865 if (!B) return true;
1866
1867 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1868 // ... the address of an object with static storage duration,
1869 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1870 return VD->hasGlobalStorage();
1871 // ... the address of a function,
1872 return isa<FunctionDecl>(D);
1873 }
1874
1875 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1876 return true;
1877
1878 const Expr *E = B.get<const Expr*>();
1879 switch (E->getStmtClass()) {
1880 default:
1881 return false;
1882 case Expr::CompoundLiteralExprClass: {
1883 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1884 return CLE->isFileScope() && CLE->isLValue();
1885 }
1886 case Expr::MaterializeTemporaryExprClass:
1887 // A materialized temporary might have been lifetime-extended to static
1888 // storage duration.
1889 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1890 // A string literal has static storage duration.
1891 case Expr::StringLiteralClass:
1892 case Expr::PredefinedExprClass:
1893 case Expr::ObjCStringLiteralClass:
1894 case Expr::ObjCEncodeExprClass:
1895 case Expr::CXXUuidofExprClass:
1896 return true;
1897 case Expr::ObjCBoxedExprClass:
1898 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1899 case Expr::CallExprClass:
1900 return IsStringLiteralCall(cast<CallExpr>(E));
1901 // For GCC compatibility, &&label has static storage duration.
1902 case Expr::AddrLabelExprClass:
1903 return true;
1904 // A Block literal expression may be used as the initialization value for
1905 // Block variables at global or local static scope.
1906 case Expr::BlockExprClass:
1907 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1908 case Expr::ImplicitValueInitExprClass:
1909 // FIXME:
1910 // We can never form an lvalue with an implicit value initialization as its
1911 // base through expression evaluation, so these only appear in one case: the
1912 // implicit variable declaration we invent when checking whether a constexpr
1913 // constructor can produce a constant expression. We must assume that such
1914 // an expression might be a global lvalue.
1915 return true;
1916 }
1917}
1918
1919static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1920 return LVal.Base.dyn_cast<const ValueDecl*>();
1921}
1922
1923static bool IsLiteralLValue(const LValue &Value) {
1924 if (Value.getLValueCallIndex())
1925 return false;
1926 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1927 return E && !isa<MaterializeTemporaryExpr>(E);
1928}
1929
1930static bool IsWeakLValue(const LValue &Value) {
1931 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1932 return Decl && Decl->isWeak();
1933}
1934
1935static bool isZeroSized(const LValue &Value) {
1936 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1937 if (Decl && isa<VarDecl>(Decl)) {
1938 QualType Ty = Decl->getType();
1939 if (Ty->isArrayType())
1940 return Ty->isIncompleteType() ||
1941 Decl->getASTContext().getTypeSize(Ty) == 0;
1942 }
1943 return false;
1944}
1945
1946static bool HasSameBase(const LValue &A, const LValue &B) {
1947 if (!A.getLValueBase())
1948 return !B.getLValueBase();
1949 if (!B.getLValueBase())
1950 return false;
1951
1952 if (A.getLValueBase().getOpaqueValue() !=
1953 B.getLValueBase().getOpaqueValue()) {
1954 const Decl *ADecl = GetLValueBaseDecl(A);
1955 if (!ADecl)
1956 return false;
1957 const Decl *BDecl = GetLValueBaseDecl(B);
1958 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1959 return false;
1960 }
1961
1962 return IsGlobalLValue(A.getLValueBase()) ||
1963 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1964 A.getLValueVersion() == B.getLValueVersion());
1965}
1966
1967static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1968 assert(Base && "no location for a null lvalue")((Base && "no location for a null lvalue") ? static_cast
<void> (0) : __assert_fail ("Base && \"no location for a null lvalue\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 1968, __PRETTY_FUNCTION__))
;
1969 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1970 if (VD)
1971 Info.Note(VD->getLocation(), diag::note_declared_at);
1972 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1973 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1974 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1975 // FIXME: Produce a note for dangling pointers too.
1976 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1977 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1978 diag::note_constexpr_dynamic_alloc_here);
1979 }
1980 // We have no information to show for a typeid(T) object.
1981}
1982
1983enum class CheckEvaluationResultKind {
1984 ConstantExpression,
1985 FullyInitialized,
1986};
1987
1988/// Materialized temporaries that we've already checked to determine if they're
1989/// initializsed by a constant expression.
1990using CheckedTemporaries =
1991 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
1992
1993static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
1994 EvalInfo &Info, SourceLocation DiagLoc,
1995 QualType Type, const APValue &Value,
1996 Expr::ConstExprUsage Usage,
1997 SourceLocation SubobjectLoc,
1998 CheckedTemporaries &CheckedTemps);
1999
2000/// Check that this reference or pointer core constant expression is a valid
2001/// value for an address or reference constant expression. Return true if we
2002/// can fold this expression, whether or not it's a constant expression.
2003static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2004 QualType Type, const LValue &LVal,
2005 Expr::ConstExprUsage Usage,
2006 CheckedTemporaries &CheckedTemps) {
2007 bool IsReferenceType = Type->isReferenceType();
2008
2009 APValue::LValueBase Base = LVal.getLValueBase();
2010 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2011
2012 // Check that the object is a global. Note that the fake 'this' object we
2013 // manufacture when checking potential constant expressions is conservatively
2014 // assumed to be global here.
2015 if (!IsGlobalLValue(Base)) {
2016 if (Info.getLangOpts().CPlusPlus11) {
2017 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2018 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2019 << IsReferenceType << !Designator.Entries.empty()
2020 << !!VD << VD;
2021 NoteLValueLocation(Info, Base);
2022 } else {
2023 Info.FFDiag(Loc);
2024 }
2025 // Don't allow references to temporaries to escape.
2026 return false;
2027 }
2028 assert((Info.checkingPotentialConstantExpression() ||(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex
() == 0) && "have call index for global lvalue") ? static_cast
<void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2030, __PRETTY_FUNCTION__))
2029 LVal.getLValueCallIndex() == 0) &&(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex
() == 0) && "have call index for global lvalue") ? static_cast
<void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2030, __PRETTY_FUNCTION__))
2030 "have call index for global lvalue")(((Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex
() == 0) && "have call index for global lvalue") ? static_cast
<void> (0) : __assert_fail ("(Info.checkingPotentialConstantExpression() || LVal.getLValueCallIndex() == 0) && \"have call index for global lvalue\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2030, __PRETTY_FUNCTION__))
;
2031
2032 if (Base.is<DynamicAllocLValue>()) {
2033 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2034 << IsReferenceType << !Designator.Entries.empty();
2035 NoteLValueLocation(Info, Base);
2036 return false;
2037 }
2038
2039 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2040 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2041 // Check if this is a thread-local variable.
2042 if (Var->getTLSKind())
2043 // FIXME: Diagnostic!
2044 return false;
2045
2046 // A dllimport variable never acts like a constant.
2047 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2048 // FIXME: Diagnostic!
2049 return false;
2050 }
2051 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2052 // __declspec(dllimport) must be handled very carefully:
2053 // We must never initialize an expression with the thunk in C++.
2054 // Doing otherwise would allow the same id-expression to yield
2055 // different addresses for the same function in different translation
2056 // units. However, this means that we must dynamically initialize the
2057 // expression with the contents of the import address table at runtime.
2058 //
2059 // The C language has no notion of ODR; furthermore, it has no notion of
2060 // dynamic initialization. This means that we are permitted to
2061 // perform initialization with the address of the thunk.
2062 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2063 FD->hasAttr<DLLImportAttr>())
2064 // FIXME: Diagnostic!
2065 return false;
2066 }
2067 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2068 Base.dyn_cast<const Expr *>())) {
2069 if (CheckedTemps.insert(MTE).second) {
2070 QualType TempType = getType(Base);
2071 if (TempType.isDestructedType()) {
2072 Info.FFDiag(MTE->getExprLoc(),
2073 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2074 << TempType;
2075 return false;
2076 }
2077
2078 APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2079 assert(V && "evasluation result refers to uninitialised temporary")((V && "evasluation result refers to uninitialised temporary"
) ? static_cast<void> (0) : __assert_fail ("V && \"evasluation result refers to uninitialised temporary\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2079, __PRETTY_FUNCTION__))
;
2080 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2081 Info, MTE->getExprLoc(), TempType, *V,
2082 Usage, SourceLocation(), CheckedTemps))
2083 return false;
2084 }
2085 }
2086
2087 // Allow address constant expressions to be past-the-end pointers. This is
2088 // an extension: the standard requires them to point to an object.
2089 if (!IsReferenceType)
2090 return true;
2091
2092 // A reference constant expression must refer to an object.
2093 if (!Base) {
2094 // FIXME: diagnostic
2095 Info.CCEDiag(Loc);
2096 return true;
2097 }
2098
2099 // Does this refer one past the end of some object?
2100 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2101 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2102 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2103 << !Designator.Entries.empty() << !!VD << VD;
2104 NoteLValueLocation(Info, Base);
2105 }
2106
2107 return true;
2108}
2109
2110/// Member pointers are constant expressions unless they point to a
2111/// non-virtual dllimport member function.
2112static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2113 SourceLocation Loc,
2114 QualType Type,
2115 const APValue &Value,
2116 Expr::ConstExprUsage Usage) {
2117 const ValueDecl *Member = Value.getMemberPointerDecl();
2118 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2119 if (!FD)
2120 return true;
2121 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2122 !FD->hasAttr<DLLImportAttr>();
2123}
2124
2125/// Check that this core constant expression is of literal type, and if not,
2126/// produce an appropriate diagnostic.
2127static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2128 const LValue *This = nullptr) {
2129 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2130 return true;
2131
2132 // C++1y: A constant initializer for an object o [...] may also invoke
2133 // constexpr constructors for o and its subobjects even if those objects
2134 // are of non-literal class types.
2135 //
2136 // C++11 missed this detail for aggregates, so classes like this:
2137 // struct foo_t { union { int i; volatile int j; } u; };
2138 // are not (obviously) initializable like so:
2139 // __attribute__((__require_constant_initialization__))
2140 // static const foo_t x = {{0}};
2141 // because "i" is a subobject with non-literal initialization (due to the
2142 // volatile member of the union). See:
2143 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2144 // Therefore, we use the C++1y behavior.
2145 if (This && Info.EvaluatingDecl == This->getLValueBase())
2146 return true;
2147
2148 // Prvalue constant expressions must be of literal types.
2149 if (Info.getLangOpts().CPlusPlus11)
2150 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2151 << E->getType();
2152 else
2153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2154 return false;
2155}
2156
2157static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2158 EvalInfo &Info, SourceLocation DiagLoc,
2159 QualType Type, const APValue &Value,
2160 Expr::ConstExprUsage Usage,
2161 SourceLocation SubobjectLoc,
2162 CheckedTemporaries &CheckedTemps) {
2163 if (!Value.hasValue()) {
2164 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2165 << true << Type;
2166 if (SubobjectLoc.isValid())
2167 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2168 return false;
2169 }
2170
2171 // We allow _Atomic(T) to be initialized from anything that T can be
2172 // initialized from.
2173 if (const AtomicType *AT = Type->getAs<AtomicType>())
2174 Type = AT->getValueType();
2175
2176 // Core issue 1454: For a literal constant expression of array or class type,
2177 // each subobject of its value shall have been initialized by a constant
2178 // expression.
2179 if (Value.isArray()) {
2180 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2181 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2182 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2183 Value.getArrayInitializedElt(I), Usage,
2184 SubobjectLoc, CheckedTemps))
2185 return false;
2186 }
2187 if (!Value.hasArrayFiller())
2188 return true;
2189 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2190 Value.getArrayFiller(), Usage, SubobjectLoc,
2191 CheckedTemps);
2192 }
2193 if (Value.isUnion() && Value.getUnionField()) {
2194 return CheckEvaluationResult(
2195 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2196 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2197 CheckedTemps);
2198 }
2199 if (Value.isStruct()) {
2200 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2201 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2202 unsigned BaseIndex = 0;
2203 for (const CXXBaseSpecifier &BS : CD->bases()) {
2204 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2205 Value.getStructBase(BaseIndex), Usage,
2206 BS.getBeginLoc(), CheckedTemps))
2207 return false;
2208 ++BaseIndex;
2209 }
2210 }
2211 for (const auto *I : RD->fields()) {
2212 if (I->isUnnamedBitfield())
2213 continue;
2214
2215 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2216 Value.getStructField(I->getFieldIndex()),
2217 Usage, I->getLocation(), CheckedTemps))
2218 return false;
2219 }
2220 }
2221
2222 if (Value.isLValue() &&
2223 CERK == CheckEvaluationResultKind::ConstantExpression) {
2224 LValue LVal;
2225 LVal.setFrom(Info.Ctx, Value);
2226 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2227 CheckedTemps);
2228 }
2229
2230 if (Value.isMemberPointer() &&
2231 CERK == CheckEvaluationResultKind::ConstantExpression)
2232 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2233
2234 // Everything else is fine.
2235 return true;
2236}
2237
2238/// Check that this core constant expression value is a valid value for a
2239/// constant expression. If not, report an appropriate diagnostic. Does not
2240/// check that the expression is of literal type.
2241static bool
2242CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2243 const APValue &Value,
2244 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2245 CheckedTemporaries CheckedTemps;
2246 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2247 Info, DiagLoc, Type, Value, Usage,
2248 SourceLocation(), CheckedTemps);
2249}
2250
2251/// Check that this evaluated value is fully-initialized and can be loaded by
2252/// an lvalue-to-rvalue conversion.
2253static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2254 QualType Type, const APValue &Value) {
2255 CheckedTemporaries CheckedTemps;
2256 return CheckEvaluationResult(
2257 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2258 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2259}
2260
2261/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2262/// "the allocated storage is deallocated within the evaluation".
2263static bool CheckMemoryLeaks(EvalInfo &Info) {
2264 if (!Info.HeapAllocs.empty()) {
2265 // We can still fold to a constant despite a compile-time memory leak,
2266 // so long as the heap allocation isn't referenced in the result (we check
2267 // that in CheckConstantExpression).
2268 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2269 diag::note_constexpr_memory_leak)
2270 << unsigned(Info.HeapAllocs.size() - 1);
2271 }
2272 return true;
2273}
2274
2275static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2276 // A null base expression indicates a null pointer. These are always
2277 // evaluatable, and they are false unless the offset is zero.
2278 if (!Value.getLValueBase()) {
2279 Result = !Value.getLValueOffset().isZero();
2280 return true;
2281 }
2282
2283 // We have a non-null base. These are generally known to be true, but if it's
2284 // a weak declaration it can be null at runtime.
2285 Result = true;
2286 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2287 return !Decl || !Decl->isWeak();
2288}
2289
2290static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2291 switch (Val.getKind()) {
2292 case APValue::None:
2293 case APValue::Indeterminate:
2294 return false;
2295 case APValue::Int:
2296 Result = Val.getInt().getBoolValue();
2297 return true;
2298 case APValue::FixedPoint:
2299 Result = Val.getFixedPoint().getBoolValue();
2300 return true;
2301 case APValue::Float:
2302 Result = !Val.getFloat().isZero();
2303 return true;
2304 case APValue::ComplexInt:
2305 Result = Val.getComplexIntReal().getBoolValue() ||
2306 Val.getComplexIntImag().getBoolValue();
2307 return true;
2308 case APValue::ComplexFloat:
2309 Result = !Val.getComplexFloatReal().isZero() ||
2310 !Val.getComplexFloatImag().isZero();
2311 return true;
2312 case APValue::LValue:
2313 return EvalPointerValueAsBool(Val, Result);
2314 case APValue::MemberPointer:
2315 Result = Val.getMemberPointerDecl();
2316 return true;
2317 case APValue::Vector:
2318 case APValue::Array:
2319 case APValue::Struct:
2320 case APValue::Union:
2321 case APValue::AddrLabelDiff:
2322 return false;
2323 }
2324
2325 llvm_unreachable("unknown APValue kind")::llvm::llvm_unreachable_internal("unknown APValue kind", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2325)
;
2326}
2327
2328static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2329 EvalInfo &Info) {
2330 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition")((E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"
) ? static_cast<void> (0) : __assert_fail ("E->isRValue() && \"missing lvalue-to-rvalue conv in bool condition\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2330, __PRETTY_FUNCTION__))
;
2331 APValue Val;
2332 if (!Evaluate(Val, Info, E))
2333 return false;
2334 return HandleConversionToBool(Val, Result);
2335}
2336
2337template<typename T>
2338static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2339 const T &SrcValue, QualType DestType) {
2340 Info.CCEDiag(E, diag::note_constexpr_overflow)
2341 << SrcValue << DestType;
2342 return Info.noteUndefinedBehavior();
2343}
2344
2345static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2346 QualType SrcType, const APFloat &Value,
2347 QualType DestType, APSInt &Result) {
2348 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2349 // Determine whether we are converting to unsigned or signed.
2350 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2351
2352 Result = APSInt(DestWidth, !DestSigned);
2353 bool ignored;
2354 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2355 & APFloat::opInvalidOp)
2356 return HandleOverflow(Info, E, Value, DestType);
2357 return true;
2358}
2359
2360static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2361 QualType SrcType, QualType DestType,
2362 APFloat &Result) {
2363 APFloat Value = Result;
2364 bool ignored;
2365 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2366 APFloat::rmNearestTiesToEven, &ignored);
2367 return true;
2368}
2369
2370static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2371 QualType DestType, QualType SrcType,
2372 const APSInt &Value) {
2373 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2374 // Figure out if this is a truncate, extend or noop cast.
2375 // If the input is signed, do a sign extend, noop, or truncate.
2376 APSInt Result = Value.extOrTrunc(DestWidth);
2377 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2378 if (DestType->isBooleanType())
2379 Result = Value.getBoolValue();
2380 return Result;
2381}
2382
2383static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2384 QualType SrcType, const APSInt &Value,
2385 QualType DestType, APFloat &Result) {
2386 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2387 Result.convertFromAPInt(Value, Value.isSigned(),
2388 APFloat::rmNearestTiesToEven);
2389 return true;
2390}
2391
2392static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2393 APValue &Value, const FieldDecl *FD) {
2394 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield")((FD->isBitField() && "truncateBitfieldValue on non-bitfield"
) ? static_cast<void> (0) : __assert_fail ("FD->isBitField() && \"truncateBitfieldValue on non-bitfield\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2394, __PRETTY_FUNCTION__))
;
2395
2396 if (!Value.isInt()) {
2397 // Trying to store a pointer-cast-to-integer into a bitfield.
2398 // FIXME: In this case, we should provide the diagnostic for casting
2399 // a pointer to an integer.
2400 assert(Value.isLValue() && "integral value neither int nor lvalue?")((Value.isLValue() && "integral value neither int nor lvalue?"
) ? static_cast<void> (0) : __assert_fail ("Value.isLValue() && \"integral value neither int nor lvalue?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2400, __PRETTY_FUNCTION__))
;
2401 Info.FFDiag(E);
2402 return false;
2403 }
2404
2405 APSInt &Int = Value.getInt();
2406 unsigned OldBitWidth = Int.getBitWidth();
2407 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2408 if (NewBitWidth < OldBitWidth)
2409 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2410 return true;
2411}
2412
2413static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2414 llvm::APInt &Res) {
2415 APValue SVal;
2416 if (!Evaluate(SVal, Info, E))
2417 return false;
2418 if (SVal.isInt()) {
2419 Res = SVal.getInt();
2420 return true;
2421 }
2422 if (SVal.isFloat()) {
2423 Res = SVal.getFloat().bitcastToAPInt();
2424 return true;
2425 }
2426 if (SVal.isVector()) {
2427 QualType VecTy = E->getType();
2428 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2429 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2430 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2431 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2432 Res = llvm::APInt::getNullValue(VecSize);
2433 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2434 APValue &Elt = SVal.getVectorElt(i);
2435 llvm::APInt EltAsInt;
2436 if (Elt.isInt()) {
2437 EltAsInt = Elt.getInt();
2438 } else if (Elt.isFloat()) {
2439 EltAsInt = Elt.getFloat().bitcastToAPInt();
2440 } else {
2441 // Don't try to handle vectors of anything other than int or float
2442 // (not sure if it's possible to hit this case).
2443 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2444 return false;
2445 }
2446 unsigned BaseEltSize = EltAsInt.getBitWidth();
2447 if (BigEndian)
2448 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2449 else
2450 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2451 }
2452 return true;
2453 }
2454 // Give up if the input isn't an int, float, or vector. For example, we
2455 // reject "(v4i16)(intptr_t)&a".
2456 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2457 return false;
2458}
2459
2460/// Perform the given integer operation, which is known to need at most BitWidth
2461/// bits, and check for overflow in the original type (if that type was not an
2462/// unsigned type).
2463template<typename Operation>
2464static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2465 const APSInt &LHS, const APSInt &RHS,
2466 unsigned BitWidth, Operation Op,
2467 APSInt &Result) {
2468 if (LHS.isUnsigned()) {
2469 Result = Op(LHS, RHS);
2470 return true;
2471 }
2472
2473 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2474 Result = Value.trunc(LHS.getBitWidth());
2475 if (Result.extend(BitWidth) != Value) {
2476 if (Info.checkingForUndefinedBehavior())
2477 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2478 diag::warn_integer_constant_overflow)
2479 << Result.toString(10) << E->getType();
2480 else
2481 return HandleOverflow(Info, E, Value, E->getType());
2482 }
2483 return true;
2484}
2485
2486/// Perform the given binary integer operation.
2487static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2488 BinaryOperatorKind Opcode, APSInt RHS,
2489 APSInt &Result) {
2490 switch (Opcode) {
2491 default:
2492 Info.FFDiag(E);
2493 return false;
2494 case BO_Mul:
2495 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2496 std::multiplies<APSInt>(), Result);
2497 case BO_Add:
2498 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2499 std::plus<APSInt>(), Result);
2500 case BO_Sub:
2501 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2502 std::minus<APSInt>(), Result);
2503 case BO_And: Result = LHS & RHS; return true;
2504 case BO_Xor: Result = LHS ^ RHS; return true;
2505 case BO_Or: Result = LHS | RHS; return true;
2506 case BO_Div:
2507 case BO_Rem:
2508 if (RHS == 0) {
2509 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2510 return false;
2511 }
2512 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2513 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2514 // this operation and gives the two's complement result.
2515 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2516 LHS.isSigned() && LHS.isMinSignedValue())
2517 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2518 E->getType());
2519 return true;
2520 case BO_Shl: {
2521 if (Info.getLangOpts().OpenCL)
2522 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2523 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2524 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2525 RHS.isUnsigned());
2526 else if (RHS.isSigned() && RHS.isNegative()) {
2527 // During constant-folding, a negative shift is an opposite shift. Such
2528 // a shift is not a constant expression.
2529 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2530 RHS = -RHS;
2531 goto shift_right;
2532 }
2533 shift_left:
2534 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2535 // the shifted type.
2536 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2537 if (SA != RHS) {
2538 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2539 << RHS << E->getType() << LHS.getBitWidth();
2540 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2541 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2542 // operand, and must not overflow the corresponding unsigned type.
2543 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2544 // E1 x 2^E2 module 2^N.
2545 if (LHS.isNegative())
2546 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2547 else if (LHS.countLeadingZeros() < SA)
2548 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2549 }
2550 Result = LHS << SA;
2551 return true;
2552 }
2553 case BO_Shr: {
2554 if (Info.getLangOpts().OpenCL)
2555 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2556 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2557 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2558 RHS.isUnsigned());
2559 else if (RHS.isSigned() && RHS.isNegative()) {
2560 // During constant-folding, a negative shift is an opposite shift. Such a
2561 // shift is not a constant expression.
2562 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2563 RHS = -RHS;
2564 goto shift_left;
2565 }
2566 shift_right:
2567 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2568 // shifted type.
2569 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2570 if (SA != RHS)
2571 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2572 << RHS << E->getType() << LHS.getBitWidth();
2573 Result = LHS >> SA;
2574 return true;
2575 }
2576
2577 case BO_LT: Result = LHS < RHS; return true;
2578 case BO_GT: Result = LHS > RHS; return true;
2579 case BO_LE: Result = LHS <= RHS; return true;
2580 case BO_GE: Result = LHS >= RHS; return true;
2581 case BO_EQ: Result = LHS == RHS; return true;
2582 case BO_NE: Result = LHS != RHS; return true;
2583 case BO_Cmp:
2584 llvm_unreachable("BO_Cmp should be handled elsewhere")::llvm::llvm_unreachable_internal("BO_Cmp should be handled elsewhere"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2584)
;
2585 }
2586}
2587
2588/// Perform the given binary floating-point operation, in-place, on LHS.
2589static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2590 APFloat &LHS, BinaryOperatorKind Opcode,
2591 const APFloat &RHS) {
2592 switch (Opcode) {
2593 default:
2594 Info.FFDiag(E);
2595 return false;
2596 case BO_Mul:
2597 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2598 break;
2599 case BO_Add:
2600 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2601 break;
2602 case BO_Sub:
2603 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2604 break;
2605 case BO_Div:
2606 // [expr.mul]p4:
2607 // If the second operand of / or % is zero the behavior is undefined.
2608 if (RHS.isZero())
2609 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2610 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2611 break;
2612 }
2613
2614 // [expr.pre]p4:
2615 // If during the evaluation of an expression, the result is not
2616 // mathematically defined [...], the behavior is undefined.
2617 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2618 if (LHS.isNaN()) {
2619 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2620 return Info.noteUndefinedBehavior();
2621 }
2622 return true;
2623}
2624
2625/// Cast an lvalue referring to a base subobject to a derived class, by
2626/// truncating the lvalue's path to the given length.
2627static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2628 const RecordDecl *TruncatedType,
2629 unsigned TruncatedElements) {
2630 SubobjectDesignator &D = Result.Designator;
2631
2632 // Check we actually point to a derived class object.
2633 if (TruncatedElements == D.Entries.size())
2634 return true;
2635 assert(TruncatedElements >= D.MostDerivedPathLength &&((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class"
) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2636, __PRETTY_FUNCTION__))
2636 "not casting to a derived class")((TruncatedElements >= D.MostDerivedPathLength && "not casting to a derived class"
) ? static_cast<void> (0) : __assert_fail ("TruncatedElements >= D.MostDerivedPathLength && \"not casting to a derived class\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2636, __PRETTY_FUNCTION__))
;
2637 if (!Result.checkSubobject(Info, E, CSK_Derived))
2638 return false;
2639
2640 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2641 const RecordDecl *RD = TruncatedType;
2642 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2643 if (RD->isInvalidDecl()) return false;
2644 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2645 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2646 if (isVirtualBaseClass(D.Entries[I]))
2647 Result.Offset -= Layout.getVBaseClassOffset(Base);
2648 else
2649 Result.Offset -= Layout.getBaseClassOffset(Base);
2650 RD = Base;
2651 }
2652 D.Entries.resize(TruncatedElements);
2653 return true;
2654}
2655
2656static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2657 const CXXRecordDecl *Derived,
2658 const CXXRecordDecl *Base,
2659 const ASTRecordLayout *RL = nullptr) {
2660 if (!RL) {
2661 if (Derived->isInvalidDecl()) return false;
2662 RL = &Info.Ctx.getASTRecordLayout(Derived);
2663 }
2664
2665 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2666 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2667 return true;
2668}
2669
2670static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2671 const CXXRecordDecl *DerivedDecl,
2672 const CXXBaseSpecifier *Base) {
2673 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2674
2675 if (!Base->isVirtual())
2676 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2677
2678 SubobjectDesignator &D = Obj.Designator;
2679 if (D.Invalid)
2680 return false;
2681
2682 // Extract most-derived object and corresponding type.
2683 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2684 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2685 return false;
2686
2687 // Find the virtual base class.
2688 if (DerivedDecl->isInvalidDecl()) return false;
2689 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2690 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2691 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2692 return true;
2693}
2694
2695static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2696 QualType Type, LValue &Result) {
2697 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2698 PathE = E->path_end();
2699 PathI != PathE; ++PathI) {
2700 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2701 *PathI))
2702 return false;
2703 Type = (*PathI)->getType();
2704 }
2705 return true;
2706}
2707
2708/// Cast an lvalue referring to a derived class to a known base subobject.
2709static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2710 const CXXRecordDecl *DerivedRD,
2711 const CXXRecordDecl *BaseRD) {
2712 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2713 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2714 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2715 llvm_unreachable("Class must be derived from the passed in base class!")::llvm::llvm_unreachable_internal("Class must be derived from the passed in base class!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2715)
;
2716
2717 for (CXXBasePathElement &Elem : Paths.front())
2718 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2719 return false;
2720 return true;
2721}
2722
2723/// Update LVal to refer to the given field, which must be a member of the type
2724/// currently described by LVal.
2725static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2726 const FieldDecl *FD,
2727 const ASTRecordLayout *RL = nullptr) {
2728 if (!RL) {
2729 if (FD->getParent()->isInvalidDecl()) return false;
2730 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2731 }
2732
2733 unsigned I = FD->getFieldIndex();
2734 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2735 LVal.addDecl(Info, E, FD);
2736 return true;
2737}
2738
2739/// Update LVal to refer to the given indirect field.
2740static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2741 LValue &LVal,
2742 const IndirectFieldDecl *IFD) {
2743 for (const auto *C : IFD->chain())
2744 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2745 return false;
2746 return true;
2747}
2748
2749/// Get the size of the given type in char units.
2750static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2751 QualType Type, CharUnits &Size) {
2752 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2753 // extension.
2754 if (Type->isVoidType() || Type->isFunctionType()) {
2755 Size = CharUnits::One();
2756 return true;
2757 }
2758
2759 if (Type->isDependentType()) {
2760 Info.FFDiag(Loc);
2761 return false;
2762 }
2763
2764 if (!Type->isConstantSizeType()) {
2765 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2766 // FIXME: Better diagnostic.
2767 Info.FFDiag(Loc);
2768 return false;
2769 }
2770
2771 Size = Info.Ctx.getTypeSizeInChars(Type);
2772 return true;
2773}
2774
2775/// Update a pointer value to model pointer arithmetic.
2776/// \param Info - Information about the ongoing evaluation.
2777/// \param E - The expression being evaluated, for diagnostic purposes.
2778/// \param LVal - The pointer value to be updated.
2779/// \param EltTy - The pointee type represented by LVal.
2780/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2781static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2782 LValue &LVal, QualType EltTy,
2783 APSInt Adjustment) {
2784 CharUnits SizeOfPointee;
2785 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2786 return false;
2787
2788 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2789 return true;
2790}
2791
2792static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2793 LValue &LVal, QualType EltTy,
2794 int64_t Adjustment) {
2795 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2796 APSInt::get(Adjustment));
2797}
2798
2799/// Update an lvalue to refer to a component of a complex number.
2800/// \param Info - Information about the ongoing evaluation.
2801/// \param LVal - The lvalue to be updated.
2802/// \param EltTy - The complex number's component type.
2803/// \param Imag - False for the real component, true for the imaginary.
2804static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2805 LValue &LVal, QualType EltTy,
2806 bool Imag) {
2807 if (Imag) {
2808 CharUnits SizeOfComponent;
2809 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2810 return false;
2811 LVal.Offset += SizeOfComponent;
2812 }
2813 LVal.addComplex(Info, E, EltTy, Imag);
2814 return true;
2815}
2816
2817/// Try to evaluate the initializer for a variable declaration.
2818///
2819/// \param Info Information about the ongoing evaluation.
2820/// \param E An expression to be used when printing diagnostics.
2821/// \param VD The variable whose initializer should be obtained.
2822/// \param Frame The frame in which the variable was created. Must be null
2823/// if this variable is not local to the evaluation.
2824/// \param Result Filled in with a pointer to the value of the variable.
2825static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2826 const VarDecl *VD, CallStackFrame *Frame,
2827 APValue *&Result, const LValue *LVal) {
2828
2829 // If this is a parameter to an active constexpr function call, perform
2830 // argument substitution.
2831 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2832 // Assume arguments of a potential constant expression are unknown
2833 // constant expressions.
2834 if (Info.checkingPotentialConstantExpression())
2835 return false;
2836 if (!Frame || !Frame->Arguments) {
2837 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2838 return false;
2839 }
2840 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2841 return true;
2842 }
2843
2844 // If this is a local variable, dig out its value.
2845 if (Frame) {
2846 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2847 : Frame->getCurrentTemporary(VD);
2848 if (!Result) {
2849 // Assume variables referenced within a lambda's call operator that were
2850 // not declared within the call operator are captures and during checking
2851 // of a potential constant expression, assume they are unknown constant
2852 // expressions.
2853 assert(isLambdaCallOperator(Frame->Callee) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext
() != Frame->Callee || VD->isInitCapture()) && "missing value for local variable"
) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2855, __PRETTY_FUNCTION__))
2854 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext
() != Frame->Callee || VD->isInitCapture()) && "missing value for local variable"
) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2855, __PRETTY_FUNCTION__))
2855 "missing value for local variable")((isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext
() != Frame->Callee || VD->isInitCapture()) && "missing value for local variable"
) ? static_cast<void> (0) : __assert_fail ("isLambdaCallOperator(Frame->Callee) && (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && \"missing value for local variable\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2855, __PRETTY_FUNCTION__))
;
2856 if (Info.checkingPotentialConstantExpression())
2857 return false;
2858 // FIXME: implement capture evaluation during constant expr evaluation.
2859 Info.FFDiag(E->getBeginLoc(),
2860 diag::note_unimplemented_constexpr_lambda_feature_ast)
2861 << "captures not currently allowed";
2862 return false;
2863 }
2864 return true;
2865 }
2866
2867 // Dig out the initializer, and use the declaration which it's attached to.
2868 const Expr *Init = VD->getAnyInitializer(VD);
2869 if (!Init || Init->isValueDependent()) {
2870 // If we're checking a potential constant expression, the variable could be
2871 // initialized later.
2872 if (!Info.checkingPotentialConstantExpression())
2873 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2874 return false;
2875 }
2876
2877 // If we're currently evaluating the initializer of this declaration, use that
2878 // in-flight value.
2879 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2880 Result = Info.EvaluatingDeclValue;
2881 return true;
2882 }
2883
2884 // Never evaluate the initializer of a weak variable. We can't be sure that
2885 // this is the definition which will be used.
2886 if (VD->isWeak()) {
2887 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2888 return false;
2889 }
2890
2891 // Check that we can fold the initializer. In C++, we will have already done
2892 // this in the cases where it matters for conformance.
2893 SmallVector<PartialDiagnosticAt, 8> Notes;
2894 if (!VD->evaluateValue(Notes)) {
2895 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2896 Notes.size() + 1) << VD;
2897 Info.Note(VD->getLocation(), diag::note_declared_at);
2898 Info.addNotes(Notes);
2899 return false;
2900 } else if (!VD->checkInitIsICE()) {
2901 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2902 Notes.size() + 1) << VD;
2903 Info.Note(VD->getLocation(), diag::note_declared_at);
2904 Info.addNotes(Notes);
2905 }
2906
2907 Result = VD->getEvaluatedValue();
2908 return true;
2909}
2910
2911static bool IsConstNonVolatile(QualType T) {
2912 Qualifiers Quals = T.getQualifiers();
2913 return Quals.hasConst() && !Quals.hasVolatile();
2914}
2915
2916/// Get the base index of the given base class within an APValue representing
2917/// the given derived class.
2918static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2919 const CXXRecordDecl *Base) {
2920 Base = Base->getCanonicalDecl();
2921 unsigned Index = 0;
2922 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2923 E = Derived->bases_end(); I != E; ++I, ++Index) {
2924 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2925 return Index;
2926 }
2927
2928 llvm_unreachable("base class missing from derived class's bases list")::llvm::llvm_unreachable_internal("base class missing from derived class's bases list"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2928)
;
2929}
2930
2931/// Extract the value of a character from a string literal.
2932static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2933 uint64_t Index) {
2934 assert(!isa<SourceLocExpr>(Lit) &&((!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral"
) ? static_cast<void> (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2935, __PRETTY_FUNCTION__))
2935 "SourceLocExpr should have already been converted to a StringLiteral")((!isa<SourceLocExpr>(Lit) && "SourceLocExpr should have already been converted to a StringLiteral"
) ? static_cast<void> (0) : __assert_fail ("!isa<SourceLocExpr>(Lit) && \"SourceLocExpr should have already been converted to a StringLiteral\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2935, __PRETTY_FUNCTION__))
;
2936
2937 // FIXME: Support MakeStringConstant
2938 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2939 std::string Str;
2940 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2941 assert(Index <= Str.size() && "Index too large")((Index <= Str.size() && "Index too large") ? static_cast
<void> (0) : __assert_fail ("Index <= Str.size() && \"Index too large\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2941, __PRETTY_FUNCTION__))
;
2942 return APSInt::getUnsigned(Str.c_str()[Index]);
2943 }
2944
2945 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2946 Lit = PE->getFunctionName();
2947 const StringLiteral *S = cast<StringLiteral>(Lit);
2948 const ConstantArrayType *CAT =
2949 Info.Ctx.getAsConstantArrayType(S->getType());
2950 assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast
<void> (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2950, __PRETTY_FUNCTION__))
;
2951 QualType CharType = CAT->getElementType();
2952 assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type"
) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2952, __PRETTY_FUNCTION__))
;
2953
2954 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2955 CharType->isUnsignedIntegerType());
2956 if (Index < S->getLength())
2957 Value = S->getCodeUnit(Index);
2958 return Value;
2959}
2960
2961// Expand a string literal into an array of characters.
2962//
2963// FIXME: This is inefficient; we should probably introduce something similar
2964// to the LLVM ConstantDataArray to make this cheaper.
2965static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2966 APValue &Result,
2967 QualType AllocType = QualType()) {
2968 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2969 AllocType.isNull() ? S->getType() : AllocType);
2970 assert(CAT && "string literal isn't an array")((CAT && "string literal isn't an array") ? static_cast
<void> (0) : __assert_fail ("CAT && \"string literal isn't an array\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2970, __PRETTY_FUNCTION__))
;
2971 QualType CharType = CAT->getElementType();
2972 assert(CharType->isIntegerType() && "unexpected character type")((CharType->isIntegerType() && "unexpected character type"
) ? static_cast<void> (0) : __assert_fail ("CharType->isIntegerType() && \"unexpected character type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2972, __PRETTY_FUNCTION__))
;
2973
2974 unsigned Elts = CAT->getSize().getZExtValue();
2975 Result = APValue(APValue::UninitArray(),
2976 std::min(S->getLength(), Elts), Elts);
2977 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2978 CharType->isUnsignedIntegerType());
2979 if (Result.hasArrayFiller())
2980 Result.getArrayFiller() = APValue(Value);
2981 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2982 Value = S->getCodeUnit(I);
2983 Result.getArrayInitializedElt(I) = APValue(Value);
2984 }
2985}
2986
2987// Expand an array so that it has more than Index filled elements.
2988static void expandArray(APValue &Array, unsigned Index) {
2989 unsigned Size = Array.getArraySize();
2990 assert(Index < Size)((Index < Size) ? static_cast<void> (0) : __assert_fail
("Index < Size", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 2990, __PRETTY_FUNCTION__))
;
2991
2992 // Always at least double the number of elements for which we store a value.
2993 unsigned OldElts = Array.getArrayInitializedElts();
2994 unsigned NewElts = std::max(Index+1, OldElts * 2);
2995 NewElts = std::min(Size, std::max(NewElts, 8u));
2996
2997 // Copy the data across.
2998 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2999 for (unsigned I = 0; I != OldElts; ++I)
3000 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3001 for (unsigned I = OldElts; I != NewElts; ++I)
3002 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3003 if (NewValue.hasArrayFiller())
3004 NewValue.getArrayFiller() = Array.getArrayFiller();
3005 Array.swap(NewValue);
3006}
3007
3008/// Determine whether a type would actually be read by an lvalue-to-rvalue
3009/// conversion. If it's of class type, we may assume that the copy operation
3010/// is trivial. Note that this is never true for a union type with fields
3011/// (because the copy always "reads" the active member) and always true for
3012/// a non-class type.
3013static bool isReadByLvalueToRvalueConversion(QualType T) {
3014 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3015 if (!RD || (RD->isUnion() && !RD->field_empty()))
3016 return true;
3017 if (RD->isEmpty())
3018 return false;
3019
3020 for (auto *Field : RD->fields())
3021 if (isReadByLvalueToRvalueConversion(Field->getType()))
3022 return true;
3023
3024 for (auto &BaseSpec : RD->bases())
3025 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3026 return true;
3027
3028 return false;
3029}
3030
3031/// Diagnose an attempt to read from any unreadable field within the specified
3032/// type, which might be a class type.
3033static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3034 QualType T) {
3035 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3036 if (!RD)
3037 return false;
3038
3039 if (!RD->hasMutableFields())
3040 return false;
3041
3042 for (auto *Field : RD->fields()) {
3043 // If we're actually going to read this field in some way, then it can't
3044 // be mutable. If we're in a union, then assigning to a mutable field
3045 // (even an empty one) can change the active member, so that's not OK.
3046 // FIXME: Add core issue number for the union case.
3047 if (Field->isMutable() &&
3048 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3049 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3050 Info.Note(Field->getLocation(), diag::note_declared_at);
3051 return true;
3052 }
3053
3054 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3055 return true;
3056 }
3057
3058 for (auto &BaseSpec : RD->bases())
3059 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3060 return true;
3061
3062 // All mutable fields were empty, and thus not actually read.
3063 return false;
3064}
3065
3066static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3067 APValue::LValueBase Base,
3068 bool MutableSubobject = false) {
3069 // A temporary we created.
3070 if (Base.getCallIndex())
3071 return true;
3072
3073 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3074 if (!Evaluating)
3075 return false;
3076
3077 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3078
3079 switch (Info.IsEvaluatingDecl) {
3080 case EvalInfo::EvaluatingDeclKind::None:
3081 return false;
3082
3083 case EvalInfo::EvaluatingDeclKind::Ctor:
3084 // The variable whose initializer we're evaluating.
3085 if (BaseD)
3086 return declaresSameEntity(Evaluating, BaseD);
3087
3088 // A temporary lifetime-extended by the variable whose initializer we're
3089 // evaluating.
3090 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3091 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3092 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3093 return false;
3094
3095 case EvalInfo::EvaluatingDeclKind::Dtor:
3096 // C++2a [expr.const]p6:
3097 // [during constant destruction] the lifetime of a and its non-mutable
3098 // subobjects (but not its mutable subobjects) [are] considered to start
3099 // within e.
3100 //
3101 // FIXME: We can meaningfully extend this to cover non-const objects, but
3102 // we will need special handling: we should be able to access only
3103 // subobjects of such objects that are themselves declared const.
3104 if (!BaseD ||
3105 !(BaseD->getType().isConstQualified() ||
3106 BaseD->getType()->isReferenceType()) ||
3107 MutableSubobject)
3108 return false;
3109 return declaresSameEntity(Evaluating, BaseD);
3110 }
3111
3112 llvm_unreachable("unknown evaluating decl kind")::llvm::llvm_unreachable_internal("unknown evaluating decl kind"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3112)
;
3113}
3114
3115namespace {
3116/// A handle to a complete object (an object that is not a subobject of
3117/// another object).
3118struct CompleteObject {
3119 /// The identity of the object.
3120 APValue::LValueBase Base;
3121 /// The value of the complete object.
3122 APValue *Value;
3123 /// The type of the complete object.
3124 QualType Type;
3125
3126 CompleteObject() : Value(nullptr) {}
3127 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3128 : Base(Base), Value(Value), Type(Type) {}
3129
3130 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3131 // In C++14 onwards, it is permitted to read a mutable member whose
3132 // lifetime began within the evaluation.
3133 // FIXME: Should we also allow this in C++11?
3134 if (!Info.getLangOpts().CPlusPlus14)
3135 return false;
3136 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3137 }
3138
3139 explicit operator bool() const { return !Type.isNull(); }
3140};
3141} // end anonymous namespace
3142
3143static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3144 bool IsMutable = false) {
3145 // C++ [basic.type.qualifier]p1:
3146 // - A const object is an object of type const T or a non-mutable subobject
3147 // of a const object.
3148 if (ObjType.isConstQualified() && !IsMutable)
3149 SubobjType.addConst();
3150 // - A volatile object is an object of type const T or a subobject of a
3151 // volatile object.
3152 if (ObjType.isVolatileQualified())
3153 SubobjType.addVolatile();
3154 return SubobjType;
3155}
3156
3157/// Find the designated sub-object of an rvalue.
3158template<typename SubobjectHandler>
3159typename SubobjectHandler::result_type
3160findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3161 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3162 if (Sub.Invalid)
3163 // A diagnostic will have already been produced.
3164 return handler.failed();
3165 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3166 if (Info.getLangOpts().CPlusPlus11)
3167 Info.FFDiag(E, Sub.isOnePastTheEnd()
3168 ? diag::note_constexpr_access_past_end
3169 : diag::note_constexpr_access_unsized_array)
3170 << handler.AccessKind;
3171 else
3172 Info.FFDiag(E);
3173 return handler.failed();
3174 }
3175
3176 APValue *O = Obj.Value;
3177 QualType ObjType = Obj.Type;
3178 const FieldDecl *LastField = nullptr;
3179 const FieldDecl *VolatileField = nullptr;
3180
3181 // Walk the designator's path to find the subobject.
3182 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3183 // Reading an indeterminate value is undefined, but assigning over one is OK.
3184 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3185 (O->isIndeterminate() && handler.AccessKind != AK_Construct &&
3186 handler.AccessKind != AK_Assign &&
3187 handler.AccessKind != AK_ReadObjectRepresentation)) {
3188 if (!Info.checkingPotentialConstantExpression())
3189 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3190 << handler.AccessKind << O->isIndeterminate();
3191 return handler.failed();
3192 }
3193
3194 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3195 // const and volatile semantics are not applied on an object under
3196 // {con,de}struction.
3197 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3198 ObjType->isRecordType() &&
3199 Info.isEvaluatingCtorDtor(
3200 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3201 Sub.Entries.begin() + I)) !=
3202 ConstructionPhase::None) {
3203 ObjType = Info.Ctx.getCanonicalType(ObjType);
3204 ObjType.removeLocalConst();
3205 ObjType.removeLocalVolatile();
3206 }
3207
3208 // If this is our last pass, check that the final object type is OK.
3209 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3210 // Accesses to volatile objects are prohibited.
3211 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3212 if (Info.getLangOpts().CPlusPlus) {
3213 int DiagKind;
3214 SourceLocation Loc;
3215 const NamedDecl *Decl = nullptr;
3216 if (VolatileField) {
3217 DiagKind = 2;
3218 Loc = VolatileField->getLocation();
3219 Decl = VolatileField;
3220 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3221 DiagKind = 1;
3222 Loc = VD->getLocation();
3223 Decl = VD;
3224 } else {
3225 DiagKind = 0;
3226 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3227 Loc = E->getExprLoc();
3228 }
3229 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3230 << handler.AccessKind << DiagKind << Decl;
3231 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3232 } else {
3233 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3234 }
3235 return handler.failed();
3236 }
3237
3238 // If we are reading an object of class type, there may still be more
3239 // things we need to check: if there are any mutable subobjects, we
3240 // cannot perform this read. (This only happens when performing a trivial
3241 // copy or assignment.)
3242 if (ObjType->isRecordType() &&
3243 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3244 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3245 return handler.failed();
3246 }
3247
3248 if (I == N) {
3249 if (!handler.found(*O, ObjType))
3250 return false;
3251
3252 // If we modified a bit-field, truncate it to the right width.
3253 if (isModification(handler.AccessKind) &&
3254 LastField && LastField->isBitField() &&
3255 !truncateBitfieldValue(Info, E, *O, LastField))
3256 return false;
3257
3258 return true;
3259 }
3260
3261 LastField = nullptr;
3262 if (ObjType->isArrayType()) {
3263 // Next subobject is an array element.
3264 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3265 assert(CAT && "vla in literal type?")((CAT && "vla in literal type?") ? static_cast<void
> (0) : __assert_fail ("CAT && \"vla in literal type?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3265, __PRETTY_FUNCTION__))
;
3266 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3267 if (CAT->getSize().ule(Index)) {
3268 // Note, it should not be possible to form a pointer with a valid
3269 // designator which points more than one past the end of the array.
3270 if (Info.getLangOpts().CPlusPlus11)
3271 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3272 << handler.AccessKind;
3273 else
3274 Info.FFDiag(E);
3275 return handler.failed();
3276 }
3277
3278 ObjType = CAT->getElementType();
3279
3280 if (O->getArrayInitializedElts() > Index)
3281 O = &O->getArrayInitializedElt(Index);
3282 else if (!isRead(handler.AccessKind)) {
3283 expandArray(*O, Index);
3284 O = &O->getArrayInitializedElt(Index);
3285 } else
3286 O = &O->getArrayFiller();
3287 } else if (ObjType->isAnyComplexType()) {
3288 // Next subobject is a complex number.
3289 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3290 if (Index > 1) {
3291 if (Info.getLangOpts().CPlusPlus11)
3292 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3293 << handler.AccessKind;
3294 else
3295 Info.FFDiag(E);
3296 return handler.failed();
3297 }
3298
3299 ObjType = getSubobjectType(
3300 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3301
3302 assert(I == N - 1 && "extracting subobject of scalar?")((I == N - 1 && "extracting subobject of scalar?") ? static_cast
<void> (0) : __assert_fail ("I == N - 1 && \"extracting subobject of scalar?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3302, __PRETTY_FUNCTION__))
;
3303 if (O->isComplexInt()) {
3304 return handler.found(Index ? O->getComplexIntImag()
3305 : O->getComplexIntReal(), ObjType);
3306 } else {
3307 assert(O->isComplexFloat())((O->isComplexFloat()) ? static_cast<void> (0) : __assert_fail
("O->isComplexFloat()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3307, __PRETTY_FUNCTION__))
;
3308 return handler.found(Index ? O->getComplexFloatImag()
3309 : O->getComplexFloatReal(), ObjType);
3310 }
3311 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3312 if (Field->isMutable() &&
3313 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3314 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3315 << handler.AccessKind << Field;
3316 Info.Note(Field->getLocation(), diag::note_declared_at);
3317 return handler.failed();
3318 }
3319
3320 // Next subobject is a class, struct or union field.
3321 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3322 if (RD->isUnion()) {
3323 const FieldDecl *UnionField = O->getUnionField();
3324 if (!UnionField ||
3325 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3326 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3327 // Placement new onto an inactive union member makes it active.
3328 O->setUnion(Field, APValue());
3329 } else {
3330 // FIXME: If O->getUnionValue() is absent, report that there's no
3331 // active union member rather than reporting the prior active union
3332 // member. We'll need to fix nullptr_t to not use APValue() as its
3333 // representation first.
3334 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3335 << handler.AccessKind << Field << !UnionField << UnionField;
3336 return handler.failed();
3337 }
3338 }
3339 O = &O->getUnionValue();
3340 } else
3341 O = &O->getStructField(Field->getFieldIndex());
3342
3343 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3344 LastField = Field;
3345 if (Field->getType().isVolatileQualified())
3346 VolatileField = Field;
3347 } else {
3348 // Next subobject is a base class.
3349 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3350 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3351 O = &O->getStructBase(getBaseIndex(Derived, Base));
3352
3353 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3354 }
3355 }
3356}
3357
3358namespace {
3359struct ExtractSubobjectHandler {
3360 EvalInfo &Info;
3361 const Expr *E;
3362 APValue &Result;
3363 const AccessKinds AccessKind;
3364
3365 typedef bool result_type;
3366 bool failed() { return false; }
3367 bool found(APValue &Subobj, QualType SubobjType) {
3368 Result = Subobj;
3369 if (AccessKind == AK_ReadObjectRepresentation)
3370 return true;
3371 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3372 }
3373 bool found(APSInt &Value, QualType SubobjType) {
3374 Result = APValue(Value);
3375 return true;
3376 }
3377 bool found(APFloat &Value, QualType SubobjType) {
3378 Result = APValue(Value);
3379 return true;
3380 }
3381};
3382} // end anonymous namespace
3383
3384/// Extract the designated sub-object of an rvalue.
3385static bool extractSubobject(EvalInfo &Info, const Expr *E,
3386 const CompleteObject &Obj,
3387 const SubobjectDesignator &Sub, APValue &Result,
3388 AccessKinds AK = AK_Read) {
3389 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation)((AK == AK_Read || AK == AK_ReadObjectRepresentation) ? static_cast
<void> (0) : __assert_fail ("AK == AK_Read || AK == AK_ReadObjectRepresentation"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3389, __PRETTY_FUNCTION__))
;
3390 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3391 return findSubobject(Info, E, Obj, Sub, Handler);
3392}
3393
3394namespace {
3395struct ModifySubobjectHandler {
3396 EvalInfo &Info;
3397 APValue &NewVal;
3398 const Expr *E;
3399
3400 typedef bool result_type;
3401 static const AccessKinds AccessKind = AK_Assign;
3402
3403 bool checkConst(QualType QT) {
3404 // Assigning to a const object has undefined behavior.
3405 if (QT.isConstQualified()) {
3406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3407 return false;
3408 }
3409 return true;
3410 }
3411
3412 bool failed() { return false; }
3413 bool found(APValue &Subobj, QualType SubobjType) {
3414 if (!checkConst(SubobjType))
3415 return false;
3416 // We've been given ownership of NewVal, so just swap it in.
3417 Subobj.swap(NewVal);
3418 return true;
3419 }
3420 bool found(APSInt &Value, QualType SubobjType) {
3421 if (!checkConst(SubobjType))
3422 return false;
3423 if (!NewVal.isInt()) {
3424 // Maybe trying to write a cast pointer value into a complex?
3425 Info.FFDiag(E);
3426 return false;
3427 }
3428 Value = NewVal.getInt();
3429 return true;
3430 }
3431 bool found(APFloat &Value, QualType SubobjType) {
3432 if (!checkConst(SubobjType))
3433 return false;
3434 Value = NewVal.getFloat();
3435 return true;
3436 }
3437};
3438} // end anonymous namespace
3439
3440const AccessKinds ModifySubobjectHandler::AccessKind;
3441
3442/// Update the designated sub-object of an rvalue to the given value.
3443static bool modifySubobject(EvalInfo &Info, const Expr *E,
3444 const CompleteObject &Obj,
3445 const SubobjectDesignator &Sub,
3446 APValue &NewVal) {
3447 ModifySubobjectHandler Handler = { Info, NewVal, E };
3448 return findSubobject(Info, E, Obj, Sub, Handler);
3449}
3450
3451/// Find the position where two subobject designators diverge, or equivalently
3452/// the length of the common initial subsequence.
3453static unsigned FindDesignatorMismatch(QualType ObjType,
3454 const SubobjectDesignator &A,
3455 const SubobjectDesignator &B,
3456 bool &WasArrayIndex) {
3457 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3458 for (/**/; I != N; ++I) {
3459 if (!ObjType.isNull() &&
3460 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3461 // Next subobject is an array element.
3462 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3463 WasArrayIndex = true;
3464 return I;
3465 }
3466 if (ObjType->isAnyComplexType())
3467 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3468 else
3469 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3470 } else {
3471 if (A.Entries[I].getAsBaseOrMember() !=
3472 B.Entries[I].getAsBaseOrMember()) {
3473 WasArrayIndex = false;
3474 return I;
3475 }
3476 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3477 // Next subobject is a field.
3478 ObjType = FD->getType();
3479 else
3480 // Next subobject is a base class.
3481 ObjType = QualType();
3482 }
3483 }
3484 WasArrayIndex = false;
3485 return I;
3486}
3487
3488/// Determine whether the given subobject designators refer to elements of the
3489/// same array object.
3490static bool AreElementsOfSameArray(QualType ObjType,
3491 const SubobjectDesignator &A,
3492 const SubobjectDesignator &B) {
3493 if (A.Entries.size() != B.Entries.size())
3494 return false;
3495
3496 bool IsArray = A.MostDerivedIsArrayElement;
3497 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3498 // A is a subobject of the array element.
3499 return false;
3500
3501 // If A (and B) designates an array element, the last entry will be the array
3502 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3503 // of length 1' case, and the entire path must match.
3504 bool WasArrayIndex;
3505 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3506 return CommonLength >= A.Entries.size() - IsArray;
3507}
3508
3509/// Find the complete object to which an LValue refers.
3510static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3511 AccessKinds AK, const LValue &LVal,
3512 QualType LValType) {
3513 if (LVal.InvalidBase) {
3514 Info.FFDiag(E);
3515 return CompleteObject();
3516 }
3517
3518 if (!LVal.Base) {
3519 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3520 return CompleteObject();
3521 }
3522
3523 CallStackFrame *Frame = nullptr;
3524 unsigned Depth = 0;
3525 if (LVal.getLValueCallIndex()) {
3526 std::tie(Frame, Depth) =
3527 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3528 if (!Frame) {
3529 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3530 << AK << LVal.Base.is<const ValueDecl*>();
3531 NoteLValueLocation(Info, LVal.Base);
3532 return CompleteObject();
3533 }
3534 }
3535
3536 bool IsAccess = isAnyAccess(AK);
3537
3538 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3539 // is not a constant expression (even if the object is non-volatile). We also
3540 // apply this rule to C++98, in order to conform to the expected 'volatile'
3541 // semantics.
3542 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3543 if (Info.getLangOpts().CPlusPlus)
3544 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3545 << AK << LValType;
3546 else
3547 Info.FFDiag(E);
3548 return CompleteObject();
3549 }
3550
3551 // Compute value storage location and type of base object.
3552 APValue *BaseVal = nullptr;
3553 QualType BaseType = getType(LVal.Base);
3554
3555 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3556 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3557 // In C++11, constexpr, non-volatile variables initialized with constant
3558 // expressions are constant expressions too. Inside constexpr functions,
3559 // parameters are constant expressions even if they're non-const.
3560 // In C++1y, objects local to a constant expression (those with a Frame) are
3561 // both readable and writable inside constant expressions.
3562 // In C, such things can also be folded, although they are not ICEs.
3563 const VarDecl *VD = dyn_cast<VarDecl>(D);
3564 if (VD) {
3565 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3566 VD = VDef;
3567 }
3568 if (!VD || VD->isInvalidDecl()) {
3569 Info.FFDiag(E);
3570 return CompleteObject();
3571 }
3572
3573 // Unless we're looking at a local variable or argument in a constexpr call,
3574 // the variable we're reading must be const.
3575 if (!Frame) {
3576 if (Info.getLangOpts().CPlusPlus14 &&
3577 lifetimeStartedInEvaluation(Info, LVal.Base)) {
3578 // OK, we can read and modify an object if we're in the process of
3579 // evaluating its initializer, because its lifetime began in this
3580 // evaluation.
3581 } else if (isModification(AK)) {
3582 // All the remaining cases do not permit modification of the object.
3583 Info.FFDiag(E, diag::note_constexpr_modify_global);
3584 return CompleteObject();
3585 } else if (VD->isConstexpr()) {
3586 // OK, we can read this variable.
3587 } else if (BaseType->isIntegralOrEnumerationType()) {
3588 // In OpenCL if a variable is in constant address space it is a const
3589 // value.
3590 if (!(BaseType.isConstQualified() ||
3591 (Info.getLangOpts().OpenCL &&
3592 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3593 if (!IsAccess)
3594 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3595 if (Info.getLangOpts().CPlusPlus) {
3596 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3597 Info.Note(VD->getLocation(), diag::note_declared_at);
3598 } else {
3599 Info.FFDiag(E);
3600 }
3601 return CompleteObject();
3602 }
3603 } else if (!IsAccess) {
3604 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3605 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3606 // We support folding of const floating-point types, in order to make
3607 // static const data members of such types (supported as an extension)
3608 // more useful.
3609 if (Info.getLangOpts().CPlusPlus11) {
3610 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3611 Info.Note(VD->getLocation(), diag::note_declared_at);
3612 } else {
3613 Info.CCEDiag(E);
3614 }
3615 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3616 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3617 // Keep evaluating to see what we can do.
3618 } else {
3619 // FIXME: Allow folding of values of any literal type in all languages.
3620 if (Info.checkingPotentialConstantExpression() &&
3621 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3622 // The definition of this variable could be constexpr. We can't
3623 // access it right now, but may be able to in future.
3624 } else if (Info.getLangOpts().CPlusPlus11) {
3625 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3626 Info.Note(VD->getLocation(), diag::note_declared_at);
3627 } else {
3628 Info.FFDiag(E);
3629 }
3630 return CompleteObject();
3631 }
3632 }
3633
3634 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3635 return CompleteObject();
3636 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3637 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3638 if (!Alloc) {
3639 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3640 return CompleteObject();
3641 }
3642 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3643 LVal.Base.getDynamicAllocType());
3644 } else {
3645 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3646
3647 if (!Frame) {
3648 if (const MaterializeTemporaryExpr *MTE =
3649 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3650 assert(MTE->getStorageDuration() == SD_Static &&((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary"
) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3651, __PRETTY_FUNCTION__))
3651 "should have a frame for a non-global materialized temporary")((MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary"
) ? static_cast<void> (0) : __assert_fail ("MTE->getStorageDuration() == SD_Static && \"should have a frame for a non-global materialized temporary\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3651, __PRETTY_FUNCTION__))
;
3652
3653 // Per C++1y [expr.const]p2:
3654 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3655 // - a [...] glvalue of integral or enumeration type that refers to
3656 // a non-volatile const object [...]
3657 // [...]
3658 // - a [...] glvalue of literal type that refers to a non-volatile
3659 // object whose lifetime began within the evaluation of e.
3660 //
3661 // C++11 misses the 'began within the evaluation of e' check and
3662 // instead allows all temporaries, including things like:
3663 // int &&r = 1;
3664 // int x = ++r;
3665 // constexpr int k = r;
3666 // Therefore we use the C++14 rules in C++11 too.
3667 //
3668 // Note that temporaries whose lifetimes began while evaluating a
3669 // variable's constructor are not usable while evaluating the
3670 // corresponding destructor, not even if they're of const-qualified
3671 // types.
3672 if (!(BaseType.isConstQualified() &&
3673 BaseType->isIntegralOrEnumerationType()) &&
3674 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3675 if (!IsAccess)
3676 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3677 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3678 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3679 return CompleteObject();
3680 }
3681
3682 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3683 assert(BaseVal && "got reference to unevaluated temporary")((BaseVal && "got reference to unevaluated temporary"
) ? static_cast<void> (0) : __assert_fail ("BaseVal && \"got reference to unevaluated temporary\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3683, __PRETTY_FUNCTION__))
;
3684 } else {
3685 if (!IsAccess)
3686 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3687 APValue Val;
3688 LVal.moveInto(Val);
3689 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3690 << AK
3691 << Val.getAsString(Info.Ctx,
3692 Info.Ctx.getLValueReferenceType(LValType));
3693 NoteLValueLocation(Info, LVal.Base);
3694 return CompleteObject();
3695 }
3696 } else {
3697 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3698 assert(BaseVal && "missing value for temporary")((BaseVal && "missing value for temporary") ? static_cast
<void> (0) : __assert_fail ("BaseVal && \"missing value for temporary\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3698, __PRETTY_FUNCTION__))
;
3699 }
3700 }
3701
3702 // In C++14, we can't safely access any mutable state when we might be
3703 // evaluating after an unmodeled side effect.
3704 //
3705 // FIXME: Not all local state is mutable. Allow local constant subobjects
3706 // to be read here (but take care with 'mutable' fields).
3707 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3708 Info.EvalStatus.HasSideEffects) ||
3709 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3710 return CompleteObject();
3711
3712 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3713}
3714
3715/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3716/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3717/// glvalue referred to by an entity of reference type.
3718///
3719/// \param Info - Information about the ongoing evaluation.
3720/// \param Conv - The expression for which we are performing the conversion.
3721/// Used for diagnostics.
3722/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3723/// case of a non-class type).
3724/// \param LVal - The glvalue on which we are attempting to perform this action.
3725/// \param RVal - The produced value will be placed here.
3726/// \param WantObjectRepresentation - If true, we're looking for the object
3727/// representation rather than the value, and in particular,
3728/// there is no requirement that the result be fully initialized.
3729static bool
3730handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3731 const LValue &LVal, APValue &RVal,
3732 bool WantObjectRepresentation = false) {
3733 if (LVal.Designator.Invalid)
3734 return false;
3735
3736 // Check for special cases where there is no existing APValue to look at.
3737 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3738
3739 AccessKinds AK =
3740 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3741
3742 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3743 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3744 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3745 // initializer until now for such expressions. Such an expression can't be
3746 // an ICE in C, so this only matters for fold.
3747 if (Type.isVolatileQualified()) {
3748 Info.FFDiag(Conv);
3749 return false;
3750 }
3751 APValue Lit;
3752 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3753 return false;
3754 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3755 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3756 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3757 // Special-case character extraction so we don't have to construct an
3758 // APValue for the whole string.
3759 assert(LVal.Designator.Entries.size() <= 1 &&((LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals"
) ? static_cast<void> (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3760, __PRETTY_FUNCTION__))
3760 "Can only read characters from string literals")((LVal.Designator.Entries.size() <= 1 && "Can only read characters from string literals"
) ? static_cast<void> (0) : __assert_fail ("LVal.Designator.Entries.size() <= 1 && \"Can only read characters from string literals\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 3760, __PRETTY_FUNCTION__))
;
3761 if (LVal.Designator.Entries.empty()) {
3762 // Fail for now for LValue to RValue conversion of an array.
3763 // (This shouldn't show up in C/C++, but it could be triggered by a
3764 // weird EvaluateAsRValue call from a tool.)
3765 Info.FFDiag(Conv);
3766 return false;
3767 }
3768 if (LVal.Designator.isOnePastTheEnd()) {
3769 if (Info.getLangOpts().CPlusPlus11)
3770 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3771 else
3772 Info.FFDiag(Conv);
3773 return false;
3774 }
3775 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3776 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3777 return true;
3778 }
3779 }
3780
3781 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3782 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3783}
3784
3785/// Perform an assignment of Val to LVal. Takes ownership of Val.
3786static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3787 QualType LValType, APValue &Val) {
3788 if (LVal.Designator.Invalid)
3789 return false;
3790
3791 if (!Info.getLangOpts().CPlusPlus14) {
3792 Info.FFDiag(E);
3793 return false;
3794 }
3795
3796 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3797 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3798}
3799
3800namespace {
3801struct CompoundAssignSubobjectHandler {
3802 EvalInfo &Info;
3803 const Expr *E;
3804 QualType PromotedLHSType;
3805 BinaryOperatorKind Opcode;
3806 const APValue &RHS;
3807
3808 static const AccessKinds AccessKind = AK_Assign;
3809
3810 typedef bool result_type;
3811
3812 bool checkConst(QualType QT) {
3813 // Assigning to a const object has undefined behavior.
3814 if (QT.isConstQualified()) {
3815 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3816 return false;
3817 }
3818 return true;
3819 }
3820
3821 bool failed() { return false; }
3822 bool found(APValue &Subobj, QualType SubobjType) {
3823 switch (Subobj.getKind()) {
3824 case APValue::Int:
3825 return found(Subobj.getInt(), SubobjType);
3826 case APValue::Float:
3827 return found(Subobj.getFloat(), SubobjType);
3828 case APValue::ComplexInt:
3829 case APValue::ComplexFloat:
3830 // FIXME: Implement complex compound assignment.
3831 Info.FFDiag(E);
3832 return false;
3833 case APValue::LValue:
3834 return foundPointer(Subobj, SubobjType);
3835 default:
3836 // FIXME: can this happen?
3837 Info.FFDiag(E);
3838 return false;
3839 }
3840 }
3841 bool found(APSInt &Value, QualType SubobjType) {
3842 if (!checkConst(SubobjType))
3843 return false;
3844
3845 if (!SubobjType->isIntegerType()) {
3846 // We don't support compound assignment on integer-cast-to-pointer
3847 // values.
3848 Info.FFDiag(E);
3849 return false;
3850 }
3851
3852 if (RHS.isInt()) {
3853 APSInt LHS =
3854 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3855 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3856 return false;
3857 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3858 return true;
3859 } else if (RHS.isFloat()) {
3860 APFloat FValue(0.0);
3861 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3862 FValue) &&
3863 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3864 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3865 Value);
3866 }
3867
3868 Info.FFDiag(E);
3869 return false;
3870 }
3871 bool found(APFloat &Value, QualType SubobjType) {
3872 return checkConst(SubobjType) &&
3873 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3874 Value) &&
3875 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3876 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3877 }
3878 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3879 if (!checkConst(SubobjType))
3880 return false;
3881
3882 QualType PointeeType;
3883 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3884 PointeeType = PT->getPointeeType();
3885
3886 if (PointeeType.isNull() || !RHS.isInt() ||
3887 (Opcode != BO_Add && Opcode != BO_Sub)) {
3888 Info.FFDiag(E);
3889 return false;
3890 }
3891
3892 APSInt Offset = RHS.getInt();
3893 if (Opcode == BO_Sub)
3894 negateAsSigned(Offset);
3895
3896 LValue LVal;
3897 LVal.setFrom(Info.Ctx, Subobj);
3898 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3899 return false;
3900 LVal.moveInto(Subobj);
3901 return true;
3902 }
3903};
3904} // end anonymous namespace
3905
3906const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3907
3908/// Perform a compound assignment of LVal <op>= RVal.
3909static bool handleCompoundAssignment(
3910 EvalInfo &Info, const Expr *E,
3911 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3912 BinaryOperatorKind Opcode, const APValue &RVal) {
3913 if (LVal.Designator.Invalid)
3914 return false;
3915
3916 if (!Info.getLangOpts().CPlusPlus14) {
3917 Info.FFDiag(E);
3918 return false;
3919 }
3920
3921 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3922 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3923 RVal };
3924 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3925}
3926
3927namespace {
3928struct IncDecSubobjectHandler {
3929 EvalInfo &Info;
3930 const UnaryOperator *E;
3931 AccessKinds AccessKind;
3932 APValue *Old;
3933
3934 typedef bool result_type;
3935
3936 bool checkConst(QualType QT) {
3937 // Assigning to a const object has undefined behavior.
3938 if (QT.isConstQualified()) {
3939 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3940 return false;
3941 }
3942 return true;
3943 }
3944
3945 bool failed() { return false; }
3946 bool found(APValue &Subobj, QualType SubobjType) {
3947 // Stash the old value. Also clear Old, so we don't clobber it later
3948 // if we're post-incrementing a complex.
3949 if (Old) {
3950 *Old = Subobj;
3951 Old = nullptr;
3952 }
3953
3954 switch (Subobj.getKind()) {
3955 case APValue::Int:
3956 return found(Subobj.getInt(), SubobjType);
3957 case APValue::Float:
3958 return found(Subobj.getFloat(), SubobjType);
3959 case APValue::ComplexInt:
3960 return found(Subobj.getComplexIntReal(),
3961 SubobjType->castAs<ComplexType>()->getElementType()
3962 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3963 case APValue::ComplexFloat:
3964 return found(Subobj.getComplexFloatReal(),
3965 SubobjType->castAs<ComplexType>()->getElementType()
3966 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3967 case APValue::LValue:
3968 return foundPointer(Subobj, SubobjType);
3969 default:
3970 // FIXME: can this happen?
3971 Info.FFDiag(E);
3972 return false;
3973 }
3974 }
3975 bool found(APSInt &Value, QualType SubobjType) {
3976 if (!checkConst(SubobjType))
3977 return false;
3978
3979 if (!SubobjType->isIntegerType()) {
3980 // We don't support increment / decrement on integer-cast-to-pointer
3981 // values.
3982 Info.FFDiag(E);
3983 return false;
3984 }
3985
3986 if (Old) *Old = APValue(Value);
3987
3988 // bool arithmetic promotes to int, and the conversion back to bool
3989 // doesn't reduce mod 2^n, so special-case it.
3990 if (SubobjType->isBooleanType()) {
3991 if (AccessKind == AK_Increment)
3992 Value = 1;
3993 else
3994 Value = !Value;
3995 return true;
3996 }
3997
3998 bool WasNegative = Value.isNegative();
3999 if (AccessKind == AK_Increment) {
4000 ++Value;
4001
4002 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4003 APSInt ActualValue(Value, /*IsUnsigned*/true);
4004 return HandleOverflow(Info, E, ActualValue, SubobjType);
4005 }
4006 } else {
4007 --Value;
4008
4009 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4010 unsigned BitWidth = Value.getBitWidth();
4011 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4012 ActualValue.setBit(BitWidth);
4013 return HandleOverflow(Info, E, ActualValue, SubobjType);
4014 }
4015 }
4016 return true;
4017 }
4018 bool found(APFloat &Value, QualType SubobjType) {
4019 if (!checkConst(SubobjType))
4020 return false;
4021
4022 if (Old) *Old = APValue(Value);
4023
4024 APFloat One(Value.getSemantics(), 1);
4025 if (AccessKind == AK_Increment)
4026 Value.add(One, APFloat::rmNearestTiesToEven);
4027 else
4028 Value.subtract(One, APFloat::rmNearestTiesToEven);
4029 return true;
4030 }
4031 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4032 if (!checkConst(SubobjType))
4033 return false;
4034
4035 QualType PointeeType;
4036 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4037 PointeeType = PT->getPointeeType();
4038 else {
4039 Info.FFDiag(E);
4040 return false;
4041 }
4042
4043 LValue LVal;
4044 LVal.setFrom(Info.Ctx, Subobj);
4045 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4046 AccessKind == AK_Increment ? 1 : -1))
4047 return false;
4048 LVal.moveInto(Subobj);
4049 return true;
4050 }
4051};
4052} // end anonymous namespace
4053
4054/// Perform an increment or decrement on LVal.
4055static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4056 QualType LValType, bool IsIncrement, APValue *Old) {
4057 if (LVal.Designator.Invalid)
4058 return false;
4059
4060 if (!Info.getLangOpts().CPlusPlus14) {
4061 Info.FFDiag(E);
4062 return false;
4063 }
4064
4065 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4066 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4067 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4068 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4069}
4070
4071/// Build an lvalue for the object argument of a member function call.
4072static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4073 LValue &This) {
4074 if (Object->getType()->isPointerType() && Object->isRValue())
4075 return EvaluatePointer(Object, This, Info);
4076
4077 if (Object->isGLValue())
4078 return EvaluateLValue(Object, This, Info);
4079
4080 if (Object->getType()->isLiteralType(Info.Ctx))
4081 return EvaluateTemporary(Object, This, Info);
4082
4083 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4084 return false;
4085}
4086
4087/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4088/// lvalue referring to the result.
4089///
4090/// \param Info - Information about the ongoing evaluation.
4091/// \param LV - An lvalue referring to the base of the member pointer.
4092/// \param RHS - The member pointer expression.
4093/// \param IncludeMember - Specifies whether the member itself is included in
4094/// the resulting LValue subobject designator. This is not possible when
4095/// creating a bound member function.
4096/// \return The field or method declaration to which the member pointer refers,
4097/// or 0 if evaluation fails.
4098static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4099 QualType LVType,
4100 LValue &LV,
4101 const Expr *RHS,
4102 bool IncludeMember = true) {
4103 MemberPtr MemPtr;
4104 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4105 return nullptr;
4106
4107 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4108 // member value, the behavior is undefined.
4109 if (!MemPtr.getDecl()) {
4110 // FIXME: Specific diagnostic.
4111 Info.FFDiag(RHS);
4112 return nullptr;
4113 }
4114
4115 if (MemPtr.isDerivedMember()) {
4116 // This is a member of some derived class. Truncate LV appropriately.
4117 // The end of the derived-to-base path for the base object must match the
4118 // derived-to-base path for the member pointer.
4119 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4120 LV.Designator.Entries.size()) {
4121 Info.FFDiag(RHS);
4122 return nullptr;
4123 }
4124 unsigned PathLengthToMember =
4125 LV.Designator.Entries.size() - MemPtr.Path.size();
4126 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4127 const CXXRecordDecl *LVDecl = getAsBaseClass(
4128 LV.Designator.Entries[PathLengthToMember + I]);
4129 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4130 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4131 Info.FFDiag(RHS);
4132 return nullptr;
4133 }
4134 }
4135
4136 // Truncate the lvalue to the appropriate derived class.
4137 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4138 PathLengthToMember))
4139 return nullptr;
4140 } else if (!MemPtr.Path.empty()) {
4141 // Extend the LValue path with the member pointer's path.
4142 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4143 MemPtr.Path.size() + IncludeMember);
4144
4145 // Walk down to the appropriate base class.
4146 if (const PointerType *PT = LVType->getAs<PointerType>())
4147 LVType = PT->getPointeeType();
4148 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4149 assert(RD && "member pointer access on non-class-type expression")((RD && "member pointer access on non-class-type expression"
) ? static_cast<void> (0) : __assert_fail ("RD && \"member pointer access on non-class-type expression\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4149, __PRETTY_FUNCTION__))
;
4150 // The first class in the path is that of the lvalue.
4151 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4152 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4153 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4154 return nullptr;
4155 RD = Base;
4156 }
4157 // Finally cast to the class containing the member.
4158 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4159 MemPtr.getContainingRecord()))
4160 return nullptr;
4161 }
4162
4163 // Add the member. Note that we cannot build bound member functions here.
4164 if (IncludeMember) {
4165 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4166 if (!HandleLValueMember(Info, RHS, LV, FD))
4167 return nullptr;
4168 } else if (const IndirectFieldDecl *IFD =
4169 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4170 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4171 return nullptr;
4172 } else {
4173 llvm_unreachable("can't construct reference to bound member function")::llvm::llvm_unreachable_internal("can't construct reference to bound member function"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4173)
;
4174 }
4175 }
4176
4177 return MemPtr.getDecl();
4178}
4179
4180static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4181 const BinaryOperator *BO,
4182 LValue &LV,
4183 bool IncludeMember = true) {
4184 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)((BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4184, __PRETTY_FUNCTION__))
;
4185
4186 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4187 if (Info.noteFailure()) {
4188 MemberPtr MemPtr;
4189 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4190 }
4191 return nullptr;
4192 }
4193
4194 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4195 BO->getRHS(), IncludeMember);
4196}
4197
4198/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4199/// the provided lvalue, which currently refers to the base object.
4200static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4201 LValue &Result) {
4202 SubobjectDesignator &D = Result.Designator;
4203 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4204 return false;
4205
4206 QualType TargetQT = E->getType();
4207 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4208 TargetQT = PT->getPointeeType();
4209
4210 // Check this cast lands within the final derived-to-base subobject path.
4211 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4212 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4213 << D.MostDerivedType << TargetQT;
4214 return false;
4215 }
4216
4217 // Check the type of the final cast. We don't need to check the path,
4218 // since a cast can only be formed if the path is unique.
4219 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4220 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4221 const CXXRecordDecl *FinalType;
4222 if (NewEntriesSize == D.MostDerivedPathLength)
4223 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4224 else
4225 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4226 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4227 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4228 << D.MostDerivedType << TargetQT;
4229 return false;
4230 }
4231
4232 // Truncate the lvalue to the appropriate derived class.
4233 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4234}
4235
4236/// Get the value to use for a default-initialized object of type T.
4237static APValue getDefaultInitValue(QualType T) {
4238 if (auto *RD = T->getAsCXXRecordDecl()) {
4239 if (RD->isUnion())
4240 return APValue((const FieldDecl*)nullptr);
4241
4242 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4243 std::distance(RD->field_begin(), RD->field_end()));
4244
4245 unsigned Index = 0;
4246 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4247 End = RD->bases_end(); I != End; ++I, ++Index)
4248 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4249
4250 for (const auto *I : RD->fields()) {
4251 if (I->isUnnamedBitfield())
4252 continue;
4253 Struct.getStructField(I->getFieldIndex()) =
4254 getDefaultInitValue(I->getType());
4255 }
4256 return Struct;
4257 }
4258
4259 if (auto *AT =
4260 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4261 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4262 if (Array.hasArrayFiller())
4263 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4264 return Array;
4265 }
4266
4267 return APValue::IndeterminateValue();
4268}
4269
4270namespace {
4271enum EvalStmtResult {
4272 /// Evaluation failed.
4273 ESR_Failed,
4274 /// Hit a 'return' statement.
4275 ESR_Returned,
4276 /// Evaluation succeeded.
4277 ESR_Succeeded,
4278 /// Hit a 'continue' statement.
4279 ESR_Continue,
4280 /// Hit a 'break' statement.
4281 ESR_Break,
4282 /// Still scanning for 'case' or 'default' statement.
4283 ESR_CaseNotFound
4284};
4285}
4286
4287static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4288 // We don't need to evaluate the initializer for a static local.
4289 if (!VD->hasLocalStorage())
4290 return true;
4291
4292 LValue Result;
4293 APValue &Val =
4294 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4295
4296 const Expr *InitE = VD->getInit();
4297 if (!InitE) {
4298 Val = getDefaultInitValue(VD->getType());
4299 return true;
4300 }
4301
4302 if (InitE->isValueDependent())
4303 return false;
4304
4305 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4306 // Wipe out any partially-computed value, to allow tracking that this
4307 // evaluation failed.
4308 Val = APValue();
4309 return false;
4310 }
4311
4312 return true;
4313}
4314
4315static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4316 bool OK = true;
4317
4318 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4319 OK &= EvaluateVarDecl(Info, VD);
4320
4321 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4322 for (auto *BD : DD->bindings())
4323 if (auto *VD = BD->getHoldingVar())
4324 OK &= EvaluateDecl(Info, VD);
4325
4326 return OK;
4327}
4328
4329
4330/// Evaluate a condition (either a variable declaration or an expression).
4331static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4332 const Expr *Cond, bool &Result) {
4333 FullExpressionRAII Scope(Info);
4334 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4335 return false;
4336 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4337 return false;
4338 return Scope.destroy();
4339}
4340
4341namespace {
4342/// A location where the result (returned value) of evaluating a
4343/// statement should be stored.
4344struct StmtResult {
4345 /// The APValue that should be filled in with the returned value.
4346 APValue &Value;
4347 /// The location containing the result, if any (used to support RVO).
4348 const LValue *Slot;
4349};
4350
4351struct TempVersionRAII {
4352 CallStackFrame &Frame;
4353
4354 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4355 Frame.pushTempVersion();
4356 }
4357
4358 ~TempVersionRAII() {
4359 Frame.popTempVersion();
4360 }
4361};
4362
4363}
4364
4365static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4366 const Stmt *S,
4367 const SwitchCase *SC = nullptr);
4368
4369/// Evaluate the body of a loop, and translate the result as appropriate.
4370static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4371 const Stmt *Body,
4372 const SwitchCase *Case = nullptr) {
4373 BlockScopeRAII Scope(Info);
4374
4375 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4376 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4377 ESR = ESR_Failed;
4378
4379 switch (ESR) {
4380 case ESR_Break:
4381 return ESR_Succeeded;
4382 case ESR_Succeeded:
4383 case ESR_Continue:
4384 return ESR_Continue;
4385 case ESR_Failed:
4386 case ESR_Returned:
4387 case ESR_CaseNotFound:
4388 return ESR;
4389 }
4390 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4390)
;
4391}
4392
4393/// Evaluate a switch statement.
4394static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4395 const SwitchStmt *SS) {
4396 BlockScopeRAII Scope(Info);
4397
4398 // Evaluate the switch condition.
4399 APSInt Value;
4400 {
4401 if (const Stmt *Init = SS->getInit()) {
4402 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4403 if (ESR != ESR_Succeeded) {
4404 if (ESR != ESR_Failed && !Scope.destroy())
4405 ESR = ESR_Failed;
4406 return ESR;
4407 }
4408 }
4409
4410 FullExpressionRAII CondScope(Info);
4411 if (SS->getConditionVariable() &&
4412 !EvaluateDecl(Info, SS->getConditionVariable()))
4413 return ESR_Failed;
4414 if (!EvaluateInteger(SS->getCond(), Value, Info))
4415 return ESR_Failed;
4416 if (!CondScope.destroy())
4417 return ESR_Failed;
4418 }
4419
4420 // Find the switch case corresponding to the value of the condition.
4421 // FIXME: Cache this lookup.
4422 const SwitchCase *Found = nullptr;
4423 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4424 SC = SC->getNextSwitchCase()) {
4425 if (isa<DefaultStmt>(SC)) {
4426 Found = SC;
4427 continue;
4428 }
4429
4430 const CaseStmt *CS = cast<CaseStmt>(SC);
4431 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4432 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4433 : LHS;
4434 if (LHS <= Value && Value <= RHS) {
4435 Found = SC;
4436 break;
4437 }
4438 }
4439
4440 if (!Found)
4441 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4442
4443 // Search the switch body for the switch case and evaluate it from there.
4444 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4445 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4446 return ESR_Failed;
4447
4448 switch (ESR) {
4449 case ESR_Break:
4450 return ESR_Succeeded;
4451 case ESR_Succeeded:
4452 case ESR_Continue:
4453 case ESR_Failed:
4454 case ESR_Returned:
4455 return ESR;
4456 case ESR_CaseNotFound:
4457 // This can only happen if the switch case is nested within a statement
4458 // expression. We have no intention of supporting that.
4459 Info.FFDiag(Found->getBeginLoc(),
4460 diag::note_constexpr_stmt_expr_unsupported);
4461 return ESR_Failed;
4462 }
4463 llvm_unreachable("Invalid EvalStmtResult!")::llvm::llvm_unreachable_internal("Invalid EvalStmtResult!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4463)
;
4464}
4465
4466// Evaluate a statement.
4467static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4468 const Stmt *S, const SwitchCase *Case) {
4469 if (!Info.nextStep(S))
4470 return ESR_Failed;
4471
4472 // If we're hunting down a 'case' or 'default' label, recurse through
4473 // substatements until we hit the label.
4474 if (Case) {
4475 switch (S->getStmtClass()) {
4476 case Stmt::CompoundStmtClass:
4477 // FIXME: Precompute which substatement of a compound statement we
4478 // would jump to, and go straight there rather than performing a
4479 // linear scan each time.
4480 case Stmt::LabelStmtClass:
4481 case Stmt::AttributedStmtClass:
4482 case Stmt::DoStmtClass:
4483 break;
4484
4485 case Stmt::CaseStmtClass:
4486 case Stmt::DefaultStmtClass:
4487 if (Case == S)
4488 Case = nullptr;
4489 break;
4490
4491 case Stmt::IfStmtClass: {
4492 // FIXME: Precompute which side of an 'if' we would jump to, and go
4493 // straight there rather than scanning both sides.
4494 const IfStmt *IS = cast<IfStmt>(S);
4495
4496 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4497 // preceded by our switch label.
4498 BlockScopeRAII Scope(Info);
4499
4500 // Step into the init statement in case it brings an (uninitialized)
4501 // variable into scope.
4502 if (const Stmt *Init = IS->getInit()) {
4503 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4504 if (ESR != ESR_CaseNotFound) {
4505 assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail
("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4505, __PRETTY_FUNCTION__))
;
4506 return ESR;
4507 }
4508 }
4509
4510 // Condition variable must be initialized if it exists.
4511 // FIXME: We can skip evaluating the body if there's a condition
4512 // variable, as there can't be any case labels within it.
4513 // (The same is true for 'for' statements.)
4514
4515 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4516 if (ESR == ESR_Failed)
4517 return ESR;
4518 if (ESR != ESR_CaseNotFound)
4519 return Scope.destroy() ? ESR : ESR_Failed;
4520 if (!IS->getElse())
4521 return ESR_CaseNotFound;
4522
4523 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4524 if (ESR == ESR_Failed)
4525 return ESR;
4526 if (ESR != ESR_CaseNotFound)
4527 return Scope.destroy() ? ESR : ESR_Failed;
4528 return ESR_CaseNotFound;
4529 }
4530
4531 case Stmt::WhileStmtClass: {
4532 EvalStmtResult ESR =
4533 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4534 if (ESR != ESR_Continue)
4535 return ESR;
4536 break;
4537 }
4538
4539 case Stmt::ForStmtClass: {
4540 const ForStmt *FS = cast<ForStmt>(S);
4541 BlockScopeRAII Scope(Info);
4542
4543 // Step into the init statement in case it brings an (uninitialized)
4544 // variable into scope.
4545 if (const Stmt *Init = FS->getInit()) {
4546 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4547 if (ESR != ESR_CaseNotFound) {
4548 assert(ESR != ESR_Succeeded)((ESR != ESR_Succeeded) ? static_cast<void> (0) : __assert_fail
("ESR != ESR_Succeeded", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 4548, __PRETTY_FUNCTION__))
;
4549 return ESR;
4550 }
4551 }
4552
4553 EvalStmtResult ESR =
4554 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4555 if (ESR != ESR_Continue)
4556 return ESR;
4557 if (FS->getInc()) {
4558 FullExpressionRAII IncScope(Info);
4559 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4560 return ESR_Failed;
4561 }
4562 break;
4563 }
4564
4565 case Stmt::DeclStmtClass: {
4566 // Start the lifetime of any uninitialized variables we encounter. They
4567 // might be used by the selected branch of the switch.
4568 const DeclStmt *DS = cast<DeclStmt>(S);
4569 for (const auto *D : DS->decls()) {
4570 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4571 if (VD->hasLocalStorage() && !VD->getInit())
4572 if (!EvaluateVarDecl(Info, VD))
4573 return ESR_Failed;
4574 // FIXME: If the variable has initialization that can't be jumped
4575 // over, bail out of any immediately-surrounding compound-statement
4576 // too. There can't be any case labels here.
4577 }
4578 }
4579 return ESR_CaseNotFound;
4580 }
4581
4582 default:
4583 return ESR_CaseNotFound;
4584 }
4585 }
4586
4587 switch (S->getStmtClass()) {
4588 default:
4589 if (const Expr *E = dyn_cast<Expr>(S)) {
4590 // Don't bother evaluating beyond an expression-statement which couldn't
4591 // be evaluated.
4592 // FIXME: Do we need the FullExpressionRAII object here?
4593 // VisitExprWithCleanups should create one when necessary.
4594 FullExpressionRAII Scope(Info);
4595 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4596 return ESR_Failed;
4597 return ESR_Succeeded;
4598 }
4599
4600 Info.FFDiag(S->getBeginLoc());
4601 return ESR_Failed;
4602
4603 case Stmt::NullStmtClass:
4604 return ESR_Succeeded;
4605
4606 case Stmt::DeclStmtClass: {
4607 const DeclStmt *DS = cast<DeclStmt>(S);
4608 for (const auto *D : DS->decls()) {
4609 // Each declaration initialization is its own full-expression.
4610 FullExpressionRAII Scope(Info);
4611 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4612 return ESR_Failed;
4613 if (!Scope.destroy())
4614 return ESR_Failed;
4615 }
4616 return ESR_Succeeded;
4617 }
4618
4619 case Stmt::ReturnStmtClass: {
4620 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4621 FullExpressionRAII Scope(Info);
4622 if (RetExpr &&
4623 !(Result.Slot
4624 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4625 : Evaluate(Result.Value, Info, RetExpr)))
4626 return ESR_Failed;
4627 return Scope.destroy() ? ESR_Returned : ESR_Failed;
4628 }
4629
4630 case Stmt::CompoundStmtClass: {
4631 BlockScopeRAII Scope(Info);
4632
4633 const CompoundStmt *CS = cast<CompoundStmt>(S);
4634 for (const auto *BI : CS->body()) {
4635 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4636 if (ESR == ESR_Succeeded)
4637 Case = nullptr;
4638 else if (ESR != ESR_CaseNotFound) {
4639 if (ESR != ESR_Failed && !Scope.destroy())
4640 return ESR_Failed;
4641 return ESR;
4642 }
4643 }
4644 if (Case)
4645 return ESR_CaseNotFound;
4646 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4647 }
4648
4649 case Stmt::IfStmtClass: {
4650 const IfStmt *IS = cast<IfStmt>(S);
4651
4652 // Evaluate the condition, as either a var decl or as an expression.
4653 BlockScopeRAII Scope(Info);
4654 if (const Stmt *Init = IS->getInit()) {
4655 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4656 if (ESR != ESR_Succeeded) {
4657 if (ESR != ESR_Failed && !Scope.destroy())
4658 return ESR_Failed;
4659 return ESR;
4660 }
4661 }
4662 bool Cond;
4663 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4664 return ESR_Failed;
4665
4666 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4667 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4668 if (ESR != ESR_Succeeded) {
4669 if (ESR != ESR_Failed && !Scope.destroy())
4670 return ESR_Failed;
4671 return ESR;
4672 }
4673 }
4674 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4675 }
4676
4677 case Stmt::WhileStmtClass: {
4678 const WhileStmt *WS = cast<WhileStmt>(S);
4679 while (true) {
4680 BlockScopeRAII Scope(Info);
4681 bool Continue;
4682 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4683 Continue))
4684 return ESR_Failed;
4685 if (!Continue)
4686 break;
4687
4688 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4689 if (ESR != ESR_Continue) {
4690 if (ESR != ESR_Failed && !Scope.destroy())
4691 return ESR_Failed;
4692 return ESR;
4693 }
4694 if (!Scope.destroy())
4695 return ESR_Failed;
4696 }
4697 return ESR_Succeeded;
4698 }
4699
4700 case Stmt::DoStmtClass: {
4701 const DoStmt *DS = cast<DoStmt>(S);
4702 bool Continue;
4703 do {
4704 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4705 if (ESR != ESR_Continue)
4706 return ESR;
4707 Case = nullptr;
4708
4709 FullExpressionRAII CondScope(Info);
4710 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4711 !CondScope.destroy())
4712 return ESR_Failed;
4713 } while (Continue);
4714 return ESR_Succeeded;
4715 }
4716
4717 case Stmt::ForStmtClass: {
4718 const ForStmt *FS = cast<ForStmt>(S);
4719 BlockScopeRAII ForScope(Info);
4720 if (FS->getInit()) {
4721 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4722 if (ESR != ESR_Succeeded) {
4723 if (ESR != ESR_Failed && !ForScope.destroy())
4724 return ESR_Failed;
4725 return ESR;
4726 }
4727 }
4728 while (true) {
4729 BlockScopeRAII IterScope(Info);
4730 bool Continue = true;
4731 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4732 FS->getCond(), Continue))
4733 return ESR_Failed;
4734 if (!Continue)
4735 break;
4736
4737 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4738 if (ESR != ESR_Continue) {
4739 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4740 return ESR_Failed;
4741 return ESR;
4742 }
4743
4744 if (FS->getInc()) {
4745 FullExpressionRAII IncScope(Info);
4746 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4747 return ESR_Failed;
4748 }
4749
4750 if (!IterScope.destroy())
4751 return ESR_Failed;
4752 }
4753 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4754 }
4755
4756 case Stmt::CXXForRangeStmtClass: {
4757 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4758 BlockScopeRAII Scope(Info);
4759
4760 // Evaluate the init-statement if present.
4761 if (FS->getInit()) {
4762 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4763 if (ESR != ESR_Succeeded) {
4764 if (ESR != ESR_Failed && !Scope.destroy())
4765 return ESR_Failed;
4766 return ESR;
4767 }
4768 }
4769
4770 // Initialize the __range variable.
4771 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4772 if (ESR != ESR_Succeeded) {
4773 if (ESR != ESR_Failed && !Scope.destroy())
4774 return ESR_Failed;
4775 return ESR;
4776 }
4777
4778 // Create the __begin and __end iterators.
4779 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4780 if (ESR != ESR_Succeeded) {
4781 if (ESR != ESR_Failed && !Scope.destroy())
4782 return ESR_Failed;
4783 return ESR;
4784 }
4785 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4786 if (ESR != ESR_Succeeded) {
4787 if (ESR != ESR_Failed && !Scope.destroy())
4788 return ESR_Failed;
4789 return ESR;
4790 }
4791
4792 while (true) {
4793 // Condition: __begin != __end.
4794 {
4795 bool Continue = true;
4796 FullExpressionRAII CondExpr(Info);
4797 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4798 return ESR_Failed;
4799 if (!Continue)
4800 break;
4801 }
4802
4803 // User's variable declaration, initialized by *__begin.
4804 BlockScopeRAII InnerScope(Info);
4805 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4806 if (ESR != ESR_Succeeded) {
4807 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4808 return ESR_Failed;
4809 return ESR;
4810 }
4811
4812 // Loop body.
4813 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4814 if (ESR != ESR_Continue) {
4815 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4816 return ESR_Failed;
4817 return ESR;
4818 }
4819
4820 // Increment: ++__begin
4821 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4822 return ESR_Failed;
4823
4824 if (!InnerScope.destroy())
4825 return ESR_Failed;
4826 }
4827
4828 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4829 }
4830
4831 case Stmt::SwitchStmtClass:
4832 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4833
4834 case Stmt::ContinueStmtClass:
4835 return ESR_Continue;
4836
4837 case Stmt::BreakStmtClass:
4838 return ESR_Break;
4839
4840 case Stmt::LabelStmtClass:
4841 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4842
4843 case Stmt::AttributedStmtClass:
4844 // As a general principle, C++11 attributes can be ignored without
4845 // any semantic impact.
4846 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4847 Case);
4848
4849 case Stmt::CaseStmtClass:
4850 case Stmt::DefaultStmtClass:
4851 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4852 case Stmt::CXXTryStmtClass:
4853 // Evaluate try blocks by evaluating all sub statements.
4854 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4855 }
4856}
4857
4858/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4859/// default constructor. If so, we'll fold it whether or not it's marked as
4860/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4861/// so we need special handling.
4862static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4863 const CXXConstructorDecl *CD,
4864 bool IsValueInitialization) {
4865 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4866 return false;
4867
4868 // Value-initialization does not call a trivial default constructor, so such a
4869 // call is a core constant expression whether or not the constructor is
4870 // constexpr.
4871 if (!CD->isConstexpr() && !IsValueInitialization) {
4872 if (Info.getLangOpts().CPlusPlus11) {
4873 // FIXME: If DiagDecl is an implicitly-declared special member function,
4874 // we should be much more explicit about why it's not constexpr.
4875 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4876 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4877 Info.Note(CD->getLocation(), diag::note_declared_at);
4878 } else {
4879 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4880 }
4881 }
4882 return true;
4883}
4884
4885/// CheckConstexprFunction - Check that a function can be called in a constant
4886/// expression.
4887static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4888 const FunctionDecl *Declaration,
4889 const FunctionDecl *Definition,
4890 const Stmt *Body) {
4891 // Potential constant expressions can contain calls to declared, but not yet
4892 // defined, constexpr functions.
4893 if (Info.checkingPotentialConstantExpression() && !Definition &&
18
Assuming the condition is false
4894 Declaration->isConstexpr())
4895 return false;
4896
4897 // Bail out if the function declaration itself is invalid. We will
4898 // have produced a relevant diagnostic while parsing it, so just
4899 // note the problematic sub-expression.
4900 if (Declaration->isInvalidDecl()) {
19
Assuming the condition is false
20
Taking false branch
4901 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4902 return false;
4903 }
4904
4905 // DR1872: An instantiated virtual constexpr function can't be called in a
4906 // constant expression (prior to C++20). We can still constant-fold such a
4907 // call.
4908 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
21
Assuming field 'CPlusPlus2a' is not equal to 0
4909 cast<CXXMethodDecl>(Declaration)->isVirtual())
4910 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4911
4912 if (Definition && Definition->isInvalidDecl()) {
22
Assuming 'Definition' is non-null
23
Assuming the condition is false
24
Taking false branch
4913 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4914 return false;
4915 }
4916
4917 // Can we evaluate this function call?
4918 if (Definition
24.1
'Definition' is non-null
24.1
'Definition' is non-null
24.1
'Definition' is non-null
&& Definition->isConstexpr() && Body)
25
Assuming 'Body' is non-null
26
Taking true branch
4919 return true;
4920
4921 if (Info.getLangOpts().CPlusPlus11) {
4922 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4923
4924 // If this function is not constexpr because it is an inherited
4925 // non-constexpr constructor, diagnose that directly.
4926 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4927 if (CD && CD->isInheritingConstructor()) {
4928 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4929 if (!Inherited->isConstexpr())
4930 DiagDecl = CD = Inherited;
4931 }
4932
4933 // FIXME: If DiagDecl is an implicitly-declared special member function
4934 // or an inheriting constructor, we should be much more explicit about why
4935 // it's not constexpr.
4936 if (CD && CD->isInheritingConstructor())
4937 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4938 << CD->getInheritedConstructor().getConstructor()->getParent();
4939 else
4940 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4941 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4942 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4943 } else {
4944 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4945 }
4946 return false;
4947}
4948
4949namespace {
4950struct CheckDynamicTypeHandler {
4951 AccessKinds AccessKind;
4952 typedef bool result_type;
4953 bool failed() { return false; }
4954 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4955 bool found(APSInt &Value, QualType SubobjType) { return true; }
4956 bool found(APFloat &Value, QualType SubobjType) { return true; }
4957};
4958} // end anonymous namespace
4959
4960/// Check that we can access the notional vptr of an object / determine its
4961/// dynamic type.
4962static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4963 AccessKinds AK, bool Polymorphic) {
4964 if (This.Designator.Invalid)
4965 return false;
4966
4967 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4968
4969 if (!Obj)
4970 return false;
4971
4972 if (!Obj.Value) {
4973 // The object is not usable in constant expressions, so we can't inspect
4974 // its value to see if it's in-lifetime or what the active union members
4975 // are. We can still check for a one-past-the-end lvalue.
4976 if (This.Designator.isOnePastTheEnd() ||
4977 This.Designator.isMostDerivedAnUnsizedArray()) {
4978 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4979 ? diag::note_constexpr_access_past_end
4980 : diag::note_constexpr_access_unsized_array)
4981 << AK;
4982 return false;
4983 } else if (Polymorphic) {
4984 // Conservatively refuse to perform a polymorphic operation if we would
4985 // not be able to read a notional 'vptr' value.
4986 APValue Val;
4987 This.moveInto(Val);
4988 QualType StarThisType =
4989 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4990 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4991 << AK << Val.getAsString(Info.Ctx, StarThisType);
4992 return false;
4993 }
4994 return true;
4995 }
4996
4997 CheckDynamicTypeHandler Handler{AK};
4998 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4999}
5000
5001/// Check that the pointee of the 'this' pointer in a member function call is
5002/// either within its lifetime or in its period of construction or destruction.
5003static bool
5004checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5005 const LValue &This,
5006 const CXXMethodDecl *NamedMember) {
5007 return checkDynamicType(
5008 Info, E, This,
5009 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5010}
5011
5012struct DynamicType {
5013 /// The dynamic class type of the object.
5014 const CXXRecordDecl *Type;
5015 /// The corresponding path length in the lvalue.
5016 unsigned PathLength;
5017};
5018
5019static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5020 unsigned PathLength) {
5021 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=((PathLength >= Designator.MostDerivedPathLength &&
PathLength <= Designator.Entries.size() && "invalid path length"
) ? static_cast<void> (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5022, __PRETTY_FUNCTION__))
5022 Designator.Entries.size() && "invalid path length")((PathLength >= Designator.MostDerivedPathLength &&
PathLength <= Designator.Entries.size() && "invalid path length"
) ? static_cast<void> (0) : __assert_fail ("PathLength >= Designator.MostDerivedPathLength && PathLength <= Designator.Entries.size() && \"invalid path length\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5022, __PRETTY_FUNCTION__))
;
5023 return (PathLength == Designator.MostDerivedPathLength)
5024 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5025 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5026}
5027
5028/// Determine the dynamic type of an object.
5029static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5030 LValue &This, AccessKinds AK) {
5031 // If we don't have an lvalue denoting an object of class type, there is no
5032 // meaningful dynamic type. (We consider objects of non-class type to have no
5033 // dynamic type.)
5034 if (!checkDynamicType(Info, E, This, AK, true))
5035 return None;
5036
5037 // Refuse to compute a dynamic type in the presence of virtual bases. This
5038 // shouldn't happen other than in constant-folding situations, since literal
5039 // types can't have virtual bases.
5040 //
5041 // Note that consumers of DynamicType assume that the type has no virtual
5042 // bases, and will need modifications if this restriction is relaxed.
5043 const CXXRecordDecl *Class =
5044 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5045 if (!Class || Class->getNumVBases()) {
5046 Info.FFDiag(E);
5047 return None;
5048 }
5049
5050 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5051 // binary search here instead. But the overwhelmingly common case is that
5052 // we're not in the middle of a constructor, so it probably doesn't matter
5053 // in practice.
5054 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5055 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5056 PathLength <= Path.size(); ++PathLength) {
5057 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5058 Path.slice(0, PathLength))) {
5059 case ConstructionPhase::Bases:
5060 case ConstructionPhase::DestroyingBases:
5061 // We're constructing or destroying a base class. This is not the dynamic
5062 // type.
5063 break;
5064
5065 case ConstructionPhase::None:
5066 case ConstructionPhase::AfterBases:
5067 case ConstructionPhase::Destroying:
5068 // We've finished constructing the base classes and not yet started
5069 // destroying them again, so this is the dynamic type.
5070 return DynamicType{getBaseClassType(This.Designator, PathLength),
5071 PathLength};
5072 }
5073 }
5074
5075 // CWG issue 1517: we're constructing a base class of the object described by
5076 // 'This', so that object has not yet begun its period of construction and
5077 // any polymorphic operation on it results in undefined behavior.
5078 Info.FFDiag(E);
5079 return None;
5080}
5081
5082/// Perform virtual dispatch.
5083static const CXXMethodDecl *HandleVirtualDispatch(
5084 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5085 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5086 Optional<DynamicType> DynType = ComputeDynamicType(
5087 Info, E, This,
5088 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5089 if (!DynType)
5090 return nullptr;
5091
5092 // Find the final overrider. It must be declared in one of the classes on the
5093 // path from the dynamic type to the static type.
5094 // FIXME: If we ever allow literal types to have virtual base classes, that
5095 // won't be true.
5096 const CXXMethodDecl *Callee = Found;
5097 unsigned PathLength = DynType->PathLength;
5098 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5099 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5100 const CXXMethodDecl *Overrider =
5101 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5102 if (Overrider) {
5103 Callee = Overrider;
5104 break;
5105 }
5106 }
5107
5108 // C++2a [class.abstract]p6:
5109 // the effect of making a virtual call to a pure virtual function [...] is
5110 // undefined
5111 if (Callee->isPure()) {
5112 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5113 Info.Note(Callee->getLocation(), diag::note_declared_at);
5114 return nullptr;
5115 }
5116
5117 // If necessary, walk the rest of the path to determine the sequence of
5118 // covariant adjustment steps to apply.
5119 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5120 Found->getReturnType())) {
5121 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5122 for (unsigned CovariantPathLength = PathLength + 1;
5123 CovariantPathLength != This.Designator.Entries.size();
5124 ++CovariantPathLength) {
5125 const CXXRecordDecl *NextClass =
5126 getBaseClassType(This.Designator, CovariantPathLength);
5127 const CXXMethodDecl *Next =
5128 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5129 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5130 Next->getReturnType(), CovariantAdjustmentPath.back()))
5131 CovariantAdjustmentPath.push_back(Next->getReturnType());
5132 }
5133 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5134 CovariantAdjustmentPath.back()))
5135 CovariantAdjustmentPath.push_back(Found->getReturnType());
5136 }
5137
5138 // Perform 'this' adjustment.
5139 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5140 return nullptr;
5141
5142 return Callee;
5143}
5144
5145/// Perform the adjustment from a value returned by a virtual function to
5146/// a value of the statically expected type, which may be a pointer or
5147/// reference to a base class of the returned type.
5148static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5149 APValue &Result,
5150 ArrayRef<QualType> Path) {
5151 assert(Result.isLValue() &&((Result.isLValue() && "unexpected kind of APValue for covariant return"
) ? static_cast<void> (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5152, __PRETTY_FUNCTION__))
5152 "unexpected kind of APValue for covariant return")((Result.isLValue() && "unexpected kind of APValue for covariant return"
) ? static_cast<void> (0) : __assert_fail ("Result.isLValue() && \"unexpected kind of APValue for covariant return\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5152, __PRETTY_FUNCTION__))
;
5153 if (Result.isNullPointer())
5154 return true;
5155
5156 LValue LVal;
5157 LVal.setFrom(Info.Ctx, Result);
5158
5159 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5160 for (unsigned I = 1; I != Path.size(); ++I) {
5161 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5162 assert(OldClass && NewClass && "unexpected kind of covariant return")((OldClass && NewClass && "unexpected kind of covariant return"
) ? static_cast<void> (0) : __assert_fail ("OldClass && NewClass && \"unexpected kind of covariant return\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5162, __PRETTY_FUNCTION__))
;
5163 if (OldClass != NewClass &&
5164 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5165 return false;
5166 OldClass = NewClass;
5167 }
5168
5169 LVal.moveInto(Result);
5170 return true;
5171}
5172
5173/// Determine whether \p Base, which is known to be a direct base class of
5174/// \p Derived, is a public base class.
5175static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5176 const CXXRecordDecl *Base) {
5177 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5178 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5179 if (BaseClass && declaresSameEntity(BaseClass, Base))
5180 return BaseSpec.getAccessSpecifier() == AS_public;
5181 }
5182 llvm_unreachable("Base is not a direct base of Derived")::llvm::llvm_unreachable_internal("Base is not a direct base of Derived"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5182)
;
5183}
5184
5185/// Apply the given dynamic cast operation on the provided lvalue.
5186///
5187/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5188/// to find a suitable target subobject.
5189static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5190 LValue &Ptr) {
5191 // We can't do anything with a non-symbolic pointer value.
5192 SubobjectDesignator &D = Ptr.Designator;
5193 if (D.Invalid)
5194 return false;
5195
5196 // C++ [expr.dynamic.cast]p6:
5197 // If v is a null pointer value, the result is a null pointer value.
5198 if (Ptr.isNullPointer() && !E->isGLValue())
5199 return true;
5200
5201 // For all the other cases, we need the pointer to point to an object within
5202 // its lifetime / period of construction / destruction, and we need to know
5203 // its dynamic type.
5204 Optional<DynamicType> DynType =
5205 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5206 if (!DynType)
5207 return false;
5208
5209 // C++ [expr.dynamic.cast]p7:
5210 // If T is "pointer to cv void", then the result is a pointer to the most
5211 // derived object
5212 if (E->getType()->isVoidPointerType())
5213 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5214
5215 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5216 assert(C && "dynamic_cast target is not void pointer nor class")((C && "dynamic_cast target is not void pointer nor class"
) ? static_cast<void> (0) : __assert_fail ("C && \"dynamic_cast target is not void pointer nor class\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5216, __PRETTY_FUNCTION__))
;
5217 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5218
5219 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5220 // C++ [expr.dynamic.cast]p9:
5221 if (!E->isGLValue()) {
5222 // The value of a failed cast to pointer type is the null pointer value
5223 // of the required result type.
5224 Ptr.setNull(Info.Ctx, E->getType());
5225 return true;
5226 }
5227
5228 // A failed cast to reference type throws [...] std::bad_cast.
5229 unsigned DiagKind;
5230 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5231 DynType->Type->isDerivedFrom(C)))
5232 DiagKind = 0;
5233 else if (!Paths || Paths->begin() == Paths->end())
5234 DiagKind = 1;
5235 else if (Paths->isAmbiguous(CQT))
5236 DiagKind = 2;
5237 else {
5238 assert(Paths->front().Access != AS_public && "why did the cast fail?")((Paths->front().Access != AS_public && "why did the cast fail?"
) ? static_cast<void> (0) : __assert_fail ("Paths->front().Access != AS_public && \"why did the cast fail?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5238, __PRETTY_FUNCTION__))
;
5239 DiagKind = 3;
5240 }
5241 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5242 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5243 << Info.Ctx.getRecordType(DynType->Type)
5244 << E->getType().getUnqualifiedType();
5245 return false;
5246 };
5247
5248 // Runtime check, phase 1:
5249 // Walk from the base subobject towards the derived object looking for the
5250 // target type.
5251 for (int PathLength = Ptr.Designator.Entries.size();
5252 PathLength >= (int)DynType->PathLength; --PathLength) {
5253 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5254 if (declaresSameEntity(Class, C))
5255 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5256 // We can only walk across public inheritance edges.
5257 if (PathLength > (int)DynType->PathLength &&
5258 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5259 Class))
5260 return RuntimeCheckFailed(nullptr);
5261 }
5262
5263 // Runtime check, phase 2:
5264 // Search the dynamic type for an unambiguous public base of type C.
5265 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5266 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5267 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5268 Paths.front().Access == AS_public) {
5269 // Downcast to the dynamic type...
5270 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5271 return false;
5272 // ... then upcast to the chosen base class subobject.
5273 for (CXXBasePathElement &Elem : Paths.front())
5274 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5275 return false;
5276 return true;
5277 }
5278
5279 // Otherwise, the runtime check fails.
5280 return RuntimeCheckFailed(&Paths);
5281}
5282
5283namespace {
5284struct StartLifetimeOfUnionMemberHandler {
5285 const FieldDecl *Field;
5286
5287 static const AccessKinds AccessKind = AK_Assign;
5288
5289 typedef bool result_type;
5290 bool failed() { return false; }
5291 bool found(APValue &Subobj, QualType SubobjType) {
5292 // We are supposed to perform no initialization but begin the lifetime of
5293 // the object. We interpret that as meaning to do what default
5294 // initialization of the object would do if all constructors involved were
5295 // trivial:
5296 // * All base, non-variant member, and array element subobjects' lifetimes
5297 // begin
5298 // * No variant members' lifetimes begin
5299 // * All scalar subobjects whose lifetimes begin have indeterminate values
5300 assert(SubobjType->isUnionType())((SubobjType->isUnionType()) ? static_cast<void> (0)
: __assert_fail ("SubobjType->isUnionType()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5300, __PRETTY_FUNCTION__))
;
5301 if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5302 !Subobj.getUnionValue().hasValue())
5303 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5304 return true;
5305 }
5306 bool found(APSInt &Value, QualType SubobjType) {
5307 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5307)
;
5308 }
5309 bool found(APFloat &Value, QualType SubobjType) {
5310 llvm_unreachable("wrong value kind for union object")::llvm::llvm_unreachable_internal("wrong value kind for union object"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5310)
;
5311 }
5312};
5313} // end anonymous namespace
5314
5315const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5316
5317/// Handle a builtin simple-assignment or a call to a trivial assignment
5318/// operator whose left-hand side might involve a union member access. If it
5319/// does, implicitly start the lifetime of any accessed union elements per
5320/// C++20 [class.union]5.
5321static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5322 const LValue &LHS) {
5323 if (LHS.InvalidBase || LHS.Designator.Invalid)
63
Assuming field 'InvalidBase' is false
64
Assuming field 'Invalid' is 0
65
Taking false branch
5324 return false;
5325
5326 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5327 // C++ [class.union]p5:
5328 // define the set S(E) of subexpressions of E as follows:
5329 unsigned PathLength = LHS.Designator.Entries.size();
5330 for (const Expr *E = LHSExpr; E != nullptr;) {
66
Assuming the condition is false
67
Assuming pointer value is null
68
Loop condition is false. Execution continues on line 5391
5331 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5332 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5333 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5334 // Note that we can't implicitly start the lifetime of a reference,
5335 // so we don't need to proceed any further if we reach one.
5336 if (!FD || FD->getType()->isReferenceType())
5337 break;
5338
5339 // ... and also contains A.B if B names a union member ...
5340 if (FD->getParent()->isUnion()) {
5341 // ... of a non-class, non-array type, or of a class type with a
5342 // trivial default constructor that is not deleted, or an array of
5343 // such types.
5344 auto *RD =
5345 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5346 if (!RD || RD->hasTrivialDefaultConstructor())
5347 UnionPathLengths.push_back({PathLength - 1, FD});
5348 }
5349
5350 E = ME->getBase();
5351 --PathLength;
5352 assert(declaresSameEntity(FD,((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .
getAsBaseOrMember().getPointer())) ? static_cast<void> (
0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5354, __PRETTY_FUNCTION__))
5353 LHS.Designator.Entries[PathLength]((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .
getAsBaseOrMember().getPointer())) ? static_cast<void> (
0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5354, __PRETTY_FUNCTION__))
5354 .getAsBaseOrMember().getPointer()))((declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .
getAsBaseOrMember().getPointer())) ? static_cast<void> (
0) : __assert_fail ("declaresSameEntity(FD, LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5354, __PRETTY_FUNCTION__))
;
5355
5356 // -- If E is of the form A[B] and is interpreted as a built-in array
5357 // subscripting operator, S(E) is [S(the array operand, if any)].
5358 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5359 // Step over an ArrayToPointerDecay implicit cast.
5360 auto *Base = ASE->getBase()->IgnoreImplicit();
5361 if (!Base->getType()->isArrayType())
5362 break;
5363
5364 E = Base;
5365 --PathLength;
5366
5367 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5368 // Step over a derived-to-base conversion.
5369 E = ICE->getSubExpr();
5370 if (ICE->getCastKind() == CK_NoOp)
5371 continue;
5372 if (ICE->getCastKind() != CK_DerivedToBase &&
5373 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5374 break;
5375 // Walk path backwards as we walk up from the base to the derived class.
5376 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5377 --PathLength;
5378 (void)Elt;
5379 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl
(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer
())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5381, __PRETTY_FUNCTION__))
5380 LHS.Designator.Entries[PathLength]((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl
(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer
())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5381, __PRETTY_FUNCTION__))
5381 .getAsBaseOrMember().getPointer()))((declaresSameEntity(Elt->getType()->getAsCXXRecordDecl
(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer
())) ? static_cast<void> (0) : __assert_fail ("declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] .getAsBaseOrMember().getPointer())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5381, __PRETTY_FUNCTION__))
;
5382 }
5383
5384 // -- Otherwise, S(E) is empty.
5385 } else {
5386 break;
5387 }
5388 }
5389
5390 // Common case: no unions' lifetimes are started.
5391 if (UnionPathLengths.empty())
69
Calling 'SmallVectorBase::empty'
72
Returning from 'SmallVectorBase::empty'
73
Taking false branch
5392 return true;
5393
5394 // if modification of X [would access an inactive union member], an object
5395 // of the type of X is implicitly created
5396 CompleteObject Obj =
5397 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
74
Called C++ object pointer is null
5398 if (!Obj)
5399 return false;
5400 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5401 llvm::reverse(UnionPathLengths)) {
5402 // Form a designator for the union object.
5403 SubobjectDesignator D = LHS.Designator;
5404 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5405
5406 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5407 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5408 return false;
5409 }
5410
5411 return true;
5412}
5413
5414/// Determine if a class has any fields that might need to be copied by a
5415/// trivial copy or move operation.
5416static bool hasFields(const CXXRecordDecl *RD) {
5417 if (!RD || RD->isEmpty())
5418 return false;
5419 for (auto *FD : RD->fields()) {
5420 if (FD->isUnnamedBitfield())
5421 continue;
5422 return true;
5423 }
5424 for (auto &Base : RD->bases())
5425 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5426 return true;
5427 return false;
5428}
5429
5430namespace {
5431typedef SmallVector<APValue, 8> ArgVector;
5432}
5433
5434/// EvaluateArgs - Evaluate the arguments to a function call.
5435static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5436 EvalInfo &Info, const FunctionDecl *Callee) {
5437 bool Success = true;
5438 llvm::SmallBitVector ForbiddenNullArgs;
5439 if (Callee->hasAttr<NonNullAttr>()) {
30
Taking false branch
5440 ForbiddenNullArgs.resize(Args.size());
5441 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5442 if (!Attr->args_size()) {
5443 ForbiddenNullArgs.set();
5444 break;
5445 } else
5446 for (auto Idx : Attr->args()) {
5447 unsigned ASTIdx = Idx.getASTIndex();
5448 if (ASTIdx >= Args.size())
5449 continue;
5450 ForbiddenNullArgs[ASTIdx] = 1;
5451 }
5452 }
5453 }
5454 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
31
Assuming the condition is false
32
Loop condition is false. Execution continues on line 5471
5455 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5456 // If we're checking for a potential constant expression, evaluate all
5457 // initializers even if some of them fail.
5458 if (!Info.noteFailure())
5459 return false;
5460 Success = false;
5461 } else if (!ForbiddenNullArgs.empty() &&
5462 ForbiddenNullArgs[Idx] &&
5463 ArgValues[Idx].isLValue() &&
5464 ArgValues[Idx].isNullPointer()) {
5465 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5466 if (!Info.noteFailure())
5467 return false;
5468 Success = false;
5469 }
5470 }
5471 return Success;
33
Returning the value 1 (loaded from 'Success'), which participates in a condition later
5472}
5473
5474/// Evaluate a function call.
5475static bool HandleFunctionCall(SourceLocation CallLoc,
5476 const FunctionDecl *Callee, const LValue *This,
5477 ArrayRef<const Expr*> Args, const Stmt *Body,
5478 EvalInfo &Info, APValue &Result,
5479 const LValue *ResultSlot) {
5480 ArgVector ArgValues(Args.size());
5481 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
29
Calling 'EvaluateArgs'
34
Returning from 'EvaluateArgs'
35
Taking false branch
5482 return false;
5483
5484 if (!Info.CheckCallLimit(CallLoc))
36
Calling 'EvalInfo::CheckCallLimit'
43
Returning from 'EvalInfo::CheckCallLimit'
44
Taking false branch
5485 return false;
5486
5487 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5488
5489 // For a trivial copy or move assignment, perform an APValue copy. This is
5490 // essential for unions, where the operations performed by the assignment
5491 // operator cannot be represented as statements.
5492 //
5493 // Skip this for non-union classes with no fields; in that case, the defaulted
5494 // copy/move does not actually read the object.
5495 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
45
Assuming 'Callee' is a 'CXXMethodDecl'
5496 if (MD
45.1
'MD' is non-null
45.1
'MD' is non-null
45.1
'MD' is non-null
&& MD->isDefaulted() &&
46
Assuming the condition is true
53
Taking true branch
5497 (MD->getParent()->isUnion() ||
47
Calling 'TagDecl::isUnion'
50
Returning from 'TagDecl::isUnion'
5498 (MD->isTrivial() && hasFields(MD->getParent())))) {
51
Assuming the condition is true
52
Assuming the condition is true
5499 assert
53.1
'This' is non-null
53.1
'This' is non-null
53.1
'This' is non-null
(This &&((This && (MD->isCopyAssignmentOperator() || MD->
isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5500, __PRETTY_FUNCTION__))
54
Assuming the condition is false
55
Assuming the condition is true
56
'?' condition is true
5500 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()))((This && (MD->isCopyAssignmentOperator() || MD->
isMoveAssignmentOperator())) ? static_cast<void> (0) : __assert_fail
("This && (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5500, __PRETTY_FUNCTION__))
;
5501 LValue RHS;
5502 RHS.setFrom(Info.Ctx, ArgValues[0]);
5503 APValue RHSValue;
5504 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
57
Assuming the condition is false
58
Taking false branch
5505 RHSValue, MD->getParent()->isUnion()))
5506 return false;
5507 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
59
Assuming field 'CPlusPlus2a' is not equal to 0
60
Assuming the condition is true
5508 !HandleUnionActiveMemberChange(Info, Args[0], *This))
61
Passing value via 2nd parameter 'LHSExpr'
62
Calling 'HandleUnionActiveMemberChange'
5509 return false;
5510 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5511 RHSValue))
5512 return false;
5513 This->moveInto(Result);
5514 return true;
5515 } else if (MD && isLambdaCallOperator(MD)) {
5516 // We're in a lambda; determine the lambda capture field maps unless we're
5517 // just constexpr checking a lambda's call operator. constexpr checking is
5518 // done before the captures have been added to the closure object (unless
5519 // we're inferring constexpr-ness), so we don't have access to them in this
5520 // case. But since we don't need the captures to constexpr check, we can
5521 // just ignore them.
5522 if (!Info.checkingPotentialConstantExpression())
5523 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5524 Frame.LambdaThisCaptureField);
5525 }
5526
5527 StmtResult Ret = {Result, ResultSlot};
5528 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5529 if (ESR == ESR_Succeeded) {
5530 if (Callee->getReturnType()->isVoidType())
5531 return true;
5532 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5533 }
5534 return ESR == ESR_Returned;
5535}
5536
5537/// Evaluate a constructor call.
5538static bool HandleConstructorCall(const Expr *E, const LValue &This,
5539 APValue *ArgValues,
5540 const CXXConstructorDecl *Definition,
5541 EvalInfo &Info, APValue &Result) {
5542 SourceLocation CallLoc = E->getExprLoc();
5543 if (!Info.CheckCallLimit(CallLoc))
5544 return false;
5545
5546 const CXXRecordDecl *RD = Definition->getParent();
5547 if (RD->getNumVBases()) {
5548 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5549 return false;
5550 }
5551
5552 EvalInfo::EvaluatingConstructorRAII EvalObj(
5553 Info,
5554 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5555 RD->getNumBases());
5556 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5557
5558 // FIXME: Creating an APValue just to hold a nonexistent return value is
5559 // wasteful.
5560 APValue RetVal;
5561 StmtResult Ret = {RetVal, nullptr};
5562
5563 // If it's a delegating constructor, delegate.
5564 if (Definition->isDelegatingConstructor()) {
5565 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5566 {
5567 FullExpressionRAII InitScope(Info);
5568 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5569 !InitScope.destroy())
5570 return false;
5571 }
5572 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5573 }
5574
5575 // For a trivial copy or move constructor, perform an APValue copy. This is
5576 // essential for unions (or classes with anonymous union members), where the
5577 // operations performed by the constructor cannot be represented by
5578 // ctor-initializers.
5579 //
5580 // Skip this for empty non-union classes; we should not perform an
5581 // lvalue-to-rvalue conversion on them because their copy constructor does not
5582 // actually read them.
5583 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5584 (Definition->getParent()->isUnion() ||
5585 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5586 LValue RHS;
5587 RHS.setFrom(Info.Ctx, ArgValues[0]);
5588 return handleLValueToRValueConversion(
5589 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5590 RHS, Result, Definition->getParent()->isUnion());
5591 }
5592
5593 // Reserve space for the struct members.
5594 if (!RD->isUnion() && !Result.hasValue())
5595 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5596 std::distance(RD->field_begin(), RD->field_end()));
5597
5598 if (RD->isInvalidDecl()) return false;
5599 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5600
5601 // A scope for temporaries lifetime-extended by reference members.
5602 BlockScopeRAII LifetimeExtendedScope(Info);
5603
5604 bool Success = true;
5605 unsigned BasesSeen = 0;
5606#ifndef NDEBUG
5607 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5608#endif
5609 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5610 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5611 // We might be initializing the same field again if this is an indirect
5612 // field initialization.
5613 if (FieldIt == RD->field_end() ||
5614 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5615 assert(Indirect && "fields out of order?")((Indirect && "fields out of order?") ? static_cast<
void> (0) : __assert_fail ("Indirect && \"fields out of order?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5615, __PRETTY_FUNCTION__))
;
5616 return;
5617 }
5618
5619 // Default-initialize any fields with no explicit initializer.
5620 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5621 assert(FieldIt != RD->field_end() && "missing field?")((FieldIt != RD->field_end() && "missing field?") ?
static_cast<void> (0) : __assert_fail ("FieldIt != RD->field_end() && \"missing field?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5621, __PRETTY_FUNCTION__))
;
5622 if (!FieldIt->isUnnamedBitfield())
5623 Result.getStructField(FieldIt->getFieldIndex()) =
5624 getDefaultInitValue(FieldIt->getType());
5625 }
5626 ++FieldIt;
5627 };
5628 for (const auto *I : Definition->inits()) {
5629 LValue Subobject = This;
5630 LValue SubobjectParent = This;
5631 APValue *Value = &Result;
5632
5633 // Determine the subobject to initialize.
5634 FieldDecl *FD = nullptr;
5635 if (I->isBaseInitializer()) {
5636 QualType BaseType(I->getBaseClass(), 0);
5637#ifndef NDEBUG
5638 // Non-virtual base classes are initialized in the order in the class
5639 // definition. We have already checked for virtual base classes.
5640 assert(!BaseIt->isVirtual() && "virtual base for literal type")((!BaseIt->isVirtual() && "virtual base for literal type"
) ? static_cast<void> (0) : __assert_fail ("!BaseIt->isVirtual() && \"virtual base for literal type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5640, __PRETTY_FUNCTION__))
;
5641 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
"base class initializers not in expected order") ? static_cast
<void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5642, __PRETTY_FUNCTION__))
5642 "base class initializers not in expected order")((Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
"base class initializers not in expected order") ? static_cast
<void> (0) : __assert_fail ("Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && \"base class initializers not in expected order\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5642, __PRETTY_FUNCTION__))
;
5643 ++BaseIt;
5644#endif
5645 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5646 BaseType->getAsCXXRecordDecl(), &Layout))
5647 return false;
5648 Value = &Result.getStructBase(BasesSeen++);
5649 } else if ((FD = I->getMember())) {
5650 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5651 return false;
5652 if (RD->isUnion()) {
5653 Result = APValue(FD);
5654 Value = &Result.getUnionValue();
5655 } else {
5656 SkipToField(FD, false);
5657 Value = &Result.getStructField(FD->getFieldIndex());
5658 }
5659 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5660 // Walk the indirect field decl's chain to find the object to initialize,
5661 // and make sure we've initialized every step along it.
5662 auto IndirectFieldChain = IFD->chain();
5663 for (auto *C : IndirectFieldChain) {
5664 FD = cast<FieldDecl>(C);
5665 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5666 // Switch the union field if it differs. This happens if we had
5667 // preceding zero-initialization, and we're now initializing a union
5668 // subobject other than the first.
5669 // FIXME: In this case, the values of the other subobjects are
5670 // specified, since zero-initialization sets all padding bits to zero.
5671 if (!Value->hasValue() ||
5672 (Value->isUnion() && Value->getUnionField() != FD)) {
5673 if (CD->isUnion())
5674 *Value = APValue(FD);
5675 else
5676 // FIXME: This immediately starts the lifetime of all members of an
5677 // anonymous struct. It would be preferable to strictly start member
5678 // lifetime in initialization order.
5679 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5680 }
5681 // Store Subobject as its parent before updating it for the last element
5682 // in the chain.
5683 if (C == IndirectFieldChain.back())
5684 SubobjectParent = Subobject;
5685 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5686 return false;
5687 if (CD->isUnion())
5688 Value = &Value->getUnionValue();
5689 else {
5690 if (C == IndirectFieldChain.front() && !RD->isUnion())
5691 SkipToField(FD, true);
5692 Value = &Value->getStructField(FD->getFieldIndex());
5693 }
5694 }
5695 } else {
5696 llvm_unreachable("unknown base initializer kind")::llvm::llvm_unreachable_internal("unknown base initializer kind"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ExprConstant.cpp"
, 5696)
;
5697 }
5698
5699 // Need to override This for implicit field initializers as in this case
5700 // This refers to innermost anonymous struct/union containing initializer,
5701 // not to currently constructed class.
5702 const Expr *Init = I->getInit();
5703 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5704 isa<CXXDefaultInitExpr>(Init));
5705 FullExpressionRAII InitScope(Info);
5706 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5707 (FD && FD->isBitField() &&
5708 !truncateBitfieldValue(Info, Init, *Value, FD))) {
5709 // If we're checking for a potential constant expression, evaluate all
5710 // initializers even if some of them fail.
5711 if (!Info.noteFailure())
5712 return false;
5713 Success = false;
5714 }
5715
5716 // This is the point at which the dynamic type of the object becomes this
5717 // class type.
5718 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5719 EvalObj.finishedConstructingBases();
5720 }
5721
5722 // Default-initialize any remaining fields.
5723 if (!RD->isUnion()) {
5724 for (; FieldIt != RD->field_end(); ++FieldIt) {
5725 if (!FieldIt->isUnnamedBitfield())
5726 Result.getStructField(FieldIt->getFieldIndex()) =
5727 getDefaultInitValue(FieldIt->getType());
5728 }
5729 }
5730
5731 return Success &&
5732 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5733 LifetimeExtendedScope.destroy();
5734}
5735
5736static bool HandleConstructorCall(const Expr *E, const LValue &This,
5737 ArrayRef<const Expr*> Args,
5738 const CXXConstructorDecl *Definition,
5739 EvalInfo &Info, APValue &Result) {
5740 ArgVector ArgValues(Args.size());
5741 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5742 return false;
5743
5744 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5745 Info, Result);
5746}
5747
5748static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5749 const LValue &This, APValue &Value,
5750