Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 5323, column 7
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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST/ExprConstant.cpp

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