Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 8175, column 9
Access to field 'Callee' results in a dereference of a null pointer (loaded from variable 'CurrFrame')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ExprConstant.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/include -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-02-23-121308-24221-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210223111116+16ede0956cb1/clang/lib/AST/ExprConstant.cpp

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