Bug Summary

File:clang/lib/Sema/SemaExprCXX.cpp
Warning:line 1230, column 28
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp

1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Template.h"
15#include "clang/Sema/SemaInternal.h"
16#include "TreeTransform.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/AlignedAllocation.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/SemaLambda.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42using namespace clang;
43using namespace sema;
44
45/// Handle the result of the special case name lookup for inheriting
46/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")((NNS->getAsIdentifier() == &Name && "not a constructor name"
) ? static_cast<void> (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 65, __PRETTY_FUNCTION__))
;
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 74)
;
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
83ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
87 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&((CurClass && &II == CurClass->getIdentifier()
&& "not a constructor name") ? static_cast<void>
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 89, __PRETTY_FUNCTION__))
89 "not a constructor name")((CurClass && &II == CurClass->getIdentifier()
&& "not a constructor name") ? static_cast<void>
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 89, __PRETTY_FUNCTION__))
;
90
91 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
99 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100 return ParsedType();
101
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
113 break;
114 }
115 }
116 if (!InjectedClassName) {
117 if (!CurClass->isInvalidDecl()) {
118 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119 // properly. Work around it here for now.
120 Diag(SS.getLastQualifierNameLoc(),
121 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122 }
123 return ParsedType();
124 }
125
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130 return ParsedType::make(T);
131}
132
133ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
134 IdentifierInfo &II,
135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
139 // Determine where to perform name lookup.
140
141 // FIXME: This area of the standard is very messy, and the current
142 // wording is rather unclear about which scopes we search for the
143 // destructor name; see core issues 399 and 555. Issue 399 in
144 // particular shows where the current description of destructor name
145 // lookup is completely out of line with existing practice, e.g.,
146 // this appears to be ill-formed:
147 //
148 // namespace N {
149 // template <typename T> struct S {
150 // ~S();
151 // };
152 // }
153 //
154 // void f(N::S<int>* s) {
155 // s->N::S<int>::~S();
156 // }
157 //
158 // See also PR6358 and PR6359.
159 //
160 // For now, we accept all the cases in which the name given could plausibly
161 // be interpreted as a correct destructor name, issuing off-by-default
162 // extension diagnostics on the cases that don't strictly conform to the
163 // C++20 rules. This basically means we always consider looking in the
164 // nested-name-specifier prefix, the complete nested-name-specifier, and
165 // the scope, and accept if we find the expected type in any of the three
166 // places.
167
168 if (SS.isInvalid())
169 return nullptr;
170
171 // Whether we've failed with a diagnostic already.
172 bool Failed = false;
173
174 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
175 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
176
177 // If we have an object type, it's because we are in a
178 // pseudo-destructor-expression or a member access expression, and
179 // we know what type we're looking for.
180 QualType SearchType =
181 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
182
183 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
184 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
185 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
186 if (!Type)
187 return false;
188
189 if (SearchType.isNull() || SearchType->isDependentType())
190 return true;
191
192 QualType T = Context.getTypeDeclType(Type);
193 return Context.hasSameUnqualifiedType(T, SearchType);
194 };
195
196 unsigned NumAcceptableResults = 0;
197 for (NamedDecl *D : Found) {
198 if (IsAcceptableResult(D))
199 ++NumAcceptableResults;
200
201 // Don't list a class twice in the lookup failure diagnostic if it's
202 // found by both its injected-class-name and by the name in the enclosing
203 // scope.
204 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
205 if (RD->isInjectedClassName())
206 D = cast<NamedDecl>(RD->getParent());
207
208 if (FoundDeclSet.insert(D).second)
209 FoundDecls.push_back(D);
210 }
211
212 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
213 // results, and all non-matching results if we have a search type. It's not
214 // clear what the right behavior is if destructor lookup hits an ambiguity,
215 // but other compilers do generally accept at least some kinds of
216 // ambiguity.
217 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
218 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
219 LookupResult::Filter F = Found.makeFilter();
220 while (F.hasNext()) {
221 NamedDecl *D = F.next();
222 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
223 Diag(D->getLocation(), diag::note_destructor_type_here)
224 << Context.getTypeDeclType(TD);
225 else
226 Diag(D->getLocation(), diag::note_destructor_nontype_here);
227
228 if (!IsAcceptableResult(D))
229 F.erase();
230 }
231 F.done();
232 }
233
234 if (Found.isAmbiguous())
235 Failed = true;
236
237 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
238 if (IsAcceptableResult(Type)) {
239 QualType T = Context.getTypeDeclType(Type);
240 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
241 return CreateParsedType(T,
242 Context.getTrivialTypeSourceInfo(T, NameLoc));
243 }
244 }
245
246 return nullptr;
247 };
248
249 bool IsDependent = false;
250
251 auto LookupInObjectType = [&]() -> ParsedType {
252 if (Failed || SearchType.isNull())
253 return nullptr;
254
255 IsDependent |= SearchType->isDependentType();
256
257 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
258 DeclContext *LookupCtx = computeDeclContext(SearchType);
259 if (!LookupCtx)
260 return nullptr;
261 LookupQualifiedName(Found, LookupCtx);
262 return CheckLookupResult(Found);
263 };
264
265 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
266 if (Failed)
267 return nullptr;
268
269 IsDependent |= isDependentScopeSpecifier(LookupSS);
270 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
271 if (!LookupCtx)
272 return nullptr;
273
274 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
275 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
276 Failed = true;
277 return nullptr;
278 }
279 LookupQualifiedName(Found, LookupCtx);
280 return CheckLookupResult(Found);
281 };
282
283 auto LookupInScope = [&]() -> ParsedType {
284 if (Failed || !S)
285 return nullptr;
286
287 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
288 LookupName(Found, S);
289 return CheckLookupResult(Found);
290 };
291
292 // C++2a [basic.lookup.qual]p6:
293 // In a qualified-id of the form
294 //
295 // nested-name-specifier[opt] type-name :: ~ type-name
296 //
297 // the second type-name is looked up in the same scope as the first.
298 //
299 // We interpret this as meaning that if you do a dual-scope lookup for the
300 // first name, you also do a dual-scope lookup for the second name, per
301 // C++ [basic.lookup.classref]p4:
302 //
303 // If the id-expression in a class member access is a qualified-id of the
304 // form
305 //
306 // class-name-or-namespace-name :: ...
307 //
308 // the class-name-or-namespace-name following the . or -> is first looked
309 // up in the class of the object expression and the name, if found, is used.
310 // Otherwise, it is looked up in the context of the entire
311 // postfix-expression.
312 //
313 // This looks in the same scopes as for an unqualified destructor name:
314 //
315 // C++ [basic.lookup.classref]p3:
316 // If the unqualified-id is ~ type-name, the type-name is looked up
317 // in the context of the entire postfix-expression. If the type T
318 // of the object expression is of a class type C, the type-name is
319 // also looked up in the scope of class C. At least one of the
320 // lookups shall find a name that refers to cv T.
321 //
322 // FIXME: The intent is unclear here. Should type-name::~type-name look in
323 // the scope anyway if it finds a non-matching name declared in the class?
324 // If both lookups succeed and find a dependent result, which result should
325 // we retain? (Same question for p->~type-name().)
326
327 if (NestedNameSpecifier *Prefix =
328 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
329 // This is
330 //
331 // nested-name-specifier type-name :: ~ type-name
332 //
333 // Look for the second type-name in the nested-name-specifier.
334 CXXScopeSpec PrefixSS;
335 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
336 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
337 return T;
338 } else {
339 // This is one of
340 //
341 // type-name :: ~ type-name
342 // ~ type-name
343 //
344 // Look in the scope and (if any) the object type.
345 if (ParsedType T = LookupInScope())
346 return T;
347 if (ParsedType T = LookupInObjectType())
348 return T;
349 }
350
351 if (Failed)
352 return nullptr;
353
354 if (IsDependent) {
355 // We didn't find our type, but that's OK: it's dependent anyway.
356
357 // FIXME: What if we have no nested-name-specifier?
358 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
359 SS.getWithLocInContext(Context),
360 II, NameLoc);
361 return ParsedType::make(T);
362 }
363
364 // The remaining cases are all non-standard extensions imitating the behavior
365 // of various other compilers.
366 unsigned NumNonExtensionDecls = FoundDecls.size();
367
368 if (SS.isSet()) {
369 // For compatibility with older broken C++ rules and existing code,
370 //
371 // nested-name-specifier :: ~ type-name
372 //
373 // also looks for type-name within the nested-name-specifier.
374 if (ParsedType T = LookupInNestedNameSpec(SS)) {
375 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
376 << SS.getRange()
377 << FixItHint::CreateInsertion(SS.getEndLoc(),
378 ("::" + II.getName()).str());
379 return T;
380 }
381
382 // For compatibility with other compilers and older versions of Clang,
383 //
384 // nested-name-specifier type-name :: ~ type-name
385 //
386 // also looks for type-name in the scope. Unfortunately, we can't
387 // reasonably apply this fallback for dependent nested-name-specifiers.
388 if (SS.getScopeRep()->getPrefix()) {
389 if (ParsedType T = LookupInScope()) {
390 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
391 << FixItHint::CreateRemoval(SS.getRange());
392 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
393 << GetTypeFromParser(T);
394 return T;
395 }
396 }
397 }
398
399 // We didn't find anything matching; tell the user what we did find (if
400 // anything).
401
402 // Don't tell the user about declarations we shouldn't have found.
403 FoundDecls.resize(NumNonExtensionDecls);
404
405 // List types before non-types.
406 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
407 [](NamedDecl *A, NamedDecl *B) {
408 return isa<TypeDecl>(A->getUnderlyingDecl()) >
409 isa<TypeDecl>(B->getUnderlyingDecl());
410 });
411
412 // Suggest a fixit to properly name the destroyed type.
413 auto MakeFixItHint = [&]{
414 const CXXRecordDecl *Destroyed = nullptr;
415 // FIXME: If we have a scope specifier, suggest its last component?
416 if (!SearchType.isNull())
417 Destroyed = SearchType->getAsCXXRecordDecl();
418 else if (S)
419 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
420 if (Destroyed)
421 return FixItHint::CreateReplacement(SourceRange(NameLoc),
422 Destroyed->getNameAsString());
423 return FixItHint();
424 };
425
426 if (FoundDecls.empty()) {
427 // FIXME: Attempt typo-correction?
428 Diag(NameLoc, diag::err_undeclared_destructor_name)
429 << &II << MakeFixItHint();
430 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
431 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
432 assert(!SearchType.isNull() &&((!SearchType.isNull() && "should only reject a type result if we have a search type"
) ? static_cast<void> (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 433, __PRETTY_FUNCTION__))
433 "should only reject a type result if we have a search type")((!SearchType.isNull() && "should only reject a type result if we have a search type"
) ? static_cast<void> (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 433, __PRETTY_FUNCTION__))
;
434 QualType T = Context.getTypeDeclType(TD);
435 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
436 << T << SearchType << MakeFixItHint();
437 } else {
438 Diag(NameLoc, diag::err_destructor_expr_nontype)
439 << &II << MakeFixItHint();
440 }
441 } else {
442 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
443 : diag::err_destructor_expr_mismatch)
444 << &II << SearchType << MakeFixItHint();
445 }
446
447 for (NamedDecl *FoundD : FoundDecls) {
448 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
449 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
450 << Context.getTypeDeclType(TD);
451 else
452 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
453 << FoundD;
454 }
455
456 return nullptr;
457}
458
459ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
460 ParsedType ObjectType) {
461 if (DS.getTypeSpecType() == DeclSpec::TST_error)
462 return nullptr;
463
464 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
465 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
466 return nullptr;
467 }
468
469 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 470, __PRETTY_FUNCTION__))
470 "unexpected type in getDestructorType")((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 470, __PRETTY_FUNCTION__))
;
471 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
472
473 // If we know the type of the object, check that the correct destructor
474 // type was named now; we can give better diagnostics this way.
475 QualType SearchType = GetTypeFromParser(ObjectType);
476 if (!SearchType.isNull() && !SearchType->isDependentType() &&
477 !Context.hasSameUnqualifiedType(T, SearchType)) {
478 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
479 << T << SearchType;
480 return nullptr;
481 }
482
483 return ParsedType::make(T);
484}
485
486bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
487 const UnqualifiedId &Name) {
488 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)((Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) ?
static_cast<void> (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 488, __PRETTY_FUNCTION__))
;
489
490 if (!SS.isValid())
491 return false;
492
493 switch (SS.getScopeRep()->getKind()) {
494 case NestedNameSpecifier::Identifier:
495 case NestedNameSpecifier::TypeSpec:
496 case NestedNameSpecifier::TypeSpecWithTemplate:
497 // Per C++11 [over.literal]p2, literal operators can only be declared at
498 // namespace scope. Therefore, this unqualified-id cannot name anything.
499 // Reject it early, because we have no AST representation for this in the
500 // case where the scope is dependent.
501 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
502 << SS.getScopeRep();
503 return true;
504
505 case NestedNameSpecifier::Global:
506 case NestedNameSpecifier::Super:
507 case NestedNameSpecifier::Namespace:
508 case NestedNameSpecifier::NamespaceAlias:
509 return false;
510 }
511
512 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 512)
;
513}
514
515/// Build a C++ typeid expression with a type operand.
516ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
517 SourceLocation TypeidLoc,
518 TypeSourceInfo *Operand,
519 SourceLocation RParenLoc) {
520 // C++ [expr.typeid]p4:
521 // The top-level cv-qualifiers of the lvalue expression or the type-id
522 // that is the operand of typeid are always ignored.
523 // If the type of the type-id is a class type or a reference to a class
524 // type, the class shall be completely-defined.
525 Qualifiers Quals;
526 QualType T
527 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
528 Quals);
529 if (T->getAs<RecordType>() &&
530 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
531 return ExprError();
532
533 if (T->isVariablyModifiedType())
534 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
535
536 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
537 return ExprError();
538
539 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
540 SourceRange(TypeidLoc, RParenLoc));
541}
542
543/// Build a C++ typeid expression with an expression operand.
544ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
545 SourceLocation TypeidLoc,
546 Expr *E,
547 SourceLocation RParenLoc) {
548 bool WasEvaluated = false;
549 if (E && !E->isTypeDependent()) {
550 if (E->getType()->isPlaceholderType()) {
551 ExprResult result = CheckPlaceholderExpr(E);
552 if (result.isInvalid()) return ExprError();
553 E = result.get();
554 }
555
556 QualType T = E->getType();
557 if (const RecordType *RecordT = T->getAs<RecordType>()) {
558 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
559 // C++ [expr.typeid]p3:
560 // [...] If the type of the expression is a class type, the class
561 // shall be completely-defined.
562 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
563 return ExprError();
564
565 // C++ [expr.typeid]p3:
566 // When typeid is applied to an expression other than an glvalue of a
567 // polymorphic class type [...] [the] expression is an unevaluated
568 // operand. [...]
569 if (RecordD->isPolymorphic() && E->isGLValue()) {
570 // The subexpression is potentially evaluated; switch the context
571 // and recheck the subexpression.
572 ExprResult Result = TransformToPotentiallyEvaluated(E);
573 if (Result.isInvalid()) return ExprError();
574 E = Result.get();
575
576 // We require a vtable to query the type at run time.
577 MarkVTableUsed(TypeidLoc, RecordD);
578 WasEvaluated = true;
579 }
580 }
581
582 ExprResult Result = CheckUnevaluatedOperand(E);
583 if (Result.isInvalid())
584 return ExprError();
585 E = Result.get();
586
587 // C++ [expr.typeid]p4:
588 // [...] If the type of the type-id is a reference to a possibly
589 // cv-qualified type, the result of the typeid expression refers to a
590 // std::type_info object representing the cv-unqualified referenced
591 // type.
592 Qualifiers Quals;
593 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
594 if (!Context.hasSameType(T, UnqualT)) {
595 T = UnqualT;
596 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
597 }
598 }
599
600 if (E->getType()->isVariablyModifiedType())
601 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
602 << E->getType());
603 else if (!inTemplateInstantiation() &&
604 E->HasSideEffects(Context, WasEvaluated)) {
605 // The expression operand for typeid is in an unevaluated expression
606 // context, so side effects could result in unintended consequences.
607 Diag(E->getExprLoc(), WasEvaluated
608 ? diag::warn_side_effects_typeid
609 : diag::warn_side_effects_unevaluated_context);
610 }
611
612 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
613 SourceRange(TypeidLoc, RParenLoc));
614}
615
616/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
617ExprResult
618Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
619 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
620 // typeid is not supported in OpenCL.
621 if (getLangOpts().OpenCLCPlusPlus) {
622 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
623 << "typeid");
624 }
625
626 // Find the std::type_info type.
627 if (!getStdNamespace())
628 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
629
630 if (!CXXTypeInfoDecl) {
631 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
632 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
633 LookupQualifiedName(R, getStdNamespace());
634 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
635 // Microsoft's typeinfo doesn't have type_info in std but in the global
636 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
637 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
638 LookupQualifiedName(R, Context.getTranslationUnitDecl());
639 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
640 }
641 if (!CXXTypeInfoDecl)
642 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
643 }
644
645 if (!getLangOpts().RTTI) {
646 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
647 }
648
649 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
650
651 if (isType) {
652 // The operand is a type; handle it as such.
653 TypeSourceInfo *TInfo = nullptr;
654 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
655 &TInfo);
656 if (T.isNull())
657 return ExprError();
658
659 if (!TInfo)
660 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
661
662 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
663 }
664
665 // The operand is an expression.
666 ExprResult Result =
667 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
668
669 if (!getLangOpts().RTTIData && !Result.isInvalid())
670 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
671 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
672 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
673 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
674 DiagnosticOptions::MSVC);
675 return Result;
676}
677
678/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
679/// a single GUID.
680static void
681getUuidAttrOfType(Sema &SemaRef, QualType QT,
682 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
683 // Optionally remove one level of pointer, reference or array indirection.
684 const Type *Ty = QT.getTypePtr();
685 if (QT->isPointerType() || QT->isReferenceType())
686 Ty = QT->getPointeeType().getTypePtr();
687 else if (QT->isArrayType())
688 Ty = Ty->getBaseElementTypeUnsafe();
689
690 const auto *TD = Ty->getAsTagDecl();
691 if (!TD)
692 return;
693
694 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
695 UuidAttrs.insert(Uuid);
696 return;
697 }
698
699 // __uuidof can grab UUIDs from template arguments.
700 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
701 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
702 for (const TemplateArgument &TA : TAL.asArray()) {
703 const UuidAttr *UuidForTA = nullptr;
704 if (TA.getKind() == TemplateArgument::Type)
705 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
706 else if (TA.getKind() == TemplateArgument::Declaration)
707 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
708
709 if (UuidForTA)
710 UuidAttrs.insert(UuidForTA);
711 }
712 }
713}
714
715/// Build a Microsoft __uuidof expression with a type operand.
716ExprResult Sema::BuildCXXUuidof(QualType Type,
717 SourceLocation TypeidLoc,
718 TypeSourceInfo *Operand,
719 SourceLocation RParenLoc) {
720 MSGuidDecl *Guid = nullptr;
721 if (!Operand->getType()->isDependentType()) {
722 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
723 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
724 if (UuidAttrs.empty())
725 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
726 if (UuidAttrs.size() > 1)
727 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
728 Guid = UuidAttrs.back()->getGuidDecl();
729 }
730
731 return new (Context)
732 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
733}
734
735/// Build a Microsoft __uuidof expression with an expression operand.
736ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
737 Expr *E, SourceLocation RParenLoc) {
738 MSGuidDecl *Guid = nullptr;
739 if (!E->getType()->isDependentType()) {
740 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
741 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
742 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
743 } else {
744 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
745 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
746 if (UuidAttrs.empty())
747 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
748 if (UuidAttrs.size() > 1)
749 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
750 Guid = UuidAttrs.back()->getGuidDecl();
751 }
752 }
753
754 return new (Context)
755 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
756}
757
758/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
759ExprResult
760Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
761 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
762 QualType GuidType = Context.getMSGuidType();
763 GuidType.addConst();
764
765 if (isType) {
766 // The operand is a type; handle it as such.
767 TypeSourceInfo *TInfo = nullptr;
768 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
769 &TInfo);
770 if (T.isNull())
771 return ExprError();
772
773 if (!TInfo)
774 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
775
776 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
777 }
778
779 // The operand is an expression.
780 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
781}
782
783/// ActOnCXXBoolLiteral - Parse {true,false} literals.
784ExprResult
785Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
786 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 787, __PRETTY_FUNCTION__))
787 "Unknown C++ Boolean value!")(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 787, __PRETTY_FUNCTION__))
;
788 return new (Context)
789 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
790}
791
792/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
793ExprResult
794Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
795 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
796}
797
798/// ActOnCXXThrow - Parse throw expressions.
799ExprResult
800Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
801 bool IsThrownVarInScope = false;
802 if (Ex) {
803 // C++0x [class.copymove]p31:
804 // When certain criteria are met, an implementation is allowed to omit the
805 // copy/move construction of a class object [...]
806 //
807 // - in a throw-expression, when the operand is the name of a
808 // non-volatile automatic object (other than a function or catch-
809 // clause parameter) whose scope does not extend beyond the end of the
810 // innermost enclosing try-block (if there is one), the copy/move
811 // operation from the operand to the exception object (15.1) can be
812 // omitted by constructing the automatic object directly into the
813 // exception object
814 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
815 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
816 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
817 for( ; S; S = S->getParent()) {
818 if (S->isDeclScope(Var)) {
819 IsThrownVarInScope = true;
820 break;
821 }
822
823 if (S->getFlags() &
824 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
825 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
826 Scope::TryScope))
827 break;
828 }
829 }
830 }
831 }
832
833 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
834}
835
836ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
837 bool IsThrownVarInScope) {
838 // Don't report an error if 'throw' is used in system headers.
839 if (!getLangOpts().CXXExceptions &&
840 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
841 // Delay error emission for the OpenMP device code.
842 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
843 }
844
845 // Exceptions aren't allowed in CUDA device code.
846 if (getLangOpts().CUDA)
847 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
848 << "throw" << CurrentCUDATarget();
849
850 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
851 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
852
853 if (Ex && !Ex->isTypeDependent()) {
854 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
855 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
856 return ExprError();
857
858 // Initialize the exception result. This implicitly weeds out
859 // abstract types or types with inaccessible copy constructors.
860
861 // C++0x [class.copymove]p31:
862 // When certain criteria are met, an implementation is allowed to omit the
863 // copy/move construction of a class object [...]
864 //
865 // - in a throw-expression, when the operand is the name of a
866 // non-volatile automatic object (other than a function or
867 // catch-clause
868 // parameter) whose scope does not extend beyond the end of the
869 // innermost enclosing try-block (if there is one), the copy/move
870 // operation from the operand to the exception object (15.1) can be
871 // omitted by constructing the automatic object directly into the
872 // exception object
873 const VarDecl *NRVOVariable = nullptr;
874 if (IsThrownVarInScope)
875 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
876
877 InitializedEntity Entity = InitializedEntity::InitializeException(
878 OpLoc, ExceptionObjectTy,
879 /*NRVO=*/NRVOVariable != nullptr);
880 ExprResult Res = PerformMoveOrCopyInitialization(
881 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
882 if (Res.isInvalid())
883 return ExprError();
884 Ex = Res.get();
885 }
886
887 // PPC MMA non-pointer types are not allowed as throw expr types.
888 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
889 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
890
891 return new (Context)
892 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
893}
894
895static void
896collectPublicBases(CXXRecordDecl *RD,
897 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
898 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
899 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
900 bool ParentIsPublic) {
901 for (const CXXBaseSpecifier &BS : RD->bases()) {
902 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
903 bool NewSubobject;
904 // Virtual bases constitute the same subobject. Non-virtual bases are
905 // always distinct subobjects.
906 if (BS.isVirtual())
907 NewSubobject = VBases.insert(BaseDecl).second;
908 else
909 NewSubobject = true;
910
911 if (NewSubobject)
912 ++SubobjectsSeen[BaseDecl];
913
914 // Only add subobjects which have public access throughout the entire chain.
915 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
916 if (PublicPath)
917 PublicSubobjectsSeen.insert(BaseDecl);
918
919 // Recurse on to each base subobject.
920 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
921 PublicPath);
922 }
923}
924
925static void getUnambiguousPublicSubobjects(
926 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
927 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
928 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
929 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
930 SubobjectsSeen[RD] = 1;
931 PublicSubobjectsSeen.insert(RD);
932 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
933 /*ParentIsPublic=*/true);
934
935 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
936 // Skip ambiguous objects.
937 if (SubobjectsSeen[PublicSubobject] > 1)
938 continue;
939
940 Objects.push_back(PublicSubobject);
941 }
942}
943
944/// CheckCXXThrowOperand - Validate the operand of a throw.
945bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
946 QualType ExceptionObjectTy, Expr *E) {
947 // If the type of the exception would be an incomplete type or a pointer
948 // to an incomplete type other than (cv) void the program is ill-formed.
949 QualType Ty = ExceptionObjectTy;
950 bool isPointer = false;
951 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
952 Ty = Ptr->getPointeeType();
953 isPointer = true;
954 }
955 if (!isPointer || !Ty->isVoidType()) {
956 if (RequireCompleteType(ThrowLoc, Ty,
957 isPointer ? diag::err_throw_incomplete_ptr
958 : diag::err_throw_incomplete,
959 E->getSourceRange()))
960 return true;
961
962 if (!isPointer && Ty->isSizelessType()) {
963 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
964 return true;
965 }
966
967 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
968 diag::err_throw_abstract_type, E))
969 return true;
970 }
971
972 // If the exception has class type, we need additional handling.
973 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
974 if (!RD)
975 return false;
976
977 // If we are throwing a polymorphic class type or pointer thereof,
978 // exception handling will make use of the vtable.
979 MarkVTableUsed(ThrowLoc, RD);
980
981 // If a pointer is thrown, the referenced object will not be destroyed.
982 if (isPointer)
983 return false;
984
985 // If the class has a destructor, we must be able to call it.
986 if (!RD->hasIrrelevantDestructor()) {
987 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
988 MarkFunctionReferenced(E->getExprLoc(), Destructor);
989 CheckDestructorAccess(E->getExprLoc(), Destructor,
990 PDiag(diag::err_access_dtor_exception) << Ty);
991 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
992 return true;
993 }
994 }
995
996 // The MSVC ABI creates a list of all types which can catch the exception
997 // object. This list also references the appropriate copy constructor to call
998 // if the object is caught by value and has a non-trivial copy constructor.
999 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1000 // We are only interested in the public, unambiguous bases contained within
1001 // the exception object. Bases which are ambiguous or otherwise
1002 // inaccessible are not catchable types.
1003 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1004 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1005
1006 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1007 // Attempt to lookup the copy constructor. Various pieces of machinery
1008 // will spring into action, like template instantiation, which means this
1009 // cannot be a simple walk of the class's decls. Instead, we must perform
1010 // lookup and overload resolution.
1011 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1012 if (!CD || CD->isDeleted())
1013 continue;
1014
1015 // Mark the constructor referenced as it is used by this throw expression.
1016 MarkFunctionReferenced(E->getExprLoc(), CD);
1017
1018 // Skip this copy constructor if it is trivial, we don't need to record it
1019 // in the catchable type data.
1020 if (CD->isTrivial())
1021 continue;
1022
1023 // The copy constructor is non-trivial, create a mapping from this class
1024 // type to this constructor.
1025 // N.B. The selection of copy constructor is not sensitive to this
1026 // particular throw-site. Lookup will be performed at the catch-site to
1027 // ensure that the copy constructor is, in fact, accessible (via
1028 // friendship or any other means).
1029 Context.addCopyConstructorForExceptionObject(Subobject, CD);
1030
1031 // We don't keep the instantiated default argument expressions around so
1032 // we must rebuild them here.
1033 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1034 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1035 return true;
1036 }
1037 }
1038 }
1039
1040 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1041 // the runtime with no ability for the compiler to request additional
1042 // alignment. Warn if the exception type requires alignment beyond the minimum
1043 // guaranteed by the target C++ runtime.
1044 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1045 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1046 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1047 if (ExnObjAlign < TypeAlign) {
1048 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1049 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1050 << Ty << (unsigned)TypeAlign.getQuantity()
1051 << (unsigned)ExnObjAlign.getQuantity();
1052 }
1053 }
1054
1055 return false;
1056}
1057
1058static QualType adjustCVQualifiersForCXXThisWithinLambda(
1059 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1060 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1061
1062 QualType ClassType = ThisTy->getPointeeType();
1063 LambdaScopeInfo *CurLSI = nullptr;
1064 DeclContext *CurDC = CurSemaContext;
1065
1066 // Iterate through the stack of lambdas starting from the innermost lambda to
1067 // the outermost lambda, checking if '*this' is ever captured by copy - since
1068 // that could change the cv-qualifiers of the '*this' object.
1069 // The object referred to by '*this' starts out with the cv-qualifiers of its
1070 // member function. We then start with the innermost lambda and iterate
1071 // outward checking to see if any lambda performs a by-copy capture of '*this'
1072 // - and if so, any nested lambda must respect the 'constness' of that
1073 // capturing lamdbda's call operator.
1074 //
1075
1076 // Since the FunctionScopeInfo stack is representative of the lexical
1077 // nesting of the lambda expressions during initial parsing (and is the best
1078 // place for querying information about captures about lambdas that are
1079 // partially processed) and perhaps during instantiation of function templates
1080 // that contain lambda expressions that need to be transformed BUT not
1081 // necessarily during instantiation of a nested generic lambda's function call
1082 // operator (which might even be instantiated at the end of the TU) - at which
1083 // time the DeclContext tree is mature enough to query capture information
1084 // reliably - we use a two pronged approach to walk through all the lexically
1085 // enclosing lambda expressions:
1086 //
1087 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1088 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1089 // enclosed by the call-operator of the LSI below it on the stack (while
1090 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1091 // the stack represents the innermost lambda.
1092 //
1093 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1094 // represents a lambda's call operator. If it does, we must be instantiating
1095 // a generic lambda's call operator (represented by the Current LSI, and
1096 // should be the only scenario where an inconsistency between the LSI and the
1097 // DeclContext should occur), so climb out the DeclContexts if they
1098 // represent lambdas, while querying the corresponding closure types
1099 // regarding capture information.
1100
1101 // 1) Climb down the function scope info stack.
1102 for (int I = FunctionScopes.size();
1103 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1104 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1105 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1106 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1107 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1108
1109 if (!CurLSI->isCXXThisCaptured())
1110 continue;
1111
1112 auto C = CurLSI->getCXXThisCapture();
1113
1114 if (C.isCopyCapture()) {
1115 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1116 if (CurLSI->CallOperator->isConst())
1117 ClassType.addConst();
1118 return ASTCtx.getPointerType(ClassType);
1119 }
1120 }
1121
1122 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1123 // happen during instantiation of its nested generic lambda call operator)
1124 if (isLambdaCallOperator(CurDC)) {
1125 assert(CurLSI && "While computing 'this' capture-type for a generic "((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1126, __PRETTY_FUNCTION__))
1126 "lambda, we must have a corresponding LambdaScopeInfo")((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1126, __PRETTY_FUNCTION__))
;
1127 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1131, __PRETTY_FUNCTION__))
1128 "While computing 'this' capture-type for a generic lambda, when we "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1131, __PRETTY_FUNCTION__))
1129 "run out of enclosing LSI's, yet the enclosing DC is a "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1131, __PRETTY_FUNCTION__))
1130 "lambda-call-operator we must be (i.e. Current LSI) in a generic "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1131, __PRETTY_FUNCTION__))
1131 "lambda call oeprator")((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1131, __PRETTY_FUNCTION__))
;
1132 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))((CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator
)) ? static_cast<void> (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1132, __PRETTY_FUNCTION__))
;
1133
1134 auto IsThisCaptured =
1135 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1136 IsConst = false;
1137 IsByCopy = false;
1138 for (auto &&C : Closure->captures()) {
1139 if (C.capturesThis()) {
1140 if (C.getCaptureKind() == LCK_StarThis)
1141 IsByCopy = true;
1142 if (Closure->getLambdaCallOperator()->isConst())
1143 IsConst = true;
1144 return true;
1145 }
1146 }
1147 return false;
1148 };
1149
1150 bool IsByCopyCapture = false;
1151 bool IsConstCapture = false;
1152 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1153 while (Closure &&
1154 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1155 if (IsByCopyCapture) {
1156 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1157 if (IsConstCapture)
1158 ClassType.addConst();
1159 return ASTCtx.getPointerType(ClassType);
1160 }
1161 Closure = isLambdaCallOperator(Closure->getParent())
1162 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1163 : nullptr;
1164 }
1165 }
1166 return ASTCtx.getPointerType(ClassType);
1167}
1168
1169QualType Sema::getCurrentThisType() {
1170 DeclContext *DC = getFunctionLevelDeclContext();
1171 QualType ThisTy = CXXThisTypeOverride;
1172
1173 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1174 if (method && method->isInstance())
1175 ThisTy = method->getThisType();
1176 }
1177
1178 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1179 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1180
1181 // This is a lambda call operator that is being instantiated as a default
1182 // initializer. DC must point to the enclosing class type, so we can recover
1183 // the 'this' type from it.
1184 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1185 // There are no cv-qualifiers for 'this' within default initializers,
1186 // per [expr.prim.general]p4.
1187 ThisTy = Context.getPointerType(ClassTy);
1188 }
1189
1190 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1191 // might need to be adjusted if the lambda or any of its enclosing lambda's
1192 // captures '*this' by copy.
1193 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1194 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1195 CurContext, Context);
1196 return ThisTy;
1197}
1198
1199Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1200 Decl *ContextDecl,
1201 Qualifiers CXXThisTypeQuals,
1202 bool Enabled)
1203 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1204{
1205 if (!Enabled || !ContextDecl)
1206 return;
1207
1208 CXXRecordDecl *Record = nullptr;
1209 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1210 Record = Template->getTemplatedDecl();
1211 else
1212 Record = cast<CXXRecordDecl>(ContextDecl);
1213
1214 QualType T = S.Context.getRecordType(Record);
1215 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1216
1217 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1218
1219 this->Enabled = true;
1220}
1221
1222
1223Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1224 if (Enabled) {
1225 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1226 }
1227}
1228
1229static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1230 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
32
Called C++ object pointer is null
1231 assert(!LSI->isCXXThisCaptured())((!LSI->isCXXThisCaptured()) ? static_cast<void> (0)
: __assert_fail ("!LSI->isCXXThisCaptured()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1231, __PRETTY_FUNCTION__))
;
1232 // [=, this] {}; // until C++20: Error: this when = is the default
1233 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1234 !Sema.getLangOpts().CPlusPlus20)
1235 return;
1236 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1237 << FixItHint::CreateInsertion(
1238 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1239}
1240
1241bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1242 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1243 const bool ByCopy) {
1244 // We don't need to capture this in an unevaluated context.
1245 if (isUnevaluatedContext() && !Explicit)
5
Calling 'Sema::isUnevaluatedContext'
14
Returning from 'Sema::isUnevaluatedContext'
1246 return true;
1247
1248 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? static_cast<void> (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1248, __PRETTY_FUNCTION__))
;
15
'?' condition is true
1249
1250 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15.1
'FunctionScopeIndexToStopAt' is null
15.1
'FunctionScopeIndexToStopAt' is null
16
'?' condition is false
1251 ? *FunctionScopeIndexToStopAt 1252 : FunctionScopes.size() - 1; 1253 1254 // Check that we can capture the *enclosing object* (referred to by '*this') 1255 // by the capturing-entity/closure (lambda/block/etc) at 1256 // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 1257 1258 // Note: The *enclosing object* can only be captured by-value by a 1259 // closure that is a lambda, using the explicit notation: 1260 // [*this] { ... }. 1261 // Every other capture of the *enclosing object* results in its by-reference 1262 // capture. 1263 1264 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 1265 // stack), we can capture the *enclosing object* only if: 1266 // - 'L' has an explicit byref or byval capture of the *enclosing object* 1267 // - or, 'L' has an implicit capture. 1268 // AND 1269 // -- there is no enclosing closure 1270 // -- or, there is some enclosing closure 'E' that has already captured the 1271 // *enclosing object*, and every intervening closure (if any) between 'E' 1272 // and 'L' can implicitly capture the *enclosing object*. 1273 // -- or, every enclosing closure can implicitly capture the 1274 // *enclosing object* 1275 1276 1277 unsigned NumCapturingClosures = 0; 1278 for (int idx = MaxFunctionScopesIndex; idx
16.1
'idx' is >= 0
16.1
'idx' is >= 0
>= 0; idx--) {
17
Loop condition is true. Entering loop body
1279 if (CapturingScopeInfo *CSI
18.1
'CSI' is non-null
18.1
'CSI' is non-null
=
19
Taking true branch
1280 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
18
Assuming the object is a 'CapturingScopeInfo'
1281 if (CSI->CXXThisCaptureIndex != 0) {
20
Assuming field 'CXXThisCaptureIndex' is equal to 0
21
Taking false branch
1282 // 'this' is already being captured; there isn't anything more to do. 1283 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 1284 break; 1285 } 1286 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
22
Assuming 'CSI' is not a 'LambdaScopeInfo'
23
'LSI' initialized to a null pointer value
1287 if (LSI
23.1
'LSI' is null
23.1
'LSI' is null
&& isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 1288 // This context can't implicitly capture 'this'; fail out. 1289 if (BuildAndDiagnose) { 1290 Diag(Loc, diag::err_this_capture) 1291 << (Explicit && idx == MaxFunctionScopesIndex); 1292 if (!Explicit) 1293 buildLambdaThisCaptureFixit(*this, LSI); 1294 } 1295 return true; 1296 } 1297 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
24
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_LambdaByref
1298 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
25
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_LambdaByval
1299 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
26
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_Block
1300 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
27
Assuming field 'ImpCaptureStyle' is not equal to ImpCap_CapturedRegion
1301 (Explicit
27.1
'Explicit' is false
27.1
'Explicit' is false
&& idx == MaxFunctionScopesIndex)) { 1302 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 1303 // iteration through can be an explicit capture, all enclosing closures, 1304 // if any, must perform implicit captures. 1305 1306 // This closure can capture 'this'; continue looking upwards. 1307 NumCapturingClosures++; 1308 continue; 1309 } 1310 // This context can't implicitly capture 'this'; fail out. 1311 if (BuildAndDiagnose
27.2
'BuildAndDiagnose' is true
27.2
'BuildAndDiagnose' is true
)
28
Taking true branch
1312 Diag(Loc, diag::err_this_capture) 1313 << (Explicit
28.1
'Explicit' is false
28.1
'Explicit' is false
&& idx == MaxFunctionScopesIndex); 1314 1315 if (!Explicit
28.2
'Explicit' is false
28.2
'Explicit' is false
)
29
Taking true branch
1316 buildLambdaThisCaptureFixit(*this, LSI);
30
Passing null pointer value via 2nd parameter 'LSI'
31
Calling 'buildLambdaThisCaptureFixit'
1317 return true; 1318 } 1319 break; 1320 } 1321 if (!BuildAndDiagnose) return false; 1322 1323 // If we got here, then the closure at MaxFunctionScopesIndex on the 1324 // FunctionScopes stack, can capture the *enclosing object*, so capture it 1325 // (including implicit by-reference captures in any enclosing closures). 1326 1327 // In the loop below, respect the ByCopy flag only for the closure requesting 1328 // the capture (i.e. first iteration through the loop below). Ignore it for 1329 // all enclosing closure's up to NumCapturingClosures (since they must be 1330 // implicitly capturing the *enclosing object* by reference (see loop 1331 // above)). 1332 assert((!ByCopy ||(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1335, __PRETTY_FUNCTION__))
1333 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1335, __PRETTY_FUNCTION__))
1334 "Only a lambda can capture the enclosing object (referred to by "(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1335, __PRETTY_FUNCTION__))
1335 "*this) by copy")(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1335, __PRETTY_FUNCTION__))
; 1336 QualType ThisTy = getCurrentThisType(); 1337 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 1338 --idx, --NumCapturingClosures) { 1339 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 1340 1341 // The type of the corresponding data member (not a 'this' pointer if 'by 1342 // copy'). 1343 QualType CaptureType = ThisTy; 1344 if (ByCopy) { 1345 // If we are capturing the object referred to by '*this' by copy, ignore 1346 // any cv qualifiers inherited from the type of the member function for 1347 // the type of the closure-type's corresponding data member and any use 1348 // of 'this'. 1349 CaptureType = ThisTy->getPointeeType(); 1350 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 1351 } 1352 1353 bool isNested = NumCapturingClosures > 1; 1354 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 1355 } 1356 return false; 1357} 1358 1359ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 1360 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 1361 /// is a non-lvalue expression whose value is the address of the object for 1362 /// which the function is called. 1363 1364 QualType ThisTy = getCurrentThisType(); 1365 if (ThisTy.isNull())
1
Taking false branch
1366 return Diag(Loc, diag::err_invalid_this_use); 1367 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
2
Calling 'Sema::BuildCXXThisExpr'
1368} 1369 1370Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 1371 bool IsImplicit) { 1372 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); 1373 MarkThisReferenced(This);
3
Calling 'Sema::MarkThisReferenced'
1374 return This; 1375} 1376 1377void Sema::MarkThisReferenced(CXXThisExpr *This) { 1378 CheckCXXThisCapture(This->getExprLoc());
4
Calling 'Sema::CheckCXXThisCapture'
1379} 1380 1381bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 1382 // If we're outside the body of a member function, then we'll have a specified 1383 // type for 'this'. 1384 if (CXXThisTypeOverride.isNull()) 1385 return false; 1386 1387 // Determine whether we're looking into a class that's currently being 1388 // defined. 1389 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 1390 return Class && Class->isBeingDefined(); 1391} 1392 1393/// Parse construction of a specified type. 1394/// Can be interpreted either as function-style casting ("int(x)") 1395/// or class type construction ("ClassType(x,y,z)") 1396/// or creation of a value-initialized type ("int()"). 1397ExprResult 1398Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 1399 SourceLocation LParenOrBraceLoc, 1400 MultiExprArg exprs, 1401 SourceLocation RParenOrBraceLoc, 1402 bool ListInitialization) { 1403 if (!TypeRep) 1404 return ExprError(); 1405 1406 TypeSourceInfo *TInfo; 1407 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 1408 if (!TInfo) 1409 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 1410 1411 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 1412 RParenOrBraceLoc, ListInitialization); 1413 // Avoid creating a non-type-dependent expression that contains typos. 1414 // Non-type-dependent expressions are liable to be discarded without 1415 // checking for embedded typos. 1416 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 1417 !Result.get()->isTypeDependent()) 1418 Result = CorrectDelayedTyposInExpr(Result.get()); 1419 else if (Result.isInvalid()) 1420 Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), 1421 RParenOrBraceLoc, exprs, Ty); 1422 return Result; 1423} 1424 1425ExprResult 1426Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 1427 SourceLocation LParenOrBraceLoc, 1428 MultiExprArg Exprs, 1429 SourceLocation RParenOrBraceLoc, 1430 bool ListInitialization) { 1431 QualType Ty = TInfo->getType(); 1432 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 1433 1434 assert((!ListInitialization ||(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1436, __PRETTY_FUNCTION__))
1435 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1436, __PRETTY_FUNCTION__))
1436 "List initialization must have initializer list as expression.")(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1436, __PRETTY_FUNCTION__))
; 1437 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 1438 1439 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 1440 InitializationKind Kind = 1441 Exprs.size() 1442 ? ListInitialization 1443 ? InitializationKind::CreateDirectList( 1444 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 1445 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 1446 RParenOrBraceLoc) 1447 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 1448 RParenOrBraceLoc); 1449 1450 // C++1z [expr.type.conv]p1: 1451 // If the type is a placeholder for a deduced class type, [...perform class 1452 // template argument deduction...] 1453 DeducedType *Deduced = Ty->getContainedDeducedType(); 1454 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 1455 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 1456 Kind, Exprs); 1457 if (Ty.isNull()) 1458 return ExprError(); 1459 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 1460 } 1461 1462 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 1463 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization 1464 // directly. We work around this by dropping the locations of the braces. 1465 SourceRange Locs = ListInitialization 1466 ? SourceRange() 1467 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1468 return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), 1469 TInfo, Locs.getBegin(), Exprs, 1470 Locs.getEnd()); 1471 } 1472 1473 // C++ [expr.type.conv]p1: 1474 // If the expression list is a parenthesized single expression, the type 1475 // conversion expression is equivalent (in definedness, and if defined in 1476 // meaning) to the corresponding cast expression. 1477 if (Exprs.size() == 1 && !ListInitialization && 1478 !isa<InitListExpr>(Exprs[0])) { 1479 Expr *Arg = Exprs[0]; 1480 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 1481 RParenOrBraceLoc); 1482 } 1483 1484 // For an expression of the form T(), T shall not be an array type. 1485 QualType ElemTy = Ty; 1486 if (Ty->isArrayType()) { 1487 if (!ListInitialization) 1488 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 1489 << FullRange); 1490 ElemTy = Context.getBaseElementType(Ty); 1491 } 1492 1493 // There doesn't seem to be an explicit rule against this but sanity demands 1494 // we only construct objects with object types. 1495 if (Ty->isFunctionType()) 1496 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 1497 << Ty << FullRange); 1498 1499 // C++17 [expr.type.conv]p2: 1500 // If the type is cv void and the initializer is (), the expression is a 1501 // prvalue of the specified type that performs no initialization. 1502 if (!Ty->isVoidType() && 1503 RequireCompleteType(TyBeginLoc, ElemTy, 1504 diag::err_invalid_incomplete_type_use, FullRange)) 1505 return ExprError(); 1506 1507 // Otherwise, the expression is a prvalue of the specified type whose 1508 // result object is direct-initialized (11.6) with the initializer. 1509 InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 1510 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 1511 1512 if (Result.isInvalid()) 1513 return Result; 1514 1515 Expr *Inner = Result.get(); 1516 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 1517 Inner = BTE->getSubExpr(); 1518 if (!isa<CXXTemporaryObjectExpr>(Inner) && 1519 !isa<CXXScalarValueInitExpr>(Inner)) { 1520 // If we created a CXXTemporaryObjectExpr, that node also represents the 1521 // functional cast. Otherwise, create an explicit cast to represent 1522 // the syntactic form of a functional-style cast that was used here. 1523 // 1524 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 1525 // would give a more consistent AST representation than using a 1526 // CXXTemporaryObjectExpr. It's also weird that the functional cast 1527 // is sometimes handled by initialization and sometimes not. 1528 QualType ResultType = Result.get()->getType(); 1529 SourceRange Locs = ListInitialization 1530 ? SourceRange() 1531 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1532 Result = CXXFunctionalCastExpr::Create( 1533 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 1534 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), 1535 Locs.getBegin(), Locs.getEnd()); 1536 } 1537 1538 return Result; 1539} 1540 1541bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 1542 // [CUDA] Ignore this function, if we can't call it. 1543 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); 1544 if (getLangOpts().CUDA) { 1545 auto CallPreference = IdentifyCUDAPreference(Caller, Method); 1546 // If it's not callable at all, it's not the right function. 1547 if (CallPreference < CFP_WrongSide) 1548 return false; 1549 if (CallPreference == CFP_WrongSide) { 1550 // Maybe. We have to check if there are better alternatives. 1551 DeclContext::lookup_result R = 1552 Method->getDeclContext()->lookup(Method->getDeclName()); 1553 for (const auto *D : R) { 1554 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1555 if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) 1556 return false; 1557 } 1558 } 1559 // We've found no better variants. 1560 } 1561 } 1562 1563 SmallVector<const FunctionDecl*, 4> PreventedBy; 1564 bool Result = Method->isUsualDeallocationFunction(PreventedBy); 1565 1566 if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 1567 return Result; 1568 1569 // In case of CUDA, return true if none of the 1-argument deallocator 1570 // functions are actually callable. 1571 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 1572 assert(FD->getNumParams() == 1 &&((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy"
) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1573, __PRETTY_FUNCTION__))
1573 "Only single-operand functions should be in PreventedBy")((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy"
) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1573, __PRETTY_FUNCTION__))
; 1574 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; 1575 }); 1576} 1577 1578/// Determine whether the given function is a non-placement 1579/// deallocation function. 1580static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 1581 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1582 return S.isUsualDeallocationFunction(Method); 1583 1584 if (FD->getOverloadedOperator() != OO_Delete && 1585 FD->getOverloadedOperator() != OO_Array_Delete) 1586 return false; 1587 1588 unsigned UsualParams = 1; 1589 1590 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 1591 S.Context.hasSameUnqualifiedType( 1592 FD->getParamDecl(UsualParams)->getType(), 1593 S.Context.getSizeType())) 1594 ++UsualParams; 1595 1596 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 1597 S.Context.hasSameUnqualifiedType( 1598 FD->getParamDecl(UsualParams)->getType(), 1599 S.Context.getTypeDeclType(S.getStdAlignValT()))) 1600 ++UsualParams; 1601 1602 return UsualParams == FD->getNumParams(); 1603} 1604 1605namespace { 1606 struct UsualDeallocFnInfo { 1607 UsualDeallocFnInfo() : Found(), FD(nullptr) {} 1608 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 1609 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 1610 Destroying(false), HasSizeT(false), HasAlignValT(false), 1611 CUDAPref(Sema::CFP_Native) { 1612 // A function template declaration is never a usual deallocation function. 1613 if (!FD) 1614 return; 1615 unsigned NumBaseParams = 1; 1616 if (FD->isDestroyingOperatorDelete()) { 1617 Destroying = true; 1618 ++NumBaseParams; 1619 } 1620 1621 if (NumBaseParams < FD->getNumParams() && 1622 S.Context.hasSameUnqualifiedType( 1623 FD->getParamDecl(NumBaseParams)->getType(), 1624 S.Context.getSizeType())) { 1625 ++NumBaseParams; 1626 HasSizeT = true; 1627 } 1628 1629 if (NumBaseParams < FD->getNumParams() && 1630 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 1631 ++NumBaseParams; 1632 HasAlignValT = true; 1633 } 1634 1635 // In CUDA, determine how much we'd like / dislike to call this. 1636 if (S.getLangOpts().CUDA) 1637 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 1638 CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 1639 } 1640 1641 explicit operator bool() const { return FD; } 1642 1643 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 1644 bool WantAlign) const { 1645 // C++ P0722: 1646 // A destroying operator delete is preferred over a non-destroying 1647 // operator delete. 1648 if (Destroying != Other.Destroying) 1649 return Destroying; 1650 1651 // C++17 [expr.delete]p10: 1652 // If the type has new-extended alignment, a function with a parameter 1653 // of type std::align_val_t is preferred; otherwise a function without 1654 // such a parameter is preferred 1655 if (HasAlignValT != Other.HasAlignValT) 1656 return HasAlignValT == WantAlign; 1657 1658 if (HasSizeT != Other.HasSizeT) 1659 return HasSizeT == WantSize; 1660 1661 // Use CUDA call preference as a tiebreaker. 1662 return CUDAPref > Other.CUDAPref; 1663 } 1664 1665 DeclAccessPair Found; 1666 FunctionDecl *FD; 1667 bool Destroying, HasSizeT, HasAlignValT; 1668 Sema::CUDAFunctionPreference CUDAPref; 1669 }; 1670} 1671 1672/// Determine whether a type has new-extended alignment. This may be called when 1673/// the type is incomplete (for a delete-expression with an incomplete pointee 1674/// type), in which case it will conservatively return false if the alignment is 1675/// not known. 1676static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 1677 return S.getLangOpts().AlignedAllocation && 1678 S.getASTContext().getTypeAlignIfKnown(AllocType) > 1679 S.getASTContext().getTargetInfo().getNewAlign(); 1680} 1681 1682/// Select the correct "usual" deallocation function to use from a selection of 1683/// deallocation functions (either global or class-scope). 1684static UsualDeallocFnInfo resolveDeallocationOverload( 1685 Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 1686 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 1687 UsualDeallocFnInfo Best; 1688 1689 for (auto I = R.begin(), E = R.end(); I != E; ++I) { 1690 UsualDeallocFnInfo Info(S, I.getPair()); 1691 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 1692 Info.CUDAPref == Sema::CFP_Never) 1693 continue; 1694 1695 if (!Best) { 1696 Best = Info; 1697 if (BestFns) 1698 BestFns->push_back(Info); 1699 continue; 1700 } 1701 1702 if (Best.isBetterThan(Info, WantSize, WantAlign)) 1703 continue; 1704 1705 // If more than one preferred function is found, all non-preferred 1706 // functions are eliminated from further consideration. 1707 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 1708 BestFns->clear(); 1709 1710 Best = Info; 1711 if (BestFns) 1712 BestFns->push_back(Info); 1713 } 1714 1715 return Best; 1716} 1717 1718/// Determine whether a given type is a class for which 'delete[]' would call 1719/// a member 'operator delete[]' with a 'size_t' parameter. This implies that 1720/// we need to store the array size (even if the type is 1721/// trivially-destructible). 1722static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 1723 QualType allocType) { 1724 const RecordType *record = 1725 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 1726 if (!record) return false; 1727 1728 // Try to find an operator delete[] in class scope. 1729 1730 DeclarationName deleteName = 1731 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 1732 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 1733 S.LookupQualifiedName(ops, record->getDecl()); 1734 1735 // We're just doing this for information. 1736 ops.suppressDiagnostics(); 1737 1738 // Very likely: there's no operator delete[]. 1739 if (ops.empty()) return false; 1740 1741 // If it's ambiguous, it should be illegal to call operator delete[] 1742 // on this thing, so it doesn't matter if we allocate extra space or not. 1743 if (ops.isAmbiguous()) return false; 1744 1745 // C++17 [expr.delete]p10: 1746 // If the deallocation functions have class scope, the one without a 1747 // parameter of type std::size_t is selected. 1748 auto Best = resolveDeallocationOverload( 1749 S, ops, /*WantSize*/false, 1750 /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 1751 return Best && Best.HasSizeT; 1752} 1753 1754/// Parsed a C++ 'new' expression (C++ 5.3.4). 1755/// 1756/// E.g.: 1757/// @code new (memory) int[size][4] @endcode 1758/// or 1759/// @code ::new Foo(23, "hello") @endcode 1760/// 1761/// \param StartLoc The first location of the expression. 1762/// \param UseGlobal True if 'new' was prefixed with '::'. 1763/// \param PlacementLParen Opening paren of the placement arguments. 1764/// \param PlacementArgs Placement new arguments. 1765/// \param PlacementRParen Closing paren of the placement arguments. 1766/// \param TypeIdParens If the type is in parens, the source range. 1767/// \param D The type to be allocated, as well as array dimensions. 1768/// \param Initializer The initializing expression or initializer-list, or null 1769/// if there is none. 1770ExprResult 1771Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 1772 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 1773 SourceLocation PlacementRParen, SourceRange TypeIdParens, 1774 Declarator &D, Expr *Initializer) { 1775 Optional<Expr *> ArraySize; 1776 // If the specified type is an array, unwrap it and save the expression. 1777 if (D.getNumTypeObjects() > 0 && 1778 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 1779 DeclaratorChunk &Chunk = D.getTypeObject(0); 1780 if (D.getDeclSpec().hasAutoTypeSpec()) 1781 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 1782 << D.getSourceRange()); 1783 if (Chunk.Arr.hasStatic) 1784 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 1785 << D.getSourceRange()); 1786 if (!Chunk.Arr.NumElts && !Initializer) 1787 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 1788 << D.getSourceRange()); 1789 1790 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 1791 D.DropFirstTypeObject(); 1792 } 1793 1794 // Every dimension shall be of constant size. 1795 if (ArraySize) { 1796 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 1797 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 1798 break; 1799 1800 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 1801 if (Expr *NumElts = (Expr *)Array.NumElts) { 1802 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1803 // FIXME: GCC permits constant folding here. We should either do so consistently 1804 // or not do so at all, rather than changing behavior in C++14 onwards. 1805 if (getLangOpts().CPlusPlus14) { 1806 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 1807 // shall be a converted constant expression (5.19) of type std::size_t 1808 // and shall evaluate to a strictly positive value. 1809 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 1810 Array.NumElts 1811 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1812 CCEK_ArrayBound) 1813 .get(); 1814 } else { 1815 Array.NumElts = 1816 VerifyIntegerConstantExpression( 1817 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) 1818 .get(); 1819 } 1820 if (!Array.NumElts) 1821 return ExprError(); 1822 } 1823 } 1824 } 1825 } 1826 1827 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 1828 QualType AllocType = TInfo->getType(); 1829 if (D.isInvalidType()) 1830 return ExprError(); 1831 1832 SourceRange DirectInitRange; 1833 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 1834 DirectInitRange = List->getSourceRange(); 1835 1836 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 1837 PlacementLParen, PlacementArgs, PlacementRParen, 1838 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 1839 Initializer); 1840} 1841 1842static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 1843 Expr *Init) { 1844 if (!Init) 1845 return true; 1846 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 1847 return PLE->getNumExprs() == 0; 1848 if (isa<ImplicitValueInitExpr>(Init)) 1849 return true; 1850 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 1851 return !CCE->isListInitialization() && 1852 CCE->getConstructor()->isDefaultConstructor(); 1853 else if (Style == CXXNewExpr::ListInit) { 1854 assert(isa<InitListExpr>(Init) &&((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1855, __PRETTY_FUNCTION__))
1855 "Shouldn't create list CXXConstructExprs for arrays.")((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1855, __PRETTY_FUNCTION__))
; 1856 return true; 1857 } 1858 return false; 1859} 1860 1861bool 1862Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 1863 if (!getLangOpts().AlignedAllocationUnavailable) 1864 return false; 1865 if (FD.isDefined()) 1866 return false; 1867 Optional<unsigned> AlignmentParam; 1868 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && 1869 AlignmentParam.hasValue()) 1870 return true; 1871 return false; 1872} 1873 1874// Emit a diagnostic if an aligned allocation/deallocation function that is not 1875// implemented in the standard library is selected. 1876void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 1877 SourceLocation Loc) { 1878 if (isUnavailableAlignedAllocationFunction(FD)) { 1879 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 1880 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 1881 getASTContext().getTargetInfo().getPlatformName()); 1882 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); 1883 1884 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 1885 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 1886 Diag(Loc, diag::err_aligned_allocation_unavailable) 1887 << IsDelete << FD.getType().getAsString() << OSName 1888 << OSVersion.getAsString() << OSVersion.empty(); 1889 Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 1890 } 1891} 1892 1893ExprResult 1894Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 1895 SourceLocation PlacementLParen, 1896 MultiExprArg PlacementArgs, 1897 SourceLocation PlacementRParen, 1898 SourceRange TypeIdParens, 1899 QualType AllocType, 1900 TypeSourceInfo *AllocTypeInfo, 1901 Optional<Expr *> ArraySize, 1902 SourceRange DirectInitRange, 1903 Expr *Initializer) { 1904 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 1905 SourceLocation StartLoc = Range.getBegin(); 1906 1907 CXXNewExpr::InitializationStyle initStyle; 1908 if (DirectInitRange.isValid()) { 1909 assert(Initializer && "Have parens but no initializer.")((Initializer && "Have parens but no initializer.") ?
static_cast<void> (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1909, __PRETTY_FUNCTION__))
; 1910 initStyle = CXXNewExpr::CallInit; 1911 } else if (Initializer && isa<InitListExpr>(Initializer)) 1912 initStyle = CXXNewExpr::ListInit; 1913 else { 1914 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1916, __PRETTY_FUNCTION__))
1915 isa<CXXConstructExpr>(Initializer)) &&(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1916, __PRETTY_FUNCTION__))
1916 "Initializer expression that cannot have been implicitly created.")(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1916, __PRETTY_FUNCTION__))
; 1917 initStyle = CXXNewExpr::NoInit; 1918 } 1919 1920 Expr **Inits = &Initializer; 1921 unsigned NumInits = Initializer ? 1 : 0; 1922 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 1923 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")((initStyle == CXXNewExpr::CallInit && "paren init for non-call init"
) ? static_cast<void> (0) : __assert_fail ("initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 1923, __PRETTY_FUNCTION__))
; 1924 Inits = List->getExprs(); 1925 NumInits = List->getNumExprs(); 1926 } 1927 1928 // C++11 [expr.new]p15: 1929 // A new-expression that creates an object of type T initializes that 1930 // object as follows: 1931 InitializationKind Kind 1932 // - If the new-initializer is omitted, the object is default- 1933 // initialized (8.5); if no initialization is performed, 1934 // the object has indeterminate value 1935 = initStyle == CXXNewExpr::NoInit 1936 ? InitializationKind::CreateDefault(TypeRange.getBegin()) 1937 // - Otherwise, the new-initializer is interpreted according to 1938 // the 1939 // initialization rules of 8.5 for direct-initialization. 1940 : initStyle == CXXNewExpr::ListInit 1941 ? InitializationKind::CreateDirectList( 1942 TypeRange.getBegin(), Initializer->getBeginLoc(), 1943 Initializer->getEndLoc()) 1944 : InitializationKind::CreateDirect(TypeRange.getBegin(), 1945 DirectInitRange.getBegin(), 1946 DirectInitRange.getEnd()); 1947 1948 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 1949 auto *Deduced = AllocType->getContainedDeducedType(); 1950 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 1951 if (ArraySize) 1952 return ExprError( 1953 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 1954 diag::err_deduced_class_template_compound_type) 1955 << /*array*/ 2 1956 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 1957 1958 InitializedEntity Entity 1959 = InitializedEntity::InitializeNew(StartLoc, AllocType); 1960 AllocType = DeduceTemplateSpecializationFromInitializer( 1961 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); 1962 if (AllocType.isNull()) 1963 return ExprError(); 1964 } else if (Deduced) { 1965 bool Braced = (initStyle == CXXNewExpr::ListInit); 1966 if (NumInits == 1) { 1967 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { 1968 Inits = p->getInits(); 1969 NumInits = p->getNumInits(); 1970 Braced = true; 1971 } 1972 } 1973 1974 if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 1975 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 1976 << AllocType << TypeRange); 1977 if (NumInits > 1) { 1978 Expr *FirstBad = Inits[1]; 1979 return ExprError(Diag(FirstBad->getBeginLoc(), 1980 diag::err_auto_new_ctor_multiple_expressions) 1981 << AllocType << TypeRange); 1982 } 1983 if (Braced && !getLangOpts().CPlusPlus17) 1984 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 1985 << AllocType << TypeRange; 1986 Expr *Deduce = Inits[0]; 1987 QualType DeducedType; 1988 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 1989 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 1990 << AllocType << Deduce->getType() 1991 << TypeRange << Deduce->getSourceRange()); 1992 if (DeducedType.isNull()) 1993 return ExprError(); 1994 AllocType = DeducedType; 1995 } 1996 1997 // Per C++0x [expr.new]p5, the type being constructed may be a 1998 // typedef of an array type. 1999 if (!ArraySize) { 2000 if (const ConstantArrayType *Array 2001 = Context.getAsConstantArrayType(AllocType)) { 2002 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 2003 Context.getSizeType(), 2004 TypeRange.getEnd()); 2005 AllocType = Array->getElementType(); 2006 } 2007 } 2008 2009 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 2010 return ExprError(); 2011 2012 // In ARC, infer 'retaining' for the allocated 2013 if (getLangOpts().ObjCAutoRefCount && 2014 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 2015 AllocType->isObjCLifetimeType()) { 2016 AllocType = Context.getLifetimeQualifiedType(AllocType, 2017 AllocType->getObjCARCImplicitLifetime()); 2018 } 2019 2020 QualType ResultType = Context.getPointerType(AllocType); 2021 2022 if (ArraySize && *ArraySize && 2023 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 2024 ExprResult result = CheckPlaceholderExpr(*ArraySize); 2025 if (result.isInvalid()) return ExprError(); 2026 ArraySize = result.get(); 2027 } 2028 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 2029 // integral or enumeration type with a non-negative value." 2030 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 2031 // enumeration type, or a class type for which a single non-explicit 2032 // conversion function to integral or unscoped enumeration type exists. 2033 // C++1y [expr.new]p6: The expression [...] is implicitly converted to 2034 // std::size_t. 2035 llvm::Optional<uint64_t> KnownArraySize; 2036 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 2037 ExprResult ConvertedSize; 2038 if (getLangOpts().CPlusPlus14) { 2039 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")((Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"
) ? static_cast<void> (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2039, __PRETTY_FUNCTION__))
; 2040 2041 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), 2042 AA_Converting); 2043 2044 if (!ConvertedSize.isInvalid() && 2045 (*ArraySize)->getType()->getAs<RecordType>()) 2046 // Diagnose the compatibility of this conversion. 2047 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 2048 << (*ArraySize)->getType() << 0 << "'size_t'"; 2049 } else { 2050 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 2051 protected: 2052 Expr *ArraySize; 2053 2054 public: 2055 SizeConvertDiagnoser(Expr *ArraySize) 2056 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 2057 ArraySize(ArraySize) {} 2058 2059 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 2060 QualType T) override { 2061 return S.Diag(Loc, diag::err_array_size_not_integral) 2062 << S.getLangOpts().CPlusPlus11 << T; 2063 } 2064 2065 SemaDiagnosticBuilder diagnoseIncomplete( 2066 Sema &S, SourceLocation Loc, QualType T) override { 2067 return S.Diag(Loc, diag::err_array_size_incomplete_type) 2068 << T << ArraySize->getSourceRange(); 2069 } 2070 2071 SemaDiagnosticBuilder diagnoseExplicitConv( 2072 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 2073 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 2074 } 2075 2076 SemaDiagnosticBuilder noteExplicitConv( 2077 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 2078 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 2079 << ConvTy->isEnumeralType() << ConvTy; 2080 } 2081 2082 SemaDiagnosticBuilder diagnoseAmbiguous( 2083 Sema &S, SourceLocation Loc, QualType T) override { 2084 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 2085 } 2086 2087 SemaDiagnosticBuilder noteAmbiguous( 2088 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 2089 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 2090 << ConvTy->isEnumeralType() << ConvTy; 2091 } 2092 2093 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 2094 QualType T, 2095 QualType ConvTy) override { 2096 return S.Diag(Loc, 2097 S.getLangOpts().CPlusPlus11 2098 ? diag::warn_cxx98_compat_array_size_conversion 2099 : diag::ext_array_size_conversion) 2100 << T << ConvTy->isEnumeralType() << ConvTy; 2101 } 2102 } SizeDiagnoser(*ArraySize); 2103 2104 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 2105 SizeDiagnoser); 2106 } 2107 if (ConvertedSize.isInvalid()) 2108 return ExprError(); 2109 2110 ArraySize = ConvertedSize.get(); 2111 QualType SizeType = (*ArraySize)->getType(); 2112 2113 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 2114 return ExprError(); 2115 2116 // C++98 [expr.new]p7: 2117 // The expression in a direct-new-declarator shall have integral type 2118 // with a non-negative value. 2119 // 2120 // Let's see if this is a constant < 0. If so, we reject it out of hand, 2121 // per CWG1464. Otherwise, if it's not a constant, we must have an 2122 // unparenthesized array type. 2123 if (!(*ArraySize)->isValueDependent()) { 2124 // We've already performed any required implicit conversion to integer or 2125 // unscoped enumeration type. 2126 // FIXME: Per CWG1464, we are required to check the value prior to 2127 // converting to size_t. This will never find a negative array size in 2128 // C++14 onwards, because Value is always unsigned here! 2129 if (Optional<llvm::APSInt> Value = 2130 (*ArraySize)->getIntegerConstantExpr(Context)) { 2131 if (Value->isSigned() && Value->isNegative()) { 2132 return ExprError(Diag((*ArraySize)->getBeginLoc(), 2133 diag::err_typecheck_negative_array_size) 2134 << (*ArraySize)->getSourceRange()); 2135 } 2136 2137 if (!AllocType->isDependentType()) { 2138 unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits( 2139 Context, AllocType, *Value); 2140 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 2141 return ExprError( 2142 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 2143 << Value->toString(10) << (*ArraySize)->getSourceRange()); 2144 } 2145 2146 KnownArraySize = Value->getZExtValue(); 2147 } else if (TypeIdParens.isValid()) { 2148 // Can't have dynamic array size when the type-id is in parentheses. 2149 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 2150 << (*ArraySize)->getSourceRange() 2151 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 2152 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 2153 2154 TypeIdParens = SourceRange(); 2155 } 2156 } 2157 2158 // Note that we do *not* convert the argument in any way. It can 2159 // be signed, larger than size_t, whatever. 2160 } 2161 2162 FunctionDecl *OperatorNew = nullptr; 2163 FunctionDecl *OperatorDelete = nullptr; 2164 unsigned Alignment = 2165 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 2166 unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 2167 bool PassAlignment = getLangOpts().AlignedAllocation && 2168 Alignment > NewAlignment; 2169 2170 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 2171 if (!AllocType->isDependentType() && 2172 !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 2173 FindAllocationFunctions( 2174 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 2175 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, 2176 OperatorNew, OperatorDelete)) 2177 return ExprError(); 2178 2179 // If this is an array allocation, compute whether the usual array 2180 // deallocation function for the type has a size_t parameter. 2181 bool UsualArrayDeleteWantsSize = false; 2182 if (ArraySize && !AllocType->isDependentType()) 2183 UsualArrayDeleteWantsSize = 2184 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 2185 2186 SmallVector<Expr *, 8> AllPlaceArgs; 2187 if (OperatorNew) { 2188 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 2189 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 2190 : VariadicDoesNotApply; 2191 2192 // We've already converted the placement args, just fill in any default 2193 // arguments. Skip the first parameter because we don't have a corresponding 2194 // argument. Skip the second parameter too if we're passing in the 2195 // alignment; we've already filled it in. 2196 unsigned NumImplicitArgs = PassAlignment ? 2 : 1; 2197 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 2198 NumImplicitArgs, PlacementArgs, AllPlaceArgs, 2199 CallType)) 2200 return ExprError(); 2201 2202 if (!AllPlaceArgs.empty()) 2203 PlacementArgs = AllPlaceArgs; 2204 2205 // We would like to perform some checking on the given `operator new` call, 2206 // but the PlacementArgs does not contain the implicit arguments, 2207 // namely allocation size and maybe allocation alignment, 2208 // so we need to conjure them. 2209 2210 QualType SizeTy = Context.getSizeType(); 2211 unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 2212 2213 llvm::APInt SingleEltSize( 2214 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); 2215 2216 // How many bytes do we want to allocate here? 2217 llvm::Optional<llvm::APInt> AllocationSize; 2218 if (!ArraySize.hasValue() && !AllocType->isDependentType()) { 2219 // For non-array operator new, we only want to allocate one element. 2220 AllocationSize = SingleEltSize; 2221 } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) { 2222 // For array operator new, only deal with static array size case. 2223 bool Overflow; 2224 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) 2225 .umul_ov(SingleEltSize, Overflow); 2226 (void)Overflow; 2227 assert(((!Overflow && "Expected that all the overflows would have been handled already."
) ? static_cast<void> (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2229, __PRETTY_FUNCTION__))
2228 !Overflow &&((!Overflow && "Expected that all the overflows would have been handled already."
) ? static_cast<void> (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2229, __PRETTY_FUNCTION__))
2229 "Expected that all the overflows would have been handled already.")((!Overflow && "Expected that all the overflows would have been handled already."
) ? static_cast<void> (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2229, __PRETTY_FUNCTION__))
; 2230 } 2231 2232 IntegerLiteral AllocationSizeLiteral( 2233 Context, 2234 AllocationSize.getValueOr(llvm::APInt::getNullValue(SizeTyWidth)), 2235 SizeTy, SourceLocation()); 2236 // Otherwise, if we failed to constant-fold the allocation size, we'll 2237 // just give up and pass-in something opaque, that isn't a null pointer. 2238 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_RValue, 2239 OK_Ordinary, /*SourceExpr=*/nullptr); 2240 2241 // Let's synthesize the alignment argument in case we will need it. 2242 // Since we *really* want to allocate these on stack, this is slightly ugly 2243 // because there might not be a `std::align_val_t` type. 2244 EnumDecl *StdAlignValT = getStdAlignValT(); 2245 QualType AlignValT = 2246 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; 2247 IntegerLiteral AlignmentLiteral( 2248 Context, 2249 llvm::APInt(Context.getTypeSize(SizeTy), 2250 Alignment / Context.getCharWidth()), 2251 SizeTy, SourceLocation()); 2252 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, 2253 CK_IntegralCast, &AlignmentLiteral, 2254 VK_RValue, FPOptionsOverride()); 2255 2256 // Adjust placement args by prepending conjured size and alignment exprs. 2257 llvm::SmallVector<Expr *, 8> CallArgs; 2258 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); 2259 CallArgs.emplace_back(AllocationSize.hasValue() 2260 ? static_cast<Expr *>(&AllocationSizeLiteral) 2261 : &OpaqueAllocationSize); 2262 if (PassAlignment) 2263 CallArgs.emplace_back(&DesiredAlignment); 2264 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); 2265 2266 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); 2267 2268 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, 2269 /*IsMemberFunction=*/false, StartLoc, Range, CallType); 2270 2271 // Warn if the type is over-aligned and is being allocated by (unaligned) 2272 // global operator new. 2273 if (PlacementArgs.empty() && !PassAlignment && 2274 (OperatorNew->isImplicit() || 2275 (OperatorNew->getBeginLoc().isValid() && 2276 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 2277 if (Alignment > NewAlignment) 2278 Diag(StartLoc, diag::warn_overaligned_type) 2279 << AllocType 2280 << unsigned(Alignment / Context.getCharWidth()) 2281 << unsigned(NewAlignment / Context.getCharWidth()); 2282 } 2283 } 2284 2285 // Array 'new' can't have any initializers except empty parentheses. 2286 // Initializer lists are also allowed, in C++11. Rely on the parser for the 2287 // dialect distinction. 2288 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 2289 SourceRange InitRange(Inits[0]->getBeginLoc(), 2290 Inits[NumInits - 1]->getEndLoc()); 2291 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 2292 return ExprError(); 2293 } 2294 2295 // If we can perform the initialization, and we've not already done so, 2296 // do it now. 2297 if (!AllocType->isDependentType() && 2298 !Expr::hasAnyTypeDependentArguments( 2299 llvm::makeArrayRef(Inits, NumInits))) { 2300 // The type we initialize is the complete type, including the array bound. 2301 QualType InitType; 2302 if (KnownArraySize) 2303 InitType = Context.getConstantArrayType( 2304 AllocType, 2305 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 2306 *KnownArraySize), 2307 *ArraySize, ArrayType::Normal, 0); 2308 else if (ArraySize) 2309 InitType = 2310 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 2311 else 2312 InitType = AllocType; 2313 2314 InitializedEntity Entity 2315 = InitializedEntity::InitializeNew(StartLoc, InitType); 2316 InitializationSequence InitSeq(*this, Entity, Kind, 2317 MultiExprArg(Inits, NumInits)); 2318 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 2319 MultiExprArg(Inits, NumInits)); 2320 if (FullInit.isInvalid()) 2321 return ExprError(); 2322 2323 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 2324 // we don't want the initialized object to be destructed. 2325 // FIXME: We should not create these in the first place. 2326 if (CXXBindTemporaryExpr *Binder = 2327 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 2328 FullInit = Binder->getSubExpr(); 2329 2330 Initializer = FullInit.get(); 2331 2332 // FIXME: If we have a KnownArraySize, check that the array bound of the 2333 // initializer is no greater than that constant value. 2334 2335 if (ArraySize && !*ArraySize) { 2336 auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 2337 if (CAT) { 2338 // FIXME: Track that the array size was inferred rather than explicitly 2339 // specified. 2340 ArraySize = IntegerLiteral::Create( 2341 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 2342 } else { 2343 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 2344 << Initializer->getSourceRange(); 2345 } 2346 } 2347 } 2348 2349 // Mark the new and delete operators as referenced. 2350 if (OperatorNew) { 2351 if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 2352 return ExprError(); 2353 MarkFunctionReferenced(StartLoc, OperatorNew); 2354 } 2355 if (OperatorDelete) { 2356 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 2357 return ExprError(); 2358 MarkFunctionReferenced(StartLoc, OperatorDelete); 2359 } 2360 2361 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 2362 PassAlignment, UsualArrayDeleteWantsSize, 2363 PlacementArgs, TypeIdParens, ArraySize, initStyle, 2364 Initializer, ResultType, AllocTypeInfo, Range, 2365 DirectInitRange); 2366} 2367 2368/// Checks that a type is suitable as the allocated type 2369/// in a new-expression. 2370bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 2371 SourceRange R) { 2372 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 2373 // abstract class type or array thereof. 2374 if (AllocType->isFunctionType()) 2375 return Diag(Loc, diag::err_bad_new_type) 2376 << AllocType << 0 << R; 2377 else if (AllocType->isReferenceType()) 2378 return Diag(Loc, diag::err_bad_new_type) 2379 << AllocType << 1 << R; 2380 else if (!AllocType->isDependentType() && 2381 RequireCompleteSizedType( 2382 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) 2383 return true; 2384 else if (RequireNonAbstractType(Loc, AllocType, 2385 diag::err_allocation_of_abstract_type)) 2386 return true; 2387 else if (AllocType->isVariablyModifiedType()) 2388 return Diag(Loc, diag::err_variably_modified_new_type) 2389 << AllocType; 2390 else if (AllocType.getAddressSpace() != LangAS::Default && 2391 !getLangOpts().OpenCLCPlusPlus) 2392 return Diag(Loc, diag::err_address_space_qualified_new) 2393 << AllocType.getUnqualifiedType() 2394 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 2395 else if (getLangOpts().ObjCAutoRefCount) { 2396 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 2397 QualType BaseAllocType = Context.getBaseElementType(AT); 2398 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 2399 BaseAllocType->isObjCLifetimeType()) 2400 return Diag(Loc, diag::err_arc_new_array_without_ownership) 2401 << BaseAllocType; 2402 } 2403 } 2404 2405 return false; 2406} 2407 2408static bool resolveAllocationOverload( 2409 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 2410 bool &PassAlignment, FunctionDecl *&Operator, 2411 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 2412 OverloadCandidateSet Candidates(R.getNameLoc(), 2413 OverloadCandidateSet::CSK_Normal); 2414 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 2415 Alloc != AllocEnd; ++Alloc) { 2416 // Even member operator new/delete are implicitly treated as 2417 // static, so don't use AddMemberCandidate. 2418 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 2419 2420 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 2421 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 2422 /*ExplicitTemplateArgs=*/nullptr, Args, 2423 Candidates, 2424 /*SuppressUserConversions=*/false); 2425 continue; 2426 } 2427 2428 FunctionDecl *Fn = cast<FunctionDecl>(D); 2429 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 2430 /*SuppressUserConversions=*/false); 2431 } 2432 2433 // Do the resolution. 2434 OverloadCandidateSet::iterator Best; 2435 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 2436 case OR_Success: { 2437 // Got one! 2438 FunctionDecl *FnDecl = Best->Function; 2439 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 2440 Best->FoundDecl) == Sema::AR_inaccessible) 2441 return true; 2442 2443 Operator = FnDecl; 2444 return false; 2445 } 2446 2447 case OR_No_Viable_Function: 2448 // C++17 [expr.new]p13: 2449 // If no matching function is found and the allocated object type has 2450 // new-extended alignment, the alignment argument is removed from the 2451 // argument list, and overload resolution is performed again. 2452 if (PassAlignment) { 2453 PassAlignment = false; 2454 AlignArg = Args[1]; 2455 Args.erase(Args.begin() + 1); 2456 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2457 Operator, &Candidates, AlignArg, 2458 Diagnose); 2459 } 2460 2461 // MSVC will fall back on trying to find a matching global operator new 2462 // if operator new[] cannot be found. Also, MSVC will leak by not 2463 // generating a call to operator delete or operator delete[], but we 2464 // will not replicate that bug. 2465 // FIXME: Find out how this interacts with the std::align_val_t fallback 2466 // once MSVC implements it. 2467 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 2468 S.Context.getLangOpts().MSVCCompat) { 2469 R.clear(); 2470 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 2471 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 2472 // FIXME: This will give bad diagnostics pointing at the wrong functions. 2473 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2474 Operator, /*Candidates=*/nullptr, 2475 /*AlignArg=*/nullptr, Diagnose); 2476 } 2477 2478 if (Diagnose) { 2479 // If this is an allocation of the form 'new (p) X' for some object 2480 // pointer p (or an expression that will decay to such a pointer), 2481 // diagnose the missing inclusion of <new>. 2482 if (!R.isClassLookup() && Args.size() == 2 && 2483 (Args[1]->getType()->isObjectPointerType() || 2484 Args[1]->getType()->isArrayType())) { 2485 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) 2486 << R.getLookupName() << Range; 2487 // Listing the candidates is unlikely to be useful; skip it. 2488 return true; 2489 } 2490 2491 // Finish checking all candidates before we note any. This checking can 2492 // produce additional diagnostics so can't be interleaved with our 2493 // emission of notes. 2494 // 2495 // For an aligned allocation, separately check the aligned and unaligned 2496 // candidates with their respective argument lists. 2497 SmallVector<OverloadCandidate*, 32> Cands; 2498 SmallVector<OverloadCandidate*, 32> AlignedCands; 2499 llvm::SmallVector<Expr*, 4> AlignedArgs; 2500 if (AlignedCandidates) { 2501 auto IsAligned = [](OverloadCandidate &C) { 2502 return C.Function->getNumParams() > 1 && 2503 C.Function->getParamDecl(1)->getType()->isAlignValT(); 2504 }; 2505 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 2506 2507 AlignedArgs.reserve(Args.size() + 1); 2508 AlignedArgs.push_back(Args[0]); 2509 AlignedArgs.push_back(AlignArg); 2510 AlignedArgs.append(Args.begin() + 1, Args.end()); 2511 AlignedCands = AlignedCandidates->CompleteCandidates( 2512 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); 2513 2514 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2515 R.getNameLoc(), IsUnaligned); 2516 } else { 2517 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2518 R.getNameLoc()); 2519 } 2520 2521 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2522 << R.getLookupName() << Range; 2523 if (AlignedCandidates) 2524 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", 2525 R.getNameLoc()); 2526 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); 2527 } 2528 return true; 2529 2530 case OR_Ambiguous: 2531 if (Diagnose) { 2532 Candidates.NoteCandidates( 2533 PartialDiagnosticAt(R.getNameLoc(), 2534 S.PDiag(diag::err_ovl_ambiguous_call) 2535 << R.getLookupName() << Range), 2536 S, OCD_AmbiguousCandidates, Args); 2537 } 2538 return true; 2539 2540 case OR_Deleted: { 2541 if (Diagnose) { 2542 Candidates.NoteCandidates( 2543 PartialDiagnosticAt(R.getNameLoc(), 2544 S.PDiag(diag::err_ovl_deleted_call) 2545 << R.getLookupName() << Range), 2546 S, OCD_AllCandidates, Args); 2547 } 2548 return true; 2549 } 2550 } 2551 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2551)
; 2552} 2553 2554bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 2555 AllocationFunctionScope NewScope, 2556 AllocationFunctionScope DeleteScope, 2557 QualType AllocType, bool IsArray, 2558 bool &PassAlignment, MultiExprArg PlaceArgs, 2559 FunctionDecl *&OperatorNew, 2560 FunctionDecl *&OperatorDelete, 2561 bool Diagnose) { 2562 // --- Choosing an allocation function --- 2563 // C++ 5.3.4p8 - 14 & 18 2564 // 1) If looking in AFS_Global scope for allocation functions, only look in 2565 // the global scope. Else, if AFS_Class, only look in the scope of the 2566 // allocated class. If AFS_Both, look in both. 2567 // 2) If an array size is given, look for operator new[], else look for 2568 // operator new. 2569 // 3) The first argument is always size_t. Append the arguments from the 2570 // placement form. 2571 2572 SmallVector<Expr*, 8> AllocArgs; 2573 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 2574 2575 // We don't care about the actual value of these arguments. 2576 // FIXME: Should the Sema create the expression and embed it in the syntax 2577 // tree? Or should the consumer just recalculate the value? 2578 // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2579 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 2580 Context.getTargetInfo().getPointerWidth(0)), 2581 Context.getSizeType(), 2582 SourceLocation()); 2583 AllocArgs.push_back(&Size); 2584 2585 QualType AlignValT = Context.VoidTy; 2586 if (PassAlignment) { 2587 DeclareGlobalNewDelete(); 2588 AlignValT = Context.getTypeDeclType(getStdAlignValT()); 2589 } 2590 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 2591 if (PassAlignment) 2592 AllocArgs.push_back(&Align); 2593 2594 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 2595 2596 // C++ [expr.new]p8: 2597 // If the allocated type is a non-array type, the allocation 2598 // function's name is operator new and the deallocation function's 2599 // name is operator delete. If the allocated type is an array 2600 // type, the allocation function's name is operator new[] and the 2601 // deallocation function's name is operator delete[]. 2602 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 2603 IsArray ? OO_Array_New : OO_New); 2604 2605 QualType AllocElemType = Context.getBaseElementType(AllocType); 2606 2607 // Find the allocation function. 2608 { 2609 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 2610 2611 // C++1z [expr.new]p9: 2612 // If the new-expression begins with a unary :: operator, the allocation 2613 // function's name is looked up in the global scope. Otherwise, if the 2614 // allocated type is a class type T or array thereof, the allocation 2615 // function's name is looked up in the scope of T. 2616 if (AllocElemType->isRecordType() && NewScope != AFS_Global) 2617 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 2618 2619 // We can see ambiguity here if the allocation function is found in 2620 // multiple base classes. 2621 if (R.isAmbiguous()) 2622 return true; 2623 2624 // If this lookup fails to find the name, or if the allocated type is not 2625 // a class type, the allocation function's name is looked up in the 2626 // global scope. 2627 if (R.empty()) { 2628 if (NewScope == AFS_Class) 2629 return true; 2630 2631 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 2632 } 2633 2634 if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 2635 if (PlaceArgs.empty()) { 2636 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 2637 } else { 2638 Diag(StartLoc, diag::err_openclcxx_placement_new); 2639 } 2640 return true; 2641 } 2642 2643 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2643, __PRETTY_FUNCTION__))
; 2644 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 2644, __PRETTY_FUNCTION__))
; 2645 2646 // We do our own custom access checks below. 2647 R.suppressDiagnostics(); 2648 2649 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 2650 OperatorNew, /*Candidates=*/nullptr, 2651 /*AlignArg=*/nullptr, Diagnose)) 2652 return true; 2653 } 2654 2655 // We don't need an operator delete if we're running under -fno-exceptions. 2656 if (!getLangOpts().Exceptions) { 2657 OperatorDelete = nullptr; 2658 return false; 2659 } 2660 2661 // Note, the name of OperatorNew might have been changed from array to 2662 // non-array by resolveAllocationOverload. 2663 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2664 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 2665 ? OO_Array_Delete 2666 : OO_Delete); 2667 2668 // C++ [expr.new]p19: 2669 // 2670 // If the new-expression begins with a unary :: operator, the 2671 // deallocation function's name is looked up in the global 2672 // scope. Otherwise, if the allocated type is a class type T or an 2673 // array thereof, the deallocation function's name is looked up in 2674 // the scope of T. If this lookup fails to find the name, or if 2675 // the allocated type is not a class type or array thereof, the 2676 // deallocation function's name is looked up in the global scope. 2677 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 2678 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2679 auto *RD = 2680 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 2681 LookupQualifiedName(FoundDelete, RD); 2682 } 2683 if (FoundDelete.isAmbiguous()) 2684 return true; // FIXME: clean up expressions? 2685 2686 // Filter out any destroying operator deletes. We can't possibly call such a 2687 // function in this context, because we're handling the case where the object 2688 // was not successfully constructed. 2689 // FIXME: This is not covered by the language rules yet. 2690 { 2691 LookupResult::Filter Filter = FoundDelete.makeFilter(); 2692 while (Filter.hasNext()) { 2693 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); 2694 if (FD && FD->isDestroyingOperatorDelete()) 2695 Filter.erase(); 2696 } 2697 Filter.done(); 2698 } 2699 2700 bool FoundGlobalDelete = FoundDelete.empty(); 2701 if (FoundDelete.empty()) { 2702 FoundDelete.clear(LookupOrdinaryName); 2703 2704 if (DeleteScope == AFS_Class) 2705 return true; 2706 2707 DeclareGlobalNewDelete(); 2708 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2709 } 2710 2711 FoundDelete.suppressDiagnostics(); 2712 2713 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 2714 2715 // Whether we're looking for a placement operator delete is dictated 2716 // by whether we selected a placement operator new, not by whether 2717 // we had explicit placement arguments. This matters for things like 2718 // struct A { void *operator new(size_t, int = 0); ... }; 2719 // A *a = new A() 2720 // 2721 // We don't have any definition for what a "placement allocation function" 2722 // is, but we assume it's any allocation function whose 2723 // parameter-declaration-clause is anything other than (size_t). 2724 // 2725 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 2726 // This affects whether an exception from the constructor of an overaligned 2727 // type uses the sized or non-sized form of aligned operator delete. 2728 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 2729 OperatorNew->isVariadic(); 2730 2731 if (isPlacementNew) { 2732 // C++ [expr.new]p20: 2733 // A declaration of a placement deallocation function matches the 2734 // declaration of a placement allocation function if it has the 2735 // same number of parameters and, after parameter transformations 2736 // (8.3.5), all parameter types except the first are 2737 // identical. [...] 2738 // 2739 // To perform this comparison, we compute the function type that 2740 // the deallocation function should have, and use that type both 2741 // for template argument deduction and for comparison purposes. 2742 QualType ExpectedFunctionType; 2743 { 2744 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 2745 2746 SmallVector<QualType, 4> ArgTypes; 2747 ArgTypes.push_back(Context.VoidPtrTy); 2748 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 2749 ArgTypes.push_back(Proto->getParamType(I)); 2750 2751 FunctionProtoType::ExtProtoInfo EPI; 2752 // FIXME: This is not part of the standard's rule. 2753 EPI.Variadic = Proto->isVariadic(); 2754 2755 ExpectedFunctionType 2756 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 2757 } 2758 2759 for (LookupResult::iterator D = FoundDelete.begin(), 2760 DEnd = FoundDelete.end(); 2761 D != DEnd; ++D) { 2762 FunctionDecl *Fn = nullptr; 2763 if (FunctionTemplateDecl *FnTmpl = 2764 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 2765 // Perform template argument deduction to try to match the 2766 // expected function type. 2767 TemplateDeductionInfo Info(StartLoc); 2768 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 2769 Info)) 2770 continue; 2771 } else 2772 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 2773 2774 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 2775 ExpectedFunctionType, 2776 /*AdjustExcpetionSpec*/true), 2777 ExpectedFunctionType)) 2778 Matches.push_back(std::make_pair(D.getPair(), Fn)); 2779 } 2780 2781 if (getLangOpts().CUDA) 2782 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 2783 } else { 2784 // C++1y [expr.new]p22: 2785 // For a non-placement allocation function, the normal deallocation 2786 // function lookup is used 2787 // 2788 // Per [expr.delete]p10, this lookup prefers a member operator delete 2789 // without a size_t argument, but prefers a non-member operator delete 2790 // with a size_t where possible (which it always is in this case). 2791 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 2792 UsualDeallocFnInfo Selected = resolveDeallocationOverload( 2793 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 2794 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 2795 &BestDeallocFns); 2796 if (Selected) 2797 Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 2798 else { 2799 // If we failed to select an operator, all remaining functions are viable 2800 // but ambiguous. 2801 for (auto Fn : BestDeallocFns) 2802 Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 2803 } 2804 } 2805 2806 // C++ [expr.new]p20: 2807 // [...] If the lookup finds a single matching deallocation 2808 // function, that function will be called; otherwise, no 2809 // deallocation function will be called. 2810 if (Matches.size() == 1) { 2811 OperatorDelete = Matches[0].second; 2812 2813 // C++1z [expr.new]p23: 2814 // If the lookup finds a usual deallocation function (3.7.4.2) 2815 // with a parameter of type std::size_t and that function, considered 2816 // as a placement deallocation function, would have been 2817 // selected as a match for the allocation function, the program 2818 // is ill-formed. 2819 if (getLangOpts().CPlusPlus11 && isPlacementNew && 2820 isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 2821 UsualDeallocFnInfo Info(*this, 2822 DeclAccessPair::make(OperatorDelete, AS_public)); 2823 // Core issue, per mail to core reflector, 2016-10-09: 2824 // If this is a member operator delete, and there is a corresponding 2825 // non-sized member operator delete, this isn't /really/ a sized 2826 // deallocation function, it just happens to have a size_t parameter. 2827 bool IsSizedDelete = Info.HasSizeT; 2828 if (IsSizedDelete && !FoundGlobalDelete) { 2829 auto NonSizedDelete = 2830 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 2831 /*WantAlign*/Info.HasAlignValT); 2832 if (NonSizedDelete && !NonSizedDelete.HasSizeT && 2833 NonSizedDelete.HasAlignValT == Info.HasAlignValT) 2834 IsSizedDelete = false; 2835 } 2836 2837 if (IsSizedDelete) { 2838 SourceRange R = PlaceArgs.empty() 2839 ? SourceRange() 2840 : SourceRange(PlaceArgs.front()->getBeginLoc(), 2841 PlaceArgs.back()->getEndLoc()); 2842 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 2843 if (!OperatorDelete->isImplicit()) 2844 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 2845 << DeleteName; 2846 } 2847 } 2848 2849 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 2850 Matches[0].first); 2851 } else if (!Matches.empty()) { 2852 // We found multiple suitable operators. Per [expr.new]p20, that means we 2853 // call no 'operator delete' function, but we should at least warn the user. 2854 // FIXME: Suppress this warning if the construction cannot throw. 2855 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 2856 << DeleteName << AllocElemType; 2857 2858 for (auto &Match : Matches) 2859 Diag(Match.second->getLocation(), 2860 diag::note_member_declared_here) << DeleteName; 2861 } 2862 2863 return false; 2864} 2865 2866/// DeclareGlobalNewDelete - Declare the global forms of operator new and 2867/// delete. These are: 2868/// @code 2869/// // C++03: 2870/// void* operator new(std::size_t) throw(std::bad_alloc); 2871/// void* operator new[](std::size_t) throw(std::bad_alloc); 2872/// void operator delete(void *) throw(); 2873/// void operator delete[](void *) throw(); 2874/// // C++11: 2875/// void* operator new(std::size_t); 2876/// void* operator new[](std::size_t); 2877/// void operator delete(void *) noexcept; 2878/// void operator delete[](void *) noexcept; 2879/// // C++1y: 2880/// void* operator new(std::size_t); 2881/// void* operator new[](std::size_t); 2882/// void operator delete(void *) noexcept; 2883/// void operator delete[](void *) noexcept; 2884/// void operator delete(void *, std::size_t) noexcept; 2885/// void operator delete[](void *, std::size_t) noexcept; 2886/// @endcode 2887/// Note that the placement and nothrow forms of new are *not* implicitly 2888/// declared. Their use requires including \<new\>. 2889void Sema::DeclareGlobalNewDelete() { 2890 if (GlobalNewDeleteDeclared) 2891 return; 2892 2893 // The implicitly declared new and delete operators 2894 // are not supported in OpenCL. 2895 if (getLangOpts().OpenCLCPlusPlus) 2896 return; 2897 2898 // C++ [basic.std.dynamic]p2: 2899 // [...] The following allocation and deallocation functions (18.4) are 2900 // implicitly declared in global scope in each translation unit of a 2901 // program 2902 // 2903 // C++03: 2904 // void* operator new(std::size_t) throw(std::bad_alloc); 2905 // void* operator new[](std::size_t) throw(std::bad_alloc); 2906 // void operator delete(void*) throw(); 2907 // void operator delete[](void*) throw(); 2908 // C++11: 2909 // void* operator new(std::size_t); 2910 // void* operator new[](std::size_t); 2911 // void operator delete(void*) noexcept; 2912 // void operator delete[](void*) noexcept; 2913 // C++1y: 2914 // void* operator new(std::size_t); 2915 // void* operator new[](std::size_t); 2916 // void operator delete(void*) noexcept; 2917 // void operator delete[](void*) noexcept; 2918 // void operator delete(void*, std::size_t) noexcept; 2919 // void operator delete[](void*, std::size_t) noexcept; 2920 // 2921 // These implicit declarations introduce only the function names operator 2922 // new, operator new[], operator delete, operator delete[]. 2923 // 2924 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 2925 // "std" or "bad_alloc" as necessary to form the exception specification. 2926 // However, we do not make these implicit declarations visible to name 2927 // lookup. 2928 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 2929 // The "std::bad_alloc" class has not yet been declared, so build it 2930 // implicitly. 2931 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 2932 getOrCreateStdNamespace(), 2933 SourceLocation(), SourceLocation(), 2934 &PP.getIdentifierTable().get("bad_alloc"), 2935 nullptr); 2936 getStdBadAlloc()->setImplicit(true); 2937 } 2938 if (!StdAlignValT && getLangOpts().AlignedAllocation) { 2939 // The "std::align_val_t" enum class has not yet been declared, so build it 2940 // implicitly. 2941 auto *AlignValT = EnumDecl::Create( 2942 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 2943 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 2944 AlignValT->setIntegerType(Context.getSizeType()); 2945 AlignValT->setPromotionType(Context.getSizeType()); 2946 AlignValT->setImplicit(true); 2947 StdAlignValT = AlignValT; 2948 } 2949 2950 GlobalNewDeleteDeclared = true; 2951 2952 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 2953 QualType SizeT = Context.getSizeType(); 2954 2955 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 2956 QualType Return, QualType Param) { 2957 llvm::SmallVector<QualType, 3> Params; 2958 Params.push_back(Param); 2959 2960 // Create up to four variants of the function (sized/aligned). 2961 bool HasSizedVariant = getLangOpts().SizedDeallocation && 2962 (Kind == OO_Delete || Kind == OO_Array_Delete); 2963 bool HasAlignedVariant = getLangOpts().AlignedAllocation; 2964 2965 int NumSizeVariants = (HasSizedVariant ? 2 : 1); 2966 int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 2967 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 2968 if (Sized) 2969 Params.push_back(SizeT); 2970 2971 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 2972 if (Aligned) 2973 Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 2974 2975 DeclareGlobalAllocationFunction( 2976 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 2977 2978 if (Aligned) 2979 Params.pop_back(); 2980 } 2981 } 2982 }; 2983 2984 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 2985 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 2986 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 2987 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 2988} 2989 2990/// DeclareGlobalAllocationFunction - Declares a single implicit global 2991/// allocation function if it doesn't already exist. 2992void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 2993 QualType Return, 2994 ArrayRef<QualType> Params) { 2995 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 2996 2997 // Check if this function is already declared. 2998 DeclContext::lookup_result R = GlobalCtx->lookup(Name); 2999 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 3000 Alloc != AllocEnd; ++Alloc) { 3001 // Only look at non-template functions, as it is the predefined, 3002 // non-templated allocation function we are trying to declare here. 3003 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 3004 if (Func->getNumParams() == Params.size()) { 3005 llvm::SmallVector<QualType, 3> FuncParams; 3006 for (auto *P : Func->parameters()) 3007 FuncParams.push_back( 3008 Context.getCanonicalType(P->getType().getUnqualifiedType())); 3009 if (llvm::makeArrayRef(FuncParams) == Params) { 3010 // Make the function visible to name lookup, even if we found it in 3011 // an unimported module. It either is an implicitly-declared global 3012 // allocation function, or is suppressing that function. 3013 Func->setVisibleDespiteOwningModule(); 3014 return; 3015 } 3016 } 3017 } 3018 } 3019 3020 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 3021 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 3022 3023 QualType BadAllocType; 3024 bool HasBadAllocExceptionSpec 3025 = (Name.getCXXOverloadedOperator() == OO_New || 3026 Name.getCXXOverloadedOperator() == OO_Array_New); 3027 if (HasBadAllocExceptionSpec) { 3028 if (!getLangOpts().CPlusPlus11) { 3029 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 3030 assert(StdBadAlloc && "Must have std::bad_alloc declared")((StdBadAlloc && "Must have std::bad_alloc declared")
? static_cast<void> (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3030, __PRETTY_FUNCTION__))
; 3031 EPI.ExceptionSpec.Type = EST_Dynamic; 3032 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 3033 } 3034 } else { 3035 EPI.ExceptionSpec = 3036 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 3037 } 3038 3039 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 3040 QualType FnType = Context.getFunctionType(Return, Params, EPI); 3041 FunctionDecl *Alloc = FunctionDecl::Create( 3042 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, 3043 FnType, /*TInfo=*/nullptr, SC_None, false, true); 3044 Alloc->setImplicit(); 3045 // Global allocation functions should always be visible. 3046 Alloc->setVisibleDespiteOwningModule(); 3047 3048 Alloc->addAttr(VisibilityAttr::CreateImplicit( 3049 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 3050 ? VisibilityAttr::Hidden 3051 : VisibilityAttr::Default)); 3052 3053 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 3054 for (QualType T : Params) { 3055 ParamDecls.push_back(ParmVarDecl::Create( 3056 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 3057 /*TInfo=*/nullptr, SC_None, nullptr)); 3058 ParamDecls.back()->setImplicit(); 3059 } 3060 Alloc->setParams(ParamDecls); 3061 if (ExtraAttr) 3062 Alloc->addAttr(ExtraAttr); 3063 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); 3064 Context.getTranslationUnitDecl()->addDecl(Alloc); 3065 IdResolver.tryAddTopLevelDecl(Alloc, Name); 3066 }; 3067 3068 if (!LangOpts.CUDA) 3069 CreateAllocationFunctionDecl(nullptr); 3070 else { 3071 // Host and device get their own declaration so each can be 3072 // defined or re-declared independently. 3073 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 3074 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 3075 } 3076} 3077 3078FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 3079 bool CanProvideSize, 3080 bool Overaligned, 3081 DeclarationName Name) { 3082 DeclareGlobalNewDelete(); 3083 3084 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 3085 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 3086 3087 // FIXME: It's possible for this to result in ambiguity, through a 3088 // user-declared variadic operator delete or the enable_if attribute. We 3089 // should probably not consider those cases to be usual deallocation 3090 // functions. But for now we just make an arbitrary choice in that case. 3091 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 3092 Overaligned); 3093 assert(Result.FD && "operator delete missing from global scope?")((Result.FD && "operator delete missing from global scope?"
) ? static_cast<void> (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3093, __PRETTY_FUNCTION__))
; 3094 return Result.FD; 3095} 3096 3097FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 3098 CXXRecordDecl *RD) { 3099 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3100 3101 FunctionDecl *OperatorDelete = nullptr; 3102 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3103 return nullptr; 3104 if (OperatorDelete) 3105 return OperatorDelete; 3106 3107 // If there's no class-specific operator delete, look up the global 3108 // non-array delete. 3109 return FindUsualDeallocationFunction( 3110 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 3111 Name); 3112} 3113 3114bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3115 DeclarationName Name, 3116 FunctionDecl *&Operator, bool Diagnose) { 3117 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 3118 // Try to find operator delete/operator delete[] in class scope. 3119 LookupQualifiedName(Found, RD); 3120 3121 if (Found.isAmbiguous()) 3122 return true; 3123 3124 Found.suppressDiagnostics(); 3125 3126 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 3127 3128 // C++17 [expr.delete]p10: 3129 // If the deallocation functions have class scope, the one without a 3130 // parameter of type std::size_t is selected. 3131 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 3132 resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 3133 /*WantAlign*/ Overaligned, &Matches); 3134 3135 // If we could find an overload, use it. 3136 if (Matches.size() == 1) { 3137 Operator = cast<CXXMethodDecl>(Matches[0].FD); 3138 3139 // FIXME: DiagnoseUseOfDecl? 3140 if (Operator->isDeleted()) { 3141 if (Diagnose) { 3142 Diag(StartLoc, diag::err_deleted_function_use); 3143 NoteDeletedFunction(Operator); 3144 } 3145 return true; 3146 } 3147 3148 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 3149 Matches[0].Found, Diagnose) == AR_inaccessible) 3150 return true; 3151 3152 return false; 3153 } 3154 3155 // We found multiple suitable operators; complain about the ambiguity. 3156 // FIXME: The standard doesn't say to do this; it appears that the intent 3157 // is that this should never happen. 3158 if (!Matches.empty()) { 3159 if (Diagnose) { 3160 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 3161 << Name << RD; 3162 for (auto &Match : Matches) 3163 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 3164 } 3165 return true; 3166 } 3167 3168 // We did find operator delete/operator delete[] declarations, but 3169 // none of them were suitable. 3170 if (!Found.empty()) { 3171 if (Diagnose) { 3172 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 3173 << Name << RD; 3174 3175 for (NamedDecl *D : Found) 3176 Diag(D->getUnderlyingDecl()->getLocation(), 3177 diag::note_member_declared_here) << Name; 3178 } 3179 return true; 3180 } 3181 3182 Operator = nullptr; 3183 return false; 3184} 3185 3186namespace { 3187/// Checks whether delete-expression, and new-expression used for 3188/// initializing deletee have the same array form. 3189class MismatchingNewDeleteDetector { 3190public: 3191 enum MismatchResult { 3192 /// Indicates that there is no mismatch or a mismatch cannot be proven. 3193 NoMismatch, 3194 /// Indicates that variable is initialized with mismatching form of \a new. 3195 VarInitMismatches, 3196 /// Indicates that member is initialized with mismatching form of \a new. 3197 MemberInitMismatches, 3198 /// Indicates that 1 or more constructors' definitions could not been 3199 /// analyzed, and they will be checked again at the end of translation unit. 3200 AnalyzeLater 3201 }; 3202 3203 /// \param EndOfTU True, if this is the final analysis at the end of 3204 /// translation unit. False, if this is the initial analysis at the point 3205 /// delete-expression was encountered. 3206 explicit MismatchingNewDeleteDetector(bool EndOfTU) 3207 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 3208 HasUndefinedConstructors(false) {} 3209 3210 /// Checks whether pointee of a delete-expression is initialized with 3211 /// matching form of new-expression. 3212 /// 3213 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 3214 /// point where delete-expression is encountered, then a warning will be 3215 /// issued immediately. If return value is \c AnalyzeLater at the point where 3216 /// delete-expression is seen, then member will be analyzed at the end of 3217 /// translation unit. \c AnalyzeLater is returned iff at least one constructor 3218 /// couldn't be analyzed. If at least one constructor initializes the member 3219 /// with matching type of new, the return value is \c NoMismatch. 3220 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 3221 /// Analyzes a class member. 3222 /// \param Field Class member to analyze. 3223 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 3224 /// for deleting the \p Field. 3225 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 3226 FieldDecl *Field; 3227 /// List of mismatching new-expressions used for initialization of the pointee 3228 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 3229 /// Indicates whether delete-expression was in array form. 3230 bool IsArrayForm; 3231 3232private: 3233 const bool EndOfTU; 3234 /// Indicates that there is at least one constructor without body. 3235 bool HasUndefinedConstructors; 3236 /// Returns \c CXXNewExpr from given initialization expression. 3237 /// \param E Expression used for initializing pointee in delete-expression. 3238 /// E can be a single-element \c InitListExpr consisting of new-expression. 3239 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 3240 /// Returns whether member is initialized with mismatching form of 3241 /// \c new either by the member initializer or in-class initialization. 3242 /// 3243 /// If bodies of all constructors are not visible at the end of translation 3244 /// unit or at least one constructor initializes member with the matching 3245 /// form of \c new, mismatch cannot be proven, and this function will return 3246 /// \c NoMismatch. 3247 MismatchResult analyzeMemberExpr(const MemberExpr *ME); 3248 /// Returns whether variable is initialized with mismatching form of 3249 /// \c new. 3250 /// 3251 /// If variable is initialized with matching form of \c new or variable is not 3252 /// initialized with a \c new expression, this function will return true. 3253 /// If variable is initialized with mismatching form of \c new, returns false. 3254 /// \param D Variable to analyze. 3255 bool hasMatchingVarInit(const DeclRefExpr *D); 3256 /// Checks whether the constructor initializes pointee with mismatching 3257 /// form of \c new. 3258 /// 3259 /// Returns true, if member is initialized with matching form of \c new in 3260 /// member initializer list. Returns false, if member is initialized with the 3261 /// matching form of \c new in this constructor's initializer or given 3262 /// constructor isn't defined at the point where delete-expression is seen, or 3263 /// member isn't initialized by the constructor. 3264 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 3265 /// Checks whether member is initialized with matching form of 3266 /// \c new in member initializer list. 3267 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 3268 /// Checks whether member is initialized with mismatching form of \c new by 3269 /// in-class initializer. 3270 MismatchResult analyzeInClassInitializer(); 3271}; 3272} 3273 3274MismatchingNewDeleteDetector::MismatchResult 3275MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 3276 NewExprs.clear(); 3277 assert(DE && "Expected delete-expression")((DE && "Expected delete-expression") ? static_cast<
void> (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3277, __PRETTY_FUNCTION__))
; 3278 IsArrayForm = DE->isArrayForm(); 3279 const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 3280 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 3281 return analyzeMemberExpr(ME); 3282 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 3283 if (!hasMatchingVarInit(D)) 3284 return VarInitMismatches; 3285 } 3286 return NoMismatch; 3287} 3288 3289const CXXNewExpr * 3290MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 3291 assert(E != nullptr && "Expected a valid initializer expression")((E != nullptr && "Expected a valid initializer expression"
) ? static_cast<void> (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3291, __PRETTY_FUNCTION__))
; 3292 E = E->IgnoreParenImpCasts(); 3293 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 3294 if (ILE->getNumInits() == 1) 3295 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 3296 } 3297 3298 return dyn_cast_or_null<const CXXNewExpr>(E); 3299} 3300 3301bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 3302 const CXXCtorInitializer *CI) { 3303 const CXXNewExpr *NE = nullptr; 3304 if (Field == CI->getMember() && 3305 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 3306 if (NE->isArray() == IsArrayForm) 3307 return true; 3308 else 3309 NewExprs.push_back(NE); 3310 } 3311 return false; 3312} 3313 3314bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 3315 const CXXConstructorDecl *CD) { 3316 if (CD->isImplicit()) 3317 return false; 3318 const FunctionDecl *Definition = CD; 3319 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 3320 HasUndefinedConstructors = true; 3321 return EndOfTU; 3322 } 3323 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 3324 if (hasMatchingNewInCtorInit(CI)) 3325 return true; 3326 } 3327 return false; 3328} 3329 3330MismatchingNewDeleteDetector::MismatchResult 3331MismatchingNewDeleteDetector::analyzeInClassInitializer() { 3332 assert(Field != nullptr && "This should be called only for members")((Field != nullptr && "This should be called only for members"
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3332, __PRETTY_FUNCTION__))
; 3333 const Expr *InitExpr = Field->getInClassInitializer(); 3334 if (!InitExpr) 3335 return EndOfTU ? NoMismatch : AnalyzeLater; 3336 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 3337 if (NE->isArray() != IsArrayForm) { 3338 NewExprs.push_back(NE); 3339 return MemberInitMismatches; 3340 } 3341 } 3342 return NoMismatch; 3343} 3344 3345MismatchingNewDeleteDetector::MismatchResult 3346MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 3347 bool DeleteWasArrayForm) { 3348 assert(Field != nullptr && "Analysis requires a valid class member.")((Field != nullptr && "Analysis requires a valid class member."
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3348, __PRETTY_FUNCTION__))
; 3349 this->Field = Field; 3350 IsArrayForm = DeleteWasArrayForm; 3351 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 3352 for (const auto *CD : RD->ctors()) { 3353 if (hasMatchingNewInCtor(CD)) 3354 return NoMismatch; 3355 } 3356 if (HasUndefinedConstructors) 3357 return EndOfTU ? NoMismatch : AnalyzeLater; 3358 if (!NewExprs.empty()) 3359 return MemberInitMismatches; 3360 return Field->hasInClassInitializer() ? analyzeInClassInitializer() 3361 : NoMismatch; 3362} 3363 3364MismatchingNewDeleteDetector::MismatchResult 3365MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 3366 assert(ME != nullptr && "Expected a member expression")((ME != nullptr && "Expected a member expression") ? static_cast
<void> (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3366, __PRETTY_FUNCTION__))
; 3367 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3368 return analyzeField(F, IsArrayForm); 3369 return NoMismatch; 3370} 3371 3372bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 3373 const CXXNewExpr *NE = nullptr; 3374 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 3375 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 3376 NE->isArray() != IsArrayForm) { 3377 NewExprs.push_back(NE); 3378 } 3379 } 3380 return NewExprs.empty(); 3381} 3382 3383static void 3384DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 3385 const MismatchingNewDeleteDetector &Detector) { 3386 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 3387 FixItHint H; 3388 if (!Detector.IsArrayForm) 3389 H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 3390 else { 3391 SourceLocation RSquare = Lexer::findLocationAfterToken( 3392 DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 3393 SemaRef.getLangOpts(), true); 3394 if (RSquare.isValid()) 3395 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 3396 } 3397 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 3398 << Detector.IsArrayForm << H; 3399 3400 for (const auto *NE : Detector.NewExprs) 3401 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 3402 << Detector.IsArrayForm; 3403} 3404 3405void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 3406 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 3407 return; 3408 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 3409 switch (Detector.analyzeDeleteExpr(DE)) { 3410 case MismatchingNewDeleteDetector::VarInitMismatches: 3411 case MismatchingNewDeleteDetector::MemberInitMismatches: { 3412 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 3413 break; 3414 } 3415 case MismatchingNewDeleteDetector::AnalyzeLater: { 3416 DeleteExprs[Detector.Field].push_back( 3417 std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 3418 break; 3419 } 3420 case MismatchingNewDeleteDetector::NoMismatch: 3421 break; 3422 } 3423} 3424 3425void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 3426 bool DeleteWasArrayForm) { 3427 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 3428 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 3429 case MismatchingNewDeleteDetector::VarInitMismatches: 3430 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3430)
; 3431 case MismatchingNewDeleteDetector::AnalyzeLater: 3432 llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3433)
3433 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3433)
; 3434 case MismatchingNewDeleteDetector::MemberInitMismatches: 3435 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 3436 break; 3437 case MismatchingNewDeleteDetector::NoMismatch: 3438 break; 3439 } 3440} 3441 3442/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 3443/// @code ::delete ptr; @endcode 3444/// or 3445/// @code delete [] ptr; @endcode 3446ExprResult 3447Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 3448 bool ArrayForm, Expr *ExE) { 3449 // C++ [expr.delete]p1: 3450 // The operand shall have a pointer type, or a class type having a single 3451 // non-explicit conversion function to a pointer type. The result has type 3452 // void. 3453 // 3454 // DR599 amends "pointer type" to "pointer to object type" in both cases. 3455 3456 ExprResult Ex = ExE; 3457 FunctionDecl *OperatorDelete = nullptr; 3458 bool ArrayFormAsWritten = ArrayForm; 3459 bool UsualArrayDeleteWantsSize = false; 3460 3461 if (!Ex.get()->isTypeDependent()) { 3462 // Perform lvalue-to-rvalue cast, if needed. 3463 Ex = DefaultLvalueConversion(Ex.get()); 3464 if (Ex.isInvalid()) 3465 return ExprError(); 3466 3467 QualType Type = Ex.get()->getType(); 3468 3469 class DeleteConverter : public ContextualImplicitConverter { 3470 public: 3471 DeleteConverter() : ContextualImplicitConverter(false, true) {} 3472 3473 bool match(QualType ConvType) override { 3474 // FIXME: If we have an operator T* and an operator void*, we must pick 3475 // the operator T*. 3476 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 3477 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 3478 return true; 3479 return false; 3480 } 3481 3482 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 3483 QualType T) override { 3484 return S.Diag(Loc, diag::err_delete_operand) << T; 3485 } 3486 3487 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3488 QualType T) override { 3489 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 3490 } 3491 3492 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3493 QualType T, 3494 QualType ConvTy) override { 3495 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 3496 } 3497 3498 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3499 QualType ConvTy) override { 3500 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3501 << ConvTy; 3502 } 3503 3504 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3505 QualType T) override { 3506 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 3507 } 3508 3509 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3510 QualType ConvTy) override { 3511 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3512 << ConvTy; 3513 } 3514 3515 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 3516 QualType T, 3517 QualType ConvTy) override { 3518 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3518)
; 3519 } 3520 } Converter; 3521 3522 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 3523 if (Ex.isInvalid()) 3524 return ExprError(); 3525 Type = Ex.get()->getType(); 3526 if (!Converter.match(Type)) 3527 // FIXME: PerformContextualImplicitConversion should return ExprError 3528 // itself in this case. 3529 return ExprError(); 3530 3531 QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 3532 QualType PointeeElem = Context.getBaseElementType(Pointee); 3533 3534 if (Pointee.getAddressSpace() != LangAS::Default && 3535 !getLangOpts().OpenCLCPlusPlus) 3536 return Diag(Ex.get()->getBeginLoc(), 3537 diag::err_address_space_qualified_delete) 3538 << Pointee.getUnqualifiedType() 3539 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 3540 3541 CXXRecordDecl *PointeeRD = nullptr; 3542 if (Pointee->isVoidType() && !isSFINAEContext()) { 3543 // The C++ standard bans deleting a pointer to a non-object type, which 3544 // effectively bans deletion of "void*". However, most compilers support 3545 // this, so we treat it as a warning unless we're in a SFINAE context. 3546 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 3547 << Type << Ex.get()->getSourceRange(); 3548 } else if (Pointee->isFunctionType() || Pointee->isVoidType() || 3549 Pointee->isSizelessType()) { 3550 return ExprError(Diag(StartLoc, diag::err_delete_operand) 3551 << Type << Ex.get()->getSourceRange()); 3552 } else if (!Pointee->isDependentType()) { 3553 // FIXME: This can result in errors if the definition was imported from a 3554 // module but is hidden. 3555 if (!RequireCompleteType(StartLoc, Pointee, 3556 diag::warn_delete_incomplete, Ex.get())) { 3557 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 3558 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 3559 } 3560 } 3561 3562 if (Pointee->isArrayType() && !ArrayForm) { 3563 Diag(StartLoc, diag::warn_delete_array_type) 3564 << Type << Ex.get()->getSourceRange() 3565 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 3566 ArrayForm = true; 3567 } 3568 3569 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 3570 ArrayForm ? OO_Array_Delete : OO_Delete); 3571 3572 if (PointeeRD) { 3573 if (!UseGlobal && 3574 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 3575 OperatorDelete)) 3576 return ExprError(); 3577 3578 // If we're allocating an array of records, check whether the 3579 // usual operator delete[] has a size_t parameter. 3580 if (ArrayForm) { 3581 // If the user specifically asked to use the global allocator, 3582 // we'll need to do the lookup into the class. 3583 if (UseGlobal) 3584 UsualArrayDeleteWantsSize = 3585 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 3586 3587 // Otherwise, the usual operator delete[] should be the 3588 // function we just found. 3589 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 3590 UsualArrayDeleteWantsSize = 3591 UsualDeallocFnInfo(*this, 3592 DeclAccessPair::make(OperatorDelete, AS_public)) 3593 .HasSizeT; 3594 } 3595 3596 if (!PointeeRD->hasIrrelevantDestructor()) 3597 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3598 MarkFunctionReferenced(StartLoc, 3599 const_cast<CXXDestructorDecl*>(Dtor)); 3600 if (DiagnoseUseOfDecl(Dtor, StartLoc)) 3601 return ExprError(); 3602 } 3603 3604 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 3605 /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 3606 /*WarnOnNonAbstractTypes=*/!ArrayForm, 3607 SourceLocation()); 3608 } 3609 3610 if (!OperatorDelete) { 3611 if (getLangOpts().OpenCLCPlusPlus) { 3612 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 3613 return ExprError(); 3614 } 3615 3616 bool IsComplete = isCompleteType(StartLoc, Pointee); 3617 bool CanProvideSize = 3618 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 3619 Pointee.isDestructedType()); 3620 bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 3621 3622 // Look for a global declaration. 3623 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 3624 Overaligned, DeleteName); 3625 } 3626 3627 MarkFunctionReferenced(StartLoc, OperatorDelete); 3628 3629 // Check access and ambiguity of destructor if we're going to call it. 3630 // Note that this is required even for a virtual delete. 3631 bool IsVirtualDelete = false; 3632 if (PointeeRD) { 3633 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3634 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 3635 PDiag(diag::err_access_dtor) << PointeeElem); 3636 IsVirtualDelete = Dtor->isVirtual(); 3637 } 3638 } 3639 3640 DiagnoseUseOfDecl(OperatorDelete, StartLoc); 3641 3642 // Convert the operand to the type of the first parameter of operator 3643 // delete. This is only necessary if we selected a destroying operator 3644 // delete that we are going to call (non-virtually); converting to void* 3645 // is trivial and left to AST consumers to handle. 3646 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 3647 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 3648 Qualifiers Qs = Pointee.getQualifiers(); 3649 if (Qs.hasCVRQualifiers()) { 3650 // Qualifiers are irrelevant to this conversion; we're only looking 3651 // for access and ambiguity. 3652 Qs.removeCVRQualifiers(); 3653 QualType Unqual = Context.getPointerType( 3654 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 3655 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 3656 } 3657 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 3658 if (Ex.isInvalid()) 3659 return ExprError(); 3660 } 3661 } 3662 3663 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 3664 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 3665 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 3666 AnalyzeDeleteExprMismatch(Result); 3667 return Result; 3668} 3669 3670static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 3671 bool IsDelete, 3672 FunctionDecl *&Operator) { 3673 3674 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 3675 IsDelete ? OO_Delete : OO_New); 3676 3677 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 3678 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 3679 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3679, __PRETTY_FUNCTION__))
; 3680 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3680, __PRETTY_FUNCTION__))
; 3681 3682 // We do our own custom access checks below. 3683 R.suppressDiagnostics(); 3684 3685 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); 3686 OverloadCandidateSet Candidates(R.getNameLoc(), 3687 OverloadCandidateSet::CSK_Normal); 3688 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 3689 FnOvl != FnOvlEnd; ++FnOvl) { 3690 // Even member operator new/delete are implicitly treated as 3691 // static, so don't use AddMemberCandidate. 3692 NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 3693 3694 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 3695 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 3696 /*ExplicitTemplateArgs=*/nullptr, Args, 3697 Candidates, 3698 /*SuppressUserConversions=*/false); 3699 continue; 3700 } 3701 3702 FunctionDecl *Fn = cast<FunctionDecl>(D); 3703 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 3704 /*SuppressUserConversions=*/false); 3705 } 3706 3707 SourceRange Range = TheCall->getSourceRange(); 3708 3709 // Do the resolution. 3710 OverloadCandidateSet::iterator Best; 3711 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 3712 case OR_Success: { 3713 // Got one! 3714 FunctionDecl *FnDecl = Best->Function; 3715 assert(R.getNamingClass() == nullptr &&((R.getNamingClass() == nullptr && "class members should not be considered"
) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3716, __PRETTY_FUNCTION__))
3716 "class members should not be considered")((R.getNamingClass() == nullptr && "class members should not be considered"
) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3716, __PRETTY_FUNCTION__))
; 3717 3718 if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 3719 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 3720 << (IsDelete ? 1 : 0) << Range; 3721 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 3722 << R.getLookupName() << FnDecl->getSourceRange(); 3723 return true; 3724 } 3725 3726 Operator = FnDecl; 3727 return false; 3728 } 3729 3730 case OR_No_Viable_Function: 3731 Candidates.NoteCandidates( 3732 PartialDiagnosticAt(R.getNameLoc(), 3733 S.PDiag(diag::err_ovl_no_viable_function_in_call) 3734 << R.getLookupName() << Range), 3735 S, OCD_AllCandidates, Args); 3736 return true; 3737 3738 case OR_Ambiguous: 3739 Candidates.NoteCandidates( 3740 PartialDiagnosticAt(R.getNameLoc(), 3741 S.PDiag(diag::err_ovl_ambiguous_call) 3742 << R.getLookupName() << Range), 3743 S, OCD_AmbiguousCandidates, Args); 3744 return true; 3745 3746 case OR_Deleted: { 3747 Candidates.NoteCandidates( 3748 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) 3749 << R.getLookupName() << Range), 3750 S, OCD_AllCandidates, Args); 3751 return true; 3752 } 3753 } 3754 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3754)
; 3755} 3756 3757ExprResult 3758Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 3759 bool IsDelete) { 3760 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3761 if (!getLangOpts().CPlusPlus) { 3762 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 3763 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 3764 << "C++"; 3765 return ExprError(); 3766 } 3767 // CodeGen assumes it can find the global new and delete to call, 3768 // so ensure that they are declared. 3769 DeclareGlobalNewDelete(); 3770 3771 FunctionDecl *OperatorNewOrDelete = nullptr; 3772 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 3773 OperatorNewOrDelete)) 3774 return ExprError(); 3775 assert(OperatorNewOrDelete && "should be found")((OperatorNewOrDelete && "should be found") ? static_cast
<void> (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3775, __PRETTY_FUNCTION__))
; 3776 3777 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 3778 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 3779 3780 TheCall->setType(OperatorNewOrDelete->getReturnType()); 3781 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3782 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 3783 InitializedEntity Entity = 3784 InitializedEntity::InitializeParameter(Context, ParamTy, false); 3785 ExprResult Arg = PerformCopyInitialization( 3786 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 3787 if (Arg.isInvalid()) 3788 return ExprError(); 3789 TheCall->setArg(i, Arg.get()); 3790 } 3791 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 3792 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr
&& "Callee expected to be implicit cast to a builtin function pointer"
) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3793, __PRETTY_FUNCTION__))
3793 "Callee expected to be implicit cast to a builtin function pointer")((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr
&& "Callee expected to be implicit cast to a builtin function pointer"
) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3793, __PRETTY_FUNCTION__))
; 3794 Callee->setType(OperatorNewOrDelete->getType()); 3795 3796 return TheCallResult; 3797} 3798 3799void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 3800 bool IsDelete, bool CallCanBeVirtual, 3801 bool WarnOnNonAbstractTypes, 3802 SourceLocation DtorLoc) { 3803 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 3804 return; 3805 3806 // C++ [expr.delete]p3: 3807 // In the first alternative (delete object), if the static type of the 3808 // object to be deleted is different from its dynamic type, the static 3809 // type shall be a base class of the dynamic type of the object to be 3810 // deleted and the static type shall have a virtual destructor or the 3811 // behavior is undefined. 3812 // 3813 const CXXRecordDecl *PointeeRD = dtor->getParent(); 3814 // Note: a final class cannot be derived from, no issue there 3815 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 3816 return; 3817 3818 // If the superclass is in a system header, there's nothing that can be done. 3819 // The `delete` (where we emit the warning) can be in a system header, 3820 // what matters for this warning is where the deleted type is defined. 3821 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 3822 return; 3823 3824 QualType ClassType = dtor->getThisType()->getPointeeType(); 3825 if (PointeeRD->isAbstract()) { 3826 // If the class is abstract, we warn by default, because we're 3827 // sure the code has undefined behavior. 3828 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 3829 << ClassType; 3830 } else if (WarnOnNonAbstractTypes) { 3831 // Otherwise, if this is not an array delete, it's a bit suspect, 3832 // but not necessarily wrong. 3833 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 3834 << ClassType; 3835 } 3836 if (!IsDelete) { 3837 std::string TypeStr; 3838 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 3839 Diag(DtorLoc, diag::note_delete_non_virtual) 3840 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 3841 } 3842} 3843 3844Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 3845 SourceLocation StmtLoc, 3846 ConditionKind CK) { 3847 ExprResult E = 3848 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 3849 if (E.isInvalid()) 3850 return ConditionError(); 3851 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 3852 CK == ConditionKind::ConstexprIf); 3853} 3854 3855/// Check the use of the given variable as a C++ condition in an if, 3856/// while, do-while, or switch statement. 3857ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 3858 SourceLocation StmtLoc, 3859 ConditionKind CK) { 3860 if (ConditionVar->isInvalidDecl()) 3861 return ExprError(); 3862 3863 QualType T = ConditionVar->getType(); 3864 3865 // C++ [stmt.select]p2: 3866 // The declarator shall not specify a function or an array. 3867 if (T->isFunctionType()) 3868 return ExprError(Diag(ConditionVar->getLocation(), 3869 diag::err_invalid_use_of_function_type) 3870 << ConditionVar->getSourceRange()); 3871 else if (T->isArrayType()) 3872 return ExprError(Diag(ConditionVar->getLocation(), 3873 diag::err_invalid_use_of_array_type) 3874 << ConditionVar->getSourceRange()); 3875 3876 ExprResult Condition = BuildDeclRefExpr( 3877 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 3878 ConditionVar->getLocation()); 3879 3880 switch (CK) { 3881 case ConditionKind::Boolean: 3882 return CheckBooleanCondition(StmtLoc, Condition.get()); 3883 3884 case ConditionKind::ConstexprIf: 3885 return CheckBooleanCondition(StmtLoc, Condition.get(), true); 3886 3887 case ConditionKind::Switch: 3888 return CheckSwitchCondition(StmtLoc, Condition.get()); 3889 } 3890 3891 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3891)
; 3892} 3893 3894/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 3895ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 3896 // C++ 6.4p4: 3897 // The value of a condition that is an initialized declaration in a statement 3898 // other than a switch statement is the value of the declared variable 3899 // implicitly converted to type bool. If that conversion is ill-formed, the 3900 // program is ill-formed. 3901 // The value of a condition that is an expression is the value of the 3902 // expression, implicitly converted to bool. 3903 // 3904 // FIXME: Return this value to the caller so they don't need to recompute it. 3905 llvm::APSInt Value(/*BitWidth*/1); 3906 return (IsConstexpr && !CondExpr->isValueDependent()) 3907 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, 3908 CCEK_ConstexprIf) 3909 : PerformContextuallyConvertToBool(CondExpr); 3910} 3911 3912/// Helper function to determine whether this is the (deprecated) C++ 3913/// conversion from a string literal to a pointer to non-const char or 3914/// non-const wchar_t (for narrow and wide string literals, 3915/// respectively). 3916bool 3917Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 3918 // Look inside the implicit cast, if it exists. 3919 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 3920 From = Cast->getSubExpr(); 3921 3922 // A string literal (2.13.4) that is not a wide string literal can 3923 // be converted to an rvalue of type "pointer to char"; a wide 3924 // string literal can be converted to an rvalue of type "pointer 3925 // to wchar_t" (C++ 4.2p2). 3926 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 3927 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 3928 if (const BuiltinType *ToPointeeType 3929 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 3930 // This conversion is considered only when there is an 3931 // explicit appropriate pointer target type (C++ 4.2p2). 3932 if (!ToPtrType->getPointeeType().hasQualifiers()) { 3933 switch (StrLit->getKind()) { 3934 case StringLiteral::UTF8: 3935 case StringLiteral::UTF16: 3936 case StringLiteral::UTF32: 3937 // We don't allow UTF literals to be implicitly converted 3938 break; 3939 case StringLiteral::Ascii: 3940 return (ToPointeeType->getKind() == BuiltinType::Char_U || 3941 ToPointeeType->getKind() == BuiltinType::Char_S); 3942 case StringLiteral::Wide: 3943 return Context.typesAreCompatible(Context.getWideCharType(), 3944 QualType(ToPointeeType, 0)); 3945 } 3946 } 3947 } 3948 3949 return false; 3950} 3951 3952static ExprResult BuildCXXCastArgument(Sema &S, 3953 SourceLocation CastLoc, 3954 QualType Ty, 3955 CastKind Kind, 3956 CXXMethodDecl *Method, 3957 DeclAccessPair FoundDecl, 3958 bool HadMultipleCandidates, 3959 Expr *From) { 3960 switch (Kind) { 3961 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3961)
; 3962 case CK_ConstructorConversion: { 3963 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 3964 SmallVector<Expr*, 8> ConstructorArgs; 3965 3966 if (S.RequireNonAbstractType(CastLoc, Ty, 3967 diag::err_allocation_of_abstract_type)) 3968 return ExprError(); 3969 3970 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, 3971 ConstructorArgs)) 3972 return ExprError(); 3973 3974 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 3975 InitializedEntity::InitializeTemporary(Ty)); 3976 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3977 return ExprError(); 3978 3979 ExprResult Result = S.BuildCXXConstructExpr( 3980 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 3981 ConstructorArgs, HadMultipleCandidates, 3982 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3983 CXXConstructExpr::CK_Complete, SourceRange()); 3984 if (Result.isInvalid()) 3985 return ExprError(); 3986 3987 return S.MaybeBindToTemporary(Result.getAs<Expr>()); 3988 } 3989 3990 case CK_UserDefinedConversion: { 3991 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")((!From->getType()->isPointerType() && "Arg can't have pointer type!"
) ? static_cast<void> (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 3991, __PRETTY_FUNCTION__))
; 3992 3993 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 3994 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3995 return ExprError(); 3996 3997 // Create an implicit call expr that calls it. 3998 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 3999 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 4000 HadMultipleCandidates); 4001 if (Result.isInvalid()) 4002 return ExprError(); 4003 // Record usage of conversion in an implicit cast. 4004 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 4005 CK_UserDefinedConversion, Result.get(), 4006 nullptr, Result.get()->getValueKind(), 4007 S.CurFPFeatureOverrides()); 4008 4009 return S.MaybeBindToTemporary(Result.get()); 4010 } 4011 } 4012} 4013 4014/// PerformImplicitConversion - Perform an implicit conversion of the 4015/// expression From to the type ToType using the pre-computed implicit 4016/// conversion sequence ICS. Returns the converted 4017/// expression. Action is the kind of conversion we're performing, 4018/// used in the error message. 4019ExprResult 4020Sema::PerformImplicitConversion(Expr *From, QualType ToType, 4021 const ImplicitConversionSequence &ICS, 4022 AssignmentAction Action, 4023 CheckedConversionKind CCK) { 4024 // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 4025 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 4026 return From; 4027 4028 switch (ICS.getKind()) { 4029 case ImplicitConversionSequence::StandardConversion: { 4030 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 4031 Action, CCK); 4032 if (Res.isInvalid()) 4033 return ExprError(); 4034 From = Res.get(); 4035 break; 4036 } 4037 4038 case ImplicitConversionSequence::UserDefinedConversion: { 4039 4040 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 4041 CastKind CastKind; 4042 QualType BeforeToType; 4043 assert(FD && "no conversion function for user-defined conversion seq")((FD && "no conversion function for user-defined conversion seq"
) ? static_cast<void> (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4043, __PRETTY_FUNCTION__))
; 4044 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 4045 CastKind = CK_UserDefinedConversion; 4046 4047 // If the user-defined conversion is specified by a conversion function, 4048 // the initial standard conversion sequence converts the source type to 4049 // the implicit object parameter of the conversion function. 4050 BeforeToType = Context.getTagDeclType(Conv->getParent()); 4051 } else { 4052 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 4053 CastKind = CK_ConstructorConversion; 4054 // Do no conversion if dealing with ... for the first conversion. 4055 if (!ICS.UserDefined.EllipsisConversion) { 4056 // If the user-defined conversion is specified by a constructor, the 4057 // initial standard conversion sequence converts the source type to 4058 // the type required by the argument of the constructor 4059 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 4060 } 4061 } 4062 // Watch out for ellipsis conversion. 4063 if (!ICS.UserDefined.EllipsisConversion) { 4064 ExprResult Res = 4065 PerformImplicitConversion(From, BeforeToType, 4066 ICS.UserDefined.Before, AA_Converting, 4067 CCK); 4068 if (Res.isInvalid()) 4069 return ExprError(); 4070 From = Res.get(); 4071 } 4072 4073 ExprResult CastArg = BuildCXXCastArgument( 4074 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 4075 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 4076 ICS.UserDefined.HadMultipleCandidates, From); 4077 4078 if (CastArg.isInvalid()) 4079 return ExprError(); 4080 4081 From = CastArg.get(); 4082 4083 // C++ [over.match.oper]p7: 4084 // [...] the second standard conversion sequence of a user-defined 4085 // conversion sequence is not applied. 4086 if (CCK == CCK_ForBuiltinOverloadedOp) 4087 return From; 4088 4089 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 4090 AA_Converting, CCK); 4091 } 4092 4093 case ImplicitConversionSequence::AmbiguousConversion: 4094 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 4095 PDiag(diag::err_typecheck_ambiguous_condition) 4096 << From->getSourceRange()); 4097 return ExprError(); 4098 4099 case ImplicitConversionSequence::EllipsisConversion: 4100 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4100)
; 4101 4102 case ImplicitConversionSequence::BadConversion: 4103 Sema::AssignConvertType ConvTy = 4104 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); 4105 bool Diagnosed = DiagnoseAssignmentResult( 4106 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), 4107 ToType, From->getType(), From, Action); 4108 assert(Diagnosed && "failed to diagnose bad conversion")((Diagnosed && "failed to diagnose bad conversion") ?
static_cast<void> (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4108, __PRETTY_FUNCTION__))
; (void)Diagnosed; 4109 return ExprError(); 4110 } 4111 4112 // Everything went well. 4113 return From; 4114} 4115 4116/// PerformImplicitConversion - Perform an implicit conversion of the 4117/// expression From to the type ToType by following the standard 4118/// conversion sequence SCS. Returns the converted 4119/// expression. Flavor is the context in which we're performing this 4120/// conversion, for use in error messages. 4121ExprResult 4122Sema::PerformImplicitConversion(Expr *From, QualType ToType, 4123 const StandardConversionSequence& SCS, 4124 AssignmentAction Action, 4125 CheckedConversionKind CCK) { 4126 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 4127 4128 // Overall FIXME: we are recomputing too many types here and doing far too 4129 // much extra work. What this means is that we need to keep track of more 4130 // information that is computed when we try the implicit conversion initially, 4131 // so that we don't need to recompute anything here. 4132 QualType FromType = From->getType(); 4133 4134 if (SCS.CopyConstructor) { 4135 // FIXME: When can ToType be a reference type? 4136 assert(!ToType->isReferenceType())((!ToType->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4136, __PRETTY_FUNCTION__))
; 4137 if (SCS.Second == ICK_Derived_To_Base) { 4138 SmallVector<Expr*, 8> ConstructorArgs; 4139 if (CompleteConstructorCall( 4140 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, 4141 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) 4142 return ExprError(); 4143 return BuildCXXConstructExpr( 4144 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 4145 SCS.FoundCopyConstructor, SCS.CopyConstructor, 4146 ConstructorArgs, /*HadMultipleCandidates*/ false, 4147 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4148 CXXConstructExpr::CK_Complete, SourceRange()); 4149 } 4150 return BuildCXXConstructExpr( 4151 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 4152 SCS.FoundCopyConstructor, SCS.CopyConstructor, 4153 From, /*HadMultipleCandidates*/ false, 4154 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4155 CXXConstructExpr::CK_Complete, SourceRange()); 4156 } 4157 4158 // Resolve overloaded function references. 4159 if (Context.hasSameType(FromType, Context.OverloadTy)) { 4160 DeclAccessPair Found; 4161 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 4162 true, Found); 4163 if (!Fn) 4164 return ExprError(); 4165 4166 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 4167 return ExprError(); 4168 4169 From = FixOverloadedFunctionReference(From, Found, Fn); 4170 FromType = From->getType(); 4171 } 4172 4173 // If we're converting to an atomic type, first convert to the corresponding 4174 // non-atomic type. 4175 QualType ToAtomicType; 4176 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 4177 ToAtomicType = ToType; 4178 ToType = ToAtomic->getValueType(); 4179 } 4180 4181 QualType InitialFromType = FromType; 4182 // Perform the first implicit conversion. 4183 switch (SCS.First) { 4184 case ICK_Identity: 4185 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 4186 FromType = FromAtomic->getValueType().getUnqualifiedType(); 4187 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 4188 From, /*BasePath=*/nullptr, VK_RValue, 4189 FPOptionsOverride()); 4190 } 4191 break; 4192 4193 case ICK_Lvalue_To_Rvalue: { 4194 assert(From->getObjectKind() != OK_ObjCProperty)((From->getObjectKind() != OK_ObjCProperty) ? static_cast<
void> (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4194, __PRETTY_FUNCTION__))
; 4195 ExprResult FromRes = DefaultLvalueConversion(From); 4196 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")((!FromRes.isInvalid() && "Can't perform deduced conversion?!"
) ? static_cast<void> (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4196, __PRETTY_FUNCTION__))
; 4197 From = FromRes.get(); 4198 FromType = From->getType(); 4199 break; 4200 } 4201 4202 case ICK_Array_To_Pointer: 4203 FromType = Context.getArrayDecayedType(FromType); 4204 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 4205 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4206 break; 4207 4208 case ICK_Function_To_Pointer: 4209 FromType = Context.getPointerType(FromType); 4210 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 4211 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4212 break; 4213 4214 default: 4215 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4215)
; 4216 } 4217 4218 // Perform the second implicit conversion 4219 switch (SCS.Second) { 4220 case ICK_Identity: 4221 // C++ [except.spec]p5: 4222 // [For] assignment to and initialization of pointers to functions, 4223 // pointers to member functions, and references to functions: the 4224 // target entity shall allow at least the exceptions allowed by the 4225 // source value in the assignment or initialization. 4226 switch (Action) { 4227 case AA_Assigning: 4228 case AA_Initializing: 4229 // Note, function argument passing and returning are initialization. 4230 case AA_Passing: 4231 case AA_Returning: 4232 case AA_Sending: 4233 case AA_Passing_CFAudited: 4234 if (CheckExceptionSpecCompatibility(From, ToType)) 4235 return ExprError(); 4236 break; 4237 4238 case AA_Casting: 4239 case AA_Converting: 4240 // Casts and implicit conversions are not initialization, so are not 4241 // checked for exception specification mismatches. 4242 break; 4243 } 4244 // Nothing else to do. 4245 break; 4246 4247 case ICK_Integral_Promotion: 4248 case ICK_Integral_Conversion: 4249 if (ToType->isBooleanType()) { 4250 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4252, __PRETTY_FUNCTION__))
4251 SCS.Second == ICK_Integral_Promotion &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4252, __PRETTY_FUNCTION__))
4252 "only enums with fixed underlying type can promote to bool")((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4252, __PRETTY_FUNCTION__))
; 4253 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 4254 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4255 } else { 4256 From = ImpCastExprToType(From, ToType, CK_IntegralCast, 4257 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4258 } 4259 break; 4260 4261 case ICK_Floating_Promotion: 4262 case ICK_Floating_Conversion: 4263 From = ImpCastExprToType(From, ToType, CK_FloatingCast, 4264 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4265 break; 4266 4267 case ICK_Complex_Promotion: 4268 case ICK_Complex_Conversion: { 4269 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4270 QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 4271 CastKind CK; 4272 if (FromEl->isRealFloatingType()) { 4273 if (ToEl->isRealFloatingType()) 4274 CK = CK_FloatingComplexCast; 4275 else 4276 CK = CK_FloatingComplexToIntegralComplex; 4277 } else if (ToEl->isRealFloatingType()) { 4278 CK = CK_IntegralComplexToFloatingComplex; 4279 } else { 4280 CK = CK_IntegralComplexCast; 4281 } 4282 From = ImpCastExprToType(From, ToType, CK, 4283 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4284 break; 4285 } 4286 4287 case ICK_Floating_Integral: 4288 if (ToType->isRealFloatingType()) 4289 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 4290 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4291 else 4292 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 4293 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4294 break; 4295 4296 case ICK_Compatible_Conversion: 4297 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4298 /*BasePath=*/nullptr, CCK).get(); 4299 break; 4300 4301 case ICK_Writeback_Conversion: 4302 case ICK_Pointer_Conversion: { 4303 if (SCS.IncompatibleObjC && Action != AA_Casting) { 4304 // Diagnose incompatible Objective-C conversions 4305 if (Action == AA_Initializing || Action == AA_Assigning) 4306 Diag(From->getBeginLoc(), 4307 diag::ext_typecheck_convert_incompatible_pointer) 4308 << ToType << From->getType() << Action << From->getSourceRange() 4309 << 0; 4310 else 4311 Diag(From->getBeginLoc(), 4312 diag::ext_typecheck_convert_incompatible_pointer) 4313 << From->getType() << ToType << Action << From->getSourceRange() 4314 << 0; 4315 4316 if (From->getType()->isObjCObjectPointerType() && 4317 ToType->isObjCObjectPointerType()) 4318 EmitRelatedResultTypeNote(From); 4319 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 4320 !CheckObjCARCUnavailableWeakConversion(ToType, 4321 From->getType())) { 4322 if (Action == AA_Initializing) 4323 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 4324 else 4325 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 4326 << (Action == AA_Casting) << From->getType() << ToType 4327 << From->getSourceRange(); 4328 } 4329 4330 // Defer address space conversion to the third conversion. 4331 QualType FromPteeType = From->getType()->getPointeeType(); 4332 QualType ToPteeType = ToType->getPointeeType(); 4333 QualType NewToType = ToType; 4334 if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4335 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4336 NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4337 NewToType = Context.getAddrSpaceQualType(NewToType, 4338 FromPteeType.getAddressSpace()); 4339 if (ToType->isObjCObjectPointerType()) 4340 NewToType = Context.getObjCObjectPointerType(NewToType); 4341 else if (ToType->isBlockPointerType()) 4342 NewToType = Context.getBlockPointerType(NewToType); 4343 else 4344 NewToType = Context.getPointerType(NewToType); 4345 } 4346 4347 CastKind Kind; 4348 CXXCastPath BasePath; 4349 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 4350 return ExprError(); 4351 4352 // Make sure we extend blocks if necessary. 4353 // FIXME: doing this here is really ugly. 4354 if (Kind == CK_BlockPointerToObjCPointerCast) { 4355 ExprResult E = From; 4356 (void) PrepareCastToObjCObjectPointer(E); 4357 From = E.get(); 4358 } 4359 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4360 CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4361 From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK) 4362 .get(); 4363 break; 4364 } 4365 4366 case ICK_Pointer_Member: { 4367 CastKind Kind; 4368 CXXCastPath BasePath; 4369 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 4370 return ExprError(); 4371 if (CheckExceptionSpecCompatibility(From, ToType)) 4372 return ExprError(); 4373 4374 // We may not have been able to figure out what this member pointer resolved 4375 // to up until this exact point. Attempt to lock-in it's inheritance model. 4376 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4377 (void)isCompleteType(From->getExprLoc(), From->getType()); 4378 (void)isCompleteType(From->getExprLoc(), ToType); 4379 } 4380 4381 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 4382 .get(); 4383 break; 4384 } 4385 4386 case ICK_Boolean_Conversion: 4387 // Perform half-to-boolean conversion via float. 4388 if (From->getType()->isHalfType()) { 4389 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 4390 FromType = Context.FloatTy; 4391 } 4392 4393 From = ImpCastExprToType(From, Context.BoolTy, 4394 ScalarTypeToBooleanCastKind(FromType), 4395 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4396 break; 4397 4398 case ICK_Derived_To_Base: { 4399 CXXCastPath BasePath; 4400 if (CheckDerivedToBaseConversion( 4401 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 4402 From->getSourceRange(), &BasePath, CStyle)) 4403 return ExprError(); 4404 4405 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 4406 CK_DerivedToBase, From->getValueKind(), 4407 &BasePath, CCK).get(); 4408 break; 4409 } 4410 4411 case ICK_Vector_Conversion: 4412 From = ImpCastExprToType(From, ToType, CK_BitCast, 4413 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4414 break; 4415 4416 case ICK_SVE_Vector_Conversion: 4417 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_RValue, 4418 /*BasePath=*/nullptr, CCK) 4419 .get(); 4420 break; 4421 4422 case ICK_Vector_Splat: { 4423 // Vector splat from any arithmetic type to a vector. 4424 Expr *Elem = prepareVectorSplat(ToType, From).get(); 4425 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, 4426 /*BasePath=*/nullptr, CCK).get(); 4427 break; 4428 } 4429 4430 case ICK_Complex_Real: 4431 // Case 1. x -> _Complex y 4432 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 4433 QualType ElType = ToComplex->getElementType(); 4434 bool isFloatingComplex = ElType->isRealFloatingType(); 4435 4436 // x -> y 4437 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 4438 // do nothing 4439 } else if (From->getType()->isRealFloatingType()) { 4440 From = ImpCastExprToType(From, ElType, 4441 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 4442 } else { 4443 assert(From->getType()->isIntegerType())((From->getType()->isIntegerType()) ? static_cast<void
> (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4443, __PRETTY_FUNCTION__))
; 4444 From = ImpCastExprToType(From, ElType, 4445 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 4446 } 4447 // y -> _Complex y 4448 From = ImpCastExprToType(From, ToType, 4449 isFloatingComplex ? CK_FloatingRealToComplex 4450 : CK_IntegralRealToComplex).get(); 4451 4452 // Case 2. _Complex x -> y 4453 } else { 4454 auto *FromComplex = From->getType()->castAs<ComplexType>(); 4455 QualType ElType = FromComplex->getElementType(); 4456 bool isFloatingComplex = ElType->isRealFloatingType(); 4457 4458 // _Complex x -> x 4459 From = ImpCastExprToType(From, ElType, 4460 isFloatingComplex ? CK_FloatingComplexToReal 4461 : CK_IntegralComplexToReal, 4462 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4463 4464 // x -> y 4465 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 4466 // do nothing 4467 } else if (ToType->isRealFloatingType()) { 4468 From = ImpCastExprToType(From, ToType, 4469 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 4470 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4471 } else { 4472 assert(ToType->isIntegerType())((ToType->isIntegerType()) ? static_cast<void> (0) :
__assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4472, __PRETTY_FUNCTION__))
; 4473 From = ImpCastExprToType(From, ToType, 4474 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 4475 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4476 } 4477 } 4478 break; 4479 4480 case ICK_Block_Pointer_Conversion: { 4481 LangAS AddrSpaceL = 4482 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 4483 LangAS AddrSpaceR = 4484 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 4485 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&((Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR
) && "Invalid cast") ? static_cast<void> (0) : __assert_fail
("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4486, __PRETTY_FUNCTION__))
4486 "Invalid cast")((Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR
) && "Invalid cast") ? static_cast<void> (0) : __assert_fail
("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4486, __PRETTY_FUNCTION__))
; 4487 CastKind Kind = 4488 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 4489 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 4490 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4491 break; 4492 } 4493 4494 case ICK_TransparentUnionConversion: { 4495 ExprResult FromRes = From; 4496 Sema::AssignConvertType ConvTy = 4497 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 4498 if (FromRes.isInvalid()) 4499 return ExprError(); 4500 From = FromRes.get(); 4501 assert ((ConvTy == Sema::Compatible) &&(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4502, __PRETTY_FUNCTION__))
4502 "Improper transparent union conversion")(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4502, __PRETTY_FUNCTION__))
; 4503 (void)ConvTy; 4504 break; 4505 } 4506 4507 case ICK_Zero_Event_Conversion: 4508 case ICK_Zero_Queue_Conversion: 4509 From = ImpCastExprToType(From, ToType, 4510 CK_ZeroToOCLOpaqueType, 4511 From->getValueKind()).get(); 4512 break; 4513 4514 case ICK_Lvalue_To_Rvalue: 4515 case ICK_Array_To_Pointer: 4516 case ICK_Function_To_Pointer: 4517 case ICK_Function_Conversion: 4518 case ICK_Qualification: 4519 case ICK_Num_Conversion_Kinds: 4520 case ICK_C_Only_Conversion: 4521 case ICK_Incompatible_Pointer_Conversion: 4522 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4522)
; 4523 } 4524 4525 switch (SCS.Third) { 4526 case ICK_Identity: 4527 // Nothing to do. 4528 break; 4529 4530 case ICK_Function_Conversion: 4531 // If both sides are functions (or pointers/references to them), there could 4532 // be incompatible exception declarations. 4533 if (CheckExceptionSpecCompatibility(From, ToType)) 4534 return ExprError(); 4535 4536 From = ImpCastExprToType(From, ToType, CK_NoOp, 4537 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4538 break; 4539 4540 case ICK_Qualification: { 4541 ExprValueKind VK = From->getValueKind(); 4542 CastKind CK = CK_NoOp; 4543 4544 if (ToType->isReferenceType() && 4545 ToType->getPointeeType().getAddressSpace() != 4546 From->getType().getAddressSpace()) 4547 CK = CK_AddressSpaceConversion; 4548 4549 if (ToType->isPointerType() && 4550 ToType->getPointeeType().getAddressSpace() != 4551 From->getType()->getPointeeType().getAddressSpace()) 4552 CK = CK_AddressSpaceConversion; 4553 4554 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 4555 /*BasePath=*/nullptr, CCK) 4556 .get(); 4557 4558 if (SCS.DeprecatedStringLiteralToCharPtr && 4559 !getLangOpts().WritableStrings) { 4560 Diag(From->getBeginLoc(), 4561 getLangOpts().CPlusPlus11 4562 ? diag::ext_deprecated_string_literal_conversion 4563 : diag::warn_deprecated_string_literal_conversion) 4564 << ToType.getNonReferenceType(); 4565 } 4566 4567 break; 4568 } 4569 4570 default: 4571 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4571)
; 4572 } 4573 4574 // If this conversion sequence involved a scalar -> atomic conversion, perform 4575 // that conversion now. 4576 if (!ToAtomicType.isNull()) { 4577 assert(Context.hasSameType(((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4578, __PRETTY_FUNCTION__))
4578 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4578, __PRETTY_FUNCTION__))
; 4579 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 4580 VK_RValue, nullptr, CCK).get(); 4581 } 4582 4583 // Materialize a temporary if we're implicitly converting to a reference 4584 // type. This is not required by the C++ rules but is necessary to maintain 4585 // AST invariants. 4586 if (ToType->isReferenceType() && From->isRValue()) { 4587 ExprResult Res = TemporaryMaterializationConversion(From); 4588 if (Res.isInvalid()) 4589 return ExprError(); 4590 From = Res.get(); 4591 } 4592 4593 // If this conversion sequence succeeded and involved implicitly converting a 4594 // _Nullable type to a _Nonnull one, complain. 4595 if (!isCast(CCK)) 4596 diagnoseNullableToNonnullConversion(ToType, InitialFromType, 4597 From->getBeginLoc()); 4598 4599 return From; 4600} 4601 4602/// Check the completeness of a type in a unary type trait. 4603/// 4604/// If the particular type trait requires a complete type, tries to complete 4605/// it. If completing the type fails, a diagnostic is emitted and false 4606/// returned. If completing the type succeeds or no completion was required, 4607/// returns true. 4608static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 4609 SourceLocation Loc, 4610 QualType ArgTy) { 4611 // C++0x [meta.unary.prop]p3: 4612 // For all of the class templates X declared in this Clause, instantiating 4613 // that template with a template argument that is a class template 4614 // specialization may result in the implicit instantiation of the template 4615 // argument if and only if the semantics of X require that the argument 4616 // must be a complete type. 4617 // We apply this rule to all the type trait expressions used to implement 4618 // these class templates. We also try to follow any GCC documented behavior 4619 // in these expressions to ensure portability of standard libraries. 4620 switch (UTT) { 4621 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4621)
; 4622 // is_complete_type somewhat obviously cannot require a complete type. 4623 case UTT_IsCompleteType: 4624 // Fall-through 4625 4626 // These traits are modeled on the type predicates in C++0x 4627 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 4628 // requiring a complete type, as whether or not they return true cannot be 4629 // impacted by the completeness of the type. 4630 case UTT_IsVoid: 4631 case UTT_IsIntegral: 4632 case UTT_IsFloatingPoint: 4633 case UTT_IsArray: 4634 case UTT_IsPointer: 4635 case UTT_IsLvalueReference: 4636 case UTT_IsRvalueReference: 4637 case UTT_IsMemberFunctionPointer: 4638 case UTT_IsMemberObjectPointer: 4639 case UTT_IsEnum: 4640 case UTT_IsUnion: 4641 case UTT_IsClass: 4642 case UTT_IsFunction: 4643 case UTT_IsReference: 4644 case UTT_IsArithmetic: 4645 case UTT_IsFundamental: 4646 case UTT_IsObject: 4647 case UTT_IsScalar: 4648 case UTT_IsCompound: 4649 case UTT_IsMemberPointer: 4650 // Fall-through 4651 4652 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 4653 // which requires some of its traits to have the complete type. However, 4654 // the completeness of the type cannot impact these traits' semantics, and 4655 // so they don't require it. This matches the comments on these traits in 4656 // Table 49. 4657 case UTT_IsConst: 4658 case UTT_IsVolatile: 4659 case UTT_IsSigned: 4660 case UTT_IsUnsigned: 4661 4662 // This type trait always returns false, checking the type is moot. 4663 case UTT_IsInterfaceClass: 4664 return true; 4665 4666 // C++14 [meta.unary.prop]: 4667 // If T is a non-union class type, T shall be a complete type. 4668 case UTT_IsEmpty: 4669 case UTT_IsPolymorphic: 4670 case UTT_IsAbstract: 4671 if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 4672 if (!RD->isUnion()) 4673 return !S.RequireCompleteType( 4674 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4675 return true; 4676 4677 // C++14 [meta.unary.prop]: 4678 // If T is a class type, T shall be a complete type. 4679 case UTT_IsFinal: 4680 case UTT_IsSealed: 4681 if (ArgTy->getAsCXXRecordDecl()) 4682 return !S.RequireCompleteType( 4683 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4684 return true; 4685 4686 // C++1z [meta.unary.prop]: 4687 // remove_all_extents_t<T> shall be a complete type or cv void. 4688 case UTT_IsAggregate: 4689 case UTT_IsTrivial: 4690 case UTT_IsTriviallyCopyable: 4691 case UTT_IsStandardLayout: 4692 case UTT_IsPOD: 4693 case UTT_IsLiteral: 4694 // Per the GCC type traits documentation, T shall be a complete type, cv void, 4695 // or an array of unknown bound. But GCC actually imposes the same constraints 4696 // as above. 4697 case UTT_HasNothrowAssign: 4698 case UTT_HasNothrowMoveAssign: 4699 case UTT_HasNothrowConstructor: 4700 case UTT_HasNothrowCopy: 4701 case UTT_HasTrivialAssign: 4702 case UTT_HasTrivialMoveAssign: 4703 case UTT_HasTrivialDefaultConstructor: 4704 case UTT_HasTrivialMoveConstructor: 4705 case UTT_HasTrivialCopy: 4706 case UTT_HasTrivialDestructor: 4707 case UTT_HasVirtualDestructor: 4708 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 4709 LLVM_FALLTHROUGH[[gnu::fallthrough]]; 4710 4711 // C++1z [meta.unary.prop]: 4712 // T shall be a complete type, cv void, or an array of unknown bound. 4713 case UTT_IsDestructible: 4714 case UTT_IsNothrowDestructible: 4715 case UTT_IsTriviallyDestructible: 4716 case UTT_HasUniqueObjectRepresentations: 4717 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 4718 return true; 4719 4720 return !S.RequireCompleteType( 4721 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4722 } 4723} 4724 4725static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 4726 Sema &Self, SourceLocation KeyLoc, ASTContext &C, 4727 bool (CXXRecordDecl::*HasTrivial)() const, 4728 bool (CXXRecordDecl::*HasNonTrivial)() const, 4729 bool (CXXMethodDecl::*IsDesiredOp)() const) 4730{ 4731 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4732 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 4733 return true; 4734 4735 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 4736 DeclarationNameInfo NameInfo(Name, KeyLoc); 4737 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 4738 if (Self.LookupQualifiedName(Res, RD)) { 4739 bool FoundOperator = false; 4740 Res.suppressDiagnostics(); 4741 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 4742 Op != OpEnd; ++Op) { 4743 if (isa<FunctionTemplateDecl>(*Op)) 4744 continue; 4745 4746 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 4747 if((Operator->*IsDesiredOp)()) { 4748 FoundOperator = true; 4749 auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); 4750 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4751 if (!CPT || !CPT->isNothrow()) 4752 return false; 4753 } 4754 } 4755 return FoundOperator; 4756 } 4757 return false; 4758} 4759 4760static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 4761 SourceLocation KeyLoc, QualType T) { 4762 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4762, __PRETTY_FUNCTION__))
; 4763 4764 ASTContext &C = Self.Context; 4765 switch(UTT) { 4766 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 4766)
; 4767 // Type trait expressions corresponding to the primary type category 4768 // predicates in C++0x [meta.unary.cat]. 4769 case UTT_IsVoid: 4770 return T->isVoidType(); 4771 case UTT_IsIntegral: 4772 return T->isIntegralType(C); 4773 case UTT_IsFloatingPoint: 4774 return T->isFloatingType(); 4775 case UTT_IsArray: 4776 return T->isArrayType(); 4777 case UTT_IsPointer: 4778 return T->isAnyPointerType(); 4779 case UTT_IsLvalueReference: 4780 return T->isLValueReferenceType(); 4781 case UTT_IsRvalueReference: 4782 return T->isRValueReferenceType(); 4783 case UTT_IsMemberFunctionPointer: 4784 return T->isMemberFunctionPointerType(); 4785 case UTT_IsMemberObjectPointer: 4786 return T->isMemberDataPointerType(); 4787 case UTT_IsEnum: 4788 return T->isEnumeralType(); 4789 case UTT_IsUnion: 4790 return T->isUnionType(); 4791 case UTT_IsClass: 4792 return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 4793 case UTT_IsFunction: 4794 return T->isFunctionType(); 4795 4796 // Type trait expressions which correspond to the convenient composition 4797 // predicates in C++0x [meta.unary.comp]. 4798 case UTT_IsReference: 4799 return T->isReferenceType(); 4800 case UTT_IsArithmetic: 4801 return T->isArithmeticType() && !T->isEnumeralType(); 4802 case UTT_IsFundamental: 4803 return T->isFundamentalType(); 4804 case UTT_IsObject: 4805 return T->isObjectType(); 4806 case UTT_IsScalar: 4807 // Note: semantic analysis depends on Objective-C lifetime types to be 4808 // considered scalar types. However, such types do not actually behave 4809 // like scalar types at run time (since they may require retain/release 4810 // operations), so we report them as non-scalar. 4811 if (T->isObjCLifetimeType()) { 4812 switch (T.getObjCLifetime()) { 4813 case Qualifiers::OCL_None: 4814 case Qualifiers::OCL_ExplicitNone: 4815 return true; 4816 4817 case Qualifiers::OCL_Strong: 4818 case Qualifiers::OCL_Weak: 4819 case Qualifiers::OCL_Autoreleasing: 4820 return false; 4821 } 4822 } 4823 4824 return T->isScalarType(); 4825 case UTT_IsCompound: 4826 return T->isCompoundType(); 4827 case UTT_IsMemberPointer: 4828 return T->isMemberPointerType(); 4829 4830 // Type trait expressions which correspond to the type property predicates 4831 // in C++0x [meta.unary.prop]. 4832 case UTT_IsConst: 4833 return T.isConstQualified(); 4834 case UTT_IsVolatile: 4835 return T.isVolatileQualified(); 4836 case UTT_IsTrivial: 4837 return T.isTrivialType(C); 4838 case UTT_IsTriviallyCopyable: 4839 return T.isTriviallyCopyableType(C); 4840 case UTT_IsStandardLayout: 4841 return T->isStandardLayoutType(); 4842 case UTT_IsPOD: 4843 return T.isPODType(C); 4844 case UTT_IsLiteral: 4845 return T->isLiteralType(C); 4846 case UTT_IsEmpty: 4847 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4848 return !RD->isUnion() && RD->isEmpty(); 4849 return false; 4850 case UTT_IsPolymorphic: 4851 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4852 return !RD->isUnion() && RD->isPolymorphic(); 4853 return false; 4854 case UTT_IsAbstract: 4855 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4856 return !RD->isUnion() && RD->isAbstract(); 4857 return false; 4858 case UTT_IsAggregate: 4859 // Report vector extensions and complex types as aggregates because they 4860 // support aggregate initialization. GCC mirrors this behavior for vectors 4861 // but not _Complex. 4862 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 4863 T->isAnyComplexType(); 4864 // __is_interface_class only returns true when CL is invoked in /CLR mode and 4865 // even then only when it is used with the 'interface struct ...' syntax 4866 // Clang doesn't support /CLR which makes this type trait moot. 4867 case UTT_IsInterfaceClass: 4868 return false; 4869 case UTT_IsFinal: 4870 case UTT_IsSealed: 4871 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4872 return RD->hasAttr<FinalAttr>(); 4873 return false; 4874 case UTT_IsSigned: 4875 // Enum types should always return false. 4876 // Floating points should always return true. 4877 return T->isFloatingType() || 4878 (T->isSignedIntegerType() && !T->isEnumeralType()); 4879 case UTT_IsUnsigned: 4880 // Enum types should always return false. 4881 return T->isUnsignedIntegerType() && !T->isEnumeralType(); 4882 4883 // Type trait expressions which query classes regarding their construction, 4884 // destruction, and copying. Rather than being based directly on the 4885 // related type predicates in the standard, they are specified by both 4886 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 4887 // specifications. 4888 // 4889 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 4890 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 4891 // 4892 // Note that these builtins do not behave as documented in g++: if a class 4893 // has both a trivial and a non-trivial special member of a particular kind, 4894 // they return false! For now, we emulate this behavior. 4895 // FIXME: This appears to be a g++ bug: more complex cases reveal that it 4896 // does not correctly compute triviality in the presence of multiple special 4897 // members of the same kind. Revisit this once the g++ bug is fixed. 4898 case UTT_HasTrivialDefaultConstructor: 4899 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4900 // If __is_pod (type) is true then the trait is true, else if type is 4901 // a cv class or union type (or array thereof) with a trivial default 4902 // constructor ([class.ctor]) then the trait is true, else it is false. 4903 if (T.isPODType(C)) 4904 return true; 4905 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4906 return RD->hasTrivialDefaultConstructor() && 4907 !RD->hasNonTrivialDefaultConstructor(); 4908 return false; 4909 case UTT_HasTrivialMoveConstructor: 4910 // This trait is implemented by MSVC 2012 and needed to parse the 4911 // standard library headers. Specifically this is used as the logic 4912 // behind std::is_trivially_move_constructible (20.9.4.3). 4913 if (T.isPODType(C)) 4914 return true; 4915 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4916 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 4917 return false; 4918 case UTT_HasTrivialCopy: 4919 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4920 // If __is_pod (type) is true or type is a reference type then 4921 // the trait is true, else if type is a cv class or union type 4922 // with a trivial copy constructor ([class.copy]) then the trait 4923 // is true, else it is false. 4924 if (T.isPODType(C) || T->isReferenceType()) 4925 return true; 4926 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4927 return RD->hasTrivialCopyConstructor() && 4928 !RD->hasNonTrivialCopyConstructor(); 4929 return false; 4930 case UTT_HasTrivialMoveAssign: 4931 // This trait is implemented by MSVC 2012 and needed to parse the 4932 // standard library headers. Specifically it is used as the logic 4933 // behind std::is_trivially_move_assignable (20.9.4.3) 4934 if (T.isPODType(C)) 4935 return true; 4936 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4937 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 4938 return false; 4939 case UTT_HasTrivialAssign: 4940 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4941 // If type is const qualified or is a reference type then the 4942 // trait is false. Otherwise if __is_pod (type) is true then the 4943 // trait is true, else if type is a cv class or union type with 4944 // a trivial copy assignment ([class.copy]) then the trait is 4945 // true, else it is false. 4946 // Note: the const and reference restrictions are interesting, 4947 // given that const and reference members don't prevent a class 4948 // from having a trivial copy assignment operator (but do cause 4949 // errors if the copy assignment operator is actually used, q.v. 4950 // [class.copy]p12). 4951 4952 if (T.isConstQualified()) 4953 return false; 4954 if (T.isPODType(C)) 4955 return true; 4956 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4957 return RD->hasTrivialCopyAssignment() && 4958 !RD->hasNonTrivialCopyAssignment(); 4959 return false; 4960 case UTT_IsDestructible: 4961 case UTT_IsTriviallyDestructible: 4962 case UTT_IsNothrowDestructible: 4963 // C++14 [meta.unary.prop]: 4964 // For reference types, is_destructible<T>::value is true. 4965 if (T->isReferenceType()) 4966 return true; 4967 4968 // Objective-C++ ARC: autorelease types don't require destruction. 4969 if (T->isObjCLifetimeType() && 4970 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 4971 return true; 4972 4973 // C++14 [meta.unary.prop]: 4974 // For incomplete types and function types, is_destructible<T>::value is 4975 // false. 4976 if (T->isIncompleteType() || T->isFunctionType()) 4977 return false; 4978 4979 // A type that requires destruction (via a non-trivial destructor or ARC 4980 // lifetime semantics) is not trivially-destructible. 4981 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 4982 return false; 4983 4984 // C++14 [meta.unary.prop]: 4985 // For object types and given U equal to remove_all_extents_t<T>, if the 4986 // expression std::declval<U&>().~U() is well-formed when treated as an 4987 // unevaluated operand (Clause 5), then is_destructible<T>::value is true 4988 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 4989 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 4990 if (!Destructor) 4991 return false; 4992 // C++14 [dcl.fct.def.delete]p2: 4993 // A program that refers to a deleted function implicitly or 4994 // explicitly, other than to declare it, is ill-formed. 4995 if (Destructor->isDeleted()) 4996 return false; 4997 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 4998 return false; 4999 if (UTT == UTT_IsNothrowDestructible) { 5000 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); 5001 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5002 if (!CPT || !CPT->isNothrow()) 5003 return false; 5004 } 5005 } 5006 return true; 5007 5008 case UTT_HasTrivialDestructor: 5009 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 5010 // If __is_pod (type) is true or type is a reference type 5011 // then the trait is true, else if type is a cv class or union 5012 // type (or array thereof) with a trivial destructor 5013 // ([class.dtor]) then the trait is true, else it is 5014 // false. 5015 if (T.isPODType(C) || T->isReferenceType()) 5016 return true; 5017 5018 // Objective-C++ ARC: autorelease types don't require destruction. 5019 if (T->isObjCLifetimeType() && 5020 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 5021 return true; 5022 5023 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 5024 return RD->hasTrivialDestructor(); 5025 return false; 5026 // TODO: Propagate nothrowness for implicitly declared special members. 5027 case UTT_HasNothrowAssign: 5028 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5029 // If type is const qualified or is a reference type then the 5030 // trait is false. Otherwise if __has_trivial_assign (type) 5031 // is true then the trait is true, else if type is a cv class 5032 // or union type with copy assignment operators that are known 5033 // not to throw an exception then the trait is true, else it is 5034 // false. 5035 if (C.getBaseElementType(T).isConstQualified()) 5036 return false; 5037 if (T->isReferenceType()) 5038 return false; 5039 if (T.isPODType(C) || T->isObjCLifetimeType()) 5040 return true; 5041 5042 if (const RecordType *RT = T->getAs<RecordType>()) 5043 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 5044 &CXXRecordDecl::hasTrivialCopyAssignment, 5045 &CXXRecordDecl::hasNonTrivialCopyAssignment, 5046 &CXXMethodDecl::isCopyAssignmentOperator); 5047 return false; 5048 case UTT_HasNothrowMoveAssign: 5049 // This trait is implemented by MSVC 2012 and needed to parse the 5050 // standard library headers. Specifically this is used as the logic 5051 // behind std::is_nothrow_move_assignable (20.9.4.3). 5052 if (T.isPODType(C)) 5053 return true; 5054 5055 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 5056 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 5057 &CXXRecordDecl::hasTrivialMoveAssignment, 5058 &CXXRecordDecl::hasNonTrivialMoveAssignment, 5059 &CXXMethodDecl::isMoveAssignmentOperator); 5060 return false; 5061 case UTT_HasNothrowCopy: 5062 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5063 // If __has_trivial_copy (type) is true then the trait is true, else 5064 // if type is a cv class or union type with copy constructors that are 5065 // known not to throw an exception then the trait is true, else it is 5066 // false. 5067 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 5068 return true; 5069 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 5070 if (RD->hasTrivialCopyConstructor() && 5071 !RD->hasNonTrivialCopyConstructor()) 5072 return true; 5073 5074 bool FoundConstructor = false; 5075 unsigned FoundTQs; 5076 for (const auto *ND : Self.LookupConstructors(RD)) { 5077 // A template constructor is never a copy constructor. 5078 // FIXME: However, it may actually be selected at the actual overload 5079 // resolution point. 5080 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 5081 continue; 5082 // UsingDecl itself is not a constructor 5083 if (isa<UsingDecl>(ND)) 5084 continue; 5085 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 5086 if (Constructor->isCopyConstructor(FoundTQs)) { 5087 FoundConstructor = true; 5088 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 5089 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5090 if (!CPT) 5091 return false; 5092 // TODO: check whether evaluating default arguments can throw. 5093 // For now, we'll be conservative and assume that they can throw. 5094 if (!CPT->isNothrow() || CPT->getNumParams() > 1) 5095 return false; 5096 } 5097 } 5098 5099 return FoundConstructor; 5100 } 5101 return false; 5102 case UTT_HasNothrowConstructor: 5103 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 5104 // If __has_trivial_constructor (type) is true then the trait is 5105 // true, else if type is a cv class or union type (or array 5106 // thereof) with a default constructor that is known not to 5107 // throw an exception then the trait is true, else it is false. 5108 if (T.isPODType(C) || T->isObjCLifetimeType()) 5109 return true; 5110 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 5111 if (RD->hasTrivialDefaultConstructor() && 5112 !RD->hasNonTrivialDefaultConstructor()) 5113 return true; 5114 5115 bool FoundConstructor = false; 5116 for (const auto *ND : Self.LookupConstructors(RD)) { 5117 // FIXME: In C++0x, a constructor template can be a default constructor. 5118 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 5119 continue; 5120 // UsingDecl itself is not a constructor 5121 if (isa<UsingDecl>(ND)) 5122 continue; 5123 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 5124 if (Constructor->isDefaultConstructor()) { 5125 FoundConstructor = true; 5126 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 5127 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5128 if (!CPT) 5129 return false; 5130 // FIXME: check whether evaluating default arguments can throw. 5131 // For now, we'll be conservative and assume that they can throw. 5132 if (!CPT->isNothrow() || CPT->getNumParams() > 0) 5133 return false; 5134 } 5135 } 5136 return FoundConstructor; 5137 } 5138 return false; 5139 case UTT_HasVirtualDestructor: 5140 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5141 // If type is a class type with a virtual destructor ([class.dtor]) 5142 // then the trait is true, else it is false. 5143 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5144 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 5145 return Destructor->isVirtual(); 5146 return false; 5147 5148 // These type trait expressions are modeled on the specifications for the 5149 // Embarcadero C++0x type trait functions: 5150 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 5151 case UTT_IsCompleteType: 5152 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 5153 // Returns True if and only if T is a complete type at the point of the 5154 // function call. 5155 return !T->isIncompleteType(); 5156 case UTT_HasUniqueObjectRepresentations: 5157 return C.hasUniqueObjectRepresentations(T); 5158 } 5159} 5160 5161static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 5162 QualType RhsT, SourceLocation KeyLoc); 5163 5164static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 5165 ArrayRef<TypeSourceInfo *> Args, 5166 SourceLocation RParenLoc) { 5167 if (Kind <= UTT_Last) 5168 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 5169 5170 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 5171 // traits to avoid duplication. 5172 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 5173 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 5174 Args[1]->getType(), RParenLoc); 5175 5176 switch (Kind) { 5177 case clang::BTT_ReferenceBindsToTemporary: 5178 case clang::TT_IsConstructible: 5179 case clang::TT_IsNothrowConstructible: 5180 case clang::TT_IsTriviallyConstructible: { 5181 // C++11 [meta.unary.prop]: 5182 // is_trivially_constructible is defined as: 5183 // 5184 // is_constructible<T, Args...>::value is true and the variable 5185 // definition for is_constructible, as defined below, is known to call 5186 // no operation that is not trivial. 5187 // 5188 // The predicate condition for a template specialization 5189 // is_constructible<T, Args...> shall be satisfied if and only if the 5190 // following variable definition would be well-formed for some invented 5191 // variable t: 5192 // 5193 // T t(create<Args>()...); 5194 assert(!Args.empty())((!Args.empty()) ? static_cast<void> (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5194, __PRETTY_FUNCTION__))
; 5195 5196 // Precondition: T and all types in the parameter pack Args shall be 5197 // complete types, (possibly cv-qualified) void, or arrays of 5198 // unknown bound. 5199 for (const auto *TSI : Args) { 5200 QualType ArgTy = TSI->getType(); 5201 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 5202 continue; 5203 5204 if (S.RequireCompleteType(KWLoc, ArgTy, 5205 diag::err_incomplete_type_used_in_type_trait_expr)) 5206 return false; 5207 } 5208 5209 // Make sure the first argument is not incomplete nor a function type. 5210 QualType T = Args[0]->getType(); 5211 if (T->isIncompleteType() || T->isFunctionType()) 5212 return false; 5213 5214 // Make sure the first argument is not an abstract type. 5215 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5216 if (RD && RD->isAbstract()) 5217 return false; 5218 5219 llvm::BumpPtrAllocator OpaqueExprAllocator; 5220 SmallVector<Expr *, 2> ArgExprs; 5221 ArgExprs.reserve(Args.size() - 1); 5222 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 5223 QualType ArgTy = Args[I]->getType(); 5224 if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 5225 ArgTy = S.Context.getRValueReferenceType(ArgTy); 5226 ArgExprs.push_back( 5227 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 5228 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 5229 ArgTy.getNonLValueExprType(S.Context), 5230 Expr::getValueKindForType(ArgTy))); 5231 } 5232 5233 // Perform the initialization in an unevaluated context within a SFINAE 5234 // trap at translation unit scope. 5235 EnterExpressionEvaluationContext Unevaluated( 5236 S, Sema::ExpressionEvaluationContext::Unevaluated); 5237 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 5238 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 5239 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 5240 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 5241 RParenLoc)); 5242 InitializationSequence Init(S, To, InitKind, ArgExprs); 5243 if (Init.Failed()) 5244 return false; 5245 5246 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 5247 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 5248 return false; 5249 5250 if (Kind == clang::TT_IsConstructible) 5251 return true; 5252 5253 if (Kind == clang::BTT_ReferenceBindsToTemporary) { 5254 if (!T->isReferenceType()) 5255 return false; 5256 5257 return !Init.isDirectReferenceBinding(); 5258 } 5259 5260 if (Kind == clang::TT_IsNothrowConstructible) 5261 return S.canThrow(Result.get()) == CT_Cannot; 5262 5263 if (Kind == clang::TT_IsTriviallyConstructible) { 5264 // Under Objective-C ARC and Weak, if the destination has non-trivial 5265 // Objective-C lifetime, this is a non-trivial construction. 5266 if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 5267 return false; 5268 5269 // The initialization succeeded; now make sure there are no non-trivial 5270 // calls. 5271 return !Result.get()->hasNonTrivialCall(S.Context); 5272 } 5273 5274 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5274)
; 5275 return false; 5276 } 5277 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5277)
; 5278 } 5279 5280 return false; 5281} 5282 5283ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 5284 ArrayRef<TypeSourceInfo *> Args, 5285 SourceLocation RParenLoc) { 5286 QualType ResultType = Context.getLogicalOperationType(); 5287 5288 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 5289 *this, Kind, KWLoc, Args[0]->getType())) 5290 return ExprError(); 5291 5292 bool Dependent = false; 5293 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 5294 if (Args[I]->getType()->isDependentType()) { 5295 Dependent = true; 5296 break; 5297 } 5298 } 5299 5300 bool Result = false; 5301 if (!Dependent) 5302 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 5303 5304 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 5305 RParenLoc, Result); 5306} 5307 5308ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 5309 ArrayRef<ParsedType> Args, 5310 SourceLocation RParenLoc) { 5311 SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 5312 ConvertedArgs.reserve(Args.size()); 5313 5314 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 5315 TypeSourceInfo *TInfo; 5316 QualType T = GetTypeFromParser(Args[I], &TInfo); 5317 if (!TInfo) 5318 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 5319 5320 ConvertedArgs.push_back(TInfo); 5321 } 5322 5323 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 5324} 5325 5326static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 5327 QualType RhsT, SourceLocation KeyLoc) { 5328 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5329, __PRETTY_FUNCTION__))
5329 "Cannot evaluate traits of dependent types")((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5329, __PRETTY_FUNCTION__))
; 5330 5331 switch(BTT) { 5332 case BTT_IsBaseOf: { 5333 // C++0x [meta.rel]p2 5334 // Base is a base class of Derived without regard to cv-qualifiers or 5335 // Base and Derived are not unions and name the same class type without 5336 // regard to cv-qualifiers. 5337 5338 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 5339 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 5340 if (!rhsRecord || !lhsRecord) { 5341 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 5342 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 5343 if (!LHSObjTy || !RHSObjTy) 5344 return false; 5345 5346 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 5347 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 5348 if (!BaseInterface || !DerivedInterface) 5349 return false; 5350 5351 if (Self.RequireCompleteType( 5352 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 5353 return false; 5354 5355 return BaseInterface->isSuperClassOf(DerivedInterface); 5356 } 5357 5358 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5359, __PRETTY_FUNCTION__))
5359 == (lhsRecord == rhsRecord))((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5359, __PRETTY_FUNCTION__))
; 5360 5361 // Unions are never base classes, and never have base classes. 5362 // It doesn't matter if they are complete or not. See PR#41843 5363 if (lhsRecord && lhsRecord->getDecl()->isUnion()) 5364 return false; 5365 if (rhsRecord && rhsRecord->getDecl()->isUnion()) 5366 return false; 5367 5368 if (lhsRecord == rhsRecord) 5369 return true; 5370 5371 // C++0x [meta.rel]p2: 5372 // If Base and Derived are class types and are different types 5373 // (ignoring possible cv-qualifiers) then Derived shall be a 5374 // complete type. 5375 if (Self.RequireCompleteType(KeyLoc, RhsT, 5376 diag::err_incomplete_type_used_in_type_trait_expr)) 5377 return false; 5378 5379 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 5380 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 5381 } 5382 case BTT_IsSame: 5383 return Self.Context.hasSameType(LhsT, RhsT); 5384 case BTT_TypeCompatible: { 5385 // GCC ignores cv-qualifiers on arrays for this builtin. 5386 Qualifiers LhsQuals, RhsQuals; 5387 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 5388 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 5389 return Self.Context.typesAreCompatible(Lhs, Rhs); 5390 } 5391 case BTT_IsConvertible: 5392 case BTT_IsConvertibleTo: { 5393 // C++0x [meta.rel]p4: 5394 // Given the following function prototype: 5395 // 5396 // template <class T> 5397 // typename add_rvalue_reference<T>::type create(); 5398 // 5399 // the predicate condition for a template specialization 5400 // is_convertible<From, To> shall be satisfied if and only if 5401 // the return expression in the following code would be 5402 // well-formed, including any implicit conversions to the return 5403 // type of the function: 5404 // 5405 // To test() { 5406 // return create<From>(); 5407 // } 5408 // 5409 // Access checking is performed as if in a context unrelated to To and 5410 // From. Only the validity of the immediate context of the expression 5411 // of the return-statement (including conversions to the return type) 5412 // is considered. 5413 // 5414 // We model the initialization as a copy-initialization of a temporary 5415 // of the appropriate type, which for this expression is identical to the 5416 // return statement (since NRVO doesn't apply). 5417 5418 // Functions aren't allowed to return function or array types. 5419 if (RhsT->isFunctionType() || RhsT->isArrayType()) 5420 return false; 5421 5422 // A return statement in a void function must have void type. 5423 if (RhsT->isVoidType()) 5424 return LhsT->isVoidType(); 5425 5426 // A function definition requires a complete, non-abstract return type. 5427 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 5428 return false; 5429 5430 // Compute the result of add_rvalue_reference. 5431 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5432 LhsT = Self.Context.getRValueReferenceType(LhsT); 5433 5434 // Build a fake source and destination for initialization. 5435 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 5436 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5437 Expr::getValueKindForType(LhsT)); 5438 Expr *FromPtr = &From; 5439 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 5440 SourceLocation())); 5441 5442 // Perform the initialization in an unevaluated context within a SFINAE 5443 // trap at translation unit scope. 5444 EnterExpressionEvaluationContext Unevaluated( 5445 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5446 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5447 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5448 InitializationSequence Init(Self, To, Kind, FromPtr); 5449 if (Init.Failed()) 5450 return false; 5451 5452 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 5453 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 5454 } 5455 5456 case BTT_IsAssignable: 5457 case BTT_IsNothrowAssignable: 5458 case BTT_IsTriviallyAssignable: { 5459 // C++11 [meta.unary.prop]p3: 5460 // is_trivially_assignable is defined as: 5461 // is_assignable<T, U>::value is true and the assignment, as defined by 5462 // is_assignable, is known to call no operation that is not trivial 5463 // 5464 // is_assignable is defined as: 5465 // The expression declval<T>() = declval<U>() is well-formed when 5466 // treated as an unevaluated operand (Clause 5). 5467 // 5468 // For both, T and U shall be complete types, (possibly cv-qualified) 5469 // void, or arrays of unknown bound. 5470 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 5471 Self.RequireCompleteType(KeyLoc, LhsT, 5472 diag::err_incomplete_type_used_in_type_trait_expr)) 5473 return false; 5474 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 5475 Self.RequireCompleteType(KeyLoc, RhsT, 5476 diag::err_incomplete_type_used_in_type_trait_expr)) 5477 return false; 5478 5479 // cv void is never assignable. 5480 if (LhsT->isVoidType() || RhsT->isVoidType()) 5481 return false; 5482 5483 // Build expressions that emulate the effect of declval<T>() and 5484 // declval<U>(). 5485 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5486 LhsT = Self.Context.getRValueReferenceType(LhsT); 5487 if (RhsT->isObjectType() || RhsT->isFunctionType()) 5488 RhsT = Self.Context.getRValueReferenceType(RhsT); 5489 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5490 Expr::getValueKindForType(LhsT)); 5491 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 5492 Expr::getValueKindForType(RhsT)); 5493 5494 // Attempt the assignment in an unevaluated context within a SFINAE 5495 // trap at translation unit scope. 5496 EnterExpressionEvaluationContext Unevaluated( 5497 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5498 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5499 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5500 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 5501 &Rhs); 5502 if (Result.isInvalid()) 5503 return false; 5504 5505 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 5506 Self.CheckUnusedVolatileAssignment(Result.get()); 5507 5508 if (SFINAE.hasErrorOccurred()) 5509 return false; 5510 5511 if (BTT == BTT_IsAssignable) 5512 return true; 5513 5514 if (BTT == BTT_IsNothrowAssignable) 5515 return Self.canThrow(Result.get()) == CT_Cannot; 5516 5517 if (BTT == BTT_IsTriviallyAssignable) { 5518 // Under Objective-C ARC and Weak, if the destination has non-trivial 5519 // Objective-C lifetime, this is a non-trivial assignment. 5520 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 5521 return false; 5522 5523 return !Result.get()->hasNonTrivialCall(Self.Context); 5524 } 5525 5526 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5526)
; 5527 return false; 5528 } 5529 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5529)
; 5530 } 5531 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5531)
; 5532} 5533 5534ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 5535 SourceLocation KWLoc, 5536 ParsedType Ty, 5537 Expr* DimExpr, 5538 SourceLocation RParen) { 5539 TypeSourceInfo *TSInfo; 5540 QualType T = GetTypeFromParser(Ty, &TSInfo); 5541 if (!TSInfo) 5542 TSInfo = Context.getTrivialTypeSourceInfo(T); 5543 5544 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 5545} 5546 5547static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 5548 QualType T, Expr *DimExpr, 5549 SourceLocation KeyLoc) { 5550 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5550, __PRETTY_FUNCTION__))
; 5551 5552 switch(ATT) { 5553 case ATT_ArrayRank: 5554 if (T->isArrayType()) { 5555 unsigned Dim = 0; 5556 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 5557 ++Dim; 5558 T = AT->getElementType(); 5559 } 5560 return Dim; 5561 } 5562 return 0; 5563 5564 case ATT_ArrayExtent: { 5565 llvm::APSInt Value; 5566 uint64_t Dim; 5567 if (Self.VerifyIntegerConstantExpression( 5568 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) 5569 .isInvalid()) 5570 return 0; 5571 if (Value.isSigned() && Value.isNegative()) { 5572 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 5573 << DimExpr->getSourceRange(); 5574 return 0; 5575 } 5576 Dim = Value.getLimitedValue(); 5577 5578 if (T->isArrayType()) { 5579 unsigned D = 0; 5580 bool Matched = false; 5581 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 5582 if (Dim == D) { 5583 Matched = true; 5584 break; 5585 } 5586 ++D; 5587 T = AT->getElementType(); 5588 } 5589 5590 if (Matched && T->isArrayType()) { 5591 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 5592 return CAT->getSize().getLimitedValue(); 5593 } 5594 } 5595 return 0; 5596 } 5597 } 5598 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5598)
; 5599} 5600 5601ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 5602 SourceLocation KWLoc, 5603 TypeSourceInfo *TSInfo, 5604 Expr* DimExpr, 5605 SourceLocation RParen) { 5606 QualType T = TSInfo->getType(); 5607 5608 // FIXME: This should likely be tracked as an APInt to remove any host 5609 // assumptions about the width of size_t on the target. 5610 uint64_t Value = 0; 5611 if (!T->isDependentType()) 5612 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 5613 5614 // While the specification for these traits from the Embarcadero C++ 5615 // compiler's documentation says the return type is 'unsigned int', Clang 5616 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 5617 // compiler, there is no difference. On several other platforms this is an 5618 // important distinction. 5619 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 5620 RParen, Context.getSizeType()); 5621} 5622 5623ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 5624 SourceLocation KWLoc, 5625 Expr *Queried, 5626 SourceLocation RParen) { 5627 // If error parsing the expression, ignore. 5628 if (!Queried) 5629 return ExprError(); 5630 5631 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 5632 5633 return Result; 5634} 5635 5636static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 5637 switch (ET) { 5638 case ET_IsLValueExpr: return E->isLValue(); 5639 case ET_IsRValueExpr: return E->isRValue(); 5640 } 5641 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5641)
; 5642} 5643 5644ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 5645 SourceLocation KWLoc, 5646 Expr *Queried, 5647 SourceLocation RParen) { 5648 if (Queried->isTypeDependent()) { 5649 // Delay type-checking for type-dependent expressions. 5650 } else if (Queried->getType()->isPlaceholderType()) { 5651 ExprResult PE = CheckPlaceholderExpr(Queried); 5652 if (PE.isInvalid()) return ExprError(); 5653 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 5654 } 5655 5656 bool Value = EvaluateExpressionTrait(ET, Queried); 5657 5658 return new (Context) 5659 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 5660} 5661 5662QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 5663 ExprValueKind &VK, 5664 SourceLocation Loc, 5665 bool isIndirect) { 5666 assert(!LHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5668, __PRETTY_FUNCTION__))
5667 !RHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5668, __PRETTY_FUNCTION__))
5668 "placeholders should have been weeded out by now")((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaExprCXX.cpp"
, 5668, __PRETTY_FUNCTION__))
; 5669 5670 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 5671 // temporary materialization conversion otherwise. 5672 if (isIndirect) 5673 LHS = DefaultLvalueConversion(LHS.get()); 5674 else if (LHS.get()->isRValue()) 5675 LHS = TemporaryMaterializationConversion(LHS.get()); 5676 if (LHS.isInvalid()) 5677 return QualType(); 5678 5679 // The RHS always undergoes lvalue conversions. 5680 RHS = DefaultLvalueConversion(RHS.get()); 5681 if (RHS.isInvalid()) return QualType(); 5682 5683 const char *OpSpelling = isIndirect ? "->*" : ".*"; 5684 // C++ 5.5p2 5685 // The binary operator .* [p3: ->*] binds its second operand, which shall 5686 // be of type "pointer to member of T" (where T is a completely-defined 5687 // class type) [...] 5688 QualType RHSType = RHS.get()->getType(); 5689 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 5690 if (!MemPtr) { 5691 Diag(Loc, diag::err_bad_memptr_rhs) 5692 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 5693 return QualType(); 5694 } 5695 5696 QualType Class(MemPtr->getClass(), 0); 5697 5698 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 5699 // member pointer points must be completely-defined. However, there is no 5700 // reason for this semantic distinction, and the rule is not enforced by 5701 // other compilers. Therefore, we do not check this property, as it is 5702 // likely to be considered a defect. 5703 5704 // C++ 5.5p2 5705 // [...] to its first operand, which shall be of class T or of a class of 5706 // which T is an unambiguous and accessible base class. [p3: a pointer to 5707 // such a class] 5708 QualType LHSType = LHS.get()->getType(); 5709 if (isIndirect) { 5710 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 5711 LHSType = Ptr->getPointeeType(); 5712 else { 5713 Diag(Loc, diag::err_bad_memptr_lhs) 5714 << OpSpelling << 1 << LHSType 5715 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 5716 return QualType(); 5717 } 5718 } 5719 5720 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 5721 // If we want to check the hierarchy, we need a complete type. 5722 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 5723 OpSpelling, (int)isIndirect)) { 5724 return QualType(); 5725 } 5726 5727 if (!IsDerivedFrom(Loc, LHSType, Class)) { 5728 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 5729 << (int)isIndirect << LHS.get()->getType(); 5730 return QualType(); 5731 } 5732 5733 CXXCastPath BasePath; 5734 if (CheckDerivedToBaseConversion( 5735 LHSType, Class, Loc, 5736 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 5737 &BasePath)) 5738 return QualType(); 5739 5740 // Cast LHS to type of use. 5741 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 5742 if (isIndirect) 5743 UseType = Context.getPointerType(UseType); 5744 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 5745 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 5746 &BasePath); 5747 } 5748 5749 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 5750 // Diagnose use of pointer-to-member type which when used as 5751 // the functional cast in a pointer-to-member expression. 5752 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 5753 return QualType(); 5754 } 5755 5756 // C++ 5.5p2 5757 // The result is an object or a function of the type specified by the 5758 // second operand. 5759 // The cv qualifiers are the union of those in the pointer and the left side, 5760 // in accordance with 5.5p5 and 5.2.5. 5761 QualType Result = MemPtr->getPointeeType(); 5762 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 5763 5764 // C++0x [expr.mptr.oper]p6: 5765 // In a .* expression whose object expression is an rvalue, the program is 5766 // ill-formed if the second operand is a pointer to member function with 5767 // ref-qualifier &. In a ->* expression or in a .* expression whose object 5768 // expression is an lvalue, the program is ill-formed if the second operand 5769 // is a pointer to member function with ref-qualifier &&. 5770 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 5771 switch (Proto->getRefQualifier()) { 5772 case RQ_None: 5773 // Do nothing 5774 break; 5775 5776 case RQ_LValue: 5777 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 5778 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 5779 // is (exactly) 'const'. 5780 if (Proto->isConst() && !Proto->isVolatile()) 5781 Diag(Loc, getLangOpts().CPlusPlus20 5782 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 5783 : diag::ext_pointer_to_const_ref_member_on_rvalue); 5784 else 5785 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 5786 << RHSType << 1 << LHS.get()->getSourceRange(); 5787 } 5788 break; 5789 5790 case RQ_RValue: 5791 if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 5792 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 5793 << RHSType << 0 << LHS.get()->getSourceRange(); 5794 break; 5795 } 5796 } 5797 5798 // C++ [expr.mptr.oper]p6: 5799 // The result of a .* expression whose second operand is