Bug Summary

File:clang/lib/AST/ExprConstant.cpp
Warning:line 8170, 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 -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-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/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-12/lib/clang/12.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-12~++20201129111111+e987fbdd85d/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -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-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/clang/lib/AST/ExprConstant.cpp

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