Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ExprConstant.cpp

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