Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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