Bug Summary

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