1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// Implements semantic analysis for C++ expressions.
12 //===----------------------------------------------------------------------===//
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/ExprConcepts.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/Type.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/AlignedAllocation.h"
28 #include "clang/Basic/DiagnosticSema.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/TokenKinds.h"
32 #include "clang/Basic/TypeTraits.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/EnterExpressionEvaluationContext.h"
36 #include "clang/Sema/Initialization.h"
37 #include "clang/Sema/Lookup.h"
38 #include "clang/Sema/ParsedTemplate.h"
39 #include "clang/Sema/Scope.h"
40 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/SemaInternal.h"
42 #include "clang/Sema/SemaLambda.h"
43 #include "clang/Sema/Template.h"
44 #include "clang/Sema/TemplateDeduction.h"
45 #include "llvm/ADT/APInt.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/TypeSize.h"
51 using namespace clang
;
54 /// Handle the result of the special case name lookup for inheriting
55 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
56 /// constructor names in member using declarations, even if 'X' is not the
57 /// name of the corresponding type.
58 ParsedType
Sema::getInheritingConstructorName(CXXScopeSpec
&SS
,
59 SourceLocation NameLoc
,
60 IdentifierInfo
&Name
) {
61 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
63 // Convert the nested-name-specifier into a type.
65 switch (NNS
->getKind()) {
66 case NestedNameSpecifier::TypeSpec
:
67 case NestedNameSpecifier::TypeSpecWithTemplate
:
68 Type
= QualType(NNS
->getAsType(), 0);
71 case NestedNameSpecifier::Identifier
:
72 // Strip off the last layer of the nested-name-specifier and build a
73 // typename type for it.
74 assert(NNS
->getAsIdentifier() == &Name
&& "not a constructor name");
75 Type
= Context
.getDependentNameType(
76 ElaboratedTypeKeyword::None
, NNS
->getPrefix(), NNS
->getAsIdentifier());
79 case NestedNameSpecifier::Global
:
80 case NestedNameSpecifier::Super
:
81 case NestedNameSpecifier::Namespace
:
82 case NestedNameSpecifier::NamespaceAlias
:
83 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
86 // This reference to the type is located entirely at the location of the
87 // final identifier in the qualified-id.
88 return CreateParsedType(Type
,
89 Context
.getTrivialTypeSourceInfo(Type
, NameLoc
));
92 ParsedType
Sema::getConstructorName(IdentifierInfo
&II
,
93 SourceLocation NameLoc
,
94 Scope
*S
, CXXScopeSpec
&SS
,
95 bool EnteringContext
) {
96 CXXRecordDecl
*CurClass
= getCurrentClass(S
, &SS
);
97 assert(CurClass
&& &II
== CurClass
->getIdentifier() &&
98 "not a constructor name");
100 // When naming a constructor as a member of a dependent context (eg, in a
101 // friend declaration or an inherited constructor declaration), form an
102 // unresolved "typename" type.
103 if (CurClass
->isDependentContext() && !EnteringContext
&& SS
.getScopeRep()) {
104 QualType T
= Context
.getDependentNameType(ElaboratedTypeKeyword::None
,
105 SS
.getScopeRep(), &II
);
106 return ParsedType::make(T
);
109 if (SS
.isNotEmpty() && RequireCompleteDeclContext(SS
, CurClass
))
112 // Find the injected-class-name declaration. Note that we make no attempt to
113 // diagnose cases where the injected-class-name is shadowed: the only
114 // declaration that can validly shadow the injected-class-name is a
115 // non-static data member, and if the class contains both a non-static data
116 // member and a constructor then it is ill-formed (we check that in
117 // CheckCompletedCXXClass).
118 CXXRecordDecl
*InjectedClassName
= nullptr;
119 for (NamedDecl
*ND
: CurClass
->lookup(&II
)) {
120 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
);
121 if (RD
&& RD
->isInjectedClassName()) {
122 InjectedClassName
= RD
;
126 if (!InjectedClassName
) {
127 if (!CurClass
->isInvalidDecl()) {
128 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
129 // properly. Work around it here for now.
130 Diag(SS
.getLastQualifierNameLoc(),
131 diag::err_incomplete_nested_name_spec
) << CurClass
<< SS
.getRange();
136 QualType T
= Context
.getTypeDeclType(InjectedClassName
);
137 DiagnoseUseOfDecl(InjectedClassName
, NameLoc
);
138 MarkAnyDeclReferenced(NameLoc
, InjectedClassName
, /*OdrUse=*/false);
140 return ParsedType::make(T
);
143 ParsedType
Sema::getDestructorName(IdentifierInfo
&II
, SourceLocation NameLoc
,
144 Scope
*S
, CXXScopeSpec
&SS
,
145 ParsedType ObjectTypePtr
,
146 bool EnteringContext
) {
147 // Determine where to perform name lookup.
149 // FIXME: This area of the standard is very messy, and the current
150 // wording is rather unclear about which scopes we search for the
151 // destructor name; see core issues 399 and 555. Issue 399 in
152 // particular shows where the current description of destructor name
153 // lookup is completely out of line with existing practice, e.g.,
154 // this appears to be ill-formed:
157 // template <typename T> struct S {
162 // void f(N::S<int>* s) {
163 // s->N::S<int>::~S();
166 // See also PR6358 and PR6359.
168 // For now, we accept all the cases in which the name given could plausibly
169 // be interpreted as a correct destructor name, issuing off-by-default
170 // extension diagnostics on the cases that don't strictly conform to the
171 // C++20 rules. This basically means we always consider looking in the
172 // nested-name-specifier prefix, the complete nested-name-specifier, and
173 // the scope, and accept if we find the expected type in any of the three
179 // Whether we've failed with a diagnostic already.
182 llvm::SmallVector
<NamedDecl
*, 8> FoundDecls
;
183 llvm::SmallPtrSet
<CanonicalDeclPtr
<Decl
>, 8> FoundDeclSet
;
185 // If we have an object type, it's because we are in a
186 // pseudo-destructor-expression or a member access expression, and
187 // we know what type we're looking for.
188 QualType SearchType
=
189 ObjectTypePtr
? GetTypeFromParser(ObjectTypePtr
) : QualType();
191 auto CheckLookupResult
= [&](LookupResult
&Found
) -> ParsedType
{
192 auto IsAcceptableResult
= [&](NamedDecl
*D
) -> bool {
193 auto *Type
= dyn_cast
<TypeDecl
>(D
->getUnderlyingDecl());
197 if (SearchType
.isNull() || SearchType
->isDependentType())
200 QualType T
= Context
.getTypeDeclType(Type
);
201 return Context
.hasSameUnqualifiedType(T
, SearchType
);
204 unsigned NumAcceptableResults
= 0;
205 for (NamedDecl
*D
: Found
) {
206 if (IsAcceptableResult(D
))
207 ++NumAcceptableResults
;
209 // Don't list a class twice in the lookup failure diagnostic if it's
210 // found by both its injected-class-name and by the name in the enclosing
212 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
))
213 if (RD
->isInjectedClassName())
214 D
= cast
<NamedDecl
>(RD
->getParent());
216 if (FoundDeclSet
.insert(D
).second
)
217 FoundDecls
.push_back(D
);
220 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
221 // results, and all non-matching results if we have a search type. It's not
222 // clear what the right behavior is if destructor lookup hits an ambiguity,
223 // but other compilers do generally accept at least some kinds of
225 if (Found
.isAmbiguous() && NumAcceptableResults
== 1) {
226 Diag(NameLoc
, diag::ext_dtor_name_ambiguous
);
227 LookupResult::Filter F
= Found
.makeFilter();
228 while (F
.hasNext()) {
229 NamedDecl
*D
= F
.next();
230 if (auto *TD
= dyn_cast
<TypeDecl
>(D
->getUnderlyingDecl()))
231 Diag(D
->getLocation(), diag::note_destructor_type_here
)
232 << Context
.getTypeDeclType(TD
);
234 Diag(D
->getLocation(), diag::note_destructor_nontype_here
);
236 if (!IsAcceptableResult(D
))
242 if (Found
.isAmbiguous())
245 if (TypeDecl
*Type
= Found
.getAsSingle
<TypeDecl
>()) {
246 if (IsAcceptableResult(Type
)) {
247 QualType T
= Context
.getTypeDeclType(Type
);
248 MarkAnyDeclReferenced(Type
->getLocation(), Type
, /*OdrUse=*/false);
249 return CreateParsedType(
250 Context
.getElaboratedType(ElaboratedTypeKeyword::None
, nullptr, T
),
251 Context
.getTrivialTypeSourceInfo(T
, NameLoc
));
258 bool IsDependent
= false;
260 auto LookupInObjectType
= [&]() -> ParsedType
{
261 if (Failed
|| SearchType
.isNull())
264 IsDependent
|= SearchType
->isDependentType();
266 LookupResult
Found(*this, &II
, NameLoc
, LookupDestructorName
);
267 DeclContext
*LookupCtx
= computeDeclContext(SearchType
);
270 LookupQualifiedName(Found
, LookupCtx
);
271 return CheckLookupResult(Found
);
274 auto LookupInNestedNameSpec
= [&](CXXScopeSpec
&LookupSS
) -> ParsedType
{
278 IsDependent
|= isDependentScopeSpecifier(LookupSS
);
279 DeclContext
*LookupCtx
= computeDeclContext(LookupSS
, EnteringContext
);
283 LookupResult
Found(*this, &II
, NameLoc
, LookupDestructorName
);
284 if (RequireCompleteDeclContext(LookupSS
, LookupCtx
)) {
288 LookupQualifiedName(Found
, LookupCtx
);
289 return CheckLookupResult(Found
);
292 auto LookupInScope
= [&]() -> ParsedType
{
296 LookupResult
Found(*this, &II
, NameLoc
, LookupDestructorName
);
297 LookupName(Found
, S
);
298 return CheckLookupResult(Found
);
301 // C++2a [basic.lookup.qual]p6:
302 // In a qualified-id of the form
304 // nested-name-specifier[opt] type-name :: ~ type-name
306 // the second type-name is looked up in the same scope as the first.
308 // We interpret this as meaning that if you do a dual-scope lookup for the
309 // first name, you also do a dual-scope lookup for the second name, per
310 // C++ [basic.lookup.classref]p4:
312 // If the id-expression in a class member access is a qualified-id of the
315 // class-name-or-namespace-name :: ...
317 // the class-name-or-namespace-name following the . or -> is first looked
318 // up in the class of the object expression and the name, if found, is used.
319 // Otherwise, it is looked up in the context of the entire
320 // postfix-expression.
322 // This looks in the same scopes as for an unqualified destructor name:
324 // C++ [basic.lookup.classref]p3:
325 // If the unqualified-id is ~ type-name, the type-name is looked up
326 // in the context of the entire postfix-expression. If the type T
327 // of the object expression is of a class type C, the type-name is
328 // also looked up in the scope of class C. At least one of the
329 // lookups shall find a name that refers to cv T.
331 // FIXME: The intent is unclear here. Should type-name::~type-name look in
332 // the scope anyway if it finds a non-matching name declared in the class?
333 // If both lookups succeed and find a dependent result, which result should
334 // we retain? (Same question for p->~type-name().)
336 if (NestedNameSpecifier
*Prefix
=
337 SS
.isSet() ? SS
.getScopeRep()->getPrefix() : nullptr) {
340 // nested-name-specifier type-name :: ~ type-name
342 // Look for the second type-name in the nested-name-specifier.
343 CXXScopeSpec PrefixSS
;
344 PrefixSS
.Adopt(NestedNameSpecifierLoc(Prefix
, SS
.location_data()));
345 if (ParsedType T
= LookupInNestedNameSpec(PrefixSS
))
350 // type-name :: ~ type-name
353 // Look in the scope and (if any) the object type.
354 if (ParsedType T
= LookupInScope())
356 if (ParsedType T
= LookupInObjectType())
364 // We didn't find our type, but that's OK: it's dependent anyway.
366 // FIXME: What if we have no nested-name-specifier?
368 CheckTypenameType(ElaboratedTypeKeyword::None
, SourceLocation(),
369 SS
.getWithLocInContext(Context
), II
, NameLoc
);
370 return ParsedType::make(T
);
373 // The remaining cases are all non-standard extensions imitating the behavior
374 // of various other compilers.
375 unsigned NumNonExtensionDecls
= FoundDecls
.size();
378 // For compatibility with older broken C++ rules and existing code,
380 // nested-name-specifier :: ~ type-name
382 // also looks for type-name within the nested-name-specifier.
383 if (ParsedType T
= LookupInNestedNameSpec(SS
)) {
384 Diag(SS
.getEndLoc(), diag::ext_dtor_named_in_wrong_scope
)
386 << FixItHint::CreateInsertion(SS
.getEndLoc(),
387 ("::" + II
.getName()).str());
391 // For compatibility with other compilers and older versions of Clang,
393 // nested-name-specifier type-name :: ~ type-name
395 // also looks for type-name in the scope. Unfortunately, we can't
396 // reasonably apply this fallback for dependent nested-name-specifiers.
397 if (SS
.isValid() && SS
.getScopeRep()->getPrefix()) {
398 if (ParsedType T
= LookupInScope()) {
399 Diag(SS
.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope
)
400 << FixItHint::CreateRemoval(SS
.getRange());
401 Diag(FoundDecls
.back()->getLocation(), diag::note_destructor_type_here
)
402 << GetTypeFromParser(T
);
408 // We didn't find anything matching; tell the user what we did find (if
411 // Don't tell the user about declarations we shouldn't have found.
412 FoundDecls
.resize(NumNonExtensionDecls
);
414 // List types before non-types.
415 std::stable_sort(FoundDecls
.begin(), FoundDecls
.end(),
416 [](NamedDecl
*A
, NamedDecl
*B
) {
417 return isa
<TypeDecl
>(A
->getUnderlyingDecl()) >
418 isa
<TypeDecl
>(B
->getUnderlyingDecl());
421 // Suggest a fixit to properly name the destroyed type.
422 auto MakeFixItHint
= [&]{
423 const CXXRecordDecl
*Destroyed
= nullptr;
424 // FIXME: If we have a scope specifier, suggest its last component?
425 if (!SearchType
.isNull())
426 Destroyed
= SearchType
->getAsCXXRecordDecl();
428 Destroyed
= dyn_cast_or_null
<CXXRecordDecl
>(S
->getEntity());
430 return FixItHint::CreateReplacement(SourceRange(NameLoc
),
431 Destroyed
->getNameAsString());
435 if (FoundDecls
.empty()) {
436 // FIXME: Attempt typo-correction?
437 Diag(NameLoc
, diag::err_undeclared_destructor_name
)
438 << &II
<< MakeFixItHint();
439 } else if (!SearchType
.isNull() && FoundDecls
.size() == 1) {
440 if (auto *TD
= dyn_cast
<TypeDecl
>(FoundDecls
[0]->getUnderlyingDecl())) {
441 assert(!SearchType
.isNull() &&
442 "should only reject a type result if we have a search type");
443 QualType T
= Context
.getTypeDeclType(TD
);
444 Diag(NameLoc
, diag::err_destructor_expr_type_mismatch
)
445 << T
<< SearchType
<< MakeFixItHint();
447 Diag(NameLoc
, diag::err_destructor_expr_nontype
)
448 << &II
<< MakeFixItHint();
451 Diag(NameLoc
, SearchType
.isNull() ? diag::err_destructor_name_nontype
452 : diag::err_destructor_expr_mismatch
)
453 << &II
<< SearchType
<< MakeFixItHint();
456 for (NamedDecl
*FoundD
: FoundDecls
) {
457 if (auto *TD
= dyn_cast
<TypeDecl
>(FoundD
->getUnderlyingDecl()))
458 Diag(FoundD
->getLocation(), diag::note_destructor_type_here
)
459 << Context
.getTypeDeclType(TD
);
461 Diag(FoundD
->getLocation(), diag::note_destructor_nontype_here
)
468 ParsedType
Sema::getDestructorTypeForDecltype(const DeclSpec
&DS
,
469 ParsedType ObjectType
) {
470 if (DS
.getTypeSpecType() == DeclSpec::TST_error
)
473 if (DS
.getTypeSpecType() == DeclSpec::TST_decltype_auto
) {
474 Diag(DS
.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid
);
478 assert(DS
.getTypeSpecType() == DeclSpec::TST_decltype
&&
479 "unexpected type in getDestructorType");
480 QualType T
= BuildDecltypeType(DS
.getRepAsExpr());
482 // If we know the type of the object, check that the correct destructor
483 // type was named now; we can give better diagnostics this way.
484 QualType SearchType
= GetTypeFromParser(ObjectType
);
485 if (!SearchType
.isNull() && !SearchType
->isDependentType() &&
486 !Context
.hasSameUnqualifiedType(T
, SearchType
)) {
487 Diag(DS
.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch
)
492 return ParsedType::make(T
);
495 bool Sema::checkLiteralOperatorId(const CXXScopeSpec
&SS
,
496 const UnqualifiedId
&Name
, bool IsUDSuffix
) {
497 assert(Name
.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId
);
501 // double operator""_Bq(long double); // OK: not a reserved identifier
502 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
503 IdentifierInfo
*II
= Name
.Identifier
;
504 ReservedIdentifierStatus Status
= II
->isReserved(PP
.getLangOpts());
505 SourceLocation Loc
= Name
.getEndLoc();
506 if (!PP
.getSourceManager().isInSystemHeader(Loc
)) {
507 if (auto Hint
= FixItHint::CreateReplacement(
508 Name
.getSourceRange(),
509 (StringRef("operator\"\"") + II
->getName()).str());
510 isReservedInAllContexts(Status
)) {
511 Diag(Loc
, diag::warn_reserved_extern_symbol
)
512 << II
<< static_cast<int>(Status
) << Hint
;
514 Diag(Loc
, diag::warn_deprecated_literal_operator_id
) << II
<< Hint
;
522 switch (SS
.getScopeRep()->getKind()) {
523 case NestedNameSpecifier::Identifier
:
524 case NestedNameSpecifier::TypeSpec
:
525 case NestedNameSpecifier::TypeSpecWithTemplate
:
526 // Per C++11 [over.literal]p2, literal operators can only be declared at
527 // namespace scope. Therefore, this unqualified-id cannot name anything.
528 // Reject it early, because we have no AST representation for this in the
529 // case where the scope is dependent.
530 Diag(Name
.getBeginLoc(), diag::err_literal_operator_id_outside_namespace
)
534 case NestedNameSpecifier::Global
:
535 case NestedNameSpecifier::Super
:
536 case NestedNameSpecifier::Namespace
:
537 case NestedNameSpecifier::NamespaceAlias
:
541 llvm_unreachable("unknown nested name specifier kind");
544 /// Build a C++ typeid expression with a type operand.
545 ExprResult
Sema::BuildCXXTypeId(QualType TypeInfoType
,
546 SourceLocation TypeidLoc
,
547 TypeSourceInfo
*Operand
,
548 SourceLocation RParenLoc
) {
549 // C++ [expr.typeid]p4:
550 // The top-level cv-qualifiers of the lvalue expression or the type-id
551 // that is the operand of typeid are always ignored.
552 // If the type of the type-id is a class type or a reference to a class
553 // type, the class shall be completely-defined.
556 = Context
.getUnqualifiedArrayType(Operand
->getType().getNonReferenceType(),
558 if (T
->getAs
<RecordType
>() &&
559 RequireCompleteType(TypeidLoc
, T
, diag::err_incomplete_typeid
))
562 if (T
->isVariablyModifiedType())
563 return ExprError(Diag(TypeidLoc
, diag::err_variably_modified_typeid
) << T
);
565 if (CheckQualifiedFunctionForTypeId(T
, TypeidLoc
))
568 return new (Context
) CXXTypeidExpr(TypeInfoType
.withConst(), Operand
,
569 SourceRange(TypeidLoc
, RParenLoc
));
572 /// Build a C++ typeid expression with an expression operand.
573 ExprResult
Sema::BuildCXXTypeId(QualType TypeInfoType
,
574 SourceLocation TypeidLoc
,
576 SourceLocation RParenLoc
) {
577 bool WasEvaluated
= false;
578 if (E
&& !E
->isTypeDependent()) {
579 if (E
->hasPlaceholderType()) {
580 ExprResult result
= CheckPlaceholderExpr(E
);
581 if (result
.isInvalid()) return ExprError();
585 QualType T
= E
->getType();
586 if (const RecordType
*RecordT
= T
->getAs
<RecordType
>()) {
587 CXXRecordDecl
*RecordD
= cast
<CXXRecordDecl
>(RecordT
->getDecl());
588 // C++ [expr.typeid]p3:
589 // [...] If the type of the expression is a class type, the class
590 // shall be completely-defined.
591 if (RequireCompleteType(TypeidLoc
, T
, diag::err_incomplete_typeid
))
594 // C++ [expr.typeid]p3:
595 // When typeid is applied to an expression other than an glvalue of a
596 // polymorphic class type [...] [the] expression is an unevaluated
598 if (RecordD
->isPolymorphic() && E
->isGLValue()) {
599 if (isUnevaluatedContext()) {
600 // The operand was processed in unevaluated context, switch the
601 // context and recheck the subexpression.
602 ExprResult Result
= TransformToPotentiallyEvaluated(E
);
603 if (Result
.isInvalid())
608 // We require a vtable to query the type at run time.
609 MarkVTableUsed(TypeidLoc
, RecordD
);
614 ExprResult Result
= CheckUnevaluatedOperand(E
);
615 if (Result
.isInvalid())
619 // C++ [expr.typeid]p4:
620 // [...] If the type of the type-id is a reference to a possibly
621 // cv-qualified type, the result of the typeid expression refers to a
622 // std::type_info object representing the cv-unqualified referenced
625 QualType UnqualT
= Context
.getUnqualifiedArrayType(T
, Quals
);
626 if (!Context
.hasSameType(T
, UnqualT
)) {
628 E
= ImpCastExprToType(E
, UnqualT
, CK_NoOp
, E
->getValueKind()).get();
632 if (E
->getType()->isVariablyModifiedType())
633 return ExprError(Diag(TypeidLoc
, diag::err_variably_modified_typeid
)
635 else if (!inTemplateInstantiation() &&
636 E
->HasSideEffects(Context
, WasEvaluated
)) {
637 // The expression operand for typeid is in an unevaluated expression
638 // context, so side effects could result in unintended consequences.
639 Diag(E
->getExprLoc(), WasEvaluated
640 ? diag::warn_side_effects_typeid
641 : diag::warn_side_effects_unevaluated_context
);
644 return new (Context
) CXXTypeidExpr(TypeInfoType
.withConst(), E
,
645 SourceRange(TypeidLoc
, RParenLoc
));
648 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
650 Sema::ActOnCXXTypeid(SourceLocation OpLoc
, SourceLocation LParenLoc
,
651 bool isType
, void *TyOrExpr
, SourceLocation RParenLoc
) {
652 // typeid is not supported in OpenCL.
653 if (getLangOpts().OpenCLCPlusPlus
) {
654 return ExprError(Diag(OpLoc
, diag::err_openclcxx_not_supported
)
658 // Find the std::type_info type.
659 if (!getStdNamespace())
660 return ExprError(Diag(OpLoc
, diag::err_need_header_before_typeid
));
662 if (!CXXTypeInfoDecl
) {
663 IdentifierInfo
*TypeInfoII
= &PP
.getIdentifierTable().get("type_info");
664 LookupResult
R(*this, TypeInfoII
, SourceLocation(), LookupTagName
);
665 LookupQualifiedName(R
, getStdNamespace());
666 CXXTypeInfoDecl
= R
.getAsSingle
<RecordDecl
>();
667 // Microsoft's typeinfo doesn't have type_info in std but in the global
668 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
669 if (!CXXTypeInfoDecl
&& LangOpts
.MSVCCompat
) {
670 LookupQualifiedName(R
, Context
.getTranslationUnitDecl());
671 CXXTypeInfoDecl
= R
.getAsSingle
<RecordDecl
>();
673 if (!CXXTypeInfoDecl
)
674 return ExprError(Diag(OpLoc
, diag::err_need_header_before_typeid
));
677 if (!getLangOpts().RTTI
) {
678 return ExprError(Diag(OpLoc
, diag::err_no_typeid_with_fno_rtti
));
681 QualType TypeInfoType
= Context
.getTypeDeclType(CXXTypeInfoDecl
);
684 // The operand is a type; handle it as such.
685 TypeSourceInfo
*TInfo
= nullptr;
686 QualType T
= GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr
),
692 TInfo
= Context
.getTrivialTypeSourceInfo(T
, OpLoc
);
694 return BuildCXXTypeId(TypeInfoType
, OpLoc
, TInfo
, RParenLoc
);
697 // The operand is an expression.
699 BuildCXXTypeId(TypeInfoType
, OpLoc
, (Expr
*)TyOrExpr
, RParenLoc
);
701 if (!getLangOpts().RTTIData
&& !Result
.isInvalid())
702 if (auto *CTE
= dyn_cast
<CXXTypeidExpr
>(Result
.get()))
703 if (CTE
->isPotentiallyEvaluated() && !CTE
->isMostDerived(Context
))
704 Diag(OpLoc
, diag::warn_no_typeid_with_rtti_disabled
)
705 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
706 DiagnosticOptions::MSVC
);
710 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
713 getUuidAttrOfType(Sema
&SemaRef
, QualType QT
,
714 llvm::SmallSetVector
<const UuidAttr
*, 1> &UuidAttrs
) {
715 // Optionally remove one level of pointer, reference or array indirection.
716 const Type
*Ty
= QT
.getTypePtr();
717 if (QT
->isPointerType() || QT
->isReferenceType())
718 Ty
= QT
->getPointeeType().getTypePtr();
719 else if (QT
->isArrayType())
720 Ty
= Ty
->getBaseElementTypeUnsafe();
722 const auto *TD
= Ty
->getAsTagDecl();
726 if (const auto *Uuid
= TD
->getMostRecentDecl()->getAttr
<UuidAttr
>()) {
727 UuidAttrs
.insert(Uuid
);
731 // __uuidof can grab UUIDs from template arguments.
732 if (const auto *CTSD
= dyn_cast
<ClassTemplateSpecializationDecl
>(TD
)) {
733 const TemplateArgumentList
&TAL
= CTSD
->getTemplateArgs();
734 for (const TemplateArgument
&TA
: TAL
.asArray()) {
735 const UuidAttr
*UuidForTA
= nullptr;
736 if (TA
.getKind() == TemplateArgument::Type
)
737 getUuidAttrOfType(SemaRef
, TA
.getAsType(), UuidAttrs
);
738 else if (TA
.getKind() == TemplateArgument::Declaration
)
739 getUuidAttrOfType(SemaRef
, TA
.getAsDecl()->getType(), UuidAttrs
);
742 UuidAttrs
.insert(UuidForTA
);
747 /// Build a Microsoft __uuidof expression with a type operand.
748 ExprResult
Sema::BuildCXXUuidof(QualType Type
,
749 SourceLocation TypeidLoc
,
750 TypeSourceInfo
*Operand
,
751 SourceLocation RParenLoc
) {
752 MSGuidDecl
*Guid
= nullptr;
753 if (!Operand
->getType()->isDependentType()) {
754 llvm::SmallSetVector
<const UuidAttr
*, 1> UuidAttrs
;
755 getUuidAttrOfType(*this, Operand
->getType(), UuidAttrs
);
756 if (UuidAttrs
.empty())
757 return ExprError(Diag(TypeidLoc
, diag::err_uuidof_without_guid
));
758 if (UuidAttrs
.size() > 1)
759 return ExprError(Diag(TypeidLoc
, diag::err_uuidof_with_multiple_guids
));
760 Guid
= UuidAttrs
.back()->getGuidDecl();
764 CXXUuidofExpr(Type
, Operand
, Guid
, SourceRange(TypeidLoc
, RParenLoc
));
767 /// Build a Microsoft __uuidof expression with an expression operand.
768 ExprResult
Sema::BuildCXXUuidof(QualType Type
, SourceLocation TypeidLoc
,
769 Expr
*E
, SourceLocation RParenLoc
) {
770 MSGuidDecl
*Guid
= nullptr;
771 if (!E
->getType()->isDependentType()) {
772 if (E
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
)) {
773 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
774 Guid
= Context
.getMSGuidDecl(MSGuidDecl::Parts
{});
776 llvm::SmallSetVector
<const UuidAttr
*, 1> UuidAttrs
;
777 getUuidAttrOfType(*this, E
->getType(), UuidAttrs
);
778 if (UuidAttrs
.empty())
779 return ExprError(Diag(TypeidLoc
, diag::err_uuidof_without_guid
));
780 if (UuidAttrs
.size() > 1)
781 return ExprError(Diag(TypeidLoc
, diag::err_uuidof_with_multiple_guids
));
782 Guid
= UuidAttrs
.back()->getGuidDecl();
787 CXXUuidofExpr(Type
, E
, Guid
, SourceRange(TypeidLoc
, RParenLoc
));
790 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
792 Sema::ActOnCXXUuidof(SourceLocation OpLoc
, SourceLocation LParenLoc
,
793 bool isType
, void *TyOrExpr
, SourceLocation RParenLoc
) {
794 QualType GuidType
= Context
.getMSGuidType();
798 // The operand is a type; handle it as such.
799 TypeSourceInfo
*TInfo
= nullptr;
800 QualType T
= GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr
),
806 TInfo
= Context
.getTrivialTypeSourceInfo(T
, OpLoc
);
808 return BuildCXXUuidof(GuidType
, OpLoc
, TInfo
, RParenLoc
);
811 // The operand is an expression.
812 return BuildCXXUuidof(GuidType
, OpLoc
, (Expr
*)TyOrExpr
, RParenLoc
);
815 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
817 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc
, tok::TokenKind Kind
) {
818 assert((Kind
== tok::kw_true
|| Kind
== tok::kw_false
) &&
819 "Unknown C++ Boolean value!");
821 CXXBoolLiteralExpr(Kind
== tok::kw_true
, Context
.BoolTy
, OpLoc
);
824 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
826 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc
) {
827 return new (Context
) CXXNullPtrLiteralExpr(Context
.NullPtrTy
, Loc
);
830 /// ActOnCXXThrow - Parse throw expressions.
832 Sema::ActOnCXXThrow(Scope
*S
, SourceLocation OpLoc
, Expr
*Ex
) {
833 bool IsThrownVarInScope
= false;
835 // C++0x [class.copymove]p31:
836 // When certain criteria are met, an implementation is allowed to omit the
837 // copy/move construction of a class object [...]
839 // - in a throw-expression, when the operand is the name of a
840 // non-volatile automatic object (other than a function or catch-
841 // clause parameter) whose scope does not extend beyond the end of the
842 // innermost enclosing try-block (if there is one), the copy/move
843 // operation from the operand to the exception object (15.1) can be
844 // omitted by constructing the automatic object directly into the
846 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Ex
->IgnoreParens()))
847 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
848 if (Var
->hasLocalStorage() && !Var
->getType().isVolatileQualified()) {
849 for( ; S
; S
= S
->getParent()) {
850 if (S
->isDeclScope(Var
)) {
851 IsThrownVarInScope
= true;
855 // FIXME: Many of the scope checks here seem incorrect.
857 (Scope::FnScope
| Scope::ClassScope
| Scope::BlockScope
|
858 Scope::ObjCMethodScope
| Scope::TryScope
))
865 return BuildCXXThrow(OpLoc
, Ex
, IsThrownVarInScope
);
868 ExprResult
Sema::BuildCXXThrow(SourceLocation OpLoc
, Expr
*Ex
,
869 bool IsThrownVarInScope
) {
870 const llvm::Triple
&T
= Context
.getTargetInfo().getTriple();
871 const bool IsOpenMPGPUTarget
=
872 getLangOpts().OpenMPIsTargetDevice
&& (T
.isNVPTX() || T
.isAMDGCN());
873 // Don't report an error if 'throw' is used in system headers or in an OpenMP
874 // target region compiled for a GPU architecture.
875 if (!IsOpenMPGPUTarget
&& !getLangOpts().CXXExceptions
&&
876 !getSourceManager().isInSystemHeader(OpLoc
) && !getLangOpts().CUDA
) {
877 // Delay error emission for the OpenMP device code.
878 targetDiag(OpLoc
, diag::err_exceptions_disabled
) << "throw";
881 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
882 if (IsOpenMPGPUTarget
)
883 targetDiag(OpLoc
, diag::warn_throw_not_valid_on_target
) << T
.str();
885 // Exceptions aren't allowed in CUDA device code.
886 if (getLangOpts().CUDA
)
887 CUDADiagIfDeviceCode(OpLoc
, diag::err_cuda_device_exceptions
)
888 << "throw" << CurrentCUDATarget();
890 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
891 Diag(OpLoc
, diag::err_omp_simd_region_cannot_use_stmt
) << "throw";
893 if (Ex
&& !Ex
->isTypeDependent()) {
894 // Initialize the exception result. This implicitly weeds out
895 // abstract types or types with inaccessible copy constructors.
897 // C++0x [class.copymove]p31:
898 // When certain criteria are met, an implementation is allowed to omit the
899 // copy/move construction of a class object [...]
901 // - in a throw-expression, when the operand is the name of a
902 // non-volatile automatic object (other than a function or
904 // parameter) whose scope does not extend beyond the end of the
905 // innermost enclosing try-block (if there is one), the copy/move
906 // operation from the operand to the exception object (15.1) can be
907 // omitted by constructing the automatic object directly into the
909 NamedReturnInfo NRInfo
=
910 IsThrownVarInScope
? getNamedReturnInfo(Ex
) : NamedReturnInfo();
912 QualType ExceptionObjectTy
= Context
.getExceptionObjectType(Ex
->getType());
913 if (CheckCXXThrowOperand(OpLoc
, ExceptionObjectTy
, Ex
))
916 InitializedEntity Entity
=
917 InitializedEntity::InitializeException(OpLoc
, ExceptionObjectTy
);
918 ExprResult Res
= PerformMoveOrCopyInitialization(Entity
, NRInfo
, Ex
);
924 // PPC MMA non-pointer types are not allowed as throw expr types.
925 if (Ex
&& Context
.getTargetInfo().getTriple().isPPC64())
926 CheckPPCMMAType(Ex
->getType(), Ex
->getBeginLoc());
929 CXXThrowExpr(Ex
, Context
.VoidTy
, OpLoc
, IsThrownVarInScope
);
933 collectPublicBases(CXXRecordDecl
*RD
,
934 llvm::DenseMap
<CXXRecordDecl
*, unsigned> &SubobjectsSeen
,
935 llvm::SmallPtrSetImpl
<CXXRecordDecl
*> &VBases
,
936 llvm::SetVector
<CXXRecordDecl
*> &PublicSubobjectsSeen
,
937 bool ParentIsPublic
) {
938 for (const CXXBaseSpecifier
&BS
: RD
->bases()) {
939 CXXRecordDecl
*BaseDecl
= BS
.getType()->getAsCXXRecordDecl();
941 // Virtual bases constitute the same subobject. Non-virtual bases are
942 // always distinct subobjects.
944 NewSubobject
= VBases
.insert(BaseDecl
).second
;
949 ++SubobjectsSeen
[BaseDecl
];
951 // Only add subobjects which have public access throughout the entire chain.
952 bool PublicPath
= ParentIsPublic
&& BS
.getAccessSpecifier() == AS_public
;
954 PublicSubobjectsSeen
.insert(BaseDecl
);
956 // Recurse on to each base subobject.
957 collectPublicBases(BaseDecl
, SubobjectsSeen
, VBases
, PublicSubobjectsSeen
,
962 static void getUnambiguousPublicSubobjects(
963 CXXRecordDecl
*RD
, llvm::SmallVectorImpl
<CXXRecordDecl
*> &Objects
) {
964 llvm::DenseMap
<CXXRecordDecl
*, unsigned> SubobjectsSeen
;
965 llvm::SmallSet
<CXXRecordDecl
*, 2> VBases
;
966 llvm::SetVector
<CXXRecordDecl
*> PublicSubobjectsSeen
;
967 SubobjectsSeen
[RD
] = 1;
968 PublicSubobjectsSeen
.insert(RD
);
969 collectPublicBases(RD
, SubobjectsSeen
, VBases
, PublicSubobjectsSeen
,
970 /*ParentIsPublic=*/true);
972 for (CXXRecordDecl
*PublicSubobject
: PublicSubobjectsSeen
) {
973 // Skip ambiguous objects.
974 if (SubobjectsSeen
[PublicSubobject
] > 1)
977 Objects
.push_back(PublicSubobject
);
981 /// CheckCXXThrowOperand - Validate the operand of a throw.
982 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc
,
983 QualType ExceptionObjectTy
, Expr
*E
) {
984 // If the type of the exception would be an incomplete type or a pointer
985 // to an incomplete type other than (cv) void the program is ill-formed.
986 QualType Ty
= ExceptionObjectTy
;
987 bool isPointer
= false;
988 if (const PointerType
* Ptr
= Ty
->getAs
<PointerType
>()) {
989 Ty
= Ptr
->getPointeeType();
993 // Cannot throw WebAssembly reference type.
994 if (Ty
.isWebAssemblyReferenceType()) {
995 Diag(ThrowLoc
, diag::err_wasm_reftype_tc
) << 0 << E
->getSourceRange();
999 // Cannot throw WebAssembly table.
1000 if (isPointer
&& Ty
.isWebAssemblyReferenceType()) {
1001 Diag(ThrowLoc
, diag::err_wasm_table_art
) << 2 << E
->getSourceRange();
1005 if (!isPointer
|| !Ty
->isVoidType()) {
1006 if (RequireCompleteType(ThrowLoc
, Ty
,
1007 isPointer
? diag::err_throw_incomplete_ptr
1008 : diag::err_throw_incomplete
,
1009 E
->getSourceRange()))
1012 if (!isPointer
&& Ty
->isSizelessType()) {
1013 Diag(ThrowLoc
, diag::err_throw_sizeless
) << Ty
<< E
->getSourceRange();
1017 if (RequireNonAbstractType(ThrowLoc
, ExceptionObjectTy
,
1018 diag::err_throw_abstract_type
, E
))
1022 // If the exception has class type, we need additional handling.
1023 CXXRecordDecl
*RD
= Ty
->getAsCXXRecordDecl();
1027 // If we are throwing a polymorphic class type or pointer thereof,
1028 // exception handling will make use of the vtable.
1029 MarkVTableUsed(ThrowLoc
, RD
);
1031 // If a pointer is thrown, the referenced object will not be destroyed.
1035 // If the class has a destructor, we must be able to call it.
1036 if (!RD
->hasIrrelevantDestructor()) {
1037 if (CXXDestructorDecl
*Destructor
= LookupDestructor(RD
)) {
1038 MarkFunctionReferenced(E
->getExprLoc(), Destructor
);
1039 CheckDestructorAccess(E
->getExprLoc(), Destructor
,
1040 PDiag(diag::err_access_dtor_exception
) << Ty
);
1041 if (DiagnoseUseOfDecl(Destructor
, E
->getExprLoc()))
1046 // The MSVC ABI creates a list of all types which can catch the exception
1047 // object. This list also references the appropriate copy constructor to call
1048 // if the object is caught by value and has a non-trivial copy constructor.
1049 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
1050 // We are only interested in the public, unambiguous bases contained within
1051 // the exception object. Bases which are ambiguous or otherwise
1052 // inaccessible are not catchable types.
1053 llvm::SmallVector
<CXXRecordDecl
*, 2> UnambiguousPublicSubobjects
;
1054 getUnambiguousPublicSubobjects(RD
, UnambiguousPublicSubobjects
);
1056 for (CXXRecordDecl
*Subobject
: UnambiguousPublicSubobjects
) {
1057 // Attempt to lookup the copy constructor. Various pieces of machinery
1058 // will spring into action, like template instantiation, which means this
1059 // cannot be a simple walk of the class's decls. Instead, we must perform
1060 // lookup and overload resolution.
1061 CXXConstructorDecl
*CD
= LookupCopyingConstructor(Subobject
, 0);
1062 if (!CD
|| CD
->isDeleted())
1065 // Mark the constructor referenced as it is used by this throw expression.
1066 MarkFunctionReferenced(E
->getExprLoc(), CD
);
1068 // Skip this copy constructor if it is trivial, we don't need to record it
1069 // in the catchable type data.
1070 if (CD
->isTrivial())
1073 // The copy constructor is non-trivial, create a mapping from this class
1074 // type to this constructor.
1075 // N.B. The selection of copy constructor is not sensitive to this
1076 // particular throw-site. Lookup will be performed at the catch-site to
1077 // ensure that the copy constructor is, in fact, accessible (via
1078 // friendship or any other means).
1079 Context
.addCopyConstructorForExceptionObject(Subobject
, CD
);
1081 // We don't keep the instantiated default argument expressions around so
1082 // we must rebuild them here.
1083 for (unsigned I
= 1, E
= CD
->getNumParams(); I
!= E
; ++I
) {
1084 if (CheckCXXDefaultArgExpr(ThrowLoc
, CD
, CD
->getParamDecl(I
)))
1090 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1091 // the runtime with no ability for the compiler to request additional
1092 // alignment. Warn if the exception type requires alignment beyond the minimum
1093 // guaranteed by the target C++ runtime.
1094 if (Context
.getTargetInfo().getCXXABI().isItaniumFamily()) {
1095 CharUnits TypeAlign
= Context
.getTypeAlignInChars(Ty
);
1096 CharUnits ExnObjAlign
= Context
.getExnObjectAlignment();
1097 if (ExnObjAlign
< TypeAlign
) {
1098 Diag(ThrowLoc
, diag::warn_throw_underaligned_obj
);
1099 Diag(ThrowLoc
, diag::note_throw_underaligned_obj
)
1100 << Ty
<< (unsigned)TypeAlign
.getQuantity()
1101 << (unsigned)ExnObjAlign
.getQuantity();
1108 static QualType
adjustCVQualifiersForCXXThisWithinLambda(
1109 ArrayRef
<FunctionScopeInfo
*> FunctionScopes
, QualType ThisTy
,
1110 DeclContext
*CurSemaContext
, ASTContext
&ASTCtx
) {
1112 QualType ClassType
= ThisTy
->getPointeeType();
1113 LambdaScopeInfo
*CurLSI
= nullptr;
1114 DeclContext
*CurDC
= CurSemaContext
;
1116 // Iterate through the stack of lambdas starting from the innermost lambda to
1117 // the outermost lambda, checking if '*this' is ever captured by copy - since
1118 // that could change the cv-qualifiers of the '*this' object.
1119 // The object referred to by '*this' starts out with the cv-qualifiers of its
1120 // member function. We then start with the innermost lambda and iterate
1121 // outward checking to see if any lambda performs a by-copy capture of '*this'
1122 // - and if so, any nested lambda must respect the 'constness' of that
1123 // capturing lamdbda's call operator.
1126 // Since the FunctionScopeInfo stack is representative of the lexical
1127 // nesting of the lambda expressions during initial parsing (and is the best
1128 // place for querying information about captures about lambdas that are
1129 // partially processed) and perhaps during instantiation of function templates
1130 // that contain lambda expressions that need to be transformed BUT not
1131 // necessarily during instantiation of a nested generic lambda's function call
1132 // operator (which might even be instantiated at the end of the TU) - at which
1133 // time the DeclContext tree is mature enough to query capture information
1134 // reliably - we use a two pronged approach to walk through all the lexically
1135 // enclosing lambda expressions:
1137 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1138 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1139 // enclosed by the call-operator of the LSI below it on the stack (while
1140 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1141 // the stack represents the innermost lambda.
1143 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1144 // represents a lambda's call operator. If it does, we must be instantiating
1145 // a generic lambda's call operator (represented by the Current LSI, and
1146 // should be the only scenario where an inconsistency between the LSI and the
1147 // DeclContext should occur), so climb out the DeclContexts if they
1148 // represent lambdas, while querying the corresponding closure types
1149 // regarding capture information.
1151 // 1) Climb down the function scope info stack.
1152 for (int I
= FunctionScopes
.size();
1153 I
-- && isa
<LambdaScopeInfo
>(FunctionScopes
[I
]) &&
1154 (!CurLSI
|| !CurLSI
->Lambda
|| CurLSI
->Lambda
->getDeclContext() ==
1155 cast
<LambdaScopeInfo
>(FunctionScopes
[I
])->CallOperator
);
1156 CurDC
= getLambdaAwareParentOfDeclContext(CurDC
)) {
1157 CurLSI
= cast
<LambdaScopeInfo
>(FunctionScopes
[I
]);
1159 if (!CurLSI
->isCXXThisCaptured())
1162 auto C
= CurLSI
->getCXXThisCapture();
1164 if (C
.isCopyCapture()) {
1165 if (CurLSI
->lambdaCaptureShouldBeConst())
1166 ClassType
.addConst();
1167 return ASTCtx
.getPointerType(ClassType
);
1171 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1172 // can happen during instantiation of its nested generic lambda call
1173 // operator); 2. if we're in a lambda scope (lambda body).
1174 if (CurLSI
&& isLambdaCallOperator(CurDC
)) {
1175 assert(isGenericLambdaCallOperatorSpecialization(CurLSI
->CallOperator
) &&
1176 "While computing 'this' capture-type for a generic lambda, when we "
1177 "run out of enclosing LSI's, yet the enclosing DC is a "
1178 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1179 "lambda call oeprator");
1180 assert(CurDC
== getLambdaAwareParentOfDeclContext(CurLSI
->CallOperator
));
1182 auto IsThisCaptured
=
1183 [](CXXRecordDecl
*Closure
, bool &IsByCopy
, bool &IsConst
) {
1186 for (auto &&C
: Closure
->captures()) {
1187 if (C
.capturesThis()) {
1188 if (C
.getCaptureKind() == LCK_StarThis
)
1190 if (Closure
->getLambdaCallOperator()->isConst())
1198 bool IsByCopyCapture
= false;
1199 bool IsConstCapture
= false;
1200 CXXRecordDecl
*Closure
= cast
<CXXRecordDecl
>(CurDC
->getParent());
1202 IsThisCaptured(Closure
, IsByCopyCapture
, IsConstCapture
)) {
1203 if (IsByCopyCapture
) {
1205 ClassType
.addConst();
1206 return ASTCtx
.getPointerType(ClassType
);
1208 Closure
= isLambdaCallOperator(Closure
->getParent())
1209 ? cast
<CXXRecordDecl
>(Closure
->getParent()->getParent())
1213 return ASTCtx
.getPointerType(ClassType
);
1216 QualType
Sema::getCurrentThisType() {
1217 DeclContext
*DC
= getFunctionLevelDeclContext();
1218 QualType ThisTy
= CXXThisTypeOverride
;
1220 if (CXXMethodDecl
*method
= dyn_cast
<CXXMethodDecl
>(DC
)) {
1221 if (method
&& method
->isImplicitObjectMemberFunction())
1222 ThisTy
= method
->getThisType().getNonReferenceType();
1225 if (ThisTy
.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext
) &&
1226 inTemplateInstantiation() && isa
<CXXRecordDecl
>(DC
)) {
1228 // This is a lambda call operator that is being instantiated as a default
1229 // initializer. DC must point to the enclosing class type, so we can recover
1230 // the 'this' type from it.
1231 QualType ClassTy
= Context
.getTypeDeclType(cast
<CXXRecordDecl
>(DC
));
1232 // There are no cv-qualifiers for 'this' within default initializers,
1233 // per [expr.prim.general]p4.
1234 ThisTy
= Context
.getPointerType(ClassTy
);
1237 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1238 // might need to be adjusted if the lambda or any of its enclosing lambda's
1239 // captures '*this' by copy.
1240 if (!ThisTy
.isNull() && isLambdaCallOperator(CurContext
))
1241 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes
, ThisTy
,
1242 CurContext
, Context
);
1246 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema
&S
,
1248 Qualifiers CXXThisTypeQuals
,
1250 : S(S
), OldCXXThisTypeOverride(S
.CXXThisTypeOverride
), Enabled(false)
1252 if (!Enabled
|| !ContextDecl
)
1255 CXXRecordDecl
*Record
= nullptr;
1256 if (ClassTemplateDecl
*Template
= dyn_cast
<ClassTemplateDecl
>(ContextDecl
))
1257 Record
= Template
->getTemplatedDecl();
1259 Record
= cast
<CXXRecordDecl
>(ContextDecl
);
1261 QualType T
= S
.Context
.getRecordType(Record
);
1262 T
= S
.getASTContext().getQualifiedType(T
, CXXThisTypeQuals
);
1264 S
.CXXThisTypeOverride
=
1265 S
.Context
.getLangOpts().HLSL
? T
: S
.Context
.getPointerType(T
);
1267 this->Enabled
= true;
1271 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1273 S
.CXXThisTypeOverride
= OldCXXThisTypeOverride
;
1277 static void buildLambdaThisCaptureFixit(Sema
&Sema
, LambdaScopeInfo
*LSI
) {
1278 SourceLocation DiagLoc
= LSI
->IntroducerRange
.getEnd();
1279 assert(!LSI
->isCXXThisCaptured());
1280 // [=, this] {}; // until C++20: Error: this when = is the default
1281 if (LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_LambdaByval
&&
1282 !Sema
.getLangOpts().CPlusPlus20
)
1284 Sema
.Diag(DiagLoc
, diag::note_lambda_this_capture_fixit
)
1285 << FixItHint::CreateInsertion(
1286 DiagLoc
, LSI
->NumExplicitCaptures
> 0 ? ", this" : "this");
1289 bool Sema::CheckCXXThisCapture(SourceLocation Loc
, const bool Explicit
,
1290 bool BuildAndDiagnose
, const unsigned *const FunctionScopeIndexToStopAt
,
1291 const bool ByCopy
) {
1292 // We don't need to capture this in an unevaluated context.
1293 if (isUnevaluatedContext() && !Explicit
)
1296 assert((!ByCopy
|| Explicit
) && "cannot implicitly capture *this by value");
1298 const int MaxFunctionScopesIndex
= FunctionScopeIndexToStopAt
1299 ? *FunctionScopeIndexToStopAt
1300 : FunctionScopes
.size() - 1;
1302 // Check that we can capture the *enclosing object* (referred to by '*this')
1303 // by the capturing-entity/closure (lambda/block/etc) at
1304 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1306 // Note: The *enclosing object* can only be captured by-value by a
1307 // closure that is a lambda, using the explicit notation:
1309 // Every other capture of the *enclosing object* results in its by-reference
1312 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1313 // stack), we can capture the *enclosing object* only if:
1314 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1315 // - or, 'L' has an implicit capture.
1317 // -- there is no enclosing closure
1318 // -- or, there is some enclosing closure 'E' that has already captured the
1319 // *enclosing object*, and every intervening closure (if any) between 'E'
1320 // and 'L' can implicitly capture the *enclosing object*.
1321 // -- or, every enclosing closure can implicitly capture the
1322 // *enclosing object*
1325 unsigned NumCapturingClosures
= 0;
1326 for (int idx
= MaxFunctionScopesIndex
; idx
>= 0; idx
--) {
1327 if (CapturingScopeInfo
*CSI
=
1328 dyn_cast
<CapturingScopeInfo
>(FunctionScopes
[idx
])) {
1329 if (CSI
->CXXThisCaptureIndex
!= 0) {
1330 // 'this' is already being captured; there isn't anything more to do.
1331 CSI
->Captures
[CSI
->CXXThisCaptureIndex
- 1].markUsed(BuildAndDiagnose
);
1334 LambdaScopeInfo
*LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
);
1335 if (LSI
&& isGenericLambdaCallOperatorSpecialization(LSI
->CallOperator
)) {
1336 // This context can't implicitly capture 'this'; fail out.
1337 if (BuildAndDiagnose
) {
1338 LSI
->CallOperator
->setInvalidDecl();
1339 Diag(Loc
, diag::err_this_capture
)
1340 << (Explicit
&& idx
== MaxFunctionScopesIndex
);
1342 buildLambdaThisCaptureFixit(*this, LSI
);
1346 if (CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_LambdaByref
||
1347 CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_LambdaByval
||
1348 CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_Block
||
1349 CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_CapturedRegion
||
1350 (Explicit
&& idx
== MaxFunctionScopesIndex
)) {
1351 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1352 // iteration through can be an explicit capture, all enclosing closures,
1353 // if any, must perform implicit captures.
1355 // This closure can capture 'this'; continue looking upwards.
1356 NumCapturingClosures
++;
1359 // This context can't implicitly capture 'this'; fail out.
1360 if (BuildAndDiagnose
) {
1361 LSI
->CallOperator
->setInvalidDecl();
1362 Diag(Loc
, diag::err_this_capture
)
1363 << (Explicit
&& idx
== MaxFunctionScopesIndex
);
1366 buildLambdaThisCaptureFixit(*this, LSI
);
1371 if (!BuildAndDiagnose
) return false;
1373 // If we got here, then the closure at MaxFunctionScopesIndex on the
1374 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1375 // (including implicit by-reference captures in any enclosing closures).
1377 // In the loop below, respect the ByCopy flag only for the closure requesting
1378 // the capture (i.e. first iteration through the loop below). Ignore it for
1379 // all enclosing closure's up to NumCapturingClosures (since they must be
1380 // implicitly capturing the *enclosing object* by reference (see loop
1383 isa
<LambdaScopeInfo
>(FunctionScopes
[MaxFunctionScopesIndex
])) &&
1384 "Only a lambda can capture the enclosing object (referred to by "
1386 QualType ThisTy
= getCurrentThisType();
1387 for (int idx
= MaxFunctionScopesIndex
; NumCapturingClosures
;
1388 --idx
, --NumCapturingClosures
) {
1389 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FunctionScopes
[idx
]);
1391 // The type of the corresponding data member (not a 'this' pointer if 'by
1393 QualType CaptureType
= ByCopy
? ThisTy
->getPointeeType() : ThisTy
;
1395 bool isNested
= NumCapturingClosures
> 1;
1396 CSI
->addThisCapture(isNested
, Loc
, CaptureType
, ByCopy
);
1401 ExprResult
Sema::ActOnCXXThis(SourceLocation Loc
) {
1402 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1403 /// is a non-lvalue expression whose value is the address of the object for
1404 /// which the function is called.
1405 QualType ThisTy
= getCurrentThisType();
1407 if (ThisTy
.isNull()) {
1408 DeclContext
*DC
= getFunctionLevelDeclContext();
1410 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(DC
);
1411 Method
&& Method
->isExplicitObjectMemberFunction()) {
1412 return Diag(Loc
, diag::err_invalid_this_use
) << 1;
1415 if (isLambdaCallWithExplicitObjectParameter(CurContext
))
1416 return Diag(Loc
, diag::err_invalid_this_use
) << 1;
1418 return Diag(Loc
, diag::err_invalid_this_use
) << 0;
1421 return BuildCXXThisExpr(Loc
, ThisTy
, /*IsImplicit=*/false);
1424 Expr
*Sema::BuildCXXThisExpr(SourceLocation Loc
, QualType Type
,
1426 auto *This
= CXXThisExpr::Create(Context
, Loc
, Type
, IsImplicit
);
1427 MarkThisReferenced(This
);
1431 void Sema::MarkThisReferenced(CXXThisExpr
*This
) {
1432 CheckCXXThisCapture(This
->getExprLoc());
1435 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType
) {
1436 // If we're outside the body of a member function, then we'll have a specified
1438 if (CXXThisTypeOverride
.isNull())
1441 // Determine whether we're looking into a class that's currently being
1443 CXXRecordDecl
*Class
= BaseType
->getAsCXXRecordDecl();
1444 return Class
&& Class
->isBeingDefined();
1447 /// Parse construction of a specified type.
1448 /// Can be interpreted either as function-style casting ("int(x)")
1449 /// or class type construction ("ClassType(x,y,z)")
1450 /// or creation of a value-initialized type ("int()").
1452 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep
,
1453 SourceLocation LParenOrBraceLoc
,
1455 SourceLocation RParenOrBraceLoc
,
1456 bool ListInitialization
) {
1460 TypeSourceInfo
*TInfo
;
1461 QualType Ty
= GetTypeFromParser(TypeRep
, &TInfo
);
1463 TInfo
= Context
.getTrivialTypeSourceInfo(Ty
, SourceLocation());
1465 auto Result
= BuildCXXTypeConstructExpr(TInfo
, LParenOrBraceLoc
, exprs
,
1466 RParenOrBraceLoc
, ListInitialization
);
1467 // Avoid creating a non-type-dependent expression that contains typos.
1468 // Non-type-dependent expressions are liable to be discarded without
1469 // checking for embedded typos.
1470 if (!Result
.isInvalid() && Result
.get()->isInstantiationDependent() &&
1471 !Result
.get()->isTypeDependent())
1472 Result
= CorrectDelayedTyposInExpr(Result
.get());
1473 else if (Result
.isInvalid())
1474 Result
= CreateRecoveryExpr(TInfo
->getTypeLoc().getBeginLoc(),
1475 RParenOrBraceLoc
, exprs
, Ty
);
1480 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo
*TInfo
,
1481 SourceLocation LParenOrBraceLoc
,
1483 SourceLocation RParenOrBraceLoc
,
1484 bool ListInitialization
) {
1485 QualType Ty
= TInfo
->getType();
1486 SourceLocation TyBeginLoc
= TInfo
->getTypeLoc().getBeginLoc();
1488 assert((!ListInitialization
|| Exprs
.size() == 1) &&
1489 "List initialization must have exactly one expression.");
1490 SourceRange FullRange
= SourceRange(TyBeginLoc
, RParenOrBraceLoc
);
1492 InitializedEntity Entity
=
1493 InitializedEntity::InitializeTemporary(Context
, TInfo
);
1494 InitializationKind Kind
=
1496 ? ListInitialization
1497 ? InitializationKind::CreateDirectList(
1498 TyBeginLoc
, LParenOrBraceLoc
, RParenOrBraceLoc
)
1499 : InitializationKind::CreateDirect(TyBeginLoc
, LParenOrBraceLoc
,
1501 : InitializationKind::CreateValue(TyBeginLoc
, LParenOrBraceLoc
,
1504 // C++17 [expr.type.conv]p1:
1505 // If the type is a placeholder for a deduced class type, [...perform class
1506 // template argument deduction...]
1508 // Otherwise, if the type contains a placeholder type, it is replaced by the
1509 // type determined by placeholder type deduction.
1510 DeducedType
*Deduced
= Ty
->getContainedDeducedType();
1511 if (Deduced
&& !Deduced
->isDeduced() &&
1512 isa
<DeducedTemplateSpecializationType
>(Deduced
)) {
1513 Ty
= DeduceTemplateSpecializationFromInitializer(TInfo
, Entity
,
1517 Entity
= InitializedEntity::InitializeTemporary(TInfo
, Ty
);
1518 } else if (Deduced
&& !Deduced
->isDeduced()) {
1519 MultiExprArg Inits
= Exprs
;
1520 if (ListInitialization
) {
1521 auto *ILE
= cast
<InitListExpr
>(Exprs
[0]);
1522 Inits
= MultiExprArg(ILE
->getInits(), ILE
->getNumInits());
1526 return ExprError(Diag(TyBeginLoc
, diag::err_auto_expr_init_no_expression
)
1527 << Ty
<< FullRange
);
1528 if (Inits
.size() > 1) {
1529 Expr
*FirstBad
= Inits
[1];
1530 return ExprError(Diag(FirstBad
->getBeginLoc(),
1531 diag::err_auto_expr_init_multiple_expressions
)
1532 << Ty
<< FullRange
);
1534 if (getLangOpts().CPlusPlus23
) {
1535 if (Ty
->getAs
<AutoType
>())
1536 Diag(TyBeginLoc
, diag::warn_cxx20_compat_auto_expr
) << FullRange
;
1538 Expr
*Deduce
= Inits
[0];
1539 if (isa
<InitListExpr
>(Deduce
))
1541 Diag(Deduce
->getBeginLoc(), diag::err_auto_expr_init_paren_braces
)
1542 << ListInitialization
<< Ty
<< FullRange
);
1543 QualType DeducedType
;
1544 TemplateDeductionInfo
Info(Deduce
->getExprLoc());
1545 TemplateDeductionResult Result
=
1546 DeduceAutoType(TInfo
->getTypeLoc(), Deduce
, DeducedType
, Info
);
1547 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
)
1548 return ExprError(Diag(TyBeginLoc
, diag::err_auto_expr_deduction_failure
)
1549 << Ty
<< Deduce
->getType() << FullRange
1550 << Deduce
->getSourceRange());
1551 if (DeducedType
.isNull()) {
1552 assert(Result
== TDK_AlreadyDiagnosed
);
1557 Entity
= InitializedEntity::InitializeTemporary(TInfo
, Ty
);
1560 if (Ty
->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs
))
1561 return CXXUnresolvedConstructExpr::Create(
1562 Context
, Ty
.getNonReferenceType(), TInfo
, LParenOrBraceLoc
, Exprs
,
1563 RParenOrBraceLoc
, ListInitialization
);
1565 // C++ [expr.type.conv]p1:
1566 // If the expression list is a parenthesized single expression, the type
1567 // conversion expression is equivalent (in definedness, and if defined in
1568 // meaning) to the corresponding cast expression.
1569 if (Exprs
.size() == 1 && !ListInitialization
&&
1570 !isa
<InitListExpr
>(Exprs
[0])) {
1571 Expr
*Arg
= Exprs
[0];
1572 return BuildCXXFunctionalCastExpr(TInfo
, Ty
, LParenOrBraceLoc
, Arg
,
1576 // For an expression of the form T(), T shall not be an array type.
1577 QualType ElemTy
= Ty
;
1578 if (Ty
->isArrayType()) {
1579 if (!ListInitialization
)
1580 return ExprError(Diag(TyBeginLoc
, diag::err_value_init_for_array_type
)
1582 ElemTy
= Context
.getBaseElementType(Ty
);
1585 // Only construct objects with object types.
1586 // The standard doesn't explicitly forbid function types here, but that's an
1587 // obvious oversight, as there's no way to dynamically construct a function
1589 if (Ty
->isFunctionType())
1590 return ExprError(Diag(TyBeginLoc
, diag::err_init_for_function_type
)
1591 << Ty
<< FullRange
);
1593 // C++17 [expr.type.conv]p2:
1594 // If the type is cv void and the initializer is (), the expression is a
1595 // prvalue of the specified type that performs no initialization.
1596 if (!Ty
->isVoidType() &&
1597 RequireCompleteType(TyBeginLoc
, ElemTy
,
1598 diag::err_invalid_incomplete_type_use
, FullRange
))
1601 // Otherwise, the expression is a prvalue of the specified type whose
1602 // result object is direct-initialized (11.6) with the initializer.
1603 InitializationSequence
InitSeq(*this, Entity
, Kind
, Exprs
);
1604 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Exprs
);
1606 if (Result
.isInvalid())
1609 Expr
*Inner
= Result
.get();
1610 if (CXXBindTemporaryExpr
*BTE
= dyn_cast_or_null
<CXXBindTemporaryExpr
>(Inner
))
1611 Inner
= BTE
->getSubExpr();
1612 if (auto *CE
= dyn_cast
<ConstantExpr
>(Inner
);
1613 CE
&& CE
->isImmediateInvocation())
1614 Inner
= CE
->getSubExpr();
1615 if (!isa
<CXXTemporaryObjectExpr
>(Inner
) &&
1616 !isa
<CXXScalarValueInitExpr
>(Inner
)) {
1617 // If we created a CXXTemporaryObjectExpr, that node also represents the
1618 // functional cast. Otherwise, create an explicit cast to represent
1619 // the syntactic form of a functional-style cast that was used here.
1621 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1622 // would give a more consistent AST representation than using a
1623 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1624 // is sometimes handled by initialization and sometimes not.
1625 QualType ResultType
= Result
.get()->getType();
1626 SourceRange Locs
= ListInitialization
1628 : SourceRange(LParenOrBraceLoc
, RParenOrBraceLoc
);
1629 Result
= CXXFunctionalCastExpr::Create(
1630 Context
, ResultType
, Expr::getValueKindForType(Ty
), TInfo
, CK_NoOp
,
1631 Result
.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1632 Locs
.getBegin(), Locs
.getEnd());
1638 bool Sema::isUsualDeallocationFunction(const CXXMethodDecl
*Method
) {
1639 // [CUDA] Ignore this function, if we can't call it.
1640 const FunctionDecl
*Caller
= getCurFunctionDecl(/*AllowLambda=*/true);
1641 if (getLangOpts().CUDA
) {
1642 auto CallPreference
= IdentifyCUDAPreference(Caller
, Method
);
1643 // If it's not callable at all, it's not the right function.
1644 if (CallPreference
< CFP_WrongSide
)
1646 if (CallPreference
== CFP_WrongSide
) {
1647 // Maybe. We have to check if there are better alternatives.
1648 DeclContext::lookup_result R
=
1649 Method
->getDeclContext()->lookup(Method
->getDeclName());
1650 for (const auto *D
: R
) {
1651 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
1652 if (IdentifyCUDAPreference(Caller
, FD
) > CFP_WrongSide
)
1656 // We've found no better variants.
1660 SmallVector
<const FunctionDecl
*, 4> PreventedBy
;
1661 bool Result
= Method
->isUsualDeallocationFunction(PreventedBy
);
1663 if (Result
|| !getLangOpts().CUDA
|| PreventedBy
.empty())
1666 // In case of CUDA, return true if none of the 1-argument deallocator
1667 // functions are actually callable.
1668 return llvm::none_of(PreventedBy
, [&](const FunctionDecl
*FD
) {
1669 assert(FD
->getNumParams() == 1 &&
1670 "Only single-operand functions should be in PreventedBy");
1671 return IdentifyCUDAPreference(Caller
, FD
) >= CFP_HostDevice
;
1675 /// Determine whether the given function is a non-placement
1676 /// deallocation function.
1677 static bool isNonPlacementDeallocationFunction(Sema
&S
, FunctionDecl
*FD
) {
1678 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(FD
))
1679 return S
.isUsualDeallocationFunction(Method
);
1681 if (FD
->getOverloadedOperator() != OO_Delete
&&
1682 FD
->getOverloadedOperator() != OO_Array_Delete
)
1685 unsigned UsualParams
= 1;
1687 if (S
.getLangOpts().SizedDeallocation
&& UsualParams
< FD
->getNumParams() &&
1688 S
.Context
.hasSameUnqualifiedType(
1689 FD
->getParamDecl(UsualParams
)->getType(),
1690 S
.Context
.getSizeType()))
1693 if (S
.getLangOpts().AlignedAllocation
&& UsualParams
< FD
->getNumParams() &&
1694 S
.Context
.hasSameUnqualifiedType(
1695 FD
->getParamDecl(UsualParams
)->getType(),
1696 S
.Context
.getTypeDeclType(S
.getStdAlignValT())))
1699 return UsualParams
== FD
->getNumParams();
1703 struct UsualDeallocFnInfo
{
1704 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1705 UsualDeallocFnInfo(Sema
&S
, DeclAccessPair Found
)
1706 : Found(Found
), FD(dyn_cast
<FunctionDecl
>(Found
->getUnderlyingDecl())),
1707 Destroying(false), HasSizeT(false), HasAlignValT(false),
1708 CUDAPref(Sema::CFP_Native
) {
1709 // A function template declaration is never a usual deallocation function.
1712 unsigned NumBaseParams
= 1;
1713 if (FD
->isDestroyingOperatorDelete()) {
1718 if (NumBaseParams
< FD
->getNumParams() &&
1719 S
.Context
.hasSameUnqualifiedType(
1720 FD
->getParamDecl(NumBaseParams
)->getType(),
1721 S
.Context
.getSizeType())) {
1726 if (NumBaseParams
< FD
->getNumParams() &&
1727 FD
->getParamDecl(NumBaseParams
)->getType()->isAlignValT()) {
1729 HasAlignValT
= true;
1732 // In CUDA, determine how much we'd like / dislike to call this.
1733 if (S
.getLangOpts().CUDA
)
1734 CUDAPref
= S
.IdentifyCUDAPreference(
1735 S
.getCurFunctionDecl(/*AllowLambda=*/true), FD
);
1738 explicit operator bool() const { return FD
; }
1740 bool isBetterThan(const UsualDeallocFnInfo
&Other
, bool WantSize
,
1741 bool WantAlign
) const {
1743 // A destroying operator delete is preferred over a non-destroying
1745 if (Destroying
!= Other
.Destroying
)
1748 // C++17 [expr.delete]p10:
1749 // If the type has new-extended alignment, a function with a parameter
1750 // of type std::align_val_t is preferred; otherwise a function without
1751 // such a parameter is preferred
1752 if (HasAlignValT
!= Other
.HasAlignValT
)
1753 return HasAlignValT
== WantAlign
;
1755 if (HasSizeT
!= Other
.HasSizeT
)
1756 return HasSizeT
== WantSize
;
1758 // Use CUDA call preference as a tiebreaker.
1759 return CUDAPref
> Other
.CUDAPref
;
1762 DeclAccessPair Found
;
1764 bool Destroying
, HasSizeT
, HasAlignValT
;
1765 Sema::CUDAFunctionPreference CUDAPref
;
1769 /// Determine whether a type has new-extended alignment. This may be called when
1770 /// the type is incomplete (for a delete-expression with an incomplete pointee
1771 /// type), in which case it will conservatively return false if the alignment is
1773 static bool hasNewExtendedAlignment(Sema
&S
, QualType AllocType
) {
1774 return S
.getLangOpts().AlignedAllocation
&&
1775 S
.getASTContext().getTypeAlignIfKnown(AllocType
) >
1776 S
.getASTContext().getTargetInfo().getNewAlign();
1779 /// Select the correct "usual" deallocation function to use from a selection of
1780 /// deallocation functions (either global or class-scope).
1781 static UsualDeallocFnInfo
resolveDeallocationOverload(
1782 Sema
&S
, LookupResult
&R
, bool WantSize
, bool WantAlign
,
1783 llvm::SmallVectorImpl
<UsualDeallocFnInfo
> *BestFns
= nullptr) {
1784 UsualDeallocFnInfo Best
;
1786 for (auto I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
1787 UsualDeallocFnInfo
Info(S
, I
.getPair());
1788 if (!Info
|| !isNonPlacementDeallocationFunction(S
, Info
.FD
) ||
1789 Info
.CUDAPref
== Sema::CFP_Never
)
1795 BestFns
->push_back(Info
);
1799 if (Best
.isBetterThan(Info
, WantSize
, WantAlign
))
1802 // If more than one preferred function is found, all non-preferred
1803 // functions are eliminated from further consideration.
1804 if (BestFns
&& Info
.isBetterThan(Best
, WantSize
, WantAlign
))
1809 BestFns
->push_back(Info
);
1815 /// Determine whether a given type is a class for which 'delete[]' would call
1816 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1817 /// we need to store the array size (even if the type is
1818 /// trivially-destructible).
1819 static bool doesUsualArrayDeleteWantSize(Sema
&S
, SourceLocation loc
,
1820 QualType allocType
) {
1821 const RecordType
*record
=
1822 allocType
->getBaseElementTypeUnsafe()->getAs
<RecordType
>();
1823 if (!record
) return false;
1825 // Try to find an operator delete[] in class scope.
1827 DeclarationName deleteName
=
1828 S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Array_Delete
);
1829 LookupResult
ops(S
, deleteName
, loc
, Sema::LookupOrdinaryName
);
1830 S
.LookupQualifiedName(ops
, record
->getDecl());
1832 // We're just doing this for information.
1833 ops
.suppressDiagnostics();
1835 // Very likely: there's no operator delete[].
1836 if (ops
.empty()) return false;
1838 // If it's ambiguous, it should be illegal to call operator delete[]
1839 // on this thing, so it doesn't matter if we allocate extra space or not.
1840 if (ops
.isAmbiguous()) return false;
1842 // C++17 [expr.delete]p10:
1843 // If the deallocation functions have class scope, the one without a
1844 // parameter of type std::size_t is selected.
1845 auto Best
= resolveDeallocationOverload(
1846 S
, ops
, /*WantSize*/false,
1847 /*WantAlign*/hasNewExtendedAlignment(S
, allocType
));
1848 return Best
&& Best
.HasSizeT
;
1851 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1854 /// @code new (memory) int[size][4] @endcode
1856 /// @code ::new Foo(23, "hello") @endcode
1858 /// \param StartLoc The first location of the expression.
1859 /// \param UseGlobal True if 'new' was prefixed with '::'.
1860 /// \param PlacementLParen Opening paren of the placement arguments.
1861 /// \param PlacementArgs Placement new arguments.
1862 /// \param PlacementRParen Closing paren of the placement arguments.
1863 /// \param TypeIdParens If the type is in parens, the source range.
1864 /// \param D The type to be allocated, as well as array dimensions.
1865 /// \param Initializer The initializing expression or initializer-list, or null
1866 /// if there is none.
1868 Sema::ActOnCXXNew(SourceLocation StartLoc
, bool UseGlobal
,
1869 SourceLocation PlacementLParen
, MultiExprArg PlacementArgs
,
1870 SourceLocation PlacementRParen
, SourceRange TypeIdParens
,
1871 Declarator
&D
, Expr
*Initializer
) {
1872 std::optional
<Expr
*> ArraySize
;
1873 // If the specified type is an array, unwrap it and save the expression.
1874 if (D
.getNumTypeObjects() > 0 &&
1875 D
.getTypeObject(0).Kind
== DeclaratorChunk::Array
) {
1876 DeclaratorChunk
&Chunk
= D
.getTypeObject(0);
1877 if (D
.getDeclSpec().hasAutoTypeSpec())
1878 return ExprError(Diag(Chunk
.Loc
, diag::err_new_array_of_auto
)
1879 << D
.getSourceRange());
1880 if (Chunk
.Arr
.hasStatic
)
1881 return ExprError(Diag(Chunk
.Loc
, diag::err_static_illegal_in_new
)
1882 << D
.getSourceRange());
1883 if (!Chunk
.Arr
.NumElts
&& !Initializer
)
1884 return ExprError(Diag(Chunk
.Loc
, diag::err_array_new_needs_size
)
1885 << D
.getSourceRange());
1887 ArraySize
= static_cast<Expr
*>(Chunk
.Arr
.NumElts
);
1888 D
.DropFirstTypeObject();
1891 // Every dimension shall be of constant size.
1893 for (unsigned I
= 0, N
= D
.getNumTypeObjects(); I
< N
; ++I
) {
1894 if (D
.getTypeObject(I
).Kind
!= DeclaratorChunk::Array
)
1897 DeclaratorChunk::ArrayTypeInfo
&Array
= D
.getTypeObject(I
).Arr
;
1898 if (Expr
*NumElts
= (Expr
*)Array
.NumElts
) {
1899 if (!NumElts
->isTypeDependent() && !NumElts
->isValueDependent()) {
1900 // FIXME: GCC permits constant folding here. We should either do so consistently
1901 // or not do so at all, rather than changing behavior in C++14 onwards.
1902 if (getLangOpts().CPlusPlus14
) {
1903 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1904 // shall be a converted constant expression (5.19) of type std::size_t
1905 // and shall evaluate to a strictly positive value.
1906 llvm::APSInt
Value(Context
.getIntWidth(Context
.getSizeType()));
1908 = CheckConvertedConstantExpression(NumElts
, Context
.getSizeType(), Value
,
1913 VerifyIntegerConstantExpression(
1914 NumElts
, nullptr, diag::err_new_array_nonconst
, AllowFold
)
1924 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, /*Scope=*/nullptr);
1925 QualType AllocType
= TInfo
->getType();
1926 if (D
.isInvalidType())
1929 SourceRange DirectInitRange
;
1930 if (ParenListExpr
*List
= dyn_cast_or_null
<ParenListExpr
>(Initializer
))
1931 DirectInitRange
= List
->getSourceRange();
1933 return BuildCXXNew(SourceRange(StartLoc
, D
.getEndLoc()), UseGlobal
,
1934 PlacementLParen
, PlacementArgs
, PlacementRParen
,
1935 TypeIdParens
, AllocType
, TInfo
, ArraySize
, DirectInitRange
,
1939 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style
,
1943 if (ParenListExpr
*PLE
= dyn_cast
<ParenListExpr
>(Init
))
1944 return PLE
->getNumExprs() == 0;
1945 if (isa
<ImplicitValueInitExpr
>(Init
))
1947 else if (CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(Init
))
1948 return !CCE
->isListInitialization() &&
1949 CCE
->getConstructor()->isDefaultConstructor();
1950 else if (Style
== CXXNewExpr::ListInit
) {
1951 assert(isa
<InitListExpr
>(Init
) &&
1952 "Shouldn't create list CXXConstructExprs for arrays.");
1959 Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl
&FD
) const {
1960 if (!getLangOpts().AlignedAllocationUnavailable
)
1964 std::optional
<unsigned> AlignmentParam
;
1965 if (FD
.isReplaceableGlobalAllocationFunction(&AlignmentParam
) &&
1971 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1972 // implemented in the standard library is selected.
1973 void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl
&FD
,
1974 SourceLocation Loc
) {
1975 if (isUnavailableAlignedAllocationFunction(FD
)) {
1976 const llvm::Triple
&T
= getASTContext().getTargetInfo().getTriple();
1977 StringRef OSName
= AvailabilityAttr::getPlatformNameSourceSpelling(
1978 getASTContext().getTargetInfo().getPlatformName());
1979 VersionTuple OSVersion
= alignedAllocMinVersion(T
.getOS());
1981 OverloadedOperatorKind Kind
= FD
.getDeclName().getCXXOverloadedOperator();
1982 bool IsDelete
= Kind
== OO_Delete
|| Kind
== OO_Array_Delete
;
1983 Diag(Loc
, diag::err_aligned_allocation_unavailable
)
1984 << IsDelete
<< FD
.getType().getAsString() << OSName
1985 << OSVersion
.getAsString() << OSVersion
.empty();
1986 Diag(Loc
, diag::note_silence_aligned_allocation_unavailable
);
1990 ExprResult
Sema::BuildCXXNew(SourceRange Range
, bool UseGlobal
,
1991 SourceLocation PlacementLParen
,
1992 MultiExprArg PlacementArgs
,
1993 SourceLocation PlacementRParen
,
1994 SourceRange TypeIdParens
, QualType AllocType
,
1995 TypeSourceInfo
*AllocTypeInfo
,
1996 std::optional
<Expr
*> ArraySize
,
1997 SourceRange DirectInitRange
, Expr
*Initializer
) {
1998 SourceRange TypeRange
= AllocTypeInfo
->getTypeLoc().getSourceRange();
1999 SourceLocation StartLoc
= Range
.getBegin();
2001 CXXNewExpr::InitializationStyle initStyle
;
2002 if (DirectInitRange
.isValid()) {
2003 assert(Initializer
&& "Have parens but no initializer.");
2004 initStyle
= CXXNewExpr::CallInit
;
2005 } else if (Initializer
&& isa
<InitListExpr
>(Initializer
))
2006 initStyle
= CXXNewExpr::ListInit
;
2008 assert((!Initializer
|| isa
<ImplicitValueInitExpr
>(Initializer
) ||
2009 isa
<CXXConstructExpr
>(Initializer
)) &&
2010 "Initializer expression that cannot have been implicitly created.");
2011 initStyle
= CXXNewExpr::NoInit
;
2014 MultiExprArg
Exprs(&Initializer
, Initializer
? 1 : 0);
2015 if (ParenListExpr
*List
= dyn_cast_or_null
<ParenListExpr
>(Initializer
)) {
2016 assert(initStyle
== CXXNewExpr::CallInit
&& "paren init for non-call init");
2017 Exprs
= MultiExprArg(List
->getExprs(), List
->getNumExprs());
2020 // C++11 [expr.new]p15:
2021 // A new-expression that creates an object of type T initializes that
2022 // object as follows:
2023 InitializationKind Kind
2024 // - If the new-initializer is omitted, the object is default-
2025 // initialized (8.5); if no initialization is performed,
2026 // the object has indeterminate value
2027 = initStyle
== CXXNewExpr::NoInit
2028 ? InitializationKind::CreateDefault(TypeRange
.getBegin())
2029 // - Otherwise, the new-initializer is interpreted according to
2031 // initialization rules of 8.5 for direct-initialization.
2032 : initStyle
== CXXNewExpr::ListInit
2033 ? InitializationKind::CreateDirectList(
2034 TypeRange
.getBegin(), Initializer
->getBeginLoc(),
2035 Initializer
->getEndLoc())
2036 : InitializationKind::CreateDirect(TypeRange
.getBegin(),
2037 DirectInitRange
.getBegin(),
2038 DirectInitRange
.getEnd());
2040 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2041 auto *Deduced
= AllocType
->getContainedDeducedType();
2042 if (Deduced
&& !Deduced
->isDeduced() &&
2043 isa
<DeducedTemplateSpecializationType
>(Deduced
)) {
2046 Diag(*ArraySize
? (*ArraySize
)->getExprLoc() : TypeRange
.getBegin(),
2047 diag::err_deduced_class_template_compound_type
)
2049 << (*ArraySize
? (*ArraySize
)->getSourceRange() : TypeRange
));
2051 InitializedEntity Entity
2052 = InitializedEntity::InitializeNew(StartLoc
, AllocType
);
2053 AllocType
= DeduceTemplateSpecializationFromInitializer(
2054 AllocTypeInfo
, Entity
, Kind
, Exprs
);
2055 if (AllocType
.isNull())
2057 } else if (Deduced
&& !Deduced
->isDeduced()) {
2058 MultiExprArg Inits
= Exprs
;
2059 bool Braced
= (initStyle
== CXXNewExpr::ListInit
);
2061 auto *ILE
= cast
<InitListExpr
>(Exprs
[0]);
2062 Inits
= MultiExprArg(ILE
->getInits(), ILE
->getNumInits());
2065 if (initStyle
== CXXNewExpr::NoInit
|| Inits
.empty())
2066 return ExprError(Diag(StartLoc
, diag::err_auto_new_requires_ctor_arg
)
2067 << AllocType
<< TypeRange
);
2068 if (Inits
.size() > 1) {
2069 Expr
*FirstBad
= Inits
[1];
2070 return ExprError(Diag(FirstBad
->getBeginLoc(),
2071 diag::err_auto_new_ctor_multiple_expressions
)
2072 << AllocType
<< TypeRange
);
2074 if (Braced
&& !getLangOpts().CPlusPlus17
)
2075 Diag(Initializer
->getBeginLoc(), diag::ext_auto_new_list_init
)
2076 << AllocType
<< TypeRange
;
2077 Expr
*Deduce
= Inits
[0];
2078 if (isa
<InitListExpr
>(Deduce
))
2080 Diag(Deduce
->getBeginLoc(), diag::err_auto_expr_init_paren_braces
)
2081 << Braced
<< AllocType
<< TypeRange
);
2082 QualType DeducedType
;
2083 TemplateDeductionInfo
Info(Deduce
->getExprLoc());
2084 TemplateDeductionResult Result
=
2085 DeduceAutoType(AllocTypeInfo
->getTypeLoc(), Deduce
, DeducedType
, Info
);
2086 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
)
2087 return ExprError(Diag(StartLoc
, diag::err_auto_new_deduction_failure
)
2088 << AllocType
<< Deduce
->getType() << TypeRange
2089 << Deduce
->getSourceRange());
2090 if (DeducedType
.isNull()) {
2091 assert(Result
== TDK_AlreadyDiagnosed
);
2094 AllocType
= DeducedType
;
2097 // Per C++0x [expr.new]p5, the type being constructed may be a
2098 // typedef of an array type.
2100 if (const ConstantArrayType
*Array
2101 = Context
.getAsConstantArrayType(AllocType
)) {
2102 ArraySize
= IntegerLiteral::Create(Context
, Array
->getSize(),
2103 Context
.getSizeType(),
2104 TypeRange
.getEnd());
2105 AllocType
= Array
->getElementType();
2109 if (CheckAllocatedType(AllocType
, TypeRange
.getBegin(), TypeRange
))
2112 if (ArraySize
&& !checkArrayElementAlignment(AllocType
, TypeRange
.getBegin()))
2115 // In ARC, infer 'retaining' for the allocated
2116 if (getLangOpts().ObjCAutoRefCount
&&
2117 AllocType
.getObjCLifetime() == Qualifiers::OCL_None
&&
2118 AllocType
->isObjCLifetimeType()) {
2119 AllocType
= Context
.getLifetimeQualifiedType(AllocType
,
2120 AllocType
->getObjCARCImplicitLifetime());
2123 QualType ResultType
= Context
.getPointerType(AllocType
);
2125 if (ArraySize
&& *ArraySize
&&
2126 (*ArraySize
)->getType()->isNonOverloadPlaceholderType()) {
2127 ExprResult result
= CheckPlaceholderExpr(*ArraySize
);
2128 if (result
.isInvalid()) return ExprError();
2129 ArraySize
= result
.get();
2131 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2132 // integral or enumeration type with a non-negative value."
2133 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2134 // enumeration type, or a class type for which a single non-explicit
2135 // conversion function to integral or unscoped enumeration type exists.
2136 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2138 std::optional
<uint64_t> KnownArraySize
;
2139 if (ArraySize
&& *ArraySize
&& !(*ArraySize
)->isTypeDependent()) {
2140 ExprResult ConvertedSize
;
2141 if (getLangOpts().CPlusPlus14
) {
2142 assert(Context
.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2144 ConvertedSize
= PerformImplicitConversion(*ArraySize
, Context
.getSizeType(),
2147 if (!ConvertedSize
.isInvalid() &&
2148 (*ArraySize
)->getType()->getAs
<RecordType
>())
2149 // Diagnose the compatibility of this conversion.
2150 Diag(StartLoc
, diag::warn_cxx98_compat_array_size_conversion
)
2151 << (*ArraySize
)->getType() << 0 << "'size_t'";
2153 class SizeConvertDiagnoser
: public ICEConvertDiagnoser
{
2158 SizeConvertDiagnoser(Expr
*ArraySize
)
2159 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2160 ArraySize(ArraySize
) {}
2162 SemaDiagnosticBuilder
diagnoseNotInt(Sema
&S
, SourceLocation Loc
,
2163 QualType T
) override
{
2164 return S
.Diag(Loc
, diag::err_array_size_not_integral
)
2165 << S
.getLangOpts().CPlusPlus11
<< T
;
2168 SemaDiagnosticBuilder
diagnoseIncomplete(
2169 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
2170 return S
.Diag(Loc
, diag::err_array_size_incomplete_type
)
2171 << T
<< ArraySize
->getSourceRange();
2174 SemaDiagnosticBuilder
diagnoseExplicitConv(
2175 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
2176 return S
.Diag(Loc
, diag::err_array_size_explicit_conversion
) << T
<< ConvTy
;
2179 SemaDiagnosticBuilder
noteExplicitConv(
2180 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
2181 return S
.Diag(Conv
->getLocation(), diag::note_array_size_conversion
)
2182 << ConvTy
->isEnumeralType() << ConvTy
;
2185 SemaDiagnosticBuilder
diagnoseAmbiguous(
2186 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
2187 return S
.Diag(Loc
, diag::err_array_size_ambiguous_conversion
) << T
;
2190 SemaDiagnosticBuilder
noteAmbiguous(
2191 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
2192 return S
.Diag(Conv
->getLocation(), diag::note_array_size_conversion
)
2193 << ConvTy
->isEnumeralType() << ConvTy
;
2196 SemaDiagnosticBuilder
diagnoseConversion(Sema
&S
, SourceLocation Loc
,
2198 QualType ConvTy
) override
{
2200 S
.getLangOpts().CPlusPlus11
2201 ? diag::warn_cxx98_compat_array_size_conversion
2202 : diag::ext_array_size_conversion
)
2203 << T
<< ConvTy
->isEnumeralType() << ConvTy
;
2205 } SizeDiagnoser(*ArraySize
);
2207 ConvertedSize
= PerformContextualImplicitConversion(StartLoc
, *ArraySize
,
2210 if (ConvertedSize
.isInvalid())
2213 ArraySize
= ConvertedSize
.get();
2214 QualType SizeType
= (*ArraySize
)->getType();
2216 if (!SizeType
->isIntegralOrUnscopedEnumerationType())
2219 // C++98 [expr.new]p7:
2220 // The expression in a direct-new-declarator shall have integral type
2221 // with a non-negative value.
2223 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2224 // per CWG1464. Otherwise, if it's not a constant, we must have an
2225 // unparenthesized array type.
2227 // We've already performed any required implicit conversion to integer or
2228 // unscoped enumeration type.
2229 // FIXME: Per CWG1464, we are required to check the value prior to
2230 // converting to size_t. This will never find a negative array size in
2231 // C++14 onwards, because Value is always unsigned here!
2232 if (std::optional
<llvm::APSInt
> Value
=
2233 (*ArraySize
)->getIntegerConstantExpr(Context
)) {
2234 if (Value
->isSigned() && Value
->isNegative()) {
2235 return ExprError(Diag((*ArraySize
)->getBeginLoc(),
2236 diag::err_typecheck_negative_array_size
)
2237 << (*ArraySize
)->getSourceRange());
2240 if (!AllocType
->isDependentType()) {
2241 unsigned ActiveSizeBits
=
2242 ConstantArrayType::getNumAddressingBits(Context
, AllocType
, *Value
);
2243 if (ActiveSizeBits
> ConstantArrayType::getMaxSizeBits(Context
))
2245 Diag((*ArraySize
)->getBeginLoc(), diag::err_array_too_large
)
2246 << toString(*Value
, 10) << (*ArraySize
)->getSourceRange());
2249 KnownArraySize
= Value
->getZExtValue();
2250 } else if (TypeIdParens
.isValid()) {
2251 // Can't have dynamic array size when the type-id is in parentheses.
2252 Diag((*ArraySize
)->getBeginLoc(), diag::ext_new_paren_array_nonconst
)
2253 << (*ArraySize
)->getSourceRange()
2254 << FixItHint::CreateRemoval(TypeIdParens
.getBegin())
2255 << FixItHint::CreateRemoval(TypeIdParens
.getEnd());
2257 TypeIdParens
= SourceRange();
2260 // Note that we do *not* convert the argument in any way. It can
2261 // be signed, larger than size_t, whatever.
2264 FunctionDecl
*OperatorNew
= nullptr;
2265 FunctionDecl
*OperatorDelete
= nullptr;
2266 unsigned Alignment
=
2267 AllocType
->isDependentType() ? 0 : Context
.getTypeAlign(AllocType
);
2268 unsigned NewAlignment
= Context
.getTargetInfo().getNewAlign();
2269 bool PassAlignment
= getLangOpts().AlignedAllocation
&&
2270 Alignment
> NewAlignment
;
2272 AllocationFunctionScope Scope
= UseGlobal
? AFS_Global
: AFS_Both
;
2273 if (!AllocType
->isDependentType() &&
2274 !Expr::hasAnyTypeDependentArguments(PlacementArgs
) &&
2275 FindAllocationFunctions(
2276 StartLoc
, SourceRange(PlacementLParen
, PlacementRParen
), Scope
, Scope
,
2277 AllocType
, ArraySize
.has_value(), PassAlignment
, PlacementArgs
,
2278 OperatorNew
, OperatorDelete
))
2281 // If this is an array allocation, compute whether the usual array
2282 // deallocation function for the type has a size_t parameter.
2283 bool UsualArrayDeleteWantsSize
= false;
2284 if (ArraySize
&& !AllocType
->isDependentType())
2285 UsualArrayDeleteWantsSize
=
2286 doesUsualArrayDeleteWantSize(*this, StartLoc
, AllocType
);
2288 SmallVector
<Expr
*, 8> AllPlaceArgs
;
2290 auto *Proto
= OperatorNew
->getType()->castAs
<FunctionProtoType
>();
2291 VariadicCallType CallType
= Proto
->isVariadic() ? VariadicFunction
2292 : VariadicDoesNotApply
;
2294 // We've already converted the placement args, just fill in any default
2295 // arguments. Skip the first parameter because we don't have a corresponding
2296 // argument. Skip the second parameter too if we're passing in the
2297 // alignment; we've already filled it in.
2298 unsigned NumImplicitArgs
= PassAlignment
? 2 : 1;
2299 if (GatherArgumentsForCall(PlacementLParen
, OperatorNew
, Proto
,
2300 NumImplicitArgs
, PlacementArgs
, AllPlaceArgs
,
2304 if (!AllPlaceArgs
.empty())
2305 PlacementArgs
= AllPlaceArgs
;
2307 // We would like to perform some checking on the given `operator new` call,
2308 // but the PlacementArgs does not contain the implicit arguments,
2309 // namely allocation size and maybe allocation alignment,
2310 // so we need to conjure them.
2312 QualType SizeTy
= Context
.getSizeType();
2313 unsigned SizeTyWidth
= Context
.getTypeSize(SizeTy
);
2315 llvm::APInt
SingleEltSize(
2316 SizeTyWidth
, Context
.getTypeSizeInChars(AllocType
).getQuantity());
2318 // How many bytes do we want to allocate here?
2319 std::optional
<llvm::APInt
> AllocationSize
;
2320 if (!ArraySize
&& !AllocType
->isDependentType()) {
2321 // For non-array operator new, we only want to allocate one element.
2322 AllocationSize
= SingleEltSize
;
2323 } else if (KnownArraySize
&& !AllocType
->isDependentType()) {
2324 // For array operator new, only deal with static array size case.
2326 AllocationSize
= llvm::APInt(SizeTyWidth
, *KnownArraySize
)
2327 .umul_ov(SingleEltSize
, Overflow
);
2331 "Expected that all the overflows would have been handled already.");
2334 IntegerLiteral
AllocationSizeLiteral(
2335 Context
, AllocationSize
.value_or(llvm::APInt::getZero(SizeTyWidth
)),
2336 SizeTy
, SourceLocation());
2337 // Otherwise, if we failed to constant-fold the allocation size, we'll
2338 // just give up and pass-in something opaque, that isn't a null pointer.
2339 OpaqueValueExpr
OpaqueAllocationSize(SourceLocation(), SizeTy
, VK_PRValue
,
2340 OK_Ordinary
, /*SourceExpr=*/nullptr);
2342 // Let's synthesize the alignment argument in case we will need it.
2343 // Since we *really* want to allocate these on stack, this is slightly ugly
2344 // because there might not be a `std::align_val_t` type.
2345 EnumDecl
*StdAlignValT
= getStdAlignValT();
2346 QualType AlignValT
=
2347 StdAlignValT
? Context
.getTypeDeclType(StdAlignValT
) : SizeTy
;
2348 IntegerLiteral
AlignmentLiteral(
2350 llvm::APInt(Context
.getTypeSize(SizeTy
),
2351 Alignment
/ Context
.getCharWidth()),
2352 SizeTy
, SourceLocation());
2353 ImplicitCastExpr
DesiredAlignment(ImplicitCastExpr::OnStack
, AlignValT
,
2354 CK_IntegralCast
, &AlignmentLiteral
,
2355 VK_PRValue
, FPOptionsOverride());
2357 // Adjust placement args by prepending conjured size and alignment exprs.
2358 llvm::SmallVector
<Expr
*, 8> CallArgs
;
2359 CallArgs
.reserve(NumImplicitArgs
+ PlacementArgs
.size());
2360 CallArgs
.emplace_back(AllocationSize
2361 ? static_cast<Expr
*>(&AllocationSizeLiteral
)
2362 : &OpaqueAllocationSize
);
2364 CallArgs
.emplace_back(&DesiredAlignment
);
2365 CallArgs
.insert(CallArgs
.end(), PlacementArgs
.begin(), PlacementArgs
.end());
2367 DiagnoseSentinelCalls(OperatorNew
, PlacementLParen
, CallArgs
);
2369 checkCall(OperatorNew
, Proto
, /*ThisArg=*/nullptr, CallArgs
,
2370 /*IsMemberFunction=*/false, StartLoc
, Range
, CallType
);
2372 // Warn if the type is over-aligned and is being allocated by (unaligned)
2373 // global operator new.
2374 if (PlacementArgs
.empty() && !PassAlignment
&&
2375 (OperatorNew
->isImplicit() ||
2376 (OperatorNew
->getBeginLoc().isValid() &&
2377 getSourceManager().isInSystemHeader(OperatorNew
->getBeginLoc())))) {
2378 if (Alignment
> NewAlignment
)
2379 Diag(StartLoc
, diag::warn_overaligned_type
)
2381 << unsigned(Alignment
/ Context
.getCharWidth())
2382 << unsigned(NewAlignment
/ Context
.getCharWidth());
2386 // Array 'new' can't have any initializers except empty parentheses.
2387 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2388 // dialect distinction.
2389 if (ArraySize
&& !isLegalArrayNewInitializer(initStyle
, Initializer
)) {
2390 SourceRange
InitRange(Exprs
.front()->getBeginLoc(),
2391 Exprs
.back()->getEndLoc());
2392 Diag(StartLoc
, diag::err_new_array_init_args
) << InitRange
;
2396 // If we can perform the initialization, and we've not already done so,
2398 if (!AllocType
->isDependentType() &&
2399 !Expr::hasAnyTypeDependentArguments(Exprs
)) {
2400 // The type we initialize is the complete type, including the array bound.
2403 InitType
= Context
.getConstantArrayType(
2405 llvm::APInt(Context
.getTypeSize(Context
.getSizeType()),
2407 *ArraySize
, ArraySizeModifier::Normal
, 0);
2409 InitType
= Context
.getIncompleteArrayType(AllocType
,
2410 ArraySizeModifier::Normal
, 0);
2412 InitType
= AllocType
;
2414 InitializedEntity Entity
2415 = InitializedEntity::InitializeNew(StartLoc
, InitType
);
2416 InitializationSequence
InitSeq(*this, Entity
, Kind
, Exprs
);
2417 ExprResult FullInit
= InitSeq
.Perform(*this, Entity
, Kind
, Exprs
);
2418 if (FullInit
.isInvalid())
2421 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2422 // we don't want the initialized object to be destructed.
2423 // FIXME: We should not create these in the first place.
2424 if (CXXBindTemporaryExpr
*Binder
=
2425 dyn_cast_or_null
<CXXBindTemporaryExpr
>(FullInit
.get()))
2426 FullInit
= Binder
->getSubExpr();
2428 Initializer
= FullInit
.get();
2430 // FIXME: If we have a KnownArraySize, check that the array bound of the
2431 // initializer is no greater than that constant value.
2433 if (ArraySize
&& !*ArraySize
) {
2434 auto *CAT
= Context
.getAsConstantArrayType(Initializer
->getType());
2436 // FIXME: Track that the array size was inferred rather than explicitly
2438 ArraySize
= IntegerLiteral::Create(
2439 Context
, CAT
->getSize(), Context
.getSizeType(), TypeRange
.getEnd());
2441 Diag(TypeRange
.getEnd(), diag::err_new_array_size_unknown_from_init
)
2442 << Initializer
->getSourceRange();
2447 // Mark the new and delete operators as referenced.
2449 if (DiagnoseUseOfDecl(OperatorNew
, StartLoc
))
2451 MarkFunctionReferenced(StartLoc
, OperatorNew
);
2453 if (OperatorDelete
) {
2454 if (DiagnoseUseOfDecl(OperatorDelete
, StartLoc
))
2456 MarkFunctionReferenced(StartLoc
, OperatorDelete
);
2459 return CXXNewExpr::Create(Context
, UseGlobal
, OperatorNew
, OperatorDelete
,
2460 PassAlignment
, UsualArrayDeleteWantsSize
,
2461 PlacementArgs
, TypeIdParens
, ArraySize
, initStyle
,
2462 Initializer
, ResultType
, AllocTypeInfo
, Range
,
2466 /// Checks that a type is suitable as the allocated type
2467 /// in a new-expression.
2468 bool Sema::CheckAllocatedType(QualType AllocType
, SourceLocation Loc
,
2470 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2471 // abstract class type or array thereof.
2472 if (AllocType
->isFunctionType())
2473 return Diag(Loc
, diag::err_bad_new_type
)
2474 << AllocType
<< 0 << R
;
2475 else if (AllocType
->isReferenceType())
2476 return Diag(Loc
, diag::err_bad_new_type
)
2477 << AllocType
<< 1 << R
;
2478 else if (!AllocType
->isDependentType() &&
2479 RequireCompleteSizedType(
2480 Loc
, AllocType
, diag::err_new_incomplete_or_sizeless_type
, R
))
2482 else if (RequireNonAbstractType(Loc
, AllocType
,
2483 diag::err_allocation_of_abstract_type
))
2485 else if (AllocType
->isVariablyModifiedType())
2486 return Diag(Loc
, diag::err_variably_modified_new_type
)
2488 else if (AllocType
.getAddressSpace() != LangAS::Default
&&
2489 !getLangOpts().OpenCLCPlusPlus
)
2490 return Diag(Loc
, diag::err_address_space_qualified_new
)
2491 << AllocType
.getUnqualifiedType()
2492 << AllocType
.getQualifiers().getAddressSpaceAttributePrintValue();
2493 else if (getLangOpts().ObjCAutoRefCount
) {
2494 if (const ArrayType
*AT
= Context
.getAsArrayType(AllocType
)) {
2495 QualType BaseAllocType
= Context
.getBaseElementType(AT
);
2496 if (BaseAllocType
.getObjCLifetime() == Qualifiers::OCL_None
&&
2497 BaseAllocType
->isObjCLifetimeType())
2498 return Diag(Loc
, diag::err_arc_new_array_without_ownership
)
2506 static bool resolveAllocationOverload(
2507 Sema
&S
, LookupResult
&R
, SourceRange Range
, SmallVectorImpl
<Expr
*> &Args
,
2508 bool &PassAlignment
, FunctionDecl
*&Operator
,
2509 OverloadCandidateSet
*AlignedCandidates
, Expr
*AlignArg
, bool Diagnose
) {
2510 OverloadCandidateSet
Candidates(R
.getNameLoc(),
2511 OverloadCandidateSet::CSK_Normal
);
2512 for (LookupResult::iterator Alloc
= R
.begin(), AllocEnd
= R
.end();
2513 Alloc
!= AllocEnd
; ++Alloc
) {
2514 // Even member operator new/delete are implicitly treated as
2515 // static, so don't use AddMemberCandidate.
2516 NamedDecl
*D
= (*Alloc
)->getUnderlyingDecl();
2518 if (FunctionTemplateDecl
*FnTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
)) {
2519 S
.AddTemplateOverloadCandidate(FnTemplate
, Alloc
.getPair(),
2520 /*ExplicitTemplateArgs=*/nullptr, Args
,
2522 /*SuppressUserConversions=*/false);
2526 FunctionDecl
*Fn
= cast
<FunctionDecl
>(D
);
2527 S
.AddOverloadCandidate(Fn
, Alloc
.getPair(), Args
, Candidates
,
2528 /*SuppressUserConversions=*/false);
2531 // Do the resolution.
2532 OverloadCandidateSet::iterator Best
;
2533 switch (Candidates
.BestViableFunction(S
, R
.getNameLoc(), Best
)) {
2536 FunctionDecl
*FnDecl
= Best
->Function
;
2537 if (S
.CheckAllocationAccess(R
.getNameLoc(), Range
, R
.getNamingClass(),
2538 Best
->FoundDecl
) == Sema::AR_inaccessible
)
2545 case OR_No_Viable_Function
:
2546 // C++17 [expr.new]p13:
2547 // If no matching function is found and the allocated object type has
2548 // new-extended alignment, the alignment argument is removed from the
2549 // argument list, and overload resolution is performed again.
2550 if (PassAlignment
) {
2551 PassAlignment
= false;
2553 Args
.erase(Args
.begin() + 1);
2554 return resolveAllocationOverload(S
, R
, Range
, Args
, PassAlignment
,
2555 Operator
, &Candidates
, AlignArg
,
2559 // MSVC will fall back on trying to find a matching global operator new
2560 // if operator new[] cannot be found. Also, MSVC will leak by not
2561 // generating a call to operator delete or operator delete[], but we
2562 // will not replicate that bug.
2563 // FIXME: Find out how this interacts with the std::align_val_t fallback
2564 // once MSVC implements it.
2565 if (R
.getLookupName().getCXXOverloadedOperator() == OO_Array_New
&&
2566 S
.Context
.getLangOpts().MSVCCompat
) {
2568 R
.setLookupName(S
.Context
.DeclarationNames
.getCXXOperatorName(OO_New
));
2569 S
.LookupQualifiedName(R
, S
.Context
.getTranslationUnitDecl());
2570 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2571 return resolveAllocationOverload(S
, R
, Range
, Args
, PassAlignment
,
2572 Operator
, /*Candidates=*/nullptr,
2573 /*AlignArg=*/nullptr, Diagnose
);
2577 // If this is an allocation of the form 'new (p) X' for some object
2578 // pointer p (or an expression that will decay to such a pointer),
2579 // diagnose the missing inclusion of <new>.
2580 if (!R
.isClassLookup() && Args
.size() == 2 &&
2581 (Args
[1]->getType()->isObjectPointerType() ||
2582 Args
[1]->getType()->isArrayType())) {
2583 S
.Diag(R
.getNameLoc(), diag::err_need_header_before_placement_new
)
2584 << R
.getLookupName() << Range
;
2585 // Listing the candidates is unlikely to be useful; skip it.
2589 // Finish checking all candidates before we note any. This checking can
2590 // produce additional diagnostics so can't be interleaved with our
2591 // emission of notes.
2593 // For an aligned allocation, separately check the aligned and unaligned
2594 // candidates with their respective argument lists.
2595 SmallVector
<OverloadCandidate
*, 32> Cands
;
2596 SmallVector
<OverloadCandidate
*, 32> AlignedCands
;
2597 llvm::SmallVector
<Expr
*, 4> AlignedArgs
;
2598 if (AlignedCandidates
) {
2599 auto IsAligned
= [](OverloadCandidate
&C
) {
2600 return C
.Function
->getNumParams() > 1 &&
2601 C
.Function
->getParamDecl(1)->getType()->isAlignValT();
2603 auto IsUnaligned
= [&](OverloadCandidate
&C
) { return !IsAligned(C
); };
2605 AlignedArgs
.reserve(Args
.size() + 1);
2606 AlignedArgs
.push_back(Args
[0]);
2607 AlignedArgs
.push_back(AlignArg
);
2608 AlignedArgs
.append(Args
.begin() + 1, Args
.end());
2609 AlignedCands
= AlignedCandidates
->CompleteCandidates(
2610 S
, OCD_AllCandidates
, AlignedArgs
, R
.getNameLoc(), IsAligned
);
2612 Cands
= Candidates
.CompleteCandidates(S
, OCD_AllCandidates
, Args
,
2613 R
.getNameLoc(), IsUnaligned
);
2615 Cands
= Candidates
.CompleteCandidates(S
, OCD_AllCandidates
, Args
,
2619 S
.Diag(R
.getNameLoc(), diag::err_ovl_no_viable_function_in_call
)
2620 << R
.getLookupName() << Range
;
2621 if (AlignedCandidates
)
2622 AlignedCandidates
->NoteCandidates(S
, AlignedArgs
, AlignedCands
, "",
2624 Candidates
.NoteCandidates(S
, Args
, Cands
, "", R
.getNameLoc());
2630 Candidates
.NoteCandidates(
2631 PartialDiagnosticAt(R
.getNameLoc(),
2632 S
.PDiag(diag::err_ovl_ambiguous_call
)
2633 << R
.getLookupName() << Range
),
2634 S
, OCD_AmbiguousCandidates
, Args
);
2640 Candidates
.NoteCandidates(
2641 PartialDiagnosticAt(R
.getNameLoc(),
2642 S
.PDiag(diag::err_ovl_deleted_call
)
2643 << R
.getLookupName() << Range
),
2644 S
, OCD_AllCandidates
, Args
);
2649 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2652 bool Sema::FindAllocationFunctions(SourceLocation StartLoc
, SourceRange Range
,
2653 AllocationFunctionScope NewScope
,
2654 AllocationFunctionScope DeleteScope
,
2655 QualType AllocType
, bool IsArray
,
2656 bool &PassAlignment
, MultiExprArg PlaceArgs
,
2657 FunctionDecl
*&OperatorNew
,
2658 FunctionDecl
*&OperatorDelete
,
2660 // --- Choosing an allocation function ---
2661 // C++ 5.3.4p8 - 14 & 18
2662 // 1) If looking in AFS_Global scope for allocation functions, only look in
2663 // the global scope. Else, if AFS_Class, only look in the scope of the
2664 // allocated class. If AFS_Both, look in both.
2665 // 2) If an array size is given, look for operator new[], else look for
2667 // 3) The first argument is always size_t. Append the arguments from the
2670 SmallVector
<Expr
*, 8> AllocArgs
;
2671 AllocArgs
.reserve((PassAlignment
? 2 : 1) + PlaceArgs
.size());
2673 // We don't care about the actual value of these arguments.
2674 // FIXME: Should the Sema create the expression and embed it in the syntax
2675 // tree? Or should the consumer just recalculate the value?
2676 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2677 QualType SizeTy
= Context
.getSizeType();
2678 unsigned SizeTyWidth
= Context
.getTypeSize(SizeTy
);
2679 IntegerLiteral
Size(Context
, llvm::APInt::getZero(SizeTyWidth
), SizeTy
,
2681 AllocArgs
.push_back(&Size
);
2683 QualType AlignValT
= Context
.VoidTy
;
2684 if (PassAlignment
) {
2685 DeclareGlobalNewDelete();
2686 AlignValT
= Context
.getTypeDeclType(getStdAlignValT());
2688 CXXScalarValueInitExpr
Align(AlignValT
, nullptr, SourceLocation());
2690 AllocArgs
.push_back(&Align
);
2692 AllocArgs
.insert(AllocArgs
.end(), PlaceArgs
.begin(), PlaceArgs
.end());
2694 // C++ [expr.new]p8:
2695 // If the allocated type is a non-array type, the allocation
2696 // function's name is operator new and the deallocation function's
2697 // name is operator delete. If the allocated type is an array
2698 // type, the allocation function's name is operator new[] and the
2699 // deallocation function's name is operator delete[].
2700 DeclarationName NewName
= Context
.DeclarationNames
.getCXXOperatorName(
2701 IsArray
? OO_Array_New
: OO_New
);
2703 QualType AllocElemType
= Context
.getBaseElementType(AllocType
);
2705 // Find the allocation function.
2707 LookupResult
R(*this, NewName
, StartLoc
, LookupOrdinaryName
);
2709 // C++1z [expr.new]p9:
2710 // If the new-expression begins with a unary :: operator, the allocation
2711 // function's name is looked up in the global scope. Otherwise, if the
2712 // allocated type is a class type T or array thereof, the allocation
2713 // function's name is looked up in the scope of T.
2714 if (AllocElemType
->isRecordType() && NewScope
!= AFS_Global
)
2715 LookupQualifiedName(R
, AllocElemType
->getAsCXXRecordDecl());
2717 // We can see ambiguity here if the allocation function is found in
2718 // multiple base classes.
2719 if (R
.isAmbiguous())
2722 // If this lookup fails to find the name, or if the allocated type is not
2723 // a class type, the allocation function's name is looked up in the
2726 if (NewScope
== AFS_Class
)
2729 LookupQualifiedName(R
, Context
.getTranslationUnitDecl());
2732 if (getLangOpts().OpenCLCPlusPlus
&& R
.empty()) {
2733 if (PlaceArgs
.empty()) {
2734 Diag(StartLoc
, diag::err_openclcxx_not_supported
) << "default new";
2736 Diag(StartLoc
, diag::err_openclcxx_placement_new
);
2741 assert(!R
.empty() && "implicitly declared allocation functions not found");
2742 assert(!R
.isAmbiguous() && "global allocation functions are ambiguous");
2744 // We do our own custom access checks below.
2745 R
.suppressDiagnostics();
2747 if (resolveAllocationOverload(*this, R
, Range
, AllocArgs
, PassAlignment
,
2748 OperatorNew
, /*Candidates=*/nullptr,
2749 /*AlignArg=*/nullptr, Diagnose
))
2753 // We don't need an operator delete if we're running under -fno-exceptions.
2754 if (!getLangOpts().Exceptions
) {
2755 OperatorDelete
= nullptr;
2759 // Note, the name of OperatorNew might have been changed from array to
2760 // non-array by resolveAllocationOverload.
2761 DeclarationName DeleteName
= Context
.DeclarationNames
.getCXXOperatorName(
2762 OperatorNew
->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2766 // C++ [expr.new]p19:
2768 // If the new-expression begins with a unary :: operator, the
2769 // deallocation function's name is looked up in the global
2770 // scope. Otherwise, if the allocated type is a class type T or an
2771 // array thereof, the deallocation function's name is looked up in
2772 // the scope of T. If this lookup fails to find the name, or if
2773 // the allocated type is not a class type or array thereof, the
2774 // deallocation function's name is looked up in the global scope.
2775 LookupResult
FoundDelete(*this, DeleteName
, StartLoc
, LookupOrdinaryName
);
2776 if (AllocElemType
->isRecordType() && DeleteScope
!= AFS_Global
) {
2778 cast
<CXXRecordDecl
>(AllocElemType
->castAs
<RecordType
>()->getDecl());
2779 LookupQualifiedName(FoundDelete
, RD
);
2781 if (FoundDelete
.isAmbiguous())
2782 return true; // FIXME: clean up expressions?
2784 // Filter out any destroying operator deletes. We can't possibly call such a
2785 // function in this context, because we're handling the case where the object
2786 // was not successfully constructed.
2787 // FIXME: This is not covered by the language rules yet.
2789 LookupResult::Filter Filter
= FoundDelete
.makeFilter();
2790 while (Filter
.hasNext()) {
2791 auto *FD
= dyn_cast
<FunctionDecl
>(Filter
.next()->getUnderlyingDecl());
2792 if (FD
&& FD
->isDestroyingOperatorDelete())
2798 bool FoundGlobalDelete
= FoundDelete
.empty();
2799 if (FoundDelete
.empty()) {
2800 FoundDelete
.clear(LookupOrdinaryName
);
2802 if (DeleteScope
== AFS_Class
)
2805 DeclareGlobalNewDelete();
2806 LookupQualifiedName(FoundDelete
, Context
.getTranslationUnitDecl());
2809 FoundDelete
.suppressDiagnostics();
2811 SmallVector
<std::pair
<DeclAccessPair
,FunctionDecl
*>, 2> Matches
;
2813 // Whether we're looking for a placement operator delete is dictated
2814 // by whether we selected a placement operator new, not by whether
2815 // we had explicit placement arguments. This matters for things like
2816 // struct A { void *operator new(size_t, int = 0); ... };
2819 // We don't have any definition for what a "placement allocation function"
2820 // is, but we assume it's any allocation function whose
2821 // parameter-declaration-clause is anything other than (size_t).
2823 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2824 // This affects whether an exception from the constructor of an overaligned
2825 // type uses the sized or non-sized form of aligned operator delete.
2826 bool isPlacementNew
= !PlaceArgs
.empty() || OperatorNew
->param_size() != 1 ||
2827 OperatorNew
->isVariadic();
2829 if (isPlacementNew
) {
2830 // C++ [expr.new]p20:
2831 // A declaration of a placement deallocation function matches the
2832 // declaration of a placement allocation function if it has the
2833 // same number of parameters and, after parameter transformations
2834 // (8.3.5), all parameter types except the first are
2837 // To perform this comparison, we compute the function type that
2838 // the deallocation function should have, and use that type both
2839 // for template argument deduction and for comparison purposes.
2840 QualType ExpectedFunctionType
;
2842 auto *Proto
= OperatorNew
->getType()->castAs
<FunctionProtoType
>();
2844 SmallVector
<QualType
, 4> ArgTypes
;
2845 ArgTypes
.push_back(Context
.VoidPtrTy
);
2846 for (unsigned I
= 1, N
= Proto
->getNumParams(); I
< N
; ++I
)
2847 ArgTypes
.push_back(Proto
->getParamType(I
));
2849 FunctionProtoType::ExtProtoInfo EPI
;
2850 // FIXME: This is not part of the standard's rule.
2851 EPI
.Variadic
= Proto
->isVariadic();
2853 ExpectedFunctionType
2854 = Context
.getFunctionType(Context
.VoidTy
, ArgTypes
, EPI
);
2857 for (LookupResult::iterator D
= FoundDelete
.begin(),
2858 DEnd
= FoundDelete
.end();
2860 FunctionDecl
*Fn
= nullptr;
2861 if (FunctionTemplateDecl
*FnTmpl
=
2862 dyn_cast
<FunctionTemplateDecl
>((*D
)->getUnderlyingDecl())) {
2863 // Perform template argument deduction to try to match the
2864 // expected function type.
2865 TemplateDeductionInfo
Info(StartLoc
);
2866 if (DeduceTemplateArguments(FnTmpl
, nullptr, ExpectedFunctionType
, Fn
,
2870 Fn
= cast
<FunctionDecl
>((*D
)->getUnderlyingDecl());
2872 if (Context
.hasSameType(adjustCCAndNoReturn(Fn
->getType(),
2873 ExpectedFunctionType
,
2874 /*AdjustExcpetionSpec*/true),
2875 ExpectedFunctionType
))
2876 Matches
.push_back(std::make_pair(D
.getPair(), Fn
));
2879 if (getLangOpts().CUDA
)
2880 EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2883 // C++1y [expr.new]p22:
2884 // For a non-placement allocation function, the normal deallocation
2885 // function lookup is used
2887 // Per [expr.delete]p10, this lookup prefers a member operator delete
2888 // without a size_t argument, but prefers a non-member operator delete
2889 // with a size_t where possible (which it always is in this case).
2890 llvm::SmallVector
<UsualDeallocFnInfo
, 4> BestDeallocFns
;
2891 UsualDeallocFnInfo Selected
= resolveDeallocationOverload(
2892 *this, FoundDelete
, /*WantSize*/ FoundGlobalDelete
,
2893 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType
),
2896 Matches
.push_back(std::make_pair(Selected
.Found
, Selected
.FD
));
2898 // If we failed to select an operator, all remaining functions are viable
2900 for (auto Fn
: BestDeallocFns
)
2901 Matches
.push_back(std::make_pair(Fn
.Found
, Fn
.FD
));
2905 // C++ [expr.new]p20:
2906 // [...] If the lookup finds a single matching deallocation
2907 // function, that function will be called; otherwise, no
2908 // deallocation function will be called.
2909 if (Matches
.size() == 1) {
2910 OperatorDelete
= Matches
[0].second
;
2912 // C++1z [expr.new]p23:
2913 // If the lookup finds a usual deallocation function (3.7.4.2)
2914 // with a parameter of type std::size_t and that function, considered
2915 // as a placement deallocation function, would have been
2916 // selected as a match for the allocation function, the program
2918 if (getLangOpts().CPlusPlus11
&& isPlacementNew
&&
2919 isNonPlacementDeallocationFunction(*this, OperatorDelete
)) {
2920 UsualDeallocFnInfo
Info(*this,
2921 DeclAccessPair::make(OperatorDelete
, AS_public
));
2922 // Core issue, per mail to core reflector, 2016-10-09:
2923 // If this is a member operator delete, and there is a corresponding
2924 // non-sized member operator delete, this isn't /really/ a sized
2925 // deallocation function, it just happens to have a size_t parameter.
2926 bool IsSizedDelete
= Info
.HasSizeT
;
2927 if (IsSizedDelete
&& !FoundGlobalDelete
) {
2928 auto NonSizedDelete
=
2929 resolveDeallocationOverload(*this, FoundDelete
, /*WantSize*/false,
2930 /*WantAlign*/Info
.HasAlignValT
);
2931 if (NonSizedDelete
&& !NonSizedDelete
.HasSizeT
&&
2932 NonSizedDelete
.HasAlignValT
== Info
.HasAlignValT
)
2933 IsSizedDelete
= false;
2936 if (IsSizedDelete
) {
2937 SourceRange R
= PlaceArgs
.empty()
2939 : SourceRange(PlaceArgs
.front()->getBeginLoc(),
2940 PlaceArgs
.back()->getEndLoc());
2941 Diag(StartLoc
, diag::err_placement_new_non_placement_delete
) << R
;
2942 if (!OperatorDelete
->isImplicit())
2943 Diag(OperatorDelete
->getLocation(), diag::note_previous_decl
)
2948 CheckAllocationAccess(StartLoc
, Range
, FoundDelete
.getNamingClass(),
2950 } else if (!Matches
.empty()) {
2951 // We found multiple suitable operators. Per [expr.new]p20, that means we
2952 // call no 'operator delete' function, but we should at least warn the user.
2953 // FIXME: Suppress this warning if the construction cannot throw.
2954 Diag(StartLoc
, diag::warn_ambiguous_suitable_delete_function_found
)
2955 << DeleteName
<< AllocElemType
;
2957 for (auto &Match
: Matches
)
2958 Diag(Match
.second
->getLocation(),
2959 diag::note_member_declared_here
) << DeleteName
;
2965 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2966 /// delete. These are:
2969 /// void* operator new(std::size_t) throw(std::bad_alloc);
2970 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2971 /// void operator delete(void *) throw();
2972 /// void operator delete[](void *) throw();
2974 /// void* operator new(std::size_t);
2975 /// void* operator new[](std::size_t);
2976 /// void operator delete(void *) noexcept;
2977 /// void operator delete[](void *) noexcept;
2979 /// void* operator new(std::size_t);
2980 /// void* operator new[](std::size_t);
2981 /// void operator delete(void *) noexcept;
2982 /// void operator delete[](void *) noexcept;
2983 /// void operator delete(void *, std::size_t) noexcept;
2984 /// void operator delete[](void *, std::size_t) noexcept;
2986 /// Note that the placement and nothrow forms of new are *not* implicitly
2987 /// declared. Their use requires including \<new\>.
2988 void Sema::DeclareGlobalNewDelete() {
2989 if (GlobalNewDeleteDeclared
)
2992 // The implicitly declared new and delete operators
2993 // are not supported in OpenCL.
2994 if (getLangOpts().OpenCLCPlusPlus
)
2997 // C++ [basic.stc.dynamic.general]p2:
2998 // The library provides default definitions for the global allocation
2999 // and deallocation functions. Some global allocation and deallocation
3000 // functions are replaceable ([new.delete]); these are attached to the
3001 // global module ([module.unit]).
3002 if (getLangOpts().CPlusPlusModules
&& getCurrentModule())
3003 PushGlobalModuleFragment(SourceLocation());
3005 // C++ [basic.std.dynamic]p2:
3006 // [...] The following allocation and deallocation functions (18.4) are
3007 // implicitly declared in global scope in each translation unit of a
3011 // void* operator new(std::size_t) throw(std::bad_alloc);
3012 // void* operator new[](std::size_t) throw(std::bad_alloc);
3013 // void operator delete(void*) throw();
3014 // void operator delete[](void*) throw();
3016 // void* operator new(std::size_t);
3017 // void* operator new[](std::size_t);
3018 // void operator delete(void*) noexcept;
3019 // void operator delete[](void*) noexcept;
3021 // void* operator new(std::size_t);
3022 // void* operator new[](std::size_t);
3023 // void operator delete(void*) noexcept;
3024 // void operator delete[](void*) noexcept;
3025 // void operator delete(void*, std::size_t) noexcept;
3026 // void operator delete[](void*, std::size_t) noexcept;
3028 // These implicit declarations introduce only the function names operator
3029 // new, operator new[], operator delete, operator delete[].
3031 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3032 // "std" or "bad_alloc" as necessary to form the exception specification.
3033 // However, we do not make these implicit declarations visible to name
3035 if (!StdBadAlloc
&& !getLangOpts().CPlusPlus11
) {
3036 // The "std::bad_alloc" class has not yet been declared, so build it
3038 StdBadAlloc
= CXXRecordDecl::Create(Context
, TTK_Class
,
3039 getOrCreateStdNamespace(),
3040 SourceLocation(), SourceLocation(),
3041 &PP
.getIdentifierTable().get("bad_alloc"),
3043 getStdBadAlloc()->setImplicit(true);
3045 // The implicitly declared "std::bad_alloc" should live in global module
3047 if (TheGlobalModuleFragment
) {
3048 getStdBadAlloc()->setModuleOwnershipKind(
3049 Decl::ModuleOwnershipKind::ReachableWhenImported
);
3050 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment
);
3053 if (!StdAlignValT
&& getLangOpts().AlignedAllocation
) {
3054 // The "std::align_val_t" enum class has not yet been declared, so build it
3056 auto *AlignValT
= EnumDecl::Create(
3057 Context
, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
3058 &PP
.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3060 // The implicitly declared "std::align_val_t" should live in global module
3062 if (TheGlobalModuleFragment
) {
3063 AlignValT
->setModuleOwnershipKind(
3064 Decl::ModuleOwnershipKind::ReachableWhenImported
);
3065 AlignValT
->setLocalOwningModule(TheGlobalModuleFragment
);
3068 AlignValT
->setIntegerType(Context
.getSizeType());
3069 AlignValT
->setPromotionType(Context
.getSizeType());
3070 AlignValT
->setImplicit(true);
3072 StdAlignValT
= AlignValT
;
3075 GlobalNewDeleteDeclared
= true;
3077 QualType VoidPtr
= Context
.getPointerType(Context
.VoidTy
);
3078 QualType SizeT
= Context
.getSizeType();
3080 auto DeclareGlobalAllocationFunctions
= [&](OverloadedOperatorKind Kind
,
3081 QualType Return
, QualType Param
) {
3082 llvm::SmallVector
<QualType
, 3> Params
;
3083 Params
.push_back(Param
);
3085 // Create up to four variants of the function (sized/aligned).
3086 bool HasSizedVariant
= getLangOpts().SizedDeallocation
&&
3087 (Kind
== OO_Delete
|| Kind
== OO_Array_Delete
);
3088 bool HasAlignedVariant
= getLangOpts().AlignedAllocation
;
3090 int NumSizeVariants
= (HasSizedVariant
? 2 : 1);
3091 int NumAlignVariants
= (HasAlignedVariant
? 2 : 1);
3092 for (int Sized
= 0; Sized
< NumSizeVariants
; ++Sized
) {
3094 Params
.push_back(SizeT
);
3096 for (int Aligned
= 0; Aligned
< NumAlignVariants
; ++Aligned
) {
3098 Params
.push_back(Context
.getTypeDeclType(getStdAlignValT()));
3100 DeclareGlobalAllocationFunction(
3101 Context
.DeclarationNames
.getCXXOperatorName(Kind
), Return
, Params
);
3109 DeclareGlobalAllocationFunctions(OO_New
, VoidPtr
, SizeT
);
3110 DeclareGlobalAllocationFunctions(OO_Array_New
, VoidPtr
, SizeT
);
3111 DeclareGlobalAllocationFunctions(OO_Delete
, Context
.VoidTy
, VoidPtr
);
3112 DeclareGlobalAllocationFunctions(OO_Array_Delete
, Context
.VoidTy
, VoidPtr
);
3114 if (getLangOpts().CPlusPlusModules
&& getCurrentModule())
3115 PopGlobalModuleFragment();
3118 /// DeclareGlobalAllocationFunction - Declares a single implicit global
3119 /// allocation function if it doesn't already exist.
3120 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name
,
3122 ArrayRef
<QualType
> Params
) {
3123 DeclContext
*GlobalCtx
= Context
.getTranslationUnitDecl();
3125 // Check if this function is already declared.
3126 DeclContext::lookup_result R
= GlobalCtx
->lookup(Name
);
3127 for (DeclContext::lookup_iterator Alloc
= R
.begin(), AllocEnd
= R
.end();
3128 Alloc
!= AllocEnd
; ++Alloc
) {
3129 // Only look at non-template functions, as it is the predefined,
3130 // non-templated allocation function we are trying to declare here.
3131 if (FunctionDecl
*Func
= dyn_cast
<FunctionDecl
>(*Alloc
)) {
3132 if (Func
->getNumParams() == Params
.size()) {
3133 llvm::SmallVector
<QualType
, 3> FuncParams
;
3134 for (auto *P
: Func
->parameters())
3135 FuncParams
.push_back(
3136 Context
.getCanonicalType(P
->getType().getUnqualifiedType()));
3137 if (llvm::ArrayRef(FuncParams
) == Params
) {
3138 // Make the function visible to name lookup, even if we found it in
3139 // an unimported module. It either is an implicitly-declared global
3140 // allocation function, or is suppressing that function.
3141 Func
->setVisibleDespiteOwningModule();
3148 FunctionProtoType::ExtProtoInfo
EPI(Context
.getDefaultCallingConvention(
3149 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3151 QualType BadAllocType
;
3152 bool HasBadAllocExceptionSpec
3153 = (Name
.getCXXOverloadedOperator() == OO_New
||
3154 Name
.getCXXOverloadedOperator() == OO_Array_New
);
3155 if (HasBadAllocExceptionSpec
) {
3156 if (!getLangOpts().CPlusPlus11
) {
3157 BadAllocType
= Context
.getTypeDeclType(getStdBadAlloc());
3158 assert(StdBadAlloc
&& "Must have std::bad_alloc declared");
3159 EPI
.ExceptionSpec
.Type
= EST_Dynamic
;
3160 EPI
.ExceptionSpec
.Exceptions
= llvm::ArrayRef(BadAllocType
);
3162 if (getLangOpts().NewInfallible
) {
3163 EPI
.ExceptionSpec
.Type
= EST_DynamicNone
;
3167 getLangOpts().CPlusPlus11
? EST_BasicNoexcept
: EST_DynamicNone
;
3170 auto CreateAllocationFunctionDecl
= [&](Attr
*ExtraAttr
) {
3171 QualType FnType
= Context
.getFunctionType(Return
, Params
, EPI
);
3172 FunctionDecl
*Alloc
= FunctionDecl::Create(
3173 Context
, GlobalCtx
, SourceLocation(), SourceLocation(), Name
, FnType
,
3174 /*TInfo=*/nullptr, SC_None
, getCurFPFeatures().isFPConstrained(), false,
3176 Alloc
->setImplicit();
3177 // Global allocation functions should always be visible.
3178 Alloc
->setVisibleDespiteOwningModule();
3180 if (HasBadAllocExceptionSpec
&& getLangOpts().NewInfallible
&&
3181 !getLangOpts().CheckNew
)
3183 ReturnsNonNullAttr::CreateImplicit(Context
, Alloc
->getLocation()));
3185 // C++ [basic.stc.dynamic.general]p2:
3186 // The library provides default definitions for the global allocation
3187 // and deallocation functions. Some global allocation and deallocation
3188 // functions are replaceable ([new.delete]); these are attached to the
3189 // global module ([module.unit]).
3191 // In the language wording, these functions are attched to the global
3192 // module all the time. But in the implementation, the global module
3193 // is only meaningful when we're in a module unit. So here we attach
3194 // these allocation functions to global module conditionally.
3195 if (TheGlobalModuleFragment
) {
3196 Alloc
->setModuleOwnershipKind(
3197 Decl::ModuleOwnershipKind::ReachableWhenImported
);
3198 Alloc
->setLocalOwningModule(TheGlobalModuleFragment
);
3201 Alloc
->addAttr(VisibilityAttr::CreateImplicit(
3202 Context
, LangOpts
.GlobalAllocationFunctionVisibilityHidden
3203 ? VisibilityAttr::Hidden
3204 : VisibilityAttr::Default
));
3206 llvm::SmallVector
<ParmVarDecl
*, 3> ParamDecls
;
3207 for (QualType T
: Params
) {
3208 ParamDecls
.push_back(ParmVarDecl::Create(
3209 Context
, Alloc
, SourceLocation(), SourceLocation(), nullptr, T
,
3210 /*TInfo=*/nullptr, SC_None
, nullptr));
3211 ParamDecls
.back()->setImplicit();
3213 Alloc
->setParams(ParamDecls
);
3215 Alloc
->addAttr(ExtraAttr
);
3216 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc
);
3217 Context
.getTranslationUnitDecl()->addDecl(Alloc
);
3218 IdResolver
.tryAddTopLevelDecl(Alloc
, Name
);
3222 CreateAllocationFunctionDecl(nullptr);
3224 // Host and device get their own declaration so each can be
3225 // defined or re-declared independently.
3226 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context
));
3227 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context
));
3231 FunctionDecl
*Sema::FindUsualDeallocationFunction(SourceLocation StartLoc
,
3232 bool CanProvideSize
,
3234 DeclarationName Name
) {
3235 DeclareGlobalNewDelete();
3237 LookupResult
FoundDelete(*this, Name
, StartLoc
, LookupOrdinaryName
);
3238 LookupQualifiedName(FoundDelete
, Context
.getTranslationUnitDecl());
3240 // FIXME: It's possible for this to result in ambiguity, through a
3241 // user-declared variadic operator delete or the enable_if attribute. We
3242 // should probably not consider those cases to be usual deallocation
3243 // functions. But for now we just make an arbitrary choice in that case.
3244 auto Result
= resolveDeallocationOverload(*this, FoundDelete
, CanProvideSize
,
3246 assert(Result
.FD
&& "operator delete missing from global scope?");
3250 FunctionDecl
*Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc
,
3251 CXXRecordDecl
*RD
) {
3252 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Delete
);
3254 FunctionDecl
*OperatorDelete
= nullptr;
3255 if (FindDeallocationFunction(Loc
, RD
, Name
, OperatorDelete
))
3258 return OperatorDelete
;
3260 // If there's no class-specific operator delete, look up the global
3261 // non-array delete.
3262 return FindUsualDeallocationFunction(
3263 Loc
, true, hasNewExtendedAlignment(*this, Context
.getRecordType(RD
)),
3267 bool Sema::FindDeallocationFunction(SourceLocation StartLoc
, CXXRecordDecl
*RD
,
3268 DeclarationName Name
,
3269 FunctionDecl
*&Operator
, bool Diagnose
,
3270 bool WantSize
, bool WantAligned
) {
3271 LookupResult
Found(*this, Name
, StartLoc
, LookupOrdinaryName
);
3272 // Try to find operator delete/operator delete[] in class scope.
3273 LookupQualifiedName(Found
, RD
);
3275 if (Found
.isAmbiguous())
3278 Found
.suppressDiagnostics();
3281 WantAligned
|| hasNewExtendedAlignment(*this, Context
.getRecordType(RD
));
3283 // C++17 [expr.delete]p10:
3284 // If the deallocation functions have class scope, the one without a
3285 // parameter of type std::size_t is selected.
3286 llvm::SmallVector
<UsualDeallocFnInfo
, 4> Matches
;
3287 resolveDeallocationOverload(*this, Found
, /*WantSize*/ WantSize
,
3288 /*WantAlign*/ Overaligned
, &Matches
);
3290 // If we could find an overload, use it.
3291 if (Matches
.size() == 1) {
3292 Operator
= cast
<CXXMethodDecl
>(Matches
[0].FD
);
3294 // FIXME: DiagnoseUseOfDecl?
3295 if (Operator
->isDeleted()) {
3297 Diag(StartLoc
, diag::err_deleted_function_use
);
3298 NoteDeletedFunction(Operator
);
3303 if (CheckAllocationAccess(StartLoc
, SourceRange(), Found
.getNamingClass(),
3304 Matches
[0].Found
, Diagnose
) == AR_inaccessible
)
3310 // We found multiple suitable operators; complain about the ambiguity.
3311 // FIXME: The standard doesn't say to do this; it appears that the intent
3312 // is that this should never happen.
3313 if (!Matches
.empty()) {
3315 Diag(StartLoc
, diag::err_ambiguous_suitable_delete_member_function_found
)
3317 for (auto &Match
: Matches
)
3318 Diag(Match
.FD
->getLocation(), diag::note_member_declared_here
) << Name
;
3323 // We did find operator delete/operator delete[] declarations, but
3324 // none of them were suitable.
3325 if (!Found
.empty()) {
3327 Diag(StartLoc
, diag::err_no_suitable_delete_member_function_found
)
3330 for (NamedDecl
*D
: Found
)
3331 Diag(D
->getUnderlyingDecl()->getLocation(),
3332 diag::note_member_declared_here
) << Name
;
3342 /// Checks whether delete-expression, and new-expression used for
3343 /// initializing deletee have the same array form.
3344 class MismatchingNewDeleteDetector
{
3346 enum MismatchResult
{
3347 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3349 /// Indicates that variable is initialized with mismatching form of \a new.
3351 /// Indicates that member is initialized with mismatching form of \a new.
3352 MemberInitMismatches
,
3353 /// Indicates that 1 or more constructors' definitions could not been
3354 /// analyzed, and they will be checked again at the end of translation unit.
3358 /// \param EndOfTU True, if this is the final analysis at the end of
3359 /// translation unit. False, if this is the initial analysis at the point
3360 /// delete-expression was encountered.
3361 explicit MismatchingNewDeleteDetector(bool EndOfTU
)
3362 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU
),
3363 HasUndefinedConstructors(false) {}
3365 /// Checks whether pointee of a delete-expression is initialized with
3366 /// matching form of new-expression.
3368 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3369 /// point where delete-expression is encountered, then a warning will be
3370 /// issued immediately. If return value is \c AnalyzeLater at the point where
3371 /// delete-expression is seen, then member will be analyzed at the end of
3372 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3373 /// couldn't be analyzed. If at least one constructor initializes the member
3374 /// with matching type of new, the return value is \c NoMismatch.
3375 MismatchResult
analyzeDeleteExpr(const CXXDeleteExpr
*DE
);
3376 /// Analyzes a class member.
3377 /// \param Field Class member to analyze.
3378 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3379 /// for deleting the \p Field.
3380 MismatchResult
analyzeField(FieldDecl
*Field
, bool DeleteWasArrayForm
);
3382 /// List of mismatching new-expressions used for initialization of the pointee
3383 llvm::SmallVector
<const CXXNewExpr
*, 4> NewExprs
;
3384 /// Indicates whether delete-expression was in array form.
3389 /// Indicates that there is at least one constructor without body.
3390 bool HasUndefinedConstructors
;
3391 /// Returns \c CXXNewExpr from given initialization expression.
3392 /// \param E Expression used for initializing pointee in delete-expression.
3393 /// E can be a single-element \c InitListExpr consisting of new-expression.
3394 const CXXNewExpr
*getNewExprFromInitListOrExpr(const Expr
*E
);
3395 /// Returns whether member is initialized with mismatching form of
3396 /// \c new either by the member initializer or in-class initialization.
3398 /// If bodies of all constructors are not visible at the end of translation
3399 /// unit or at least one constructor initializes member with the matching
3400 /// form of \c new, mismatch cannot be proven, and this function will return
3402 MismatchResult
analyzeMemberExpr(const MemberExpr
*ME
);
3403 /// Returns whether variable is initialized with mismatching form of
3406 /// If variable is initialized with matching form of \c new or variable is not
3407 /// initialized with a \c new expression, this function will return true.
3408 /// If variable is initialized with mismatching form of \c new, returns false.
3409 /// \param D Variable to analyze.
3410 bool hasMatchingVarInit(const DeclRefExpr
*D
);
3411 /// Checks whether the constructor initializes pointee with mismatching
3414 /// Returns true, if member is initialized with matching form of \c new in
3415 /// member initializer list. Returns false, if member is initialized with the
3416 /// matching form of \c new in this constructor's initializer or given
3417 /// constructor isn't defined at the point where delete-expression is seen, or
3418 /// member isn't initialized by the constructor.
3419 bool hasMatchingNewInCtor(const CXXConstructorDecl
*CD
);
3420 /// Checks whether member is initialized with matching form of
3421 /// \c new in member initializer list.
3422 bool hasMatchingNewInCtorInit(const CXXCtorInitializer
*CI
);
3423 /// Checks whether member is initialized with mismatching form of \c new by
3424 /// in-class initializer.
3425 MismatchResult
analyzeInClassInitializer();
3429 MismatchingNewDeleteDetector::MismatchResult
3430 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr
*DE
) {
3432 assert(DE
&& "Expected delete-expression");
3433 IsArrayForm
= DE
->isArrayForm();
3434 const Expr
*E
= DE
->getArgument()->IgnoreParenImpCasts();
3435 if (const MemberExpr
*ME
= dyn_cast
<const MemberExpr
>(E
)) {
3436 return analyzeMemberExpr(ME
);
3437 } else if (const DeclRefExpr
*D
= dyn_cast
<const DeclRefExpr
>(E
)) {
3438 if (!hasMatchingVarInit(D
))
3439 return VarInitMismatches
;
3445 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr
*E
) {
3446 assert(E
!= nullptr && "Expected a valid initializer expression");
3447 E
= E
->IgnoreParenImpCasts();
3448 if (const InitListExpr
*ILE
= dyn_cast
<const InitListExpr
>(E
)) {
3449 if (ILE
->getNumInits() == 1)
3450 E
= dyn_cast
<const CXXNewExpr
>(ILE
->getInit(0)->IgnoreParenImpCasts());
3453 return dyn_cast_or_null
<const CXXNewExpr
>(E
);
3456 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3457 const CXXCtorInitializer
*CI
) {
3458 const CXXNewExpr
*NE
= nullptr;
3459 if (Field
== CI
->getMember() &&
3460 (NE
= getNewExprFromInitListOrExpr(CI
->getInit()))) {
3461 if (NE
->isArray() == IsArrayForm
)
3464 NewExprs
.push_back(NE
);
3469 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3470 const CXXConstructorDecl
*CD
) {
3471 if (CD
->isImplicit())
3473 const FunctionDecl
*Definition
= CD
;
3474 if (!CD
->isThisDeclarationADefinition() && !CD
->isDefined(Definition
)) {
3475 HasUndefinedConstructors
= true;
3478 for (const auto *CI
: cast
<const CXXConstructorDecl
>(Definition
)->inits()) {
3479 if (hasMatchingNewInCtorInit(CI
))
3485 MismatchingNewDeleteDetector::MismatchResult
3486 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3487 assert(Field
!= nullptr && "This should be called only for members");
3488 const Expr
*InitExpr
= Field
->getInClassInitializer();
3490 return EndOfTU
? NoMismatch
: AnalyzeLater
;
3491 if (const CXXNewExpr
*NE
= getNewExprFromInitListOrExpr(InitExpr
)) {
3492 if (NE
->isArray() != IsArrayForm
) {
3493 NewExprs
.push_back(NE
);
3494 return MemberInitMismatches
;
3500 MismatchingNewDeleteDetector::MismatchResult
3501 MismatchingNewDeleteDetector::analyzeField(FieldDecl
*Field
,
3502 bool DeleteWasArrayForm
) {
3503 assert(Field
!= nullptr && "Analysis requires a valid class member.");
3504 this->Field
= Field
;
3505 IsArrayForm
= DeleteWasArrayForm
;
3506 const CXXRecordDecl
*RD
= cast
<const CXXRecordDecl
>(Field
->getParent());
3507 for (const auto *CD
: RD
->ctors()) {
3508 if (hasMatchingNewInCtor(CD
))
3511 if (HasUndefinedConstructors
)
3512 return EndOfTU
? NoMismatch
: AnalyzeLater
;
3513 if (!NewExprs
.empty())
3514 return MemberInitMismatches
;
3515 return Field
->hasInClassInitializer() ? analyzeInClassInitializer()
3519 MismatchingNewDeleteDetector::MismatchResult
3520 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr
*ME
) {
3521 assert(ME
!= nullptr && "Expected a member expression");
3522 if (FieldDecl
*F
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl()))
3523 return analyzeField(F
, IsArrayForm
);
3527 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr
*D
) {
3528 const CXXNewExpr
*NE
= nullptr;
3529 if (const VarDecl
*VD
= dyn_cast
<const VarDecl
>(D
->getDecl())) {
3530 if (VD
->hasInit() && (NE
= getNewExprFromInitListOrExpr(VD
->getInit())) &&
3531 NE
->isArray() != IsArrayForm
) {
3532 NewExprs
.push_back(NE
);
3535 return NewExprs
.empty();
3539 DiagnoseMismatchedNewDelete(Sema
&SemaRef
, SourceLocation DeleteLoc
,
3540 const MismatchingNewDeleteDetector
&Detector
) {
3541 SourceLocation EndOfDelete
= SemaRef
.getLocForEndOfToken(DeleteLoc
);
3543 if (!Detector
.IsArrayForm
)
3544 H
= FixItHint::CreateInsertion(EndOfDelete
, "[]");
3546 SourceLocation RSquare
= Lexer::findLocationAfterToken(
3547 DeleteLoc
, tok::l_square
, SemaRef
.getSourceManager(),
3548 SemaRef
.getLangOpts(), true);
3549 if (RSquare
.isValid())
3550 H
= FixItHint::CreateRemoval(SourceRange(EndOfDelete
, RSquare
));
3552 SemaRef
.Diag(DeleteLoc
, diag::warn_mismatched_delete_new
)
3553 << Detector
.IsArrayForm
<< H
;
3555 for (const auto *NE
: Detector
.NewExprs
)
3556 SemaRef
.Diag(NE
->getExprLoc(), diag::note_allocated_here
)
3557 << Detector
.IsArrayForm
;
3560 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr
*DE
) {
3561 if (Diags
.isIgnored(diag::warn_mismatched_delete_new
, SourceLocation()))
3563 MismatchingNewDeleteDetector
Detector(/*EndOfTU=*/false);
3564 switch (Detector
.analyzeDeleteExpr(DE
)) {
3565 case MismatchingNewDeleteDetector::VarInitMismatches
:
3566 case MismatchingNewDeleteDetector::MemberInitMismatches
: {
3567 DiagnoseMismatchedNewDelete(*this, DE
->getBeginLoc(), Detector
);
3570 case MismatchingNewDeleteDetector::AnalyzeLater
: {
3571 DeleteExprs
[Detector
.Field
].push_back(
3572 std::make_pair(DE
->getBeginLoc(), DE
->isArrayForm()));
3575 case MismatchingNewDeleteDetector::NoMismatch
:
3580 void Sema::AnalyzeDeleteExprMismatch(FieldDecl
*Field
, SourceLocation DeleteLoc
,
3581 bool DeleteWasArrayForm
) {
3582 MismatchingNewDeleteDetector
Detector(/*EndOfTU=*/true);
3583 switch (Detector
.analyzeField(Field
, DeleteWasArrayForm
)) {
3584 case MismatchingNewDeleteDetector::VarInitMismatches
:
3585 llvm_unreachable("This analysis should have been done for class members.");
3586 case MismatchingNewDeleteDetector::AnalyzeLater
:
3587 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3588 "translation unit.");
3589 case MismatchingNewDeleteDetector::MemberInitMismatches
:
3590 DiagnoseMismatchedNewDelete(*this, DeleteLoc
, Detector
);
3592 case MismatchingNewDeleteDetector::NoMismatch
:
3597 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3598 /// @code ::delete ptr; @endcode
3600 /// @code delete [] ptr; @endcode
3602 Sema::ActOnCXXDelete(SourceLocation StartLoc
, bool UseGlobal
,
3603 bool ArrayForm
, Expr
*ExE
) {
3604 // C++ [expr.delete]p1:
3605 // The operand shall have a pointer type, or a class type having a single
3606 // non-explicit conversion function to a pointer type. The result has type
3609 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3611 ExprResult Ex
= ExE
;
3612 FunctionDecl
*OperatorDelete
= nullptr;
3613 bool ArrayFormAsWritten
= ArrayForm
;
3614 bool UsualArrayDeleteWantsSize
= false;
3616 if (!Ex
.get()->isTypeDependent()) {
3617 // Perform lvalue-to-rvalue cast, if needed.
3618 Ex
= DefaultLvalueConversion(Ex
.get());
3622 QualType Type
= Ex
.get()->getType();
3624 class DeleteConverter
: public ContextualImplicitConverter
{
3626 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3628 bool match(QualType ConvType
) override
{
3629 // FIXME: If we have an operator T* and an operator void*, we must pick
3631 if (const PointerType
*ConvPtrType
= ConvType
->getAs
<PointerType
>())
3632 if (ConvPtrType
->getPointeeType()->isIncompleteOrObjectType())
3637 SemaDiagnosticBuilder
diagnoseNoMatch(Sema
&S
, SourceLocation Loc
,
3638 QualType T
) override
{
3639 return S
.Diag(Loc
, diag::err_delete_operand
) << T
;
3642 SemaDiagnosticBuilder
diagnoseIncomplete(Sema
&S
, SourceLocation Loc
,
3643 QualType T
) override
{
3644 return S
.Diag(Loc
, diag::err_delete_incomplete_class_type
) << T
;
3647 SemaDiagnosticBuilder
diagnoseExplicitConv(Sema
&S
, SourceLocation Loc
,
3649 QualType ConvTy
) override
{
3650 return S
.Diag(Loc
, diag::err_delete_explicit_conversion
) << T
<< ConvTy
;
3653 SemaDiagnosticBuilder
noteExplicitConv(Sema
&S
, CXXConversionDecl
*Conv
,
3654 QualType ConvTy
) override
{
3655 return S
.Diag(Conv
->getLocation(), diag::note_delete_conversion
)
3659 SemaDiagnosticBuilder
diagnoseAmbiguous(Sema
&S
, SourceLocation Loc
,
3660 QualType T
) override
{
3661 return S
.Diag(Loc
, diag::err_ambiguous_delete_operand
) << T
;
3664 SemaDiagnosticBuilder
noteAmbiguous(Sema
&S
, CXXConversionDecl
*Conv
,
3665 QualType ConvTy
) override
{
3666 return S
.Diag(Conv
->getLocation(), diag::note_delete_conversion
)
3670 SemaDiagnosticBuilder
diagnoseConversion(Sema
&S
, SourceLocation Loc
,
3672 QualType ConvTy
) override
{
3673 llvm_unreachable("conversion functions are permitted");
3677 Ex
= PerformContextualImplicitConversion(StartLoc
, Ex
.get(), Converter
);
3680 Type
= Ex
.get()->getType();
3681 if (!Converter
.match(Type
))
3682 // FIXME: PerformContextualImplicitConversion should return ExprError
3683 // itself in this case.
3686 QualType Pointee
= Type
->castAs
<PointerType
>()->getPointeeType();
3687 QualType PointeeElem
= Context
.getBaseElementType(Pointee
);
3689 if (Pointee
.getAddressSpace() != LangAS::Default
&&
3690 !getLangOpts().OpenCLCPlusPlus
)
3691 return Diag(Ex
.get()->getBeginLoc(),
3692 diag::err_address_space_qualified_delete
)
3693 << Pointee
.getUnqualifiedType()
3694 << Pointee
.getQualifiers().getAddressSpaceAttributePrintValue();
3696 CXXRecordDecl
*PointeeRD
= nullptr;
3697 if (Pointee
->isVoidType() && !isSFINAEContext()) {
3698 // The C++ standard bans deleting a pointer to a non-object type, which
3699 // effectively bans deletion of "void*". However, most compilers support
3700 // this, so we treat it as a warning unless we're in a SFINAE context.
3701 Diag(StartLoc
, diag::ext_delete_void_ptr_operand
)
3702 << Type
<< Ex
.get()->getSourceRange();
3703 } else if (Pointee
->isFunctionType() || Pointee
->isVoidType() ||
3704 Pointee
->isSizelessType()) {
3705 return ExprError(Diag(StartLoc
, diag::err_delete_operand
)
3706 << Type
<< Ex
.get()->getSourceRange());
3707 } else if (!Pointee
->isDependentType()) {
3708 // FIXME: This can result in errors if the definition was imported from a
3709 // module but is hidden.
3710 if (!RequireCompleteType(StartLoc
, Pointee
,
3711 diag::warn_delete_incomplete
, Ex
.get())) {
3712 if (const RecordType
*RT
= PointeeElem
->getAs
<RecordType
>())
3713 PointeeRD
= cast
<CXXRecordDecl
>(RT
->getDecl());
3717 if (Pointee
->isArrayType() && !ArrayForm
) {
3718 Diag(StartLoc
, diag::warn_delete_array_type
)
3719 << Type
<< Ex
.get()->getSourceRange()
3720 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc
), "[]");
3724 DeclarationName DeleteName
= Context
.DeclarationNames
.getCXXOperatorName(
3725 ArrayForm
? OO_Array_Delete
: OO_Delete
);
3729 FindDeallocationFunction(StartLoc
, PointeeRD
, DeleteName
,
3733 // If we're allocating an array of records, check whether the
3734 // usual operator delete[] has a size_t parameter.
3736 // If the user specifically asked to use the global allocator,
3737 // we'll need to do the lookup into the class.
3739 UsualArrayDeleteWantsSize
=
3740 doesUsualArrayDeleteWantSize(*this, StartLoc
, PointeeElem
);
3742 // Otherwise, the usual operator delete[] should be the
3743 // function we just found.
3744 else if (OperatorDelete
&& isa
<CXXMethodDecl
>(OperatorDelete
))
3745 UsualArrayDeleteWantsSize
=
3746 UsualDeallocFnInfo(*this,
3747 DeclAccessPair::make(OperatorDelete
, AS_public
))
3751 if (!PointeeRD
->hasIrrelevantDestructor())
3752 if (CXXDestructorDecl
*Dtor
= LookupDestructor(PointeeRD
)) {
3753 MarkFunctionReferenced(StartLoc
,
3754 const_cast<CXXDestructorDecl
*>(Dtor
));
3755 if (DiagnoseUseOfDecl(Dtor
, StartLoc
))
3759 CheckVirtualDtorCall(PointeeRD
->getDestructor(), StartLoc
,
3760 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3761 /*WarnOnNonAbstractTypes=*/!ArrayForm
,
3765 if (!OperatorDelete
) {
3766 if (getLangOpts().OpenCLCPlusPlus
) {
3767 Diag(StartLoc
, diag::err_openclcxx_not_supported
) << "default delete";
3771 bool IsComplete
= isCompleteType(StartLoc
, Pointee
);
3772 bool CanProvideSize
=
3773 IsComplete
&& (!ArrayForm
|| UsualArrayDeleteWantsSize
||
3774 Pointee
.isDestructedType());
3775 bool Overaligned
= hasNewExtendedAlignment(*this, Pointee
);
3777 // Look for a global declaration.
3778 OperatorDelete
= FindUsualDeallocationFunction(StartLoc
, CanProvideSize
,
3779 Overaligned
, DeleteName
);
3782 MarkFunctionReferenced(StartLoc
, OperatorDelete
);
3784 // Check access and ambiguity of destructor if we're going to call it.
3785 // Note that this is required even for a virtual delete.
3786 bool IsVirtualDelete
= false;
3788 if (CXXDestructorDecl
*Dtor
= LookupDestructor(PointeeRD
)) {
3789 CheckDestructorAccess(Ex
.get()->getExprLoc(), Dtor
,
3790 PDiag(diag::err_access_dtor
) << PointeeElem
);
3791 IsVirtualDelete
= Dtor
->isVirtual();
3795 DiagnoseUseOfDecl(OperatorDelete
, StartLoc
);
3797 // Convert the operand to the type of the first parameter of operator
3798 // delete. This is only necessary if we selected a destroying operator
3799 // delete that we are going to call (non-virtually); converting to void*
3800 // is trivial and left to AST consumers to handle.
3801 QualType ParamType
= OperatorDelete
->getParamDecl(0)->getType();
3802 if (!IsVirtualDelete
&& !ParamType
->getPointeeType()->isVoidType()) {
3803 Qualifiers Qs
= Pointee
.getQualifiers();
3804 if (Qs
.hasCVRQualifiers()) {
3805 // Qualifiers are irrelevant to this conversion; we're only looking
3806 // for access and ambiguity.
3807 Qs
.removeCVRQualifiers();
3808 QualType Unqual
= Context
.getPointerType(
3809 Context
.getQualifiedType(Pointee
.getUnqualifiedType(), Qs
));
3810 Ex
= ImpCastExprToType(Ex
.get(), Unqual
, CK_NoOp
);
3812 Ex
= PerformImplicitConversion(Ex
.get(), ParamType
, AA_Passing
);
3818 CXXDeleteExpr
*Result
= new (Context
) CXXDeleteExpr(
3819 Context
.VoidTy
, UseGlobal
, ArrayForm
, ArrayFormAsWritten
,
3820 UsualArrayDeleteWantsSize
, OperatorDelete
, Ex
.get(), StartLoc
);
3821 AnalyzeDeleteExprMismatch(Result
);
3825 static bool resolveBuiltinNewDeleteOverload(Sema
&S
, CallExpr
*TheCall
,
3827 FunctionDecl
*&Operator
) {
3829 DeclarationName NewName
= S
.Context
.DeclarationNames
.getCXXOperatorName(
3830 IsDelete
? OO_Delete
: OO_New
);
3832 LookupResult
R(S
, NewName
, TheCall
->getBeginLoc(), Sema::LookupOrdinaryName
);
3833 S
.LookupQualifiedName(R
, S
.Context
.getTranslationUnitDecl());
3834 assert(!R
.empty() && "implicitly declared allocation functions not found");
3835 assert(!R
.isAmbiguous() && "global allocation functions are ambiguous");
3837 // We do our own custom access checks below.
3838 R
.suppressDiagnostics();
3840 SmallVector
<Expr
*, 8> Args(TheCall
->arguments());
3841 OverloadCandidateSet
Candidates(R
.getNameLoc(),
3842 OverloadCandidateSet::CSK_Normal
);
3843 for (LookupResult::iterator FnOvl
= R
.begin(), FnOvlEnd
= R
.end();
3844 FnOvl
!= FnOvlEnd
; ++FnOvl
) {
3845 // Even member operator new/delete are implicitly treated as
3846 // static, so don't use AddMemberCandidate.
3847 NamedDecl
*D
= (*FnOvl
)->getUnderlyingDecl();
3849 if (FunctionTemplateDecl
*FnTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
)) {
3850 S
.AddTemplateOverloadCandidate(FnTemplate
, FnOvl
.getPair(),
3851 /*ExplicitTemplateArgs=*/nullptr, Args
,
3853 /*SuppressUserConversions=*/false);
3857 FunctionDecl
*Fn
= cast
<FunctionDecl
>(D
);
3858 S
.AddOverloadCandidate(Fn
, FnOvl
.getPair(), Args
, Candidates
,
3859 /*SuppressUserConversions=*/false);
3862 SourceRange Range
= TheCall
->getSourceRange();
3864 // Do the resolution.
3865 OverloadCandidateSet::iterator Best
;
3866 switch (Candidates
.BestViableFunction(S
, R
.getNameLoc(), Best
)) {
3869 FunctionDecl
*FnDecl
= Best
->Function
;
3870 assert(R
.getNamingClass() == nullptr &&
3871 "class members should not be considered");
3873 if (!FnDecl
->isReplaceableGlobalAllocationFunction()) {
3874 S
.Diag(R
.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual
)
3875 << (IsDelete
? 1 : 0) << Range
;
3876 S
.Diag(FnDecl
->getLocation(), diag::note_non_usual_function_declared_here
)
3877 << R
.getLookupName() << FnDecl
->getSourceRange();
3885 case OR_No_Viable_Function
:
3886 Candidates
.NoteCandidates(
3887 PartialDiagnosticAt(R
.getNameLoc(),
3888 S
.PDiag(diag::err_ovl_no_viable_function_in_call
)
3889 << R
.getLookupName() << Range
),
3890 S
, OCD_AllCandidates
, Args
);
3894 Candidates
.NoteCandidates(
3895 PartialDiagnosticAt(R
.getNameLoc(),
3896 S
.PDiag(diag::err_ovl_ambiguous_call
)
3897 << R
.getLookupName() << Range
),
3898 S
, OCD_AmbiguousCandidates
, Args
);
3902 Candidates
.NoteCandidates(
3903 PartialDiagnosticAt(R
.getNameLoc(), S
.PDiag(diag::err_ovl_deleted_call
)
3904 << R
.getLookupName() << Range
),
3905 S
, OCD_AllCandidates
, Args
);
3909 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3913 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult
,
3915 CallExpr
*TheCall
= cast
<CallExpr
>(TheCallResult
.get());
3916 if (!getLangOpts().CPlusPlus
) {
3917 Diag(TheCall
->getExprLoc(), diag::err_builtin_requires_language
)
3918 << (IsDelete
? "__builtin_operator_delete" : "__builtin_operator_new")
3922 // CodeGen assumes it can find the global new and delete to call,
3923 // so ensure that they are declared.
3924 DeclareGlobalNewDelete();
3926 FunctionDecl
*OperatorNewOrDelete
= nullptr;
3927 if (resolveBuiltinNewDeleteOverload(*this, TheCall
, IsDelete
,
3928 OperatorNewOrDelete
))
3930 assert(OperatorNewOrDelete
&& "should be found");
3932 DiagnoseUseOfDecl(OperatorNewOrDelete
, TheCall
->getExprLoc());
3933 MarkFunctionReferenced(TheCall
->getExprLoc(), OperatorNewOrDelete
);
3935 TheCall
->setType(OperatorNewOrDelete
->getReturnType());
3936 for (unsigned i
= 0; i
!= TheCall
->getNumArgs(); ++i
) {
3937 QualType ParamTy
= OperatorNewOrDelete
->getParamDecl(i
)->getType();
3938 InitializedEntity Entity
=
3939 InitializedEntity::InitializeParameter(Context
, ParamTy
, false);
3940 ExprResult Arg
= PerformCopyInitialization(
3941 Entity
, TheCall
->getArg(i
)->getBeginLoc(), TheCall
->getArg(i
));
3942 if (Arg
.isInvalid())
3944 TheCall
->setArg(i
, Arg
.get());
3946 auto Callee
= dyn_cast
<ImplicitCastExpr
>(TheCall
->getCallee());
3947 assert(Callee
&& Callee
->getCastKind() == CK_BuiltinFnToFnPtr
&&
3948 "Callee expected to be implicit cast to a builtin function pointer");
3949 Callee
->setType(OperatorNewOrDelete
->getType());
3951 return TheCallResult
;
3954 void Sema::CheckVirtualDtorCall(CXXDestructorDecl
*dtor
, SourceLocation Loc
,
3955 bool IsDelete
, bool CallCanBeVirtual
,
3956 bool WarnOnNonAbstractTypes
,
3957 SourceLocation DtorLoc
) {
3958 if (!dtor
|| dtor
->isVirtual() || !CallCanBeVirtual
|| isUnevaluatedContext())
3961 // C++ [expr.delete]p3:
3962 // In the first alternative (delete object), if the static type of the
3963 // object to be deleted is different from its dynamic type, the static
3964 // type shall be a base class of the dynamic type of the object to be
3965 // deleted and the static type shall have a virtual destructor or the
3966 // behavior is undefined.
3968 const CXXRecordDecl
*PointeeRD
= dtor
->getParent();
3969 // Note: a final class cannot be derived from, no issue there
3970 if (!PointeeRD
->isPolymorphic() || PointeeRD
->hasAttr
<FinalAttr
>())
3973 // If the superclass is in a system header, there's nothing that can be done.
3974 // The `delete` (where we emit the warning) can be in a system header,
3975 // what matters for this warning is where the deleted type is defined.
3976 if (getSourceManager().isInSystemHeader(PointeeRD
->getLocation()))
3979 QualType ClassType
= dtor
->getFunctionObjectParameterType();
3980 if (PointeeRD
->isAbstract()) {
3981 // If the class is abstract, we warn by default, because we're
3982 // sure the code has undefined behavior.
3983 Diag(Loc
, diag::warn_delete_abstract_non_virtual_dtor
) << (IsDelete
? 0 : 1)
3985 } else if (WarnOnNonAbstractTypes
) {
3986 // Otherwise, if this is not an array delete, it's a bit suspect,
3987 // but not necessarily wrong.
3988 Diag(Loc
, diag::warn_delete_non_virtual_dtor
) << (IsDelete
? 0 : 1)
3992 std::string TypeStr
;
3993 ClassType
.getAsStringInternal(TypeStr
, getPrintingPolicy());
3994 Diag(DtorLoc
, diag::note_delete_non_virtual
)
3995 << FixItHint::CreateInsertion(DtorLoc
, TypeStr
+ "::");
3999 Sema::ConditionResult
Sema::ActOnConditionVariable(Decl
*ConditionVar
,
4000 SourceLocation StmtLoc
,
4003 CheckConditionVariable(cast
<VarDecl
>(ConditionVar
), StmtLoc
, CK
);
4005 return ConditionError();
4006 return ConditionResult(*this, ConditionVar
, MakeFullExpr(E
.get(), StmtLoc
),
4007 CK
== ConditionKind::ConstexprIf
);
4010 /// Check the use of the given variable as a C++ condition in an if,
4011 /// while, do-while, or switch statement.
4012 ExprResult
Sema::CheckConditionVariable(VarDecl
*ConditionVar
,
4013 SourceLocation StmtLoc
,
4015 if (ConditionVar
->isInvalidDecl())
4018 QualType T
= ConditionVar
->getType();
4020 // C++ [stmt.select]p2:
4021 // The declarator shall not specify a function or an array.
4022 if (T
->isFunctionType())
4023 return ExprError(Diag(ConditionVar
->getLocation(),
4024 diag::err_invalid_use_of_function_type
)
4025 << ConditionVar
->getSourceRange());
4026 else if (T
->isArrayType())
4027 return ExprError(Diag(ConditionVar
->getLocation(),
4028 diag::err_invalid_use_of_array_type
)
4029 << ConditionVar
->getSourceRange());
4031 ExprResult Condition
= BuildDeclRefExpr(
4032 ConditionVar
, ConditionVar
->getType().getNonReferenceType(), VK_LValue
,
4033 ConditionVar
->getLocation());
4036 case ConditionKind::Boolean
:
4037 return CheckBooleanCondition(StmtLoc
, Condition
.get());
4039 case ConditionKind::ConstexprIf
:
4040 return CheckBooleanCondition(StmtLoc
, Condition
.get(), true);
4042 case ConditionKind::Switch
:
4043 return CheckSwitchCondition(StmtLoc
, Condition
.get());
4046 llvm_unreachable("unexpected condition kind");
4049 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4050 ExprResult
Sema::CheckCXXBooleanCondition(Expr
*CondExpr
, bool IsConstexpr
) {
4052 // The value of a condition that is an initialized declaration in a statement
4053 // other than a switch statement is the value of the declared variable
4054 // implicitly converted to type bool. If that conversion is ill-formed, the
4055 // program is ill-formed.
4056 // The value of a condition that is an expression is the value of the
4057 // expression, implicitly converted to bool.
4060 // If the if statement is of the form if constexpr, the value of the condition
4061 // is contextually converted to bool and the converted expression shall be
4062 // a constant expression.
4065 ExprResult E
= PerformContextuallyConvertToBool(CondExpr
);
4066 if (!IsConstexpr
|| E
.isInvalid() || E
.get()->isValueDependent())
4069 // FIXME: Return this value to the caller so they don't need to recompute it.
4071 E
= VerifyIntegerConstantExpression(
4073 diag::err_constexpr_if_condition_expression_is_not_constant
);
4077 /// Helper function to determine whether this is the (deprecated) C++
4078 /// conversion from a string literal to a pointer to non-const char or
4079 /// non-const wchar_t (for narrow and wide string literals,
4082 Sema::IsStringLiteralToNonConstPointerConversion(Expr
*From
, QualType ToType
) {
4083 // Look inside the implicit cast, if it exists.
4084 if (ImplicitCastExpr
*Cast
= dyn_cast
<ImplicitCastExpr
>(From
))
4085 From
= Cast
->getSubExpr();
4087 // A string literal (2.13.4) that is not a wide string literal can
4088 // be converted to an rvalue of type "pointer to char"; a wide
4089 // string literal can be converted to an rvalue of type "pointer
4090 // to wchar_t" (C++ 4.2p2).
4091 if (StringLiteral
*StrLit
= dyn_cast
<StringLiteral
>(From
->IgnoreParens()))
4092 if (const PointerType
*ToPtrType
= ToType
->getAs
<PointerType
>())
4093 if (const BuiltinType
*ToPointeeType
4094 = ToPtrType
->getPointeeType()->getAs
<BuiltinType
>()) {
4095 // This conversion is considered only when there is an
4096 // explicit appropriate pointer target type (C++ 4.2p2).
4097 if (!ToPtrType
->getPointeeType().hasQualifiers()) {
4098 switch (StrLit
->getKind()) {
4099 case StringLiteral::UTF8
:
4100 case StringLiteral::UTF16
:
4101 case StringLiteral::UTF32
:
4102 // We don't allow UTF literals to be implicitly converted
4104 case StringLiteral::Ordinary
:
4105 return (ToPointeeType
->getKind() == BuiltinType::Char_U
||
4106 ToPointeeType
->getKind() == BuiltinType::Char_S
);
4107 case StringLiteral::Wide
:
4108 return Context
.typesAreCompatible(Context
.getWideCharType(),
4109 QualType(ToPointeeType
, 0));
4110 case StringLiteral::Unevaluated
:
4111 assert(false && "Unevaluated string literal in expression");
4120 static ExprResult
BuildCXXCastArgument(Sema
&S
,
4121 SourceLocation CastLoc
,
4124 CXXMethodDecl
*Method
,
4125 DeclAccessPair FoundDecl
,
4126 bool HadMultipleCandidates
,
4129 default: llvm_unreachable("Unhandled cast kind!");
4130 case CK_ConstructorConversion
: {
4131 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(Method
);
4132 SmallVector
<Expr
*, 8> ConstructorArgs
;
4134 if (S
.RequireNonAbstractType(CastLoc
, Ty
,
4135 diag::err_allocation_of_abstract_type
))
4138 if (S
.CompleteConstructorCall(Constructor
, Ty
, From
, CastLoc
,
4142 S
.CheckConstructorAccess(CastLoc
, Constructor
, FoundDecl
,
4143 InitializedEntity::InitializeTemporary(Ty
));
4144 if (S
.DiagnoseUseOfDecl(Method
, CastLoc
))
4147 ExprResult Result
= S
.BuildCXXConstructExpr(
4148 CastLoc
, Ty
, FoundDecl
, cast
<CXXConstructorDecl
>(Method
),
4149 ConstructorArgs
, HadMultipleCandidates
,
4150 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4151 CXXConstructExpr::CK_Complete
, SourceRange());
4152 if (Result
.isInvalid())
4155 return S
.MaybeBindToTemporary(Result
.getAs
<Expr
>());
4158 case CK_UserDefinedConversion
: {
4159 assert(!From
->getType()->isPointerType() && "Arg can't have pointer type!");
4161 S
.CheckMemberOperatorAccess(CastLoc
, From
, /*arg*/ nullptr, FoundDecl
);
4162 if (S
.DiagnoseUseOfDecl(Method
, CastLoc
))
4165 // Create an implicit call expr that calls it.
4166 CXXConversionDecl
*Conv
= cast
<CXXConversionDecl
>(Method
);
4167 ExprResult Result
= S
.BuildCXXMemberCallExpr(From
, FoundDecl
, Conv
,
4168 HadMultipleCandidates
);
4169 if (Result
.isInvalid())
4171 // Record usage of conversion in an implicit cast.
4172 Result
= ImplicitCastExpr::Create(S
.Context
, Result
.get()->getType(),
4173 CK_UserDefinedConversion
, Result
.get(),
4174 nullptr, Result
.get()->getValueKind(),
4175 S
.CurFPFeatureOverrides());
4177 return S
.MaybeBindToTemporary(Result
.get());
4182 /// PerformImplicitConversion - Perform an implicit conversion of the
4183 /// expression From to the type ToType using the pre-computed implicit
4184 /// conversion sequence ICS. Returns the converted
4185 /// expression. Action is the kind of conversion we're performing,
4186 /// used in the error message.
4188 Sema::PerformImplicitConversion(Expr
*From
, QualType ToType
,
4189 const ImplicitConversionSequence
&ICS
,
4190 AssignmentAction Action
,
4191 CheckedConversionKind CCK
) {
4192 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4193 if (CCK
== CCK_ForBuiltinOverloadedOp
&& !From
->getType()->isRecordType())
4196 switch (ICS
.getKind()) {
4197 case ImplicitConversionSequence::StandardConversion
: {
4198 ExprResult Res
= PerformImplicitConversion(From
, ToType
, ICS
.Standard
,
4200 if (Res
.isInvalid())
4206 case ImplicitConversionSequence::UserDefinedConversion
: {
4208 FunctionDecl
*FD
= ICS
.UserDefined
.ConversionFunction
;
4210 QualType BeforeToType
;
4211 assert(FD
&& "no conversion function for user-defined conversion seq");
4212 if (const CXXConversionDecl
*Conv
= dyn_cast
<CXXConversionDecl
>(FD
)) {
4213 CastKind
= CK_UserDefinedConversion
;
4215 // If the user-defined conversion is specified by a conversion function,
4216 // the initial standard conversion sequence converts the source type to
4217 // the implicit object parameter of the conversion function.
4218 BeforeToType
= Context
.getTagDeclType(Conv
->getParent());
4220 const CXXConstructorDecl
*Ctor
= cast
<CXXConstructorDecl
>(FD
);
4221 CastKind
= CK_ConstructorConversion
;
4222 // Do no conversion if dealing with ... for the first conversion.
4223 if (!ICS
.UserDefined
.EllipsisConversion
) {
4224 // If the user-defined conversion is specified by a constructor, the
4225 // initial standard conversion sequence converts the source type to
4226 // the type required by the argument of the constructor
4227 BeforeToType
= Ctor
->getParamDecl(0)->getType().getNonReferenceType();
4230 // Watch out for ellipsis conversion.
4231 if (!ICS
.UserDefined
.EllipsisConversion
) {
4233 PerformImplicitConversion(From
, BeforeToType
,
4234 ICS
.UserDefined
.Before
, AA_Converting
,
4236 if (Res
.isInvalid())
4241 ExprResult CastArg
= BuildCXXCastArgument(
4242 *this, From
->getBeginLoc(), ToType
.getNonReferenceType(), CastKind
,
4243 cast
<CXXMethodDecl
>(FD
), ICS
.UserDefined
.FoundConversionFunction
,
4244 ICS
.UserDefined
.HadMultipleCandidates
, From
);
4246 if (CastArg
.isInvalid())
4249 From
= CastArg
.get();
4251 // C++ [over.match.oper]p7:
4252 // [...] the second standard conversion sequence of a user-defined
4253 // conversion sequence is not applied.
4254 if (CCK
== CCK_ForBuiltinOverloadedOp
)
4257 return PerformImplicitConversion(From
, ToType
, ICS
.UserDefined
.After
,
4258 AA_Converting
, CCK
);
4261 case ImplicitConversionSequence::AmbiguousConversion
:
4262 ICS
.DiagnoseAmbiguousConversion(*this, From
->getExprLoc(),
4263 PDiag(diag::err_typecheck_ambiguous_condition
)
4264 << From
->getSourceRange());
4267 case ImplicitConversionSequence::EllipsisConversion
:
4268 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
4269 llvm_unreachable("bad conversion");
4271 case ImplicitConversionSequence::BadConversion
:
4272 Sema::AssignConvertType ConvTy
=
4273 CheckAssignmentConstraints(From
->getExprLoc(), ToType
, From
->getType());
4274 bool Diagnosed
= DiagnoseAssignmentResult(
4275 ConvTy
== Compatible
? Incompatible
: ConvTy
, From
->getExprLoc(),
4276 ToType
, From
->getType(), From
, Action
);
4277 assert(Diagnosed
&& "failed to diagnose bad conversion"); (void)Diagnosed
;
4281 // Everything went well.
4285 /// PerformImplicitConversion - Perform an implicit conversion of the
4286 /// expression From to the type ToType by following the standard
4287 /// conversion sequence SCS. Returns the converted
4288 /// expression. Flavor is the context in which we're performing this
4289 /// conversion, for use in error messages.
4291 Sema::PerformImplicitConversion(Expr
*From
, QualType ToType
,
4292 const StandardConversionSequence
& SCS
,
4293 AssignmentAction Action
,
4294 CheckedConversionKind CCK
) {
4295 bool CStyle
= (CCK
== CCK_CStyleCast
|| CCK
== CCK_FunctionalCast
);
4297 // Overall FIXME: we are recomputing too many types here and doing far too
4298 // much extra work. What this means is that we need to keep track of more
4299 // information that is computed when we try the implicit conversion initially,
4300 // so that we don't need to recompute anything here.
4301 QualType FromType
= From
->getType();
4303 if (SCS
.CopyConstructor
) {
4304 // FIXME: When can ToType be a reference type?
4305 assert(!ToType
->isReferenceType());
4306 if (SCS
.Second
== ICK_Derived_To_Base
) {
4307 SmallVector
<Expr
*, 8> ConstructorArgs
;
4308 if (CompleteConstructorCall(
4309 cast
<CXXConstructorDecl
>(SCS
.CopyConstructor
), ToType
, From
,
4310 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs
))
4312 return BuildCXXConstructExpr(
4313 /*FIXME:ConstructLoc*/ SourceLocation(), ToType
,
4314 SCS
.FoundCopyConstructor
, SCS
.CopyConstructor
,
4315 ConstructorArgs
, /*HadMultipleCandidates*/ false,
4316 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4317 CXXConstructExpr::CK_Complete
, SourceRange());
4319 return BuildCXXConstructExpr(
4320 /*FIXME:ConstructLoc*/ SourceLocation(), ToType
,
4321 SCS
.FoundCopyConstructor
, SCS
.CopyConstructor
,
4322 From
, /*HadMultipleCandidates*/ false,
4323 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4324 CXXConstructExpr::CK_Complete
, SourceRange());
4327 // Resolve overloaded function references.
4328 if (Context
.hasSameType(FromType
, Context
.OverloadTy
)) {
4329 DeclAccessPair Found
;
4330 FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(From
, ToType
,
4335 if (DiagnoseUseOfDecl(Fn
, From
->getBeginLoc()))
4338 ExprResult Res
= FixOverloadedFunctionReference(From
, Found
, Fn
);
4339 if (Res
.isInvalid())
4342 // We might get back another placeholder expression if we resolved to a
4344 Res
= CheckPlaceholderExpr(Res
.get());
4345 if (Res
.isInvalid())
4349 FromType
= From
->getType();
4352 // If we're converting to an atomic type, first convert to the corresponding
4354 QualType ToAtomicType
;
4355 if (const AtomicType
*ToAtomic
= ToType
->getAs
<AtomicType
>()) {
4356 ToAtomicType
= ToType
;
4357 ToType
= ToAtomic
->getValueType();
4360 QualType InitialFromType
= FromType
;
4361 // Perform the first implicit conversion.
4362 switch (SCS
.First
) {
4364 if (const AtomicType
*FromAtomic
= FromType
->getAs
<AtomicType
>()) {
4365 FromType
= FromAtomic
->getValueType().getUnqualifiedType();
4366 From
= ImplicitCastExpr::Create(Context
, FromType
, CK_AtomicToNonAtomic
,
4367 From
, /*BasePath=*/nullptr, VK_PRValue
,
4368 FPOptionsOverride());
4372 case ICK_Lvalue_To_Rvalue
: {
4373 assert(From
->getObjectKind() != OK_ObjCProperty
);
4374 ExprResult FromRes
= DefaultLvalueConversion(From
);
4375 if (FromRes
.isInvalid())
4378 From
= FromRes
.get();
4379 FromType
= From
->getType();
4383 case ICK_Array_To_Pointer
:
4384 FromType
= Context
.getArrayDecayedType(FromType
);
4385 From
= ImpCastExprToType(From
, FromType
, CK_ArrayToPointerDecay
, VK_PRValue
,
4386 /*BasePath=*/nullptr, CCK
)
4390 case ICK_Function_To_Pointer
:
4391 FromType
= Context
.getPointerType(FromType
);
4392 From
= ImpCastExprToType(From
, FromType
, CK_FunctionToPointerDecay
,
4393 VK_PRValue
, /*BasePath=*/nullptr, CCK
)
4398 llvm_unreachable("Improper first standard conversion");
4401 // Perform the second implicit conversion
4402 switch (SCS
.Second
) {
4404 // C++ [except.spec]p5:
4405 // [For] assignment to and initialization of pointers to functions,
4406 // pointers to member functions, and references to functions: the
4407 // target entity shall allow at least the exceptions allowed by the
4408 // source value in the assignment or initialization.
4411 case AA_Initializing
:
4412 // Note, function argument passing and returning are initialization.
4416 case AA_Passing_CFAudited
:
4417 if (CheckExceptionSpecCompatibility(From
, ToType
))
4423 // Casts and implicit conversions are not initialization, so are not
4424 // checked for exception specification mismatches.
4427 // Nothing else to do.
4430 case ICK_Integral_Promotion
:
4431 case ICK_Integral_Conversion
:
4432 if (ToType
->isBooleanType()) {
4433 assert(FromType
->castAs
<EnumType
>()->getDecl()->isFixed() &&
4434 SCS
.Second
== ICK_Integral_Promotion
&&
4435 "only enums with fixed underlying type can promote to bool");
4436 From
= ImpCastExprToType(From
, ToType
, CK_IntegralToBoolean
, VK_PRValue
,
4437 /*BasePath=*/nullptr, CCK
)
4440 From
= ImpCastExprToType(From
, ToType
, CK_IntegralCast
, VK_PRValue
,
4441 /*BasePath=*/nullptr, CCK
)
4446 case ICK_Floating_Promotion
:
4447 case ICK_Floating_Conversion
:
4448 From
= ImpCastExprToType(From
, ToType
, CK_FloatingCast
, VK_PRValue
,
4449 /*BasePath=*/nullptr, CCK
)
4453 case ICK_Complex_Promotion
:
4454 case ICK_Complex_Conversion
: {
4455 QualType FromEl
= From
->getType()->castAs
<ComplexType
>()->getElementType();
4456 QualType ToEl
= ToType
->castAs
<ComplexType
>()->getElementType();
4458 if (FromEl
->isRealFloatingType()) {
4459 if (ToEl
->isRealFloatingType())
4460 CK
= CK_FloatingComplexCast
;
4462 CK
= CK_FloatingComplexToIntegralComplex
;
4463 } else if (ToEl
->isRealFloatingType()) {
4464 CK
= CK_IntegralComplexToFloatingComplex
;
4466 CK
= CK_IntegralComplexCast
;
4468 From
= ImpCastExprToType(From
, ToType
, CK
, VK_PRValue
, /*BasePath=*/nullptr,
4474 case ICK_Floating_Integral
:
4475 if (ToType
->isRealFloatingType())
4476 From
= ImpCastExprToType(From
, ToType
, CK_IntegralToFloating
, VK_PRValue
,
4477 /*BasePath=*/nullptr, CCK
)
4480 From
= ImpCastExprToType(From
, ToType
, CK_FloatingToIntegral
, VK_PRValue
,
4481 /*BasePath=*/nullptr, CCK
)
4485 case ICK_Compatible_Conversion
:
4486 From
= ImpCastExprToType(From
, ToType
, CK_NoOp
, From
->getValueKind(),
4487 /*BasePath=*/nullptr, CCK
).get();
4490 case ICK_Writeback_Conversion
:
4491 case ICK_Pointer_Conversion
: {
4492 if (SCS
.IncompatibleObjC
&& Action
!= AA_Casting
) {
4493 // Diagnose incompatible Objective-C conversions
4494 if (Action
== AA_Initializing
|| Action
== AA_Assigning
)
4495 Diag(From
->getBeginLoc(),
4496 diag::ext_typecheck_convert_incompatible_pointer
)
4497 << ToType
<< From
->getType() << Action
<< From
->getSourceRange()
4500 Diag(From
->getBeginLoc(),
4501 diag::ext_typecheck_convert_incompatible_pointer
)
4502 << From
->getType() << ToType
<< Action
<< From
->getSourceRange()
4505 if (From
->getType()->isObjCObjectPointerType() &&
4506 ToType
->isObjCObjectPointerType())
4507 EmitRelatedResultTypeNote(From
);
4508 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4509 !CheckObjCARCUnavailableWeakConversion(ToType
,
4511 if (Action
== AA_Initializing
)
4512 Diag(From
->getBeginLoc(), diag::err_arc_weak_unavailable_assign
);
4514 Diag(From
->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable
)
4515 << (Action
== AA_Casting
) << From
->getType() << ToType
4516 << From
->getSourceRange();
4519 // Defer address space conversion to the third conversion.
4520 QualType FromPteeType
= From
->getType()->getPointeeType();
4521 QualType ToPteeType
= ToType
->getPointeeType();
4522 QualType NewToType
= ToType
;
4523 if (!FromPteeType
.isNull() && !ToPteeType
.isNull() &&
4524 FromPteeType
.getAddressSpace() != ToPteeType
.getAddressSpace()) {
4525 NewToType
= Context
.removeAddrSpaceQualType(ToPteeType
);
4526 NewToType
= Context
.getAddrSpaceQualType(NewToType
,
4527 FromPteeType
.getAddressSpace());
4528 if (ToType
->isObjCObjectPointerType())
4529 NewToType
= Context
.getObjCObjectPointerType(NewToType
);
4530 else if (ToType
->isBlockPointerType())
4531 NewToType
= Context
.getBlockPointerType(NewToType
);
4533 NewToType
= Context
.getPointerType(NewToType
);
4537 CXXCastPath BasePath
;
4538 if (CheckPointerConversion(From
, NewToType
, Kind
, BasePath
, CStyle
))
4541 // Make sure we extend blocks if necessary.
4542 // FIXME: doing this here is really ugly.
4543 if (Kind
== CK_BlockPointerToObjCPointerCast
) {
4544 ExprResult E
= From
;
4545 (void) PrepareCastToObjCObjectPointer(E
);
4548 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4549 CheckObjCConversion(SourceRange(), NewToType
, From
, CCK
);
4550 From
= ImpCastExprToType(From
, NewToType
, Kind
, VK_PRValue
, &BasePath
, CCK
)
4555 case ICK_Pointer_Member
: {
4557 CXXCastPath BasePath
;
4558 if (CheckMemberPointerConversion(From
, ToType
, Kind
, BasePath
, CStyle
))
4560 if (CheckExceptionSpecCompatibility(From
, ToType
))
4563 // We may not have been able to figure out what this member pointer resolved
4564 // to up until this exact point. Attempt to lock-in it's inheritance model.
4565 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
4566 (void)isCompleteType(From
->getExprLoc(), From
->getType());
4567 (void)isCompleteType(From
->getExprLoc(), ToType
);
4571 ImpCastExprToType(From
, ToType
, Kind
, VK_PRValue
, &BasePath
, CCK
).get();
4575 case ICK_Boolean_Conversion
:
4576 // Perform half-to-boolean conversion via float.
4577 if (From
->getType()->isHalfType()) {
4578 From
= ImpCastExprToType(From
, Context
.FloatTy
, CK_FloatingCast
).get();
4579 FromType
= Context
.FloatTy
;
4582 From
= ImpCastExprToType(From
, Context
.BoolTy
,
4583 ScalarTypeToBooleanCastKind(FromType
), VK_PRValue
,
4584 /*BasePath=*/nullptr, CCK
)
4588 case ICK_Derived_To_Base
: {
4589 CXXCastPath BasePath
;
4590 if (CheckDerivedToBaseConversion(
4591 From
->getType(), ToType
.getNonReferenceType(), From
->getBeginLoc(),
4592 From
->getSourceRange(), &BasePath
, CStyle
))
4595 From
= ImpCastExprToType(From
, ToType
.getNonReferenceType(),
4596 CK_DerivedToBase
, From
->getValueKind(),
4597 &BasePath
, CCK
).get();
4601 case ICK_Vector_Conversion
:
4602 From
= ImpCastExprToType(From
, ToType
, CK_BitCast
, VK_PRValue
,
4603 /*BasePath=*/nullptr, CCK
)
4607 case ICK_SVE_Vector_Conversion
:
4608 case ICK_RVV_Vector_Conversion
:
4609 From
= ImpCastExprToType(From
, ToType
, CK_BitCast
, VK_PRValue
,
4610 /*BasePath=*/nullptr, CCK
)
4614 case ICK_Vector_Splat
: {
4615 // Vector splat from any arithmetic type to a vector.
4616 Expr
*Elem
= prepareVectorSplat(ToType
, From
).get();
4617 From
= ImpCastExprToType(Elem
, ToType
, CK_VectorSplat
, VK_PRValue
,
4618 /*BasePath=*/nullptr, CCK
)
4623 case ICK_Complex_Real
:
4624 // Case 1. x -> _Complex y
4625 if (const ComplexType
*ToComplex
= ToType
->getAs
<ComplexType
>()) {
4626 QualType ElType
= ToComplex
->getElementType();
4627 bool isFloatingComplex
= ElType
->isRealFloatingType();
4630 if (Context
.hasSameUnqualifiedType(ElType
, From
->getType())) {
4632 } else if (From
->getType()->isRealFloatingType()) {
4633 From
= ImpCastExprToType(From
, ElType
,
4634 isFloatingComplex
? CK_FloatingCast
: CK_FloatingToIntegral
).get();
4636 assert(From
->getType()->isIntegerType());
4637 From
= ImpCastExprToType(From
, ElType
,
4638 isFloatingComplex
? CK_IntegralToFloating
: CK_IntegralCast
).get();
4641 From
= ImpCastExprToType(From
, ToType
,
4642 isFloatingComplex
? CK_FloatingRealToComplex
4643 : CK_IntegralRealToComplex
).get();
4645 // Case 2. _Complex x -> y
4647 auto *FromComplex
= From
->getType()->castAs
<ComplexType
>();
4648 QualType ElType
= FromComplex
->getElementType();
4649 bool isFloatingComplex
= ElType
->isRealFloatingType();
4652 From
= ImpCastExprToType(From
, ElType
,
4653 isFloatingComplex
? CK_FloatingComplexToReal
4654 : CK_IntegralComplexToReal
,
4655 VK_PRValue
, /*BasePath=*/nullptr, CCK
)
4659 if (Context
.hasSameUnqualifiedType(ElType
, ToType
)) {
4661 } else if (ToType
->isRealFloatingType()) {
4662 From
= ImpCastExprToType(From
, ToType
,
4663 isFloatingComplex
? CK_FloatingCast
4664 : CK_IntegralToFloating
,
4665 VK_PRValue
, /*BasePath=*/nullptr, CCK
)
4668 assert(ToType
->isIntegerType());
4669 From
= ImpCastExprToType(From
, ToType
,
4670 isFloatingComplex
? CK_FloatingToIntegral
4672 VK_PRValue
, /*BasePath=*/nullptr, CCK
)
4678 case ICK_Block_Pointer_Conversion
: {
4680 ToType
->castAs
<BlockPointerType
>()->getPointeeType().getAddressSpace();
4682 FromType
->castAs
<BlockPointerType
>()->getPointeeType().getAddressSpace();
4683 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL
, AddrSpaceR
) &&
4686 AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
4687 From
= ImpCastExprToType(From
, ToType
.getUnqualifiedType(), Kind
,
4688 VK_PRValue
, /*BasePath=*/nullptr, CCK
)
4693 case ICK_TransparentUnionConversion
: {
4694 ExprResult FromRes
= From
;
4695 Sema::AssignConvertType ConvTy
=
4696 CheckTransparentUnionArgumentConstraints(ToType
, FromRes
);
4697 if (FromRes
.isInvalid())
4699 From
= FromRes
.get();
4700 assert ((ConvTy
== Sema::Compatible
) &&
4701 "Improper transparent union conversion");
4706 case ICK_Zero_Event_Conversion
:
4707 case ICK_Zero_Queue_Conversion
:
4708 From
= ImpCastExprToType(From
, ToType
,
4709 CK_ZeroToOCLOpaqueType
,
4710 From
->getValueKind()).get();
4713 case ICK_Lvalue_To_Rvalue
:
4714 case ICK_Array_To_Pointer
:
4715 case ICK_Function_To_Pointer
:
4716 case ICK_Function_Conversion
:
4717 case ICK_Qualification
:
4718 case ICK_Num_Conversion_Kinds
:
4719 case ICK_C_Only_Conversion
:
4720 case ICK_Incompatible_Pointer_Conversion
:
4721 llvm_unreachable("Improper second standard conversion");
4724 switch (SCS
.Third
) {
4729 case ICK_Function_Conversion
:
4730 // If both sides are functions (or pointers/references to them), there could
4731 // be incompatible exception declarations.
4732 if (CheckExceptionSpecCompatibility(From
, ToType
))
4735 From
= ImpCastExprToType(From
, ToType
, CK_NoOp
, VK_PRValue
,
4736 /*BasePath=*/nullptr, CCK
)
4740 case ICK_Qualification
: {
4741 ExprValueKind VK
= From
->getValueKind();
4742 CastKind CK
= CK_NoOp
;
4744 if (ToType
->isReferenceType() &&
4745 ToType
->getPointeeType().getAddressSpace() !=
4746 From
->getType().getAddressSpace())
4747 CK
= CK_AddressSpaceConversion
;
4749 if (ToType
->isPointerType() &&
4750 ToType
->getPointeeType().getAddressSpace() !=
4751 From
->getType()->getPointeeType().getAddressSpace())
4752 CK
= CK_AddressSpaceConversion
;
4755 !ToType
->getPointeeType().getQualifiers().hasUnaligned() &&
4756 From
->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
4757 Diag(From
->getBeginLoc(), diag::warn_imp_cast_drops_unaligned
)
4758 << InitialFromType
<< ToType
;
4761 From
= ImpCastExprToType(From
, ToType
.getNonLValueExprType(Context
), CK
, VK
,
4762 /*BasePath=*/nullptr, CCK
)
4765 if (SCS
.DeprecatedStringLiteralToCharPtr
&&
4766 !getLangOpts().WritableStrings
) {
4767 Diag(From
->getBeginLoc(),
4768 getLangOpts().CPlusPlus11
4769 ? diag::ext_deprecated_string_literal_conversion
4770 : diag::warn_deprecated_string_literal_conversion
)
4771 << ToType
.getNonReferenceType();
4778 llvm_unreachable("Improper third standard conversion");
4781 // If this conversion sequence involved a scalar -> atomic conversion, perform
4782 // that conversion now.
4783 if (!ToAtomicType
.isNull()) {
4784 assert(Context
.hasSameType(
4785 ToAtomicType
->castAs
<AtomicType
>()->getValueType(), From
->getType()));
4786 From
= ImpCastExprToType(From
, ToAtomicType
, CK_NonAtomicToAtomic
,
4787 VK_PRValue
, nullptr, CCK
)
4791 // Materialize a temporary if we're implicitly converting to a reference
4792 // type. This is not required by the C++ rules but is necessary to maintain
4794 if (ToType
->isReferenceType() && From
->isPRValue()) {
4795 ExprResult Res
= TemporaryMaterializationConversion(From
);
4796 if (Res
.isInvalid())
4801 // If this conversion sequence succeeded and involved implicitly converting a
4802 // _Nullable type to a _Nonnull one, complain.
4804 diagnoseNullableToNonnullConversion(ToType
, InitialFromType
,
4805 From
->getBeginLoc());
4810 /// Check the completeness of a type in a unary type trait.
4812 /// If the particular type trait requires a complete type, tries to complete
4813 /// it. If completing the type fails, a diagnostic is emitted and false
4814 /// returned. If completing the type succeeds or no completion was required,
4816 static bool CheckUnaryTypeTraitTypeCompleteness(Sema
&S
, TypeTrait UTT
,
4819 // C++0x [meta.unary.prop]p3:
4820 // For all of the class templates X declared in this Clause, instantiating
4821 // that template with a template argument that is a class template
4822 // specialization may result in the implicit instantiation of the template
4823 // argument if and only if the semantics of X require that the argument
4824 // must be a complete type.
4825 // We apply this rule to all the type trait expressions used to implement
4826 // these class templates. We also try to follow any GCC documented behavior
4827 // in these expressions to ensure portability of standard libraries.
4829 default: llvm_unreachable("not a UTT");
4830 // is_complete_type somewhat obviously cannot require a complete type.
4831 case UTT_IsCompleteType
:
4834 // These traits are modeled on the type predicates in C++0x
4835 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4836 // requiring a complete type, as whether or not they return true cannot be
4837 // impacted by the completeness of the type.
4839 case UTT_IsIntegral
:
4840 case UTT_IsFloatingPoint
:
4842 case UTT_IsBoundedArray
:
4844 case UTT_IsNullPointer
:
4845 case UTT_IsReferenceable
:
4846 case UTT_IsLvalueReference
:
4847 case UTT_IsRvalueReference
:
4848 case UTT_IsMemberFunctionPointer
:
4849 case UTT_IsMemberObjectPointer
:
4851 case UTT_IsScopedEnum
:
4854 case UTT_IsFunction
:
4855 case UTT_IsReference
:
4856 case UTT_IsArithmetic
:
4857 case UTT_IsFundamental
:
4860 case UTT_IsCompound
:
4861 case UTT_IsMemberPointer
:
4864 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4865 // which requires some of its traits to have the complete type. However,
4866 // the completeness of the type cannot impact these traits' semantics, and
4867 // so they don't require it. This matches the comments on these traits in
4870 case UTT_IsVolatile
:
4872 case UTT_IsUnboundedArray
:
4873 case UTT_IsUnsigned
:
4875 // This type trait always returns false, checking the type is moot.
4876 case UTT_IsInterfaceClass
:
4879 // C++14 [meta.unary.prop]:
4880 // If T is a non-union class type, T shall be a complete type.
4882 case UTT_IsPolymorphic
:
4883 case UTT_IsAbstract
:
4884 if (const auto *RD
= ArgTy
->getAsCXXRecordDecl())
4886 return !S
.RequireCompleteType(
4887 Loc
, ArgTy
, diag::err_incomplete_type_used_in_type_trait_expr
);
4890 // C++14 [meta.unary.prop]:
4891 // If T is a class type, T shall be a complete type.
4894 if (ArgTy
->getAsCXXRecordDecl())
4895 return !S
.RequireCompleteType(
4896 Loc
, ArgTy
, diag::err_incomplete_type_used_in_type_trait_expr
);
4899 // LWG3823: T shall be an array type, a complete type, or cv void.
4900 case UTT_IsAggregate
:
4901 if (ArgTy
->isArrayType() || ArgTy
->isVoidType())
4904 return !S
.RequireCompleteType(
4905 Loc
, ArgTy
, diag::err_incomplete_type_used_in_type_trait_expr
);
4907 // C++1z [meta.unary.prop]:
4908 // remove_all_extents_t<T> shall be a complete type or cv void.
4910 case UTT_IsTriviallyCopyable
:
4911 case UTT_IsStandardLayout
:
4914 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
4915 // impose the same constraints.
4916 case UTT_IsTriviallyRelocatable
:
4917 case UTT_IsTriviallyEqualityComparable
:
4918 case UTT_CanPassInRegs
:
4919 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4920 // or an array of unknown bound. But GCC actually imposes the same constraints
4922 case UTT_HasNothrowAssign
:
4923 case UTT_HasNothrowMoveAssign
:
4924 case UTT_HasNothrowConstructor
:
4925 case UTT_HasNothrowCopy
:
4926 case UTT_HasTrivialAssign
:
4927 case UTT_HasTrivialMoveAssign
:
4928 case UTT_HasTrivialDefaultConstructor
:
4929 case UTT_HasTrivialMoveConstructor
:
4930 case UTT_HasTrivialCopy
:
4931 case UTT_HasTrivialDestructor
:
4932 case UTT_HasVirtualDestructor
:
4933 ArgTy
= QualType(ArgTy
->getBaseElementTypeUnsafe(), 0);
4936 // C++1z [meta.unary.prop]:
4937 // T shall be a complete type, cv void, or an array of unknown bound.
4938 case UTT_IsDestructible
:
4939 case UTT_IsNothrowDestructible
:
4940 case UTT_IsTriviallyDestructible
:
4941 case UTT_HasUniqueObjectRepresentations
:
4942 if (ArgTy
->isIncompleteArrayType() || ArgTy
->isVoidType())
4945 return !S
.RequireCompleteType(
4946 Loc
, ArgTy
, diag::err_incomplete_type_used_in_type_trait_expr
);
4950 static bool HasNoThrowOperator(const RecordType
*RT
, OverloadedOperatorKind Op
,
4951 Sema
&Self
, SourceLocation KeyLoc
, ASTContext
&C
,
4952 bool (CXXRecordDecl::*HasTrivial
)() const,
4953 bool (CXXRecordDecl::*HasNonTrivial
)() const,
4954 bool (CXXMethodDecl::*IsDesiredOp
)() const)
4956 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
4957 if ((RD
->*HasTrivial
)() && !(RD
->*HasNonTrivial
)())
4960 DeclarationName Name
= C
.DeclarationNames
.getCXXOperatorName(Op
);
4961 DeclarationNameInfo
NameInfo(Name
, KeyLoc
);
4962 LookupResult
Res(Self
, NameInfo
, Sema::LookupOrdinaryName
);
4963 if (Self
.LookupQualifiedName(Res
, RD
)) {
4964 bool FoundOperator
= false;
4965 Res
.suppressDiagnostics();
4966 for (LookupResult::iterator Op
= Res
.begin(), OpEnd
= Res
.end();
4967 Op
!= OpEnd
; ++Op
) {
4968 if (isa
<FunctionTemplateDecl
>(*Op
))
4971 CXXMethodDecl
*Operator
= cast
<CXXMethodDecl
>(*Op
);
4972 if((Operator
->*IsDesiredOp
)()) {
4973 FoundOperator
= true;
4974 auto *CPT
= Operator
->getType()->castAs
<FunctionProtoType
>();
4975 CPT
= Self
.ResolveExceptionSpec(KeyLoc
, CPT
);
4976 if (!CPT
|| !CPT
->isNothrow())
4980 return FoundOperator
;
4985 static bool EvaluateUnaryTypeTrait(Sema
&Self
, TypeTrait UTT
,
4986 SourceLocation KeyLoc
, QualType T
) {
4987 assert(!T
->isDependentType() && "Cannot evaluate traits of dependent type");
4989 ASTContext
&C
= Self
.Context
;
4991 default: llvm_unreachable("not a UTT");
4992 // Type trait expressions corresponding to the primary type category
4993 // predicates in C++0x [meta.unary.cat].
4995 return T
->isVoidType();
4996 case UTT_IsIntegral
:
4997 return T
->isIntegralType(C
);
4998 case UTT_IsFloatingPoint
:
4999 return T
->isFloatingType();
5001 return T
->isArrayType();
5002 case UTT_IsBoundedArray
:
5003 if (!T
->isVariableArrayType()) {
5004 return T
->isArrayType() && !T
->isIncompleteArrayType();
5007 Self
.Diag(KeyLoc
, diag::err_vla_unsupported
)
5008 << 1 << tok::kw___is_bounded_array
;
5010 case UTT_IsUnboundedArray
:
5011 if (!T
->isVariableArrayType()) {
5012 return T
->isIncompleteArrayType();
5015 Self
.Diag(KeyLoc
, diag::err_vla_unsupported
)
5016 << 1 << tok::kw___is_unbounded_array
;
5019 return T
->isAnyPointerType();
5020 case UTT_IsNullPointer
:
5021 return T
->isNullPtrType();
5022 case UTT_IsLvalueReference
:
5023 return T
->isLValueReferenceType();
5024 case UTT_IsRvalueReference
:
5025 return T
->isRValueReferenceType();
5026 case UTT_IsMemberFunctionPointer
:
5027 return T
->isMemberFunctionPointerType();
5028 case UTT_IsMemberObjectPointer
:
5029 return T
->isMemberDataPointerType();
5031 return T
->isEnumeralType();
5032 case UTT_IsScopedEnum
:
5033 return T
->isScopedEnumeralType();
5035 return T
->isUnionType();
5037 return T
->isClassType() || T
->isStructureType() || T
->isInterfaceType();
5038 case UTT_IsFunction
:
5039 return T
->isFunctionType();
5041 // Type trait expressions which correspond to the convenient composition
5042 // predicates in C++0x [meta.unary.comp].
5043 case UTT_IsReference
:
5044 return T
->isReferenceType();
5045 case UTT_IsArithmetic
:
5046 return T
->isArithmeticType() && !T
->isEnumeralType();
5047 case UTT_IsFundamental
:
5048 return T
->isFundamentalType();
5050 return T
->isObjectType();
5052 // Note: semantic analysis depends on Objective-C lifetime types to be
5053 // considered scalar types. However, such types do not actually behave
5054 // like scalar types at run time (since they may require retain/release
5055 // operations), so we report them as non-scalar.
5056 if (T
->isObjCLifetimeType()) {
5057 switch (T
.getObjCLifetime()) {
5058 case Qualifiers::OCL_None
:
5059 case Qualifiers::OCL_ExplicitNone
:
5062 case Qualifiers::OCL_Strong
:
5063 case Qualifiers::OCL_Weak
:
5064 case Qualifiers::OCL_Autoreleasing
:
5069 return T
->isScalarType();
5070 case UTT_IsCompound
:
5071 return T
->isCompoundType();
5072 case UTT_IsMemberPointer
:
5073 return T
->isMemberPointerType();
5075 // Type trait expressions which correspond to the type property predicates
5076 // in C++0x [meta.unary.prop].
5078 return T
.isConstQualified();
5079 case UTT_IsVolatile
:
5080 return T
.isVolatileQualified();
5082 return T
.isTrivialType(C
);
5083 case UTT_IsTriviallyCopyable
:
5084 return T
.isTriviallyCopyableType(C
);
5085 case UTT_IsStandardLayout
:
5086 return T
->isStandardLayoutType();
5088 return T
.isPODType(C
);
5090 return T
->isLiteralType(C
);
5092 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5093 return !RD
->isUnion() && RD
->isEmpty();
5095 case UTT_IsPolymorphic
:
5096 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5097 return !RD
->isUnion() && RD
->isPolymorphic();
5099 case UTT_IsAbstract
:
5100 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5101 return !RD
->isUnion() && RD
->isAbstract();
5103 case UTT_IsAggregate
:
5104 // Report vector extensions and complex types as aggregates because they
5105 // support aggregate initialization. GCC mirrors this behavior for vectors
5106 // but not _Complex.
5107 return T
->isAggregateType() || T
->isVectorType() || T
->isExtVectorType() ||
5108 T
->isAnyComplexType();
5109 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5110 // even then only when it is used with the 'interface struct ...' syntax
5111 // Clang doesn't support /CLR which makes this type trait moot.
5112 case UTT_IsInterfaceClass
:
5116 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5117 return RD
->hasAttr
<FinalAttr
>();
5120 // Enum types should always return false.
5121 // Floating points should always return true.
5122 return T
->isFloatingType() ||
5123 (T
->isSignedIntegerType() && !T
->isEnumeralType());
5124 case UTT_IsUnsigned
:
5125 // Enum types should always return false.
5126 return T
->isUnsignedIntegerType() && !T
->isEnumeralType();
5128 // Type trait expressions which query classes regarding their construction,
5129 // destruction, and copying. Rather than being based directly on the
5130 // related type predicates in the standard, they are specified by both
5131 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5134 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5135 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5137 // Note that these builtins do not behave as documented in g++: if a class
5138 // has both a trivial and a non-trivial special member of a particular kind,
5139 // they return false! For now, we emulate this behavior.
5140 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5141 // does not correctly compute triviality in the presence of multiple special
5142 // members of the same kind. Revisit this once the g++ bug is fixed.
5143 case UTT_HasTrivialDefaultConstructor
:
5144 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5145 // If __is_pod (type) is true then the trait is true, else if type is
5146 // a cv class or union type (or array thereof) with a trivial default
5147 // constructor ([class.ctor]) then the trait is true, else it is false.
5150 if (CXXRecordDecl
*RD
= C
.getBaseElementType(T
)->getAsCXXRecordDecl())
5151 return RD
->hasTrivialDefaultConstructor() &&
5152 !RD
->hasNonTrivialDefaultConstructor();
5154 case UTT_HasTrivialMoveConstructor
:
5155 // This trait is implemented by MSVC 2012 and needed to parse the
5156 // standard library headers. Specifically this is used as the logic
5157 // behind std::is_trivially_move_constructible (20.9.4.3).
5160 if (CXXRecordDecl
*RD
= C
.getBaseElementType(T
)->getAsCXXRecordDecl())
5161 return RD
->hasTrivialMoveConstructor() && !RD
->hasNonTrivialMoveConstructor();
5163 case UTT_HasTrivialCopy
:
5164 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5165 // If __is_pod (type) is true or type is a reference type then
5166 // the trait is true, else if type is a cv class or union type
5167 // with a trivial copy constructor ([class.copy]) then the trait
5168 // is true, else it is false.
5169 if (T
.isPODType(C
) || T
->isReferenceType())
5171 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5172 return RD
->hasTrivialCopyConstructor() &&
5173 !RD
->hasNonTrivialCopyConstructor();
5175 case UTT_HasTrivialMoveAssign
:
5176 // This trait is implemented by MSVC 2012 and needed to parse the
5177 // standard library headers. Specifically it is used as the logic
5178 // behind std::is_trivially_move_assignable (20.9.4.3)
5181 if (CXXRecordDecl
*RD
= C
.getBaseElementType(T
)->getAsCXXRecordDecl())
5182 return RD
->hasTrivialMoveAssignment() && !RD
->hasNonTrivialMoveAssignment();
5184 case UTT_HasTrivialAssign
:
5185 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5186 // If type is const qualified or is a reference type then the
5187 // trait is false. Otherwise if __is_pod (type) is true then the
5188 // trait is true, else if type is a cv class or union type with
5189 // a trivial copy assignment ([class.copy]) then the trait is
5190 // true, else it is false.
5191 // Note: the const and reference restrictions are interesting,
5192 // given that const and reference members don't prevent a class
5193 // from having a trivial copy assignment operator (but do cause
5194 // errors if the copy assignment operator is actually used, q.v.
5195 // [class.copy]p12).
5197 if (T
.isConstQualified())
5201 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5202 return RD
->hasTrivialCopyAssignment() &&
5203 !RD
->hasNonTrivialCopyAssignment();
5205 case UTT_IsDestructible
:
5206 case UTT_IsTriviallyDestructible
:
5207 case UTT_IsNothrowDestructible
:
5208 // C++14 [meta.unary.prop]:
5209 // For reference types, is_destructible<T>::value is true.
5210 if (T
->isReferenceType())
5213 // Objective-C++ ARC: autorelease types don't require destruction.
5214 if (T
->isObjCLifetimeType() &&
5215 T
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
)
5218 // C++14 [meta.unary.prop]:
5219 // For incomplete types and function types, is_destructible<T>::value is
5221 if (T
->isIncompleteType() || T
->isFunctionType())
5224 // A type that requires destruction (via a non-trivial destructor or ARC
5225 // lifetime semantics) is not trivially-destructible.
5226 if (UTT
== UTT_IsTriviallyDestructible
&& T
.isDestructedType())
5229 // C++14 [meta.unary.prop]:
5230 // For object types and given U equal to remove_all_extents_t<T>, if the
5231 // expression std::declval<U&>().~U() is well-formed when treated as an
5232 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5233 if (auto *RD
= C
.getBaseElementType(T
)->getAsCXXRecordDecl()) {
5234 CXXDestructorDecl
*Destructor
= Self
.LookupDestructor(RD
);
5237 // C++14 [dcl.fct.def.delete]p2:
5238 // A program that refers to a deleted function implicitly or
5239 // explicitly, other than to declare it, is ill-formed.
5240 if (Destructor
->isDeleted())
5242 if (C
.getLangOpts().AccessControl
&& Destructor
->getAccess() != AS_public
)
5244 if (UTT
== UTT_IsNothrowDestructible
) {
5245 auto *CPT
= Destructor
->getType()->castAs
<FunctionProtoType
>();
5246 CPT
= Self
.ResolveExceptionSpec(KeyLoc
, CPT
);
5247 if (!CPT
|| !CPT
->isNothrow())
5253 case UTT_HasTrivialDestructor
:
5254 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5255 // If __is_pod (type) is true or type is a reference type
5256 // then the trait is true, else if type is a cv class or union
5257 // type (or array thereof) with a trivial destructor
5258 // ([class.dtor]) then the trait is true, else it is
5260 if (T
.isPODType(C
) || T
->isReferenceType())
5263 // Objective-C++ ARC: autorelease types don't require destruction.
5264 if (T
->isObjCLifetimeType() &&
5265 T
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
)
5268 if (CXXRecordDecl
*RD
= C
.getBaseElementType(T
)->getAsCXXRecordDecl())
5269 return RD
->hasTrivialDestructor();
5271 // TODO: Propagate nothrowness for implicitly declared special members.
5272 case UTT_HasNothrowAssign
:
5273 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5274 // If type is const qualified or is a reference type then the
5275 // trait is false. Otherwise if __has_trivial_assign (type)
5276 // is true then the trait is true, else if type is a cv class
5277 // or union type with copy assignment operators that are known
5278 // not to throw an exception then the trait is true, else it is
5280 if (C
.getBaseElementType(T
).isConstQualified())
5282 if (T
->isReferenceType())
5284 if (T
.isPODType(C
) || T
->isObjCLifetimeType())
5287 if (const RecordType
*RT
= T
->getAs
<RecordType
>())
5288 return HasNoThrowOperator(RT
, OO_Equal
, Self
, KeyLoc
, C
,
5289 &CXXRecordDecl::hasTrivialCopyAssignment
,
5290 &CXXRecordDecl::hasNonTrivialCopyAssignment
,
5291 &CXXMethodDecl::isCopyAssignmentOperator
);
5293 case UTT_HasNothrowMoveAssign
:
5294 // This trait is implemented by MSVC 2012 and needed to parse the
5295 // standard library headers. Specifically this is used as the logic
5296 // behind std::is_nothrow_move_assignable (20.9.4.3).
5300 if (const RecordType
*RT
= C
.getBaseElementType(T
)->getAs
<RecordType
>())
5301 return HasNoThrowOperator(RT
, OO_Equal
, Self
, KeyLoc
, C
,
5302 &CXXRecordDecl::hasTrivialMoveAssignment
,
5303 &CXXRecordDecl::hasNonTrivialMoveAssignment
,
5304 &CXXMethodDecl::isMoveAssignmentOperator
);
5306 case UTT_HasNothrowCopy
:
5307 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5308 // If __has_trivial_copy (type) is true then the trait is true, else
5309 // if type is a cv class or union type with copy constructors that are
5310 // known not to throw an exception then the trait is true, else it is
5312 if (T
.isPODType(C
) || T
->isReferenceType() || T
->isObjCLifetimeType())
5314 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl()) {
5315 if (RD
->hasTrivialCopyConstructor() &&
5316 !RD
->hasNonTrivialCopyConstructor())
5319 bool FoundConstructor
= false;
5321 for (const auto *ND
: Self
.LookupConstructors(RD
)) {
5322 // A template constructor is never a copy constructor.
5323 // FIXME: However, it may actually be selected at the actual overload
5324 // resolution point.
5325 if (isa
<FunctionTemplateDecl
>(ND
->getUnderlyingDecl()))
5327 // UsingDecl itself is not a constructor
5328 if (isa
<UsingDecl
>(ND
))
5330 auto *Constructor
= cast
<CXXConstructorDecl
>(ND
->getUnderlyingDecl());
5331 if (Constructor
->isCopyConstructor(FoundTQs
)) {
5332 FoundConstructor
= true;
5333 auto *CPT
= Constructor
->getType()->castAs
<FunctionProtoType
>();
5334 CPT
= Self
.ResolveExceptionSpec(KeyLoc
, CPT
);
5337 // TODO: check whether evaluating default arguments can throw.
5338 // For now, we'll be conservative and assume that they can throw.
5339 if (!CPT
->isNothrow() || CPT
->getNumParams() > 1)
5344 return FoundConstructor
;
5347 case UTT_HasNothrowConstructor
:
5348 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5349 // If __has_trivial_constructor (type) is true then the trait is
5350 // true, else if type is a cv class or union type (or array
5351 // thereof) with a default constructor that is known not to
5352 // throw an exception then the trait is true, else it is false.
5353 if (T
.isPODType(C
) || T
->isObjCLifetimeType())
5355 if (CXXRecordDecl
*RD
= C
.getBaseElementType(T
)->getAsCXXRecordDecl()) {
5356 if (RD
->hasTrivialDefaultConstructor() &&
5357 !RD
->hasNonTrivialDefaultConstructor())
5360 bool FoundConstructor
= false;
5361 for (const auto *ND
: Self
.LookupConstructors(RD
)) {
5362 // FIXME: In C++0x, a constructor template can be a default constructor.
5363 if (isa
<FunctionTemplateDecl
>(ND
->getUnderlyingDecl()))
5365 // UsingDecl itself is not a constructor
5366 if (isa
<UsingDecl
>(ND
))
5368 auto *Constructor
= cast
<CXXConstructorDecl
>(ND
->getUnderlyingDecl());
5369 if (Constructor
->isDefaultConstructor()) {
5370 FoundConstructor
= true;
5371 auto *CPT
= Constructor
->getType()->castAs
<FunctionProtoType
>();
5372 CPT
= Self
.ResolveExceptionSpec(KeyLoc
, CPT
);
5375 // FIXME: check whether evaluating default arguments can throw.
5376 // For now, we'll be conservative and assume that they can throw.
5377 if (!CPT
->isNothrow() || CPT
->getNumParams() > 0)
5381 return FoundConstructor
;
5384 case UTT_HasVirtualDestructor
:
5385 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5386 // If type is a class type with a virtual destructor ([class.dtor])
5387 // then the trait is true, else it is false.
5388 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
5389 if (CXXDestructorDecl
*Destructor
= Self
.LookupDestructor(RD
))
5390 return Destructor
->isVirtual();
5393 // These type trait expressions are modeled on the specifications for the
5394 // Embarcadero C++0x type trait functions:
5395 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5396 case UTT_IsCompleteType
:
5397 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5398 // Returns True if and only if T is a complete type at the point of the
5400 return !T
->isIncompleteType();
5401 case UTT_HasUniqueObjectRepresentations
:
5402 return C
.hasUniqueObjectRepresentations(T
);
5403 case UTT_IsTriviallyRelocatable
:
5404 return T
.isTriviallyRelocatableType(C
);
5405 case UTT_IsReferenceable
:
5406 return T
.isReferenceable();
5407 case UTT_CanPassInRegs
:
5408 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl(); RD
&& !T
.hasQualifiers())
5409 return RD
->canPassInRegisters();
5410 Self
.Diag(KeyLoc
, diag::err_builtin_pass_in_regs_non_class
) << T
;
5412 case UTT_IsTriviallyEqualityComparable
:
5413 return T
.isTriviallyEqualityComparableType(C
);
5417 static bool EvaluateBinaryTypeTrait(Sema
&Self
, TypeTrait BTT
, QualType LhsT
,
5418 QualType RhsT
, SourceLocation KeyLoc
);
5420 static bool EvaluateBooleanTypeTrait(Sema
&S
, TypeTrait Kind
,
5421 SourceLocation KWLoc
,
5422 ArrayRef
<TypeSourceInfo
*> Args
,
5423 SourceLocation RParenLoc
,
5428 if (Kind
<= UTT_Last
)
5429 return EvaluateUnaryTypeTrait(S
, Kind
, KWLoc
, Args
[0]->getType());
5431 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5432 // alongside the IsConstructible traits to avoid duplication.
5433 if (Kind
<= BTT_Last
&& Kind
!= BTT_ReferenceBindsToTemporary
&& Kind
!= BTT_ReferenceConstructsFromTemporary
)
5434 return EvaluateBinaryTypeTrait(S
, Kind
, Args
[0]->getType(),
5435 Args
[1]->getType(), RParenLoc
);
5438 case clang::BTT_ReferenceBindsToTemporary
:
5439 case clang::BTT_ReferenceConstructsFromTemporary
:
5440 case clang::TT_IsConstructible
:
5441 case clang::TT_IsNothrowConstructible
:
5442 case clang::TT_IsTriviallyConstructible
: {
5443 // C++11 [meta.unary.prop]:
5444 // is_trivially_constructible is defined as:
5446 // is_constructible<T, Args...>::value is true and the variable
5447 // definition for is_constructible, as defined below, is known to call
5448 // no operation that is not trivial.
5450 // The predicate condition for a template specialization
5451 // is_constructible<T, Args...> shall be satisfied if and only if the
5452 // following variable definition would be well-formed for some invented
5455 // T t(create<Args>()...);
5456 assert(!Args
.empty());
5458 // Precondition: T and all types in the parameter pack Args shall be
5459 // complete types, (possibly cv-qualified) void, or arrays of
5461 for (const auto *TSI
: Args
) {
5462 QualType ArgTy
= TSI
->getType();
5463 if (ArgTy
->isVoidType() || ArgTy
->isIncompleteArrayType())
5466 if (S
.RequireCompleteType(KWLoc
, ArgTy
,
5467 diag::err_incomplete_type_used_in_type_trait_expr
))
5471 // Make sure the first argument is not incomplete nor a function type.
5472 QualType T
= Args
[0]->getType();
5473 if (T
->isIncompleteType() || T
->isFunctionType())
5476 // Make sure the first argument is not an abstract type.
5477 CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl();
5478 if (RD
&& RD
->isAbstract())
5481 llvm::BumpPtrAllocator OpaqueExprAllocator
;
5482 SmallVector
<Expr
*, 2> ArgExprs
;
5483 ArgExprs
.reserve(Args
.size() - 1);
5484 for (unsigned I
= 1, N
= Args
.size(); I
!= N
; ++I
) {
5485 QualType ArgTy
= Args
[I
]->getType();
5486 if (ArgTy
->isObjectType() || ArgTy
->isFunctionType())
5487 ArgTy
= S
.Context
.getRValueReferenceType(ArgTy
);
5489 new (OpaqueExprAllocator
.Allocate
<OpaqueValueExpr
>())
5490 OpaqueValueExpr(Args
[I
]->getTypeLoc().getBeginLoc(),
5491 ArgTy
.getNonLValueExprType(S
.Context
),
5492 Expr::getValueKindForType(ArgTy
)));
5495 // Perform the initialization in an unevaluated context within a SFINAE
5496 // trap at translation unit scope.
5497 EnterExpressionEvaluationContext
Unevaluated(
5498 S
, Sema::ExpressionEvaluationContext::Unevaluated
);
5499 Sema::SFINAETrap
SFINAE(S
, /*AccessCheckingSFINAE=*/true);
5500 Sema::ContextRAII
TUContext(S
, S
.Context
.getTranslationUnitDecl());
5501 InitializedEntity
To(
5502 InitializedEntity::InitializeTemporary(S
.Context
, Args
[0]));
5503 InitializationKind
InitKind(InitializationKind::CreateDirect(KWLoc
, KWLoc
,
5505 InitializationSequence
Init(S
, To
, InitKind
, ArgExprs
);
5509 ExprResult Result
= Init
.Perform(S
, To
, InitKind
, ArgExprs
);
5510 if (Result
.isInvalid() || SFINAE
.hasErrorOccurred())
5513 if (Kind
== clang::TT_IsConstructible
)
5516 if (Kind
== clang::BTT_ReferenceBindsToTemporary
|| Kind
== clang::BTT_ReferenceConstructsFromTemporary
) {
5517 if (!T
->isReferenceType())
5520 if (!Init
.isDirectReferenceBinding())
5523 if (Kind
== clang::BTT_ReferenceBindsToTemporary
)
5526 QualType U
= Args
[1]->getType();
5527 if (U
->isReferenceType())
5530 QualType TPtr
= S
.Context
.getPointerType(S
.BuiltinRemoveReference(T
, UnaryTransformType::RemoveCVRef
, {}));
5531 QualType UPtr
= S
.Context
.getPointerType(S
.BuiltinRemoveReference(U
, UnaryTransformType::RemoveCVRef
, {}));
5532 return EvaluateBinaryTypeTrait(S
, TypeTrait::BTT_IsConvertibleTo
, UPtr
, TPtr
, RParenLoc
);
5535 if (Kind
== clang::TT_IsNothrowConstructible
)
5536 return S
.canThrow(Result
.get()) == CT_Cannot
;
5538 if (Kind
== clang::TT_IsTriviallyConstructible
) {
5539 // Under Objective-C ARC and Weak, if the destination has non-trivial
5540 // Objective-C lifetime, this is a non-trivial construction.
5541 if (T
.getNonReferenceType().hasNonTrivialObjCLifetime())
5544 // The initialization succeeded; now make sure there are no non-trivial
5546 return !Result
.get()->hasNonTrivialCall(S
.Context
);
5549 llvm_unreachable("unhandled type trait");
5552 default: llvm_unreachable("not a TT");
5559 void DiagnoseBuiltinDeprecation(Sema
& S
, TypeTrait Kind
,
5560 SourceLocation KWLoc
) {
5561 TypeTrait Replacement
;
5563 case UTT_HasNothrowAssign
:
5564 case UTT_HasNothrowMoveAssign
:
5565 Replacement
= BTT_IsNothrowAssignable
;
5567 case UTT_HasNothrowCopy
:
5568 case UTT_HasNothrowConstructor
:
5569 Replacement
= TT_IsNothrowConstructible
;
5571 case UTT_HasTrivialAssign
:
5572 case UTT_HasTrivialMoveAssign
:
5573 Replacement
= BTT_IsTriviallyAssignable
;
5575 case UTT_HasTrivialCopy
:
5576 Replacement
= UTT_IsTriviallyCopyable
;
5578 case UTT_HasTrivialDefaultConstructor
:
5579 case UTT_HasTrivialMoveConstructor
:
5580 Replacement
= TT_IsTriviallyConstructible
;
5582 case UTT_HasTrivialDestructor
:
5583 Replacement
= UTT_IsTriviallyDestructible
;
5588 S
.Diag(KWLoc
, diag::warn_deprecated_builtin
)
5589 << getTraitSpelling(Kind
) << getTraitSpelling(Replacement
);
5593 bool Sema::CheckTypeTraitArity(unsigned Arity
, SourceLocation Loc
, size_t N
) {
5594 if (Arity
&& N
!= Arity
) {
5595 Diag(Loc
, diag::err_type_trait_arity
)
5596 << Arity
<< 0 << (Arity
> 1) << (int)N
<< SourceRange(Loc
);
5600 if (!Arity
&& N
== 0) {
5601 Diag(Loc
, diag::err_type_trait_arity
)
5602 << 1 << 1 << 1 << (int)N
<< SourceRange(Loc
);
5608 enum class TypeTraitReturnType
{
5612 static TypeTraitReturnType
GetReturnType(TypeTrait Kind
) {
5613 return TypeTraitReturnType::Bool
;
5616 ExprResult
Sema::BuildTypeTrait(TypeTrait Kind
, SourceLocation KWLoc
,
5617 ArrayRef
<TypeSourceInfo
*> Args
,
5618 SourceLocation RParenLoc
) {
5619 if (!CheckTypeTraitArity(getTypeTraitArity(Kind
), KWLoc
, Args
.size()))
5622 if (Kind
<= UTT_Last
&& !CheckUnaryTypeTraitTypeCompleteness(
5623 *this, Kind
, KWLoc
, Args
[0]->getType()))
5626 DiagnoseBuiltinDeprecation(*this, Kind
, KWLoc
);
5628 bool Dependent
= false;
5629 for (unsigned I
= 0, N
= Args
.size(); I
!= N
; ++I
) {
5630 if (Args
[I
]->getType()->isDependentType()) {
5636 switch (GetReturnType(Kind
)) {
5637 case TypeTraitReturnType::Bool
: {
5638 bool Result
= EvaluateBooleanTypeTrait(*this, Kind
, KWLoc
, Args
, RParenLoc
,
5640 return TypeTraitExpr::Create(Context
, Context
.getLogicalOperationType(),
5641 KWLoc
, Kind
, Args
, RParenLoc
, Result
);
5644 llvm_unreachable("unhandled type trait return type");
5647 ExprResult
Sema::ActOnTypeTrait(TypeTrait Kind
, SourceLocation KWLoc
,
5648 ArrayRef
<ParsedType
> Args
,
5649 SourceLocation RParenLoc
) {
5650 SmallVector
<TypeSourceInfo
*, 4> ConvertedArgs
;
5651 ConvertedArgs
.reserve(Args
.size());
5653 for (unsigned I
= 0, N
= Args
.size(); I
!= N
; ++I
) {
5654 TypeSourceInfo
*TInfo
;
5655 QualType T
= GetTypeFromParser(Args
[I
], &TInfo
);
5657 TInfo
= Context
.getTrivialTypeSourceInfo(T
, KWLoc
);
5659 ConvertedArgs
.push_back(TInfo
);
5662 return BuildTypeTrait(Kind
, KWLoc
, ConvertedArgs
, RParenLoc
);
5665 static bool EvaluateBinaryTypeTrait(Sema
&Self
, TypeTrait BTT
, QualType LhsT
,
5666 QualType RhsT
, SourceLocation KeyLoc
) {
5667 assert(!LhsT
->isDependentType() && !RhsT
->isDependentType() &&
5668 "Cannot evaluate traits of dependent types");
5671 case BTT_IsBaseOf
: {
5672 // C++0x [meta.rel]p2
5673 // Base is a base class of Derived without regard to cv-qualifiers or
5674 // Base and Derived are not unions and name the same class type without
5675 // regard to cv-qualifiers.
5677 const RecordType
*lhsRecord
= LhsT
->getAs
<RecordType
>();
5678 const RecordType
*rhsRecord
= RhsT
->getAs
<RecordType
>();
5679 if (!rhsRecord
|| !lhsRecord
) {
5680 const ObjCObjectType
*LHSObjTy
= LhsT
->getAs
<ObjCObjectType
>();
5681 const ObjCObjectType
*RHSObjTy
= RhsT
->getAs
<ObjCObjectType
>();
5682 if (!LHSObjTy
|| !RHSObjTy
)
5685 ObjCInterfaceDecl
*BaseInterface
= LHSObjTy
->getInterface();
5686 ObjCInterfaceDecl
*DerivedInterface
= RHSObjTy
->getInterface();
5687 if (!BaseInterface
|| !DerivedInterface
)
5690 if (Self
.RequireCompleteType(
5691 KeyLoc
, RhsT
, diag::err_incomplete_type_used_in_type_trait_expr
))
5694 return BaseInterface
->isSuperClassOf(DerivedInterface
);
5697 assert(Self
.Context
.hasSameUnqualifiedType(LhsT
, RhsT
)
5698 == (lhsRecord
== rhsRecord
));
5700 // Unions are never base classes, and never have base classes.
5701 // It doesn't matter if they are complete or not. See PR#41843
5702 if (lhsRecord
&& lhsRecord
->getDecl()->isUnion())
5704 if (rhsRecord
&& rhsRecord
->getDecl()->isUnion())
5707 if (lhsRecord
== rhsRecord
)
5710 // C++0x [meta.rel]p2:
5711 // If Base and Derived are class types and are different types
5712 // (ignoring possible cv-qualifiers) then Derived shall be a
5714 if (Self
.RequireCompleteType(KeyLoc
, RhsT
,
5715 diag::err_incomplete_type_used_in_type_trait_expr
))
5718 return cast
<CXXRecordDecl
>(rhsRecord
->getDecl())
5719 ->isDerivedFrom(cast
<CXXRecordDecl
>(lhsRecord
->getDecl()));
5722 return Self
.Context
.hasSameType(LhsT
, RhsT
);
5723 case BTT_TypeCompatible
: {
5724 // GCC ignores cv-qualifiers on arrays for this builtin.
5725 Qualifiers LhsQuals
, RhsQuals
;
5726 QualType Lhs
= Self
.getASTContext().getUnqualifiedArrayType(LhsT
, LhsQuals
);
5727 QualType Rhs
= Self
.getASTContext().getUnqualifiedArrayType(RhsT
, RhsQuals
);
5728 return Self
.Context
.typesAreCompatible(Lhs
, Rhs
);
5730 case BTT_IsConvertible
:
5731 case BTT_IsConvertibleTo
: {
5732 // C++0x [meta.rel]p4:
5733 // Given the following function prototype:
5735 // template <class T>
5736 // typename add_rvalue_reference<T>::type create();
5738 // the predicate condition for a template specialization
5739 // is_convertible<From, To> shall be satisfied if and only if
5740 // the return expression in the following code would be
5741 // well-formed, including any implicit conversions to the return
5742 // type of the function:
5745 // return create<From>();
5748 // Access checking is performed as if in a context unrelated to To and
5749 // From. Only the validity of the immediate context of the expression
5750 // of the return-statement (including conversions to the return type)
5753 // We model the initialization as a copy-initialization of a temporary
5754 // of the appropriate type, which for this expression is identical to the
5755 // return statement (since NRVO doesn't apply).
5757 // Functions aren't allowed to return function or array types.
5758 if (RhsT
->isFunctionType() || RhsT
->isArrayType())
5761 // A return statement in a void function must have void type.
5762 if (RhsT
->isVoidType())
5763 return LhsT
->isVoidType();
5765 // A function definition requires a complete, non-abstract return type.
5766 if (!Self
.isCompleteType(KeyLoc
, RhsT
) || Self
.isAbstractType(KeyLoc
, RhsT
))
5769 // Compute the result of add_rvalue_reference.
5770 if (LhsT
->isObjectType() || LhsT
->isFunctionType())
5771 LhsT
= Self
.Context
.getRValueReferenceType(LhsT
);
5773 // Build a fake source and destination for initialization.
5774 InitializedEntity
To(InitializedEntity::InitializeTemporary(RhsT
));
5775 OpaqueValueExpr
From(KeyLoc
, LhsT
.getNonLValueExprType(Self
.Context
),
5776 Expr::getValueKindForType(LhsT
));
5777 Expr
*FromPtr
= &From
;
5778 InitializationKind
Kind(InitializationKind::CreateCopy(KeyLoc
,
5781 // Perform the initialization in an unevaluated context within a SFINAE
5782 // trap at translation unit scope.
5783 EnterExpressionEvaluationContext
Unevaluated(
5784 Self
, Sema::ExpressionEvaluationContext::Unevaluated
);
5785 Sema::SFINAETrap
SFINAE(Self
, /*AccessCheckingSFINAE=*/true);
5786 Sema::ContextRAII
TUContext(Self
, Self
.Context
.getTranslationUnitDecl());
5787 InitializationSequence
Init(Self
, To
, Kind
, FromPtr
);
5791 ExprResult Result
= Init
.Perform(Self
, To
, Kind
, FromPtr
);
5792 return !Result
.isInvalid() && !SFINAE
.hasErrorOccurred();
5795 case BTT_IsAssignable
:
5796 case BTT_IsNothrowAssignable
:
5797 case BTT_IsTriviallyAssignable
: {
5798 // C++11 [meta.unary.prop]p3:
5799 // is_trivially_assignable is defined as:
5800 // is_assignable<T, U>::value is true and the assignment, as defined by
5801 // is_assignable, is known to call no operation that is not trivial
5803 // is_assignable is defined as:
5804 // The expression declval<T>() = declval<U>() is well-formed when
5805 // treated as an unevaluated operand (Clause 5).
5807 // For both, T and U shall be complete types, (possibly cv-qualified)
5808 // void, or arrays of unknown bound.
5809 if (!LhsT
->isVoidType() && !LhsT
->isIncompleteArrayType() &&
5810 Self
.RequireCompleteType(KeyLoc
, LhsT
,
5811 diag::err_incomplete_type_used_in_type_trait_expr
))
5813 if (!RhsT
->isVoidType() && !RhsT
->isIncompleteArrayType() &&
5814 Self
.RequireCompleteType(KeyLoc
, RhsT
,
5815 diag::err_incomplete_type_used_in_type_trait_expr
))
5818 // cv void is never assignable.
5819 if (LhsT
->isVoidType() || RhsT
->isVoidType())
5822 // Build expressions that emulate the effect of declval<T>() and
5824 if (LhsT
->isObjectType() || LhsT
->isFunctionType())
5825 LhsT
= Self
.Context
.getRValueReferenceType(LhsT
);
5826 if (RhsT
->isObjectType() || RhsT
->isFunctionType())
5827 RhsT
= Self
.Context
.getRValueReferenceType(RhsT
);
5828 OpaqueValueExpr
Lhs(KeyLoc
, LhsT
.getNonLValueExprType(Self
.Context
),
5829 Expr::getValueKindForType(LhsT
));
5830 OpaqueValueExpr
Rhs(KeyLoc
, RhsT
.getNonLValueExprType(Self
.Context
),
5831 Expr::getValueKindForType(RhsT
));
5833 // Attempt the assignment in an unevaluated context within a SFINAE
5834 // trap at translation unit scope.
5835 EnterExpressionEvaluationContext
Unevaluated(
5836 Self
, Sema::ExpressionEvaluationContext::Unevaluated
);
5837 Sema::SFINAETrap
SFINAE(Self
, /*AccessCheckingSFINAE=*/true);
5838 Sema::ContextRAII
TUContext(Self
, Self
.Context
.getTranslationUnitDecl());
5839 ExprResult Result
= Self
.BuildBinOp(/*S=*/nullptr, KeyLoc
, BO_Assign
, &Lhs
,
5841 if (Result
.isInvalid())
5844 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5845 Self
.CheckUnusedVolatileAssignment(Result
.get());
5847 if (SFINAE
.hasErrorOccurred())
5850 if (BTT
== BTT_IsAssignable
)
5853 if (BTT
== BTT_IsNothrowAssignable
)
5854 return Self
.canThrow(Result
.get()) == CT_Cannot
;
5856 if (BTT
== BTT_IsTriviallyAssignable
) {
5857 // Under Objective-C ARC and Weak, if the destination has non-trivial
5858 // Objective-C lifetime, this is a non-trivial assignment.
5859 if (LhsT
.getNonReferenceType().hasNonTrivialObjCLifetime())
5862 return !Result
.get()->hasNonTrivialCall(Self
.Context
);
5865 llvm_unreachable("unhandled type trait");
5868 default: llvm_unreachable("not a BTT");
5870 llvm_unreachable("Unknown type trait or not implemented");
5873 ExprResult
Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT
,
5874 SourceLocation KWLoc
,
5877 SourceLocation RParen
) {
5878 TypeSourceInfo
*TSInfo
;
5879 QualType T
= GetTypeFromParser(Ty
, &TSInfo
);
5881 TSInfo
= Context
.getTrivialTypeSourceInfo(T
);
5883 return BuildArrayTypeTrait(ATT
, KWLoc
, TSInfo
, DimExpr
, RParen
);
5886 static uint64_t EvaluateArrayTypeTrait(Sema
&Self
, ArrayTypeTrait ATT
,
5887 QualType T
, Expr
*DimExpr
,
5888 SourceLocation KeyLoc
) {
5889 assert(!T
->isDependentType() && "Cannot evaluate traits of dependent type");
5893 if (T
->isArrayType()) {
5895 while (const ArrayType
*AT
= Self
.Context
.getAsArrayType(T
)) {
5897 T
= AT
->getElementType();
5903 case ATT_ArrayExtent
: {
5906 if (Self
.VerifyIntegerConstantExpression(
5907 DimExpr
, &Value
, diag::err_dimension_expr_not_constant_integer
)
5910 if (Value
.isSigned() && Value
.isNegative()) {
5911 Self
.Diag(KeyLoc
, diag::err_dimension_expr_not_constant_integer
)
5912 << DimExpr
->getSourceRange();
5915 Dim
= Value
.getLimitedValue();
5917 if (T
->isArrayType()) {
5919 bool Matched
= false;
5920 while (const ArrayType
*AT
= Self
.Context
.getAsArrayType(T
)) {
5926 T
= AT
->getElementType();
5929 if (Matched
&& T
->isArrayType()) {
5930 if (const ConstantArrayType
*CAT
= Self
.Context
.getAsConstantArrayType(T
))
5931 return CAT
->getSize().getLimitedValue();
5937 llvm_unreachable("Unknown type trait or not implemented");
5940 ExprResult
Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT
,
5941 SourceLocation KWLoc
,
5942 TypeSourceInfo
*TSInfo
,
5944 SourceLocation RParen
) {
5945 QualType T
= TSInfo
->getType();
5947 // FIXME: This should likely be tracked as an APInt to remove any host
5948 // assumptions about the width of size_t on the target.
5950 if (!T
->isDependentType())
5951 Value
= EvaluateArrayTypeTrait(*this, ATT
, T
, DimExpr
, KWLoc
);
5953 // While the specification for these traits from the Embarcadero C++
5954 // compiler's documentation says the return type is 'unsigned int', Clang
5955 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5956 // compiler, there is no difference. On several other platforms this is an
5957 // important distinction.
5958 return new (Context
) ArrayTypeTraitExpr(KWLoc
, ATT
, TSInfo
, Value
, DimExpr
,
5959 RParen
, Context
.getSizeType());
5962 ExprResult
Sema::ActOnExpressionTrait(ExpressionTrait ET
,
5963 SourceLocation KWLoc
,
5965 SourceLocation RParen
) {
5966 // If error parsing the expression, ignore.
5970 ExprResult Result
= BuildExpressionTrait(ET
, KWLoc
, Queried
, RParen
);
5975 static bool EvaluateExpressionTrait(ExpressionTrait ET
, Expr
*E
) {
5977 case ET_IsLValueExpr
: return E
->isLValue();
5978 case ET_IsRValueExpr
:
5979 return E
->isPRValue();
5981 llvm_unreachable("Expression trait not covered by switch");
5984 ExprResult
Sema::BuildExpressionTrait(ExpressionTrait ET
,
5985 SourceLocation KWLoc
,
5987 SourceLocation RParen
) {
5988 if (Queried
->isTypeDependent()) {
5989 // Delay type-checking for type-dependent expressions.
5990 } else if (Queried
->hasPlaceholderType()) {
5991 ExprResult PE
= CheckPlaceholderExpr(Queried
);
5992 if (PE
.isInvalid()) return ExprError();
5993 return BuildExpressionTrait(ET
, KWLoc
, PE
.get(), RParen
);
5996 bool Value
= EvaluateExpressionTrait(ET
, Queried
);
5998 return new (Context
)
5999 ExpressionTraitExpr(KWLoc
, ET
, Queried
, Value
, RParen
, Context
.BoolTy
);
6002 QualType
Sema::CheckPointerToMemberOperands(ExprResult
&LHS
, ExprResult
&RHS
,
6006 assert(!LHS
.get()->hasPlaceholderType() && !RHS
.get()->hasPlaceholderType() &&
6007 "placeholders should have been weeded out by now");
6009 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6010 // temporary materialization conversion otherwise.
6012 LHS
= DefaultLvalueConversion(LHS
.get());
6013 else if (LHS
.get()->isPRValue())
6014 LHS
= TemporaryMaterializationConversion(LHS
.get());
6015 if (LHS
.isInvalid())
6018 // The RHS always undergoes lvalue conversions.
6019 RHS
= DefaultLvalueConversion(RHS
.get());
6020 if (RHS
.isInvalid()) return QualType();
6022 const char *OpSpelling
= isIndirect
? "->*" : ".*";
6024 // The binary operator .* [p3: ->*] binds its second operand, which shall
6025 // be of type "pointer to member of T" (where T is a completely-defined
6026 // class type) [...]
6027 QualType RHSType
= RHS
.get()->getType();
6028 const MemberPointerType
*MemPtr
= RHSType
->getAs
<MemberPointerType
>();
6030 Diag(Loc
, diag::err_bad_memptr_rhs
)
6031 << OpSpelling
<< RHSType
<< RHS
.get()->getSourceRange();
6035 QualType
Class(MemPtr
->getClass(), 0);
6037 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6038 // member pointer points must be completely-defined. However, there is no
6039 // reason for this semantic distinction, and the rule is not enforced by
6040 // other compilers. Therefore, we do not check this property, as it is
6041 // likely to be considered a defect.
6044 // [...] to its first operand, which shall be of class T or of a class of
6045 // which T is an unambiguous and accessible base class. [p3: a pointer to
6047 QualType LHSType
= LHS
.get()->getType();
6049 if (const PointerType
*Ptr
= LHSType
->getAs
<PointerType
>())
6050 LHSType
= Ptr
->getPointeeType();
6052 Diag(Loc
, diag::err_bad_memptr_lhs
)
6053 << OpSpelling
<< 1 << LHSType
6054 << FixItHint::CreateReplacement(SourceRange(Loc
), ".*");
6059 if (!Context
.hasSameUnqualifiedType(Class
, LHSType
)) {
6060 // If we want to check the hierarchy, we need a complete type.
6061 if (RequireCompleteType(Loc
, LHSType
, diag::err_bad_memptr_lhs
,
6062 OpSpelling
, (int)isIndirect
)) {
6066 if (!IsDerivedFrom(Loc
, LHSType
, Class
)) {
6067 Diag(Loc
, diag::err_bad_memptr_lhs
) << OpSpelling
6068 << (int)isIndirect
<< LHS
.get()->getType();
6072 CXXCastPath BasePath
;
6073 if (CheckDerivedToBaseConversion(
6074 LHSType
, Class
, Loc
,
6075 SourceRange(LHS
.get()->getBeginLoc(), RHS
.get()->getEndLoc()),
6079 // Cast LHS to type of use.
6080 QualType UseType
= Context
.getQualifiedType(Class
, LHSType
.getQualifiers());
6082 UseType
= Context
.getPointerType(UseType
);
6083 ExprValueKind VK
= isIndirect
? VK_PRValue
: LHS
.get()->getValueKind();
6084 LHS
= ImpCastExprToType(LHS
.get(), UseType
, CK_DerivedToBase
, VK
,
6088 if (isa
<CXXScalarValueInitExpr
>(RHS
.get()->IgnoreParens())) {
6089 // Diagnose use of pointer-to-member type which when used as
6090 // the functional cast in a pointer-to-member expression.
6091 Diag(Loc
, diag::err_pointer_to_member_type
) << isIndirect
;
6096 // The result is an object or a function of the type specified by the
6098 // The cv qualifiers are the union of those in the pointer and the left side,
6099 // in accordance with 5.5p5 and 5.2.5.
6100 QualType Result
= MemPtr
->getPointeeType();
6101 Result
= Context
.getCVRQualifiedType(Result
, LHSType
.getCVRQualifiers());
6103 // C++0x [expr.mptr.oper]p6:
6104 // In a .* expression whose object expression is an rvalue, the program is
6105 // ill-formed if the second operand is a pointer to member function with
6106 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6107 // expression is an lvalue, the program is ill-formed if the second operand
6108 // is a pointer to member function with ref-qualifier &&.
6109 if (const FunctionProtoType
*Proto
= Result
->getAs
<FunctionProtoType
>()) {
6110 switch (Proto
->getRefQualifier()) {
6116 if (!isIndirect
&& !LHS
.get()->Classify(Context
).isLValue()) {
6117 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6118 // is (exactly) 'const'.
6119 if (Proto
->isConst() && !Proto
->isVolatile())
6120 Diag(Loc
, getLangOpts().CPlusPlus20
6121 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6122 : diag::ext_pointer_to_const_ref_member_on_rvalue
);
6124 Diag(Loc
, diag::err_pointer_to_member_oper_value_classify
)
6125 << RHSType
<< 1 << LHS
.get()->getSourceRange();
6130 if (isIndirect
|| !LHS
.get()->Classify(Context
).isRValue())
6131 Diag(Loc
, diag::err_pointer_to_member_oper_value_classify
)
6132 << RHSType
<< 0 << LHS
.get()->getSourceRange();
6137 // C++ [expr.mptr.oper]p6:
6138 // The result of a .* expression whose second operand is a pointer
6139 // to a data member is of the same value category as its
6140 // first operand. The result of a .* expression whose second
6141 // operand is a pointer to a member function is a prvalue. The
6142 // result of an ->* expression is an lvalue if its second operand
6143 // is a pointer to data member and a prvalue otherwise.
6144 if (Result
->isFunctionType()) {
6146 return Context
.BoundMemberTy
;
6147 } else if (isIndirect
) {
6150 VK
= LHS
.get()->getValueKind();
6156 /// Try to convert a type to another according to C++11 5.16p3.
6158 /// This is part of the parameter validation for the ? operator. If either
6159 /// value operand is a class type, the two operands are attempted to be
6160 /// converted to each other. This function does the conversion in one direction.
6161 /// It returns true if the program is ill-formed and has already been diagnosed
6163 static bool TryClassUnification(Sema
&Self
, Expr
*From
, Expr
*To
,
6164 SourceLocation QuestionLoc
,
6165 bool &HaveConversion
,
6167 HaveConversion
= false;
6168 ToType
= To
->getType();
6170 InitializationKind Kind
=
6171 InitializationKind::CreateCopy(To
->getBeginLoc(), SourceLocation());
6173 // The process for determining whether an operand expression E1 of type T1
6174 // can be converted to match an operand expression E2 of type T2 is defined
6176 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6177 // implicitly converted to type "lvalue reference to T2", subject to the
6178 // constraint that in the conversion the reference must bind directly to
6180 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6181 // implicitly converted to the type "rvalue reference to R2", subject to
6182 // the constraint that the reference must bind directly.
6183 if (To
->isGLValue()) {
6184 QualType T
= Self
.Context
.getReferenceQualifiedType(To
);
6185 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(T
);
6187 InitializationSequence
InitSeq(Self
, Entity
, Kind
, From
);
6188 if (InitSeq
.isDirectReferenceBinding()) {
6190 HaveConversion
= true;
6194 if (InitSeq
.isAmbiguous())
6195 return InitSeq
.Diagnose(Self
, Entity
, Kind
, From
);
6198 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6199 // -- if E1 and E2 have class type, and the underlying class types are
6200 // the same or one is a base class of the other:
6201 QualType FTy
= From
->getType();
6202 QualType TTy
= To
->getType();
6203 const RecordType
*FRec
= FTy
->getAs
<RecordType
>();
6204 const RecordType
*TRec
= TTy
->getAs
<RecordType
>();
6205 bool FDerivedFromT
= FRec
&& TRec
&& FRec
!= TRec
&&
6206 Self
.IsDerivedFrom(QuestionLoc
, FTy
, TTy
);
6207 if (FRec
&& TRec
&& (FRec
== TRec
|| FDerivedFromT
||
6208 Self
.IsDerivedFrom(QuestionLoc
, TTy
, FTy
))) {
6209 // E1 can be converted to match E2 if the class of T2 is the
6210 // same type as, or a base class of, the class of T1, and
6212 if (FRec
== TRec
|| FDerivedFromT
) {
6213 if (TTy
.isAtLeastAsQualifiedAs(FTy
)) {
6214 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(TTy
);
6215 InitializationSequence
InitSeq(Self
, Entity
, Kind
, From
);
6217 HaveConversion
= true;
6221 if (InitSeq
.isAmbiguous())
6222 return InitSeq
.Diagnose(Self
, Entity
, Kind
, From
);
6229 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6230 // implicitly converted to the type that expression E2 would have
6231 // if E2 were converted to an rvalue (or the type it has, if E2 is
6234 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6235 // to the array-to-pointer or function-to-pointer conversions.
6236 TTy
= TTy
.getNonLValueExprType(Self
.Context
);
6238 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(TTy
);
6239 InitializationSequence
InitSeq(Self
, Entity
, Kind
, From
);
6240 HaveConversion
= !InitSeq
.Failed();
6242 if (InitSeq
.isAmbiguous())
6243 return InitSeq
.Diagnose(Self
, Entity
, Kind
, From
);
6248 /// Try to find a common type for two according to C++0x 5.16p5.
6250 /// This is part of the parameter validation for the ? operator. If either
6251 /// value operand is a class type, overload resolution is used to find a
6252 /// conversion to a common type.
6253 static bool FindConditionalOverload(Sema
&Self
, ExprResult
&LHS
, ExprResult
&RHS
,
6254 SourceLocation QuestionLoc
) {
6255 Expr
*Args
[2] = { LHS
.get(), RHS
.get() };
6256 OverloadCandidateSet
CandidateSet(QuestionLoc
,
6257 OverloadCandidateSet::CSK_Operator
);
6258 Self
.AddBuiltinOperatorCandidates(OO_Conditional
, QuestionLoc
, Args
,
6261 OverloadCandidateSet::iterator Best
;
6262 switch (CandidateSet
.BestViableFunction(Self
, QuestionLoc
, Best
)) {
6264 // We found a match. Perform the conversions on the arguments and move on.
6265 ExprResult LHSRes
= Self
.PerformImplicitConversion(
6266 LHS
.get(), Best
->BuiltinParamTypes
[0], Best
->Conversions
[0],
6267 Sema::AA_Converting
);
6268 if (LHSRes
.isInvalid())
6272 ExprResult RHSRes
= Self
.PerformImplicitConversion(
6273 RHS
.get(), Best
->BuiltinParamTypes
[1], Best
->Conversions
[1],
6274 Sema::AA_Converting
);
6275 if (RHSRes
.isInvalid())
6279 Self
.MarkFunctionReferenced(QuestionLoc
, Best
->Function
);
6283 case OR_No_Viable_Function
:
6285 // Emit a better diagnostic if one of the expressions is a null pointer
6286 // constant and the other is a pointer type. In this case, the user most
6287 // likely forgot to take the address of the other expression.
6288 if (Self
.DiagnoseConditionalForNull(LHS
.get(), RHS
.get(), QuestionLoc
))
6291 Self
.Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
6292 << LHS
.get()->getType() << RHS
.get()->getType()
6293 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6297 Self
.Diag(QuestionLoc
, diag::err_conditional_ambiguous_ovl
)
6298 << LHS
.get()->getType() << RHS
.get()->getType()
6299 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6300 // FIXME: Print the possible common types by printing the return types of
6301 // the viable candidates.
6305 llvm_unreachable("Conditional operator has only built-in overloads");
6310 /// Perform an "extended" implicit conversion as returned by
6311 /// TryClassUnification.
6312 static bool ConvertForConditional(Sema
&Self
, ExprResult
&E
, QualType T
) {
6313 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(T
);
6314 InitializationKind Kind
=
6315 InitializationKind::CreateCopy(E
.get()->getBeginLoc(), SourceLocation());
6316 Expr
*Arg
= E
.get();
6317 InitializationSequence
InitSeq(Self
, Entity
, Kind
, Arg
);
6318 ExprResult Result
= InitSeq
.Perform(Self
, Entity
, Kind
, Arg
);
6319 if (Result
.isInvalid())
6326 // Check the condition operand of ?: to see if it is valid for the GCC
6328 static bool isValidVectorForConditionalCondition(ASTContext
&Ctx
,
6330 if (!CondTy
->isVectorType() && !CondTy
->isExtVectorType())
6332 const QualType EltTy
=
6333 cast
<VectorType
>(CondTy
.getCanonicalType())->getElementType();
6334 assert(!EltTy
->isEnumeralType() && "Vectors cant be enum types");
6335 return EltTy
->isIntegralType(Ctx
);
6338 static bool isValidSizelessVectorForConditionalCondition(ASTContext
&Ctx
,
6340 if (!CondTy
->isSveVLSBuiltinType())
6342 const QualType EltTy
=
6343 cast
<BuiltinType
>(CondTy
.getCanonicalType())->getSveEltType(Ctx
);
6344 assert(!EltTy
->isEnumeralType() && "Vectors cant be enum types");
6345 return EltTy
->isIntegralType(Ctx
);
6348 QualType
Sema::CheckVectorConditionalTypes(ExprResult
&Cond
, ExprResult
&LHS
,
6350 SourceLocation QuestionLoc
) {
6351 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
6352 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
6354 QualType CondType
= Cond
.get()->getType();
6355 const auto *CondVT
= CondType
->castAs
<VectorType
>();
6356 QualType CondElementTy
= CondVT
->getElementType();
6357 unsigned CondElementCount
= CondVT
->getNumElements();
6358 QualType LHSType
= LHS
.get()->getType();
6359 const auto *LHSVT
= LHSType
->getAs
<VectorType
>();
6360 QualType RHSType
= RHS
.get()->getType();
6361 const auto *RHSVT
= RHSType
->getAs
<VectorType
>();
6363 QualType ResultType
;
6366 if (LHSVT
&& RHSVT
) {
6367 if (isa
<ExtVectorType
>(CondVT
) != isa
<ExtVectorType
>(LHSVT
)) {
6368 Diag(QuestionLoc
, diag::err_conditional_vector_cond_result_mismatch
)
6369 << /*isExtVector*/ isa
<ExtVectorType
>(CondVT
);
6373 // If both are vector types, they must be the same type.
6374 if (!Context
.hasSameType(LHSType
, RHSType
)) {
6375 Diag(QuestionLoc
, diag::err_conditional_vector_mismatched
)
6376 << LHSType
<< RHSType
;
6379 ResultType
= Context
.getCommonSugaredType(LHSType
, RHSType
);
6380 } else if (LHSVT
|| RHSVT
) {
6381 ResultType
= CheckVectorOperands(
6382 LHS
, RHS
, QuestionLoc
, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6383 /*AllowBoolConversions*/ false,
6384 /*AllowBoolOperation*/ true,
6385 /*ReportInvalid*/ true);
6386 if (ResultType
.isNull())
6390 LHSType
= LHSType
.getUnqualifiedType();
6391 RHSType
= RHSType
.getUnqualifiedType();
6392 QualType ResultElementTy
=
6393 Context
.hasSameType(LHSType
, RHSType
)
6394 ? Context
.getCommonSugaredType(LHSType
, RHSType
)
6395 : UsualArithmeticConversions(LHS
, RHS
, QuestionLoc
,
6398 if (ResultElementTy
->isEnumeralType()) {
6399 Diag(QuestionLoc
, diag::err_conditional_vector_operand_type
)
6403 if (CondType
->isExtVectorType())
6405 Context
.getExtVectorType(ResultElementTy
, CondVT
->getNumElements());
6407 ResultType
= Context
.getVectorType(
6408 ResultElementTy
, CondVT
->getNumElements(), VectorKind::Generic
);
6410 LHS
= ImpCastExprToType(LHS
.get(), ResultType
, CK_VectorSplat
);
6411 RHS
= ImpCastExprToType(RHS
.get(), ResultType
, CK_VectorSplat
);
6414 assert(!ResultType
.isNull() && ResultType
->isVectorType() &&
6415 (!CondType
->isExtVectorType() || ResultType
->isExtVectorType()) &&
6416 "Result should have been a vector type");
6417 auto *ResultVectorTy
= ResultType
->castAs
<VectorType
>();
6418 QualType ResultElementTy
= ResultVectorTy
->getElementType();
6419 unsigned ResultElementCount
= ResultVectorTy
->getNumElements();
6421 if (ResultElementCount
!= CondElementCount
) {
6422 Diag(QuestionLoc
, diag::err_conditional_vector_size
) << CondType
6427 if (Context
.getTypeSize(ResultElementTy
) !=
6428 Context
.getTypeSize(CondElementTy
)) {
6429 Diag(QuestionLoc
, diag::err_conditional_vector_element_size
) << CondType
6437 QualType
Sema::CheckSizelessVectorConditionalTypes(ExprResult
&Cond
,
6440 SourceLocation QuestionLoc
) {
6441 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
6442 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
6444 QualType CondType
= Cond
.get()->getType();
6445 const auto *CondBT
= CondType
->castAs
<BuiltinType
>();
6446 QualType CondElementTy
= CondBT
->getSveEltType(Context
);
6447 llvm::ElementCount CondElementCount
=
6448 Context
.getBuiltinVectorTypeInfo(CondBT
).EC
;
6450 QualType LHSType
= LHS
.get()->getType();
6452 LHSType
->isSveVLSBuiltinType() ? LHSType
->getAs
<BuiltinType
>() : nullptr;
6453 QualType RHSType
= RHS
.get()->getType();
6455 RHSType
->isSveVLSBuiltinType() ? RHSType
->getAs
<BuiltinType
>() : nullptr;
6457 QualType ResultType
;
6459 if (LHSBT
&& RHSBT
) {
6460 // If both are sizeless vector types, they must be the same type.
6461 if (!Context
.hasSameType(LHSType
, RHSType
)) {
6462 Diag(QuestionLoc
, diag::err_conditional_vector_mismatched
)
6463 << LHSType
<< RHSType
;
6466 ResultType
= LHSType
;
6467 } else if (LHSBT
|| RHSBT
) {
6468 ResultType
= CheckSizelessVectorOperands(
6469 LHS
, RHS
, QuestionLoc
, /*IsCompAssign*/ false, ACK_Conditional
);
6470 if (ResultType
.isNull())
6473 // Both are scalar so splat
6474 QualType ResultElementTy
;
6475 LHSType
= LHSType
.getCanonicalType().getUnqualifiedType();
6476 RHSType
= RHSType
.getCanonicalType().getUnqualifiedType();
6478 if (Context
.hasSameType(LHSType
, RHSType
))
6479 ResultElementTy
= LHSType
;
6482 UsualArithmeticConversions(LHS
, RHS
, QuestionLoc
, ACK_Conditional
);
6484 if (ResultElementTy
->isEnumeralType()) {
6485 Diag(QuestionLoc
, diag::err_conditional_vector_operand_type
)
6490 ResultType
= Context
.getScalableVectorType(
6491 ResultElementTy
, CondElementCount
.getKnownMinValue());
6493 LHS
= ImpCastExprToType(LHS
.get(), ResultType
, CK_VectorSplat
);
6494 RHS
= ImpCastExprToType(RHS
.get(), ResultType
, CK_VectorSplat
);
6497 assert(!ResultType
.isNull() && ResultType
->isSveVLSBuiltinType() &&
6498 "Result should have been a vector type");
6499 auto *ResultBuiltinTy
= ResultType
->castAs
<BuiltinType
>();
6500 QualType ResultElementTy
= ResultBuiltinTy
->getSveEltType(Context
);
6501 llvm::ElementCount ResultElementCount
=
6502 Context
.getBuiltinVectorTypeInfo(ResultBuiltinTy
).EC
;
6504 if (ResultElementCount
!= CondElementCount
) {
6505 Diag(QuestionLoc
, diag::err_conditional_vector_size
)
6506 << CondType
<< ResultType
;
6510 if (Context
.getTypeSize(ResultElementTy
) !=
6511 Context
.getTypeSize(CondElementTy
)) {
6512 Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
6513 << CondType
<< ResultType
;
6520 /// Check the operands of ?: under C++ semantics.
6522 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6523 /// extension. In this case, LHS == Cond. (But they're not aliases.)
6525 /// This function also implements GCC's vector extension and the
6526 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6527 /// permit the use of a?b:c where the type of a is that of a integer vector with
6528 /// the same number of elements and size as the vectors of b and c. If one of
6529 /// either b or c is a scalar it is implicitly converted to match the type of
6530 /// the vector. Otherwise the expression is ill-formed. If both b and c are
6531 /// scalars, then b and c are checked and converted to the type of a if
6534 /// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6535 /// For the GCC extension, the ?: operator is evaluated as
6536 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6537 /// For the OpenCL extensions, the ?: operator is evaluated as
6538 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
6539 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
6540 QualType
Sema::CXXCheckConditionalOperands(ExprResult
&Cond
, ExprResult
&LHS
,
6541 ExprResult
&RHS
, ExprValueKind
&VK
,
6543 SourceLocation QuestionLoc
) {
6544 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6550 bool IsVectorConditional
=
6551 isValidVectorForConditionalCondition(Context
, Cond
.get()->getType());
6553 bool IsSizelessVectorConditional
=
6554 isValidSizelessVectorForConditionalCondition(Context
,
6555 Cond
.get()->getType());
6557 // C++11 [expr.cond]p1
6558 // The first expression is contextually converted to bool.
6559 if (!Cond
.get()->isTypeDependent()) {
6560 ExprResult CondRes
= IsVectorConditional
|| IsSizelessVectorConditional
6561 ? DefaultFunctionArrayLvalueConversion(Cond
.get())
6562 : CheckCXXBooleanCondition(Cond
.get());
6563 if (CondRes
.isInvalid())
6567 // To implement C++, the first expression typically doesn't alter the result
6568 // type of the conditional, however the GCC compatible vector extension
6569 // changes the result type to be that of the conditional. Since we cannot
6570 // know if this is a vector extension here, delay the conversion of the
6571 // LHS/RHS below until later.
6572 return Context
.DependentTy
;
6576 // Either of the arguments dependent?
6577 if (LHS
.get()->isTypeDependent() || RHS
.get()->isTypeDependent())
6578 return Context
.DependentTy
;
6580 // C++11 [expr.cond]p2
6581 // If either the second or the third operand has type (cv) void, ...
6582 QualType LTy
= LHS
.get()->getType();
6583 QualType RTy
= RHS
.get()->getType();
6584 bool LVoid
= LTy
->isVoidType();
6585 bool RVoid
= RTy
->isVoidType();
6586 if (LVoid
|| RVoid
) {
6587 // ... one of the following shall hold:
6588 // -- The second or the third operand (but not both) is a (possibly
6589 // parenthesized) throw-expression; the result is of the type
6590 // and value category of the other.
6591 bool LThrow
= isa
<CXXThrowExpr
>(LHS
.get()->IgnoreParenImpCasts());
6592 bool RThrow
= isa
<CXXThrowExpr
>(RHS
.get()->IgnoreParenImpCasts());
6594 // Void expressions aren't legal in the vector-conditional expressions.
6595 if (IsVectorConditional
) {
6596 SourceRange DiagLoc
=
6597 LVoid
? LHS
.get()->getSourceRange() : RHS
.get()->getSourceRange();
6598 bool IsThrow
= LVoid
? LThrow
: RThrow
;
6599 Diag(DiagLoc
.getBegin(), diag::err_conditional_vector_has_void
)
6600 << DiagLoc
<< IsThrow
;
6604 if (LThrow
!= RThrow
) {
6605 Expr
*NonThrow
= LThrow
? RHS
.get() : LHS
.get();
6606 VK
= NonThrow
->getValueKind();
6607 // DR (no number yet): the result is a bit-field if the
6608 // non-throw-expression operand is a bit-field.
6609 OK
= NonThrow
->getObjectKind();
6610 return NonThrow
->getType();
6613 // -- Both the second and third operands have type void; the result is of
6614 // type void and is a prvalue.
6616 return Context
.getCommonSugaredType(LTy
, RTy
);
6618 // Neither holds, error.
6619 Diag(QuestionLoc
, diag::err_conditional_void_nonvoid
)
6620 << (LVoid
? RTy
: LTy
) << (LVoid
? 0 : 1)
6621 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6626 if (IsVectorConditional
)
6627 return CheckVectorConditionalTypes(Cond
, LHS
, RHS
, QuestionLoc
);
6629 if (IsSizelessVectorConditional
)
6630 return CheckSizelessVectorConditionalTypes(Cond
, LHS
, RHS
, QuestionLoc
);
6632 // WebAssembly tables are not allowed as conditional LHS or RHS.
6633 if (LTy
->isWebAssemblyTableType() || RTy
->isWebAssemblyTableType()) {
6634 Diag(QuestionLoc
, diag::err_wasm_table_conditional_expression
)
6635 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6639 // C++11 [expr.cond]p3
6640 // Otherwise, if the second and third operand have different types, and
6641 // either has (cv) class type [...] an attempt is made to convert each of
6642 // those operands to the type of the other.
6643 if (!Context
.hasSameType(LTy
, RTy
) &&
6644 (LTy
->isRecordType() || RTy
->isRecordType())) {
6645 // These return true if a single direction is already ambiguous.
6646 QualType L2RType
, R2LType
;
6647 bool HaveL2R
, HaveR2L
;
6648 if (TryClassUnification(*this, LHS
.get(), RHS
.get(), QuestionLoc
, HaveL2R
, L2RType
))
6650 if (TryClassUnification(*this, RHS
.get(), LHS
.get(), QuestionLoc
, HaveR2L
, R2LType
))
6653 // If both can be converted, [...] the program is ill-formed.
6654 if (HaveL2R
&& HaveR2L
) {
6655 Diag(QuestionLoc
, diag::err_conditional_ambiguous
)
6656 << LTy
<< RTy
<< LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6660 // If exactly one conversion is possible, that conversion is applied to
6661 // the chosen operand and the converted operands are used in place of the
6662 // original operands for the remainder of this section.
6664 if (ConvertForConditional(*this, LHS
, L2RType
) || LHS
.isInvalid())
6666 LTy
= LHS
.get()->getType();
6667 } else if (HaveR2L
) {
6668 if (ConvertForConditional(*this, RHS
, R2LType
) || RHS
.isInvalid())
6670 RTy
= RHS
.get()->getType();
6674 // C++11 [expr.cond]p3
6675 // if both are glvalues of the same value category and the same type except
6676 // for cv-qualification, an attempt is made to convert each of those
6677 // operands to the type of the other.
6679 // Resolving a defect in P0012R1: we extend this to cover all cases where
6680 // one of the operands is reference-compatible with the other, in order
6681 // to support conditionals between functions differing in noexcept. This
6682 // will similarly cover difference in array bounds after P0388R4.
6683 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6685 ExprValueKind LVK
= LHS
.get()->getValueKind();
6686 ExprValueKind RVK
= RHS
.get()->getValueKind();
6687 if (!Context
.hasSameType(LTy
, RTy
) && LVK
== RVK
&& LVK
!= VK_PRValue
) {
6688 // DerivedToBase was already handled by the class-specific case above.
6689 // FIXME: Should we allow ObjC conversions here?
6690 const ReferenceConversions AllowedConversions
=
6691 ReferenceConversions::Qualification
|
6692 ReferenceConversions::NestedQualification
|
6693 ReferenceConversions::Function
;
6695 ReferenceConversions RefConv
;
6696 if (CompareReferenceRelationship(QuestionLoc
, LTy
, RTy
, &RefConv
) ==
6698 !(RefConv
& ~AllowedConversions
) &&
6699 // [...] subject to the constraint that the reference must bind
6701 !RHS
.get()->refersToBitField() && !RHS
.get()->refersToVectorElement()) {
6702 RHS
= ImpCastExprToType(RHS
.get(), LTy
, CK_NoOp
, RVK
);
6703 RTy
= RHS
.get()->getType();
6704 } else if (CompareReferenceRelationship(QuestionLoc
, RTy
, LTy
, &RefConv
) ==
6706 !(RefConv
& ~AllowedConversions
) &&
6707 !LHS
.get()->refersToBitField() &&
6708 !LHS
.get()->refersToVectorElement()) {
6709 LHS
= ImpCastExprToType(LHS
.get(), RTy
, CK_NoOp
, LVK
);
6710 LTy
= LHS
.get()->getType();
6714 // C++11 [expr.cond]p4
6715 // If the second and third operands are glvalues of the same value
6716 // category and have the same type, the result is of that type and
6717 // value category and it is a bit-field if the second or the third
6718 // operand is a bit-field, or if both are bit-fields.
6719 // We only extend this to bitfields, not to the crazy other kinds of
6721 bool Same
= Context
.hasSameType(LTy
, RTy
);
6722 if (Same
&& LVK
== RVK
&& LVK
!= VK_PRValue
&&
6723 LHS
.get()->isOrdinaryOrBitFieldObject() &&
6724 RHS
.get()->isOrdinaryOrBitFieldObject()) {
6725 VK
= LHS
.get()->getValueKind();
6726 if (LHS
.get()->getObjectKind() == OK_BitField
||
6727 RHS
.get()->getObjectKind() == OK_BitField
)
6729 return Context
.getCommonSugaredType(LTy
, RTy
);
6732 // C++11 [expr.cond]p5
6733 // Otherwise, the result is a prvalue. If the second and third operands
6734 // do not have the same type, and either has (cv) class type, ...
6735 if (!Same
&& (LTy
->isRecordType() || RTy
->isRecordType())) {
6736 // ... overload resolution is used to determine the conversions (if any)
6737 // to be applied to the operands. If the overload resolution fails, the
6738 // program is ill-formed.
6739 if (FindConditionalOverload(*this, LHS
, RHS
, QuestionLoc
))
6743 // C++11 [expr.cond]p6
6744 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6745 // conversions are performed on the second and third operands.
6746 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
6747 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
6748 if (LHS
.isInvalid() || RHS
.isInvalid())
6750 LTy
= LHS
.get()->getType();
6751 RTy
= RHS
.get()->getType();
6753 // After those conversions, one of the following shall hold:
6754 // -- The second and third operands have the same type; the result
6755 // is of that type. If the operands have class type, the result
6756 // is a prvalue temporary of the result type, which is
6757 // copy-initialized from either the second operand or the third
6758 // operand depending on the value of the first operand.
6759 if (Context
.hasSameType(LTy
, RTy
)) {
6760 if (LTy
->isRecordType()) {
6761 // The operands have class type. Make a temporary copy.
6762 ExprResult LHSCopy
= PerformCopyInitialization(
6763 InitializedEntity::InitializeTemporary(LTy
), SourceLocation(), LHS
);
6764 if (LHSCopy
.isInvalid())
6767 ExprResult RHSCopy
= PerformCopyInitialization(
6768 InitializedEntity::InitializeTemporary(RTy
), SourceLocation(), RHS
);
6769 if (RHSCopy
.isInvalid())
6775 return Context
.getCommonSugaredType(LTy
, RTy
);
6778 // Extension: conditional operator involving vector types.
6779 if (LTy
->isVectorType() || RTy
->isVectorType())
6780 return CheckVectorOperands(LHS
, RHS
, QuestionLoc
, /*isCompAssign*/ false,
6781 /*AllowBothBool*/ true,
6782 /*AllowBoolConversions*/ false,
6783 /*AllowBoolOperation*/ false,
6784 /*ReportInvalid*/ true);
6786 // -- The second and third operands have arithmetic or enumeration type;
6787 // the usual arithmetic conversions are performed to bring them to a
6788 // common type, and the result is of that type.
6789 if (LTy
->isArithmeticType() && RTy
->isArithmeticType()) {
6791 UsualArithmeticConversions(LHS
, RHS
, QuestionLoc
, ACK_Conditional
);
6792 if (LHS
.isInvalid() || RHS
.isInvalid())
6794 if (ResTy
.isNull()) {
6796 diag::err_typecheck_cond_incompatible_operands
) << LTy
<< RTy
6797 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6801 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, PrepareScalarCast(LHS
, ResTy
));
6802 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, PrepareScalarCast(RHS
, ResTy
));
6807 // -- The second and third operands have pointer type, or one has pointer
6808 // type and the other is a null pointer constant, or both are null
6809 // pointer constants, at least one of which is non-integral; pointer
6810 // conversions and qualification conversions are performed to bring them
6811 // to their composite pointer type. The result is of the composite
6813 // -- The second and third operands have pointer to member type, or one has
6814 // pointer to member type and the other is a null pointer constant;
6815 // pointer to member conversions and qualification conversions are
6816 // performed to bring them to a common type, whose cv-qualification
6817 // shall match the cv-qualification of either the second or the third
6818 // operand. The result is of the common type.
6819 QualType Composite
= FindCompositePointerType(QuestionLoc
, LHS
, RHS
);
6820 if (!Composite
.isNull())
6823 // Similarly, attempt to find composite type of two objective-c pointers.
6824 Composite
= FindCompositeObjCPointerType(LHS
, RHS
, QuestionLoc
);
6825 if (LHS
.isInvalid() || RHS
.isInvalid())
6827 if (!Composite
.isNull())
6830 // Check if we are using a null with a non-pointer type.
6831 if (DiagnoseConditionalForNull(LHS
.get(), RHS
.get(), QuestionLoc
))
6834 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
6835 << LHS
.get()->getType() << RHS
.get()->getType()
6836 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
6840 /// Find a merged pointer type and convert the two expressions to it.
6842 /// This finds the composite pointer type for \p E1 and \p E2 according to
6843 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6844 /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6847 /// \param Loc The location of the operator requiring these two expressions to
6848 /// be converted to the composite pointer type.
6850 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6851 QualType
Sema::FindCompositePointerType(SourceLocation Loc
,
6852 Expr
*&E1
, Expr
*&E2
,
6854 assert(getLangOpts().CPlusPlus
&& "This function assumes C++");
6857 // The composite pointer type of two operands p1 and p2 having types T1
6859 QualType T1
= E1
->getType(), T2
= E2
->getType();
6861 // where at least one is a pointer or pointer to member type or
6862 // std::nullptr_t is:
6863 bool T1IsPointerLike
= T1
->isAnyPointerType() || T1
->isMemberPointerType() ||
6864 T1
->isNullPtrType();
6865 bool T2IsPointerLike
= T2
->isAnyPointerType() || T2
->isMemberPointerType() ||
6866 T2
->isNullPtrType();
6867 if (!T1IsPointerLike
&& !T2IsPointerLike
)
6870 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6871 // This can't actually happen, following the standard, but we also use this
6872 // to implement the end of [expr.conv], which hits this case.
6874 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6875 if (T1IsPointerLike
&&
6876 E2
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
)) {
6878 E2
= ImpCastExprToType(E2
, T1
, T1
->isMemberPointerType()
6879 ? CK_NullToMemberPointer
6880 : CK_NullToPointer
).get();
6883 if (T2IsPointerLike
&&
6884 E1
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
)) {
6886 E1
= ImpCastExprToType(E1
, T2
, T2
->isMemberPointerType()
6887 ? CK_NullToMemberPointer
6888 : CK_NullToPointer
).get();
6892 // Now both have to be pointers or member pointers.
6893 if (!T1IsPointerLike
|| !T2IsPointerLike
)
6895 assert(!T1
->isNullPtrType() && !T2
->isNullPtrType() &&
6896 "nullptr_t should be a null pointer constant");
6899 enum Kind
{ Pointer
, ObjCPointer
, MemberPointer
, Array
} K
;
6900 // Qualifiers to apply under the step kind.
6902 /// The class for a pointer-to-member; a constant array type with a bound
6903 /// (if any) for an array.
6904 const Type
*ClassOrBound
;
6906 Step(Kind K
, const Type
*ClassOrBound
= nullptr)
6907 : K(K
), ClassOrBound(ClassOrBound
) {}
6908 QualType
rebuild(ASTContext
&Ctx
, QualType T
) const {
6909 T
= Ctx
.getQualifiedType(T
, Quals
);
6912 return Ctx
.getPointerType(T
);
6914 return Ctx
.getMemberPointerType(T
, ClassOrBound
);
6916 return Ctx
.getObjCObjectPointerType(T
);
6918 if (auto *CAT
= cast_or_null
<ConstantArrayType
>(ClassOrBound
))
6919 return Ctx
.getConstantArrayType(T
, CAT
->getSize(), nullptr,
6920 ArraySizeModifier::Normal
, 0);
6922 return Ctx
.getIncompleteArrayType(T
, ArraySizeModifier::Normal
, 0);
6924 llvm_unreachable("unknown step kind");
6928 SmallVector
<Step
, 8> Steps
;
6930 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6931 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6932 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6934 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6935 // to member of C2 of type cv2 U2" for some non-function type U, where
6936 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6937 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6939 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6942 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6943 // and to prepare to form the cv-combined type if so.
6944 QualType Composite1
= T1
;
6945 QualType Composite2
= T2
;
6946 unsigned NeedConstBefore
= 0;
6948 assert(!Composite1
.isNull() && !Composite2
.isNull());
6951 Composite1
= Context
.getUnqualifiedArrayType(Composite1
, Q1
);
6952 Composite2
= Context
.getUnqualifiedArrayType(Composite2
, Q2
);
6954 // Top-level qualifiers are ignored. Merge at all lower levels.
6955 if (!Steps
.empty()) {
6956 // Find the qualifier union: (approximately) the unique minimal set of
6957 // qualifiers that is compatible with both types.
6958 Qualifiers Quals
= Qualifiers::fromCVRUMask(Q1
.getCVRUQualifiers() |
6959 Q2
.getCVRUQualifiers());
6961 // Under one level of pointer or pointer-to-member, we can change to an
6962 // unambiguous compatible address space.
6963 if (Q1
.getAddressSpace() == Q2
.getAddressSpace()) {
6964 Quals
.setAddressSpace(Q1
.getAddressSpace());
6965 } else if (Steps
.size() == 1) {
6966 bool MaybeQ1
= Q1
.isAddressSpaceSupersetOf(Q2
);
6967 bool MaybeQ2
= Q2
.isAddressSpaceSupersetOf(Q1
);
6968 if (MaybeQ1
== MaybeQ2
) {
6969 // Exception for ptr size address spaces. Should be able to choose
6970 // either address space during comparison.
6971 if (isPtrSizeAddressSpace(Q1
.getAddressSpace()) ||
6972 isPtrSizeAddressSpace(Q2
.getAddressSpace()))
6975 return QualType(); // No unique best address space.
6977 Quals
.setAddressSpace(MaybeQ1
? Q1
.getAddressSpace()
6978 : Q2
.getAddressSpace());
6983 // FIXME: In C, we merge __strong and none to __strong at the top level.
6984 if (Q1
.getObjCGCAttr() == Q2
.getObjCGCAttr())
6985 Quals
.setObjCGCAttr(Q1
.getObjCGCAttr());
6986 else if (T1
->isVoidPointerType() || T2
->isVoidPointerType())
6987 assert(Steps
.size() == 1);
6991 // Mismatched lifetime qualifiers never compatibly include each other.
6992 if (Q1
.getObjCLifetime() == Q2
.getObjCLifetime())
6993 Quals
.setObjCLifetime(Q1
.getObjCLifetime());
6994 else if (T1
->isVoidPointerType() || T2
->isVoidPointerType())
6995 assert(Steps
.size() == 1);
6999 Steps
.back().Quals
= Quals
;
7000 if (Q1
!= Quals
|| Q2
!= Quals
)
7001 NeedConstBefore
= Steps
.size() - 1;
7004 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7006 const ArrayType
*Arr1
, *Arr2
;
7007 if ((Arr1
= Context
.getAsArrayType(Composite1
)) &&
7008 (Arr2
= Context
.getAsArrayType(Composite2
))) {
7009 auto *CAT1
= dyn_cast
<ConstantArrayType
>(Arr1
);
7010 auto *CAT2
= dyn_cast
<ConstantArrayType
>(Arr2
);
7011 if (CAT1
&& CAT2
&& CAT1
->getSize() == CAT2
->getSize()) {
7012 Composite1
= Arr1
->getElementType();
7013 Composite2
= Arr2
->getElementType();
7014 Steps
.emplace_back(Step::Array
, CAT1
);
7017 bool IAT1
= isa
<IncompleteArrayType
>(Arr1
);
7018 bool IAT2
= isa
<IncompleteArrayType
>(Arr2
);
7019 if ((IAT1
&& IAT2
) ||
7020 (getLangOpts().CPlusPlus20
&& (IAT1
!= IAT2
) &&
7021 ((bool)CAT1
!= (bool)CAT2
) &&
7022 (Steps
.empty() || Steps
.back().K
!= Step::Array
))) {
7023 // In C++20 onwards, we can unify an array of N T with an array of
7024 // a different or unknown bound. But we can't form an array whose
7025 // element type is an array of unknown bound by doing so.
7026 Composite1
= Arr1
->getElementType();
7027 Composite2
= Arr2
->getElementType();
7028 Steps
.emplace_back(Step::Array
);
7030 NeedConstBefore
= Steps
.size();
7035 const PointerType
*Ptr1
, *Ptr2
;
7036 if ((Ptr1
= Composite1
->getAs
<PointerType
>()) &&
7037 (Ptr2
= Composite2
->getAs
<PointerType
>())) {
7038 Composite1
= Ptr1
->getPointeeType();
7039 Composite2
= Ptr2
->getPointeeType();
7040 Steps
.emplace_back(Step::Pointer
);
7044 const ObjCObjectPointerType
*ObjPtr1
, *ObjPtr2
;
7045 if ((ObjPtr1
= Composite1
->getAs
<ObjCObjectPointerType
>()) &&
7046 (ObjPtr2
= Composite2
->getAs
<ObjCObjectPointerType
>())) {
7047 Composite1
= ObjPtr1
->getPointeeType();
7048 Composite2
= ObjPtr2
->getPointeeType();
7049 Steps
.emplace_back(Step::ObjCPointer
);
7053 const MemberPointerType
*MemPtr1
, *MemPtr2
;
7054 if ((MemPtr1
= Composite1
->getAs
<MemberPointerType
>()) &&
7055 (MemPtr2
= Composite2
->getAs
<MemberPointerType
>())) {
7056 Composite1
= MemPtr1
->getPointeeType();
7057 Composite2
= MemPtr2
->getPointeeType();
7059 // At the top level, we can perform a base-to-derived pointer-to-member
7062 // - [...] where C1 is reference-related to C2 or C2 is
7063 // reference-related to C1
7065 // (Note that the only kinds of reference-relatedness in scope here are
7066 // "same type or derived from".) At any other level, the class must
7068 const Type
*Class
= nullptr;
7069 QualType
Cls1(MemPtr1
->getClass(), 0);
7070 QualType
Cls2(MemPtr2
->getClass(), 0);
7071 if (Context
.hasSameType(Cls1
, Cls2
))
7072 Class
= MemPtr1
->getClass();
7073 else if (Steps
.empty())
7074 Class
= IsDerivedFrom(Loc
, Cls1
, Cls2
) ? MemPtr1
->getClass() :
7075 IsDerivedFrom(Loc
, Cls2
, Cls1
) ? MemPtr2
->getClass() : nullptr;
7079 Steps
.emplace_back(Step::MemberPointer
, Class
);
7083 // Special case: at the top level, we can decompose an Objective-C pointer
7084 // and a 'cv void *'. Unify the qualifiers.
7085 if (Steps
.empty() && ((Composite1
->isVoidPointerType() &&
7086 Composite2
->isObjCObjectPointerType()) ||
7087 (Composite1
->isObjCObjectPointerType() &&
7088 Composite2
->isVoidPointerType()))) {
7089 Composite1
= Composite1
->getPointeeType();
7090 Composite2
= Composite2
->getPointeeType();
7091 Steps
.emplace_back(Step::Pointer
);
7095 // FIXME: block pointer types?
7097 // Cannot unwrap any more types.
7101 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7102 // "pointer to function", where the function types are otherwise the same,
7103 // "pointer to function";
7104 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7105 // type is "pointer to member of C2 of type noexcept function", and C1
7106 // is reference-related to C2 or C2 is reference-related to C1, where
7107 // the function types are otherwise the same, "pointer to member of C2 of
7108 // type function" or "pointer to member of C1 of type function",
7111 // We also support 'noreturn' here, so as a Clang extension we generalize the
7114 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7115 // "pointer to member function" and the pointee types can be unified
7116 // by a function pointer conversion, that conversion is applied
7117 // before checking the following rules.
7119 // We've already unwrapped down to the function types, and we want to merge
7120 // rather than just convert, so do this ourselves rather than calling
7121 // IsFunctionConversion.
7123 // FIXME: In order to match the standard wording as closely as possible, we
7124 // currently only do this under a single level of pointers. Ideally, we would
7125 // allow this in general, and set NeedConstBefore to the relevant depth on
7126 // the side(s) where we changed anything. If we permit that, we should also
7127 // consider this conversion when determining type similarity and model it as
7128 // a qualification conversion.
7129 if (Steps
.size() == 1) {
7130 if (auto *FPT1
= Composite1
->getAs
<FunctionProtoType
>()) {
7131 if (auto *FPT2
= Composite2
->getAs
<FunctionProtoType
>()) {
7132 FunctionProtoType::ExtProtoInfo EPI1
= FPT1
->getExtProtoInfo();
7133 FunctionProtoType::ExtProtoInfo EPI2
= FPT2
->getExtProtoInfo();
7135 // The result is noreturn if both operands are.
7137 EPI1
.ExtInfo
.getNoReturn() && EPI2
.ExtInfo
.getNoReturn();
7138 EPI1
.ExtInfo
= EPI1
.ExtInfo
.withNoReturn(Noreturn
);
7139 EPI2
.ExtInfo
= EPI2
.ExtInfo
.withNoReturn(Noreturn
);
7141 // The result is nothrow if both operands are.
7142 SmallVector
<QualType
, 8> ExceptionTypeStorage
;
7143 EPI1
.ExceptionSpec
= EPI2
.ExceptionSpec
= Context
.mergeExceptionSpecs(
7144 EPI1
.ExceptionSpec
, EPI2
.ExceptionSpec
, ExceptionTypeStorage
,
7145 getLangOpts().CPlusPlus17
);
7147 Composite1
= Context
.getFunctionType(FPT1
->getReturnType(),
7148 FPT1
->getParamTypes(), EPI1
);
7149 Composite2
= Context
.getFunctionType(FPT2
->getReturnType(),
7150 FPT2
->getParamTypes(), EPI2
);
7155 // There are some more conversions we can perform under exactly one pointer.
7156 if (Steps
.size() == 1 && Steps
.front().K
== Step::Pointer
&&
7157 !Context
.hasSameType(Composite1
, Composite2
)) {
7158 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7159 // "pointer to cv2 T", where T is an object type or void,
7160 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7161 if (Composite1
->isVoidType() && Composite2
->isObjectType())
7162 Composite2
= Composite1
;
7163 else if (Composite2
->isVoidType() && Composite1
->isObjectType())
7164 Composite1
= Composite2
;
7165 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7166 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7167 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7168 // T1, respectively;
7170 // The "similar type" handling covers all of this except for the "T1 is a
7171 // base class of T2" case in the definition of reference-related.
7172 else if (IsDerivedFrom(Loc
, Composite1
, Composite2
))
7173 Composite1
= Composite2
;
7174 else if (IsDerivedFrom(Loc
, Composite2
, Composite1
))
7175 Composite2
= Composite1
;
7178 // At this point, either the inner types are the same or we have failed to
7179 // find a composite pointer type.
7180 if (!Context
.hasSameType(Composite1
, Composite2
))
7183 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7184 // differing qualifier.
7185 for (unsigned I
= 0; I
!= NeedConstBefore
; ++I
)
7186 Steps
[I
].Quals
.addConst();
7188 // Rebuild the composite type.
7189 QualType Composite
= Context
.getCommonSugaredType(Composite1
, Composite2
);
7190 for (auto &S
: llvm::reverse(Steps
))
7191 Composite
= S
.rebuild(Context
, Composite
);
7194 // Convert the expressions to the composite pointer type.
7195 InitializedEntity Entity
=
7196 InitializedEntity::InitializeTemporary(Composite
);
7197 InitializationKind Kind
=
7198 InitializationKind::CreateCopy(Loc
, SourceLocation());
7200 InitializationSequence
E1ToC(*this, Entity
, Kind
, E1
);
7204 InitializationSequence
E2ToC(*this, Entity
, Kind
, E2
);
7208 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7209 ExprResult E1Result
= E1ToC
.Perform(*this, Entity
, Kind
, E1
);
7210 if (E1Result
.isInvalid())
7212 E1
= E1Result
.get();
7214 ExprResult E2Result
= E2ToC
.Perform(*this, Entity
, Kind
, E2
);
7215 if (E2Result
.isInvalid())
7217 E2
= E2Result
.get();
7223 ExprResult
Sema::MaybeBindToTemporary(Expr
*E
) {
7227 assert(!isa
<CXXBindTemporaryExpr
>(E
) && "Double-bound temporary?");
7229 // If the result is a glvalue, we shouldn't bind it.
7233 // In ARC, calls that return a retainable type can return retained,
7234 // in which case we have to insert a consuming cast.
7235 if (getLangOpts().ObjCAutoRefCount
&&
7236 E
->getType()->isObjCRetainableType()) {
7238 bool ReturnsRetained
;
7240 // For actual calls, we compute this by examining the type of the
7242 if (CallExpr
*Call
= dyn_cast
<CallExpr
>(E
)) {
7243 Expr
*Callee
= Call
->getCallee()->IgnoreParens();
7244 QualType T
= Callee
->getType();
7246 if (T
== Context
.BoundMemberTy
) {
7247 // Handle pointer-to-members.
7248 if (BinaryOperator
*BinOp
= dyn_cast
<BinaryOperator
>(Callee
))
7249 T
= BinOp
->getRHS()->getType();
7250 else if (MemberExpr
*Mem
= dyn_cast
<MemberExpr
>(Callee
))
7251 T
= Mem
->getMemberDecl()->getType();
7254 if (const PointerType
*Ptr
= T
->getAs
<PointerType
>())
7255 T
= Ptr
->getPointeeType();
7256 else if (const BlockPointerType
*Ptr
= T
->getAs
<BlockPointerType
>())
7257 T
= Ptr
->getPointeeType();
7258 else if (const MemberPointerType
*MemPtr
= T
->getAs
<MemberPointerType
>())
7259 T
= MemPtr
->getPointeeType();
7261 auto *FTy
= T
->castAs
<FunctionType
>();
7262 ReturnsRetained
= FTy
->getExtInfo().getProducesResult();
7264 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7265 // type always produce a +1 object.
7266 } else if (isa
<StmtExpr
>(E
)) {
7267 ReturnsRetained
= true;
7269 // We hit this case with the lambda conversion-to-block optimization;
7270 // we don't want any extra casts here.
7271 } else if (isa
<CastExpr
>(E
) &&
7272 isa
<BlockExpr
>(cast
<CastExpr
>(E
)->getSubExpr())) {
7275 // For message sends and property references, we try to find an
7276 // actual method. FIXME: we should infer retention by selector in
7277 // cases where we don't have an actual method.
7279 ObjCMethodDecl
*D
= nullptr;
7280 if (ObjCMessageExpr
*Send
= dyn_cast
<ObjCMessageExpr
>(E
)) {
7281 D
= Send
->getMethodDecl();
7282 } else if (ObjCBoxedExpr
*BoxedExpr
= dyn_cast
<ObjCBoxedExpr
>(E
)) {
7283 D
= BoxedExpr
->getBoxingMethod();
7284 } else if (ObjCArrayLiteral
*ArrayLit
= dyn_cast
<ObjCArrayLiteral
>(E
)) {
7285 // Don't do reclaims if we're using the zero-element array
7287 if (ArrayLit
->getNumElements() == 0 &&
7288 Context
.getLangOpts().ObjCRuntime
.hasEmptyCollections())
7291 D
= ArrayLit
->getArrayWithObjectsMethod();
7292 } else if (ObjCDictionaryLiteral
*DictLit
7293 = dyn_cast
<ObjCDictionaryLiteral
>(E
)) {
7294 // Don't do reclaims if we're using the zero-element dictionary
7296 if (DictLit
->getNumElements() == 0 &&
7297 Context
.getLangOpts().ObjCRuntime
.hasEmptyCollections())
7300 D
= DictLit
->getDictWithObjectsMethod();
7303 ReturnsRetained
= (D
&& D
->hasAttr
<NSReturnsRetainedAttr
>());
7305 // Don't do reclaims on performSelector calls; despite their
7306 // return type, the invoked method doesn't necessarily actually
7307 // return an object.
7308 if (!ReturnsRetained
&&
7309 D
&& D
->getMethodFamily() == OMF_performSelector
)
7313 // Don't reclaim an object of Class type.
7314 if (!ReturnsRetained
&& E
->getType()->isObjCARCImplicitlyUnretainedType())
7317 Cleanup
.setExprNeedsCleanups(true);
7319 CastKind ck
= (ReturnsRetained
? CK_ARCConsumeObject
7320 : CK_ARCReclaimReturnedObject
);
7321 return ImplicitCastExpr::Create(Context
, E
->getType(), ck
, E
, nullptr,
7322 VK_PRValue
, FPOptionsOverride());
7325 if (E
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
7326 Cleanup
.setExprNeedsCleanups(true);
7328 if (!getLangOpts().CPlusPlus
)
7331 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7332 // a fast path for the common case that the type is directly a RecordType.
7333 const Type
*T
= Context
.getCanonicalType(E
->getType().getTypePtr());
7334 const RecordType
*RT
= nullptr;
7336 switch (T
->getTypeClass()) {
7338 RT
= cast
<RecordType
>(T
);
7340 case Type::ConstantArray
:
7341 case Type::IncompleteArray
:
7342 case Type::VariableArray
:
7343 case Type::DependentSizedArray
:
7344 T
= cast
<ArrayType
>(T
)->getElementType().getTypePtr();
7351 // That should be enough to guarantee that this type is complete, if we're
7352 // not processing a decltype expression.
7353 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
7354 if (RD
->isInvalidDecl() || RD
->isDependentContext())
7357 bool IsDecltype
= ExprEvalContexts
.back().ExprContext
==
7358 ExpressionEvaluationContextRecord::EK_Decltype
;
7359 CXXDestructorDecl
*Destructor
= IsDecltype
? nullptr : LookupDestructor(RD
);
7362 MarkFunctionReferenced(E
->getExprLoc(), Destructor
);
7363 CheckDestructorAccess(E
->getExprLoc(), Destructor
,
7364 PDiag(diag::err_access_dtor_temp
)
7366 if (DiagnoseUseOfDecl(Destructor
, E
->getExprLoc()))
7369 // If destructor is trivial, we can avoid the extra copy.
7370 if (Destructor
->isTrivial())
7373 // We need a cleanup, but we don't need to remember the temporary.
7374 Cleanup
.setExprNeedsCleanups(true);
7377 CXXTemporary
*Temp
= CXXTemporary::Create(Context
, Destructor
);
7378 CXXBindTemporaryExpr
*Bind
= CXXBindTemporaryExpr::Create(Context
, Temp
, E
);
7381 ExprEvalContexts
.back().DelayedDecltypeBinds
.push_back(Bind
);
7387 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr
) {
7388 if (SubExpr
.isInvalid())
7391 return MaybeCreateExprWithCleanups(SubExpr
.get());
7394 Expr
*Sema::MaybeCreateExprWithCleanups(Expr
*SubExpr
) {
7395 assert(SubExpr
&& "subexpression can't be null!");
7397 CleanupVarDeclMarking();
7399 unsigned FirstCleanup
= ExprEvalContexts
.back().NumCleanupObjects
;
7400 assert(ExprCleanupObjects
.size() >= FirstCleanup
);
7401 assert(Cleanup
.exprNeedsCleanups() ||
7402 ExprCleanupObjects
.size() == FirstCleanup
);
7403 if (!Cleanup
.exprNeedsCleanups())
7406 auto Cleanups
= llvm::ArrayRef(ExprCleanupObjects
.begin() + FirstCleanup
,
7407 ExprCleanupObjects
.size() - FirstCleanup
);
7409 auto *E
= ExprWithCleanups::Create(
7410 Context
, SubExpr
, Cleanup
.cleanupsHaveSideEffects(), Cleanups
);
7411 DiscardCleanupsInEvaluationContext();
7416 Stmt
*Sema::MaybeCreateStmtWithCleanups(Stmt
*SubStmt
) {
7417 assert(SubStmt
&& "sub-statement can't be null!");
7419 CleanupVarDeclMarking();
7421 if (!Cleanup
.exprNeedsCleanups())
7424 // FIXME: In order to attach the temporaries, wrap the statement into
7425 // a StmtExpr; currently this is only used for asm statements.
7426 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7427 // a new AsmStmtWithTemporaries.
7428 CompoundStmt
*CompStmt
=
7429 CompoundStmt::Create(Context
, SubStmt
, FPOptionsOverride(),
7430 SourceLocation(), SourceLocation());
7431 Expr
*E
= new (Context
)
7432 StmtExpr(CompStmt
, Context
.VoidTy
, SourceLocation(), SourceLocation(),
7433 /*FIXME TemplateDepth=*/0);
7434 return MaybeCreateExprWithCleanups(E
);
7437 /// Process the expression contained within a decltype. For such expressions,
7438 /// certain semantic checks on temporaries are delayed until this point, and
7439 /// are omitted for the 'topmost' call in the decltype expression. If the
7440 /// topmost call bound a temporary, strip that temporary off the expression.
7441 ExprResult
Sema::ActOnDecltypeExpression(Expr
*E
) {
7442 assert(ExprEvalContexts
.back().ExprContext
==
7443 ExpressionEvaluationContextRecord::EK_Decltype
&&
7444 "not in a decltype expression");
7446 ExprResult Result
= CheckPlaceholderExpr(E
);
7447 if (Result
.isInvalid())
7451 // C++11 [expr.call]p11:
7452 // If a function call is a prvalue of object type,
7453 // -- if the function call is either
7454 // -- the operand of a decltype-specifier, or
7455 // -- the right operand of a comma operator that is the operand of a
7456 // decltype-specifier,
7457 // a temporary object is not introduced for the prvalue.
7459 // Recursively rebuild ParenExprs and comma expressions to strip out the
7460 // outermost CXXBindTemporaryExpr, if any.
7461 if (ParenExpr
*PE
= dyn_cast
<ParenExpr
>(E
)) {
7462 ExprResult SubExpr
= ActOnDecltypeExpression(PE
->getSubExpr());
7463 if (SubExpr
.isInvalid())
7465 if (SubExpr
.get() == PE
->getSubExpr())
7467 return ActOnParenExpr(PE
->getLParen(), PE
->getRParen(), SubExpr
.get());
7469 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
7470 if (BO
->getOpcode() == BO_Comma
) {
7471 ExprResult RHS
= ActOnDecltypeExpression(BO
->getRHS());
7472 if (RHS
.isInvalid())
7474 if (RHS
.get() == BO
->getRHS())
7476 return BinaryOperator::Create(Context
, BO
->getLHS(), RHS
.get(), BO_Comma
,
7477 BO
->getType(), BO
->getValueKind(),
7478 BO
->getObjectKind(), BO
->getOperatorLoc(),
7479 BO
->getFPFeatures());
7483 CXXBindTemporaryExpr
*TopBind
= dyn_cast
<CXXBindTemporaryExpr
>(E
);
7484 CallExpr
*TopCall
= TopBind
? dyn_cast
<CallExpr
>(TopBind
->getSubExpr())
7491 // Disable the special decltype handling now.
7492 ExprEvalContexts
.back().ExprContext
=
7493 ExpressionEvaluationContextRecord::EK_Other
;
7495 Result
= CheckUnevaluatedOperand(E
);
7496 if (Result
.isInvalid())
7500 // In MS mode, don't perform any extra checking of call return types within a
7501 // decltype expression.
7502 if (getLangOpts().MSVCCompat
)
7505 // Perform the semantic checks we delayed until this point.
7506 for (unsigned I
= 0, N
= ExprEvalContexts
.back().DelayedDecltypeCalls
.size();
7508 CallExpr
*Call
= ExprEvalContexts
.back().DelayedDecltypeCalls
[I
];
7509 if (Call
== TopCall
)
7512 if (CheckCallReturnType(Call
->getCallReturnType(Context
),
7513 Call
->getBeginLoc(), Call
, Call
->getDirectCallee()))
7517 // Now all relevant types are complete, check the destructors are accessible
7518 // and non-deleted, and annotate them on the temporaries.
7519 for (unsigned I
= 0, N
= ExprEvalContexts
.back().DelayedDecltypeBinds
.size();
7521 CXXBindTemporaryExpr
*Bind
=
7522 ExprEvalContexts
.back().DelayedDecltypeBinds
[I
];
7523 if (Bind
== TopBind
)
7526 CXXTemporary
*Temp
= Bind
->getTemporary();
7529 Bind
->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7530 CXXDestructorDecl
*Destructor
= LookupDestructor(RD
);
7531 Temp
->setDestructor(Destructor
);
7533 MarkFunctionReferenced(Bind
->getExprLoc(), Destructor
);
7534 CheckDestructorAccess(Bind
->getExprLoc(), Destructor
,
7535 PDiag(diag::err_access_dtor_temp
)
7536 << Bind
->getType());
7537 if (DiagnoseUseOfDecl(Destructor
, Bind
->getExprLoc()))
7540 // We need a cleanup, but we don't need to remember the temporary.
7541 Cleanup
.setExprNeedsCleanups(true);
7544 // Possibly strip off the top CXXBindTemporaryExpr.
7548 /// Note a set of 'operator->' functions that were used for a member access.
7549 static void noteOperatorArrows(Sema
&S
,
7550 ArrayRef
<FunctionDecl
*> OperatorArrows
) {
7551 unsigned SkipStart
= OperatorArrows
.size(), SkipCount
= 0;
7552 // FIXME: Make this configurable?
7554 if (OperatorArrows
.size() > Limit
) {
7555 // Produce Limit-1 normal notes and one 'skipping' note.
7556 SkipStart
= (Limit
- 1) / 2 + (Limit
- 1) % 2;
7557 SkipCount
= OperatorArrows
.size() - (Limit
- 1);
7560 for (unsigned I
= 0; I
< OperatorArrows
.size(); /**/) {
7561 if (I
== SkipStart
) {
7562 S
.Diag(OperatorArrows
[I
]->getLocation(),
7563 diag::note_operator_arrows_suppressed
)
7567 S
.Diag(OperatorArrows
[I
]->getLocation(), diag::note_operator_arrow_here
)
7568 << OperatorArrows
[I
]->getCallResultType();
7574 ExprResult
Sema::ActOnStartCXXMemberReference(Scope
*S
, Expr
*Base
,
7575 SourceLocation OpLoc
,
7576 tok::TokenKind OpKind
,
7577 ParsedType
&ObjectType
,
7578 bool &MayBePseudoDestructor
) {
7579 // Since this might be a postfix expression, get rid of ParenListExprs.
7580 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Base
);
7581 if (Result
.isInvalid()) return ExprError();
7582 Base
= Result
.get();
7584 Result
= CheckPlaceholderExpr(Base
);
7585 if (Result
.isInvalid()) return ExprError();
7586 Base
= Result
.get();
7588 QualType BaseType
= Base
->getType();
7589 MayBePseudoDestructor
= false;
7590 if (BaseType
->isDependentType()) {
7591 // If we have a pointer to a dependent type and are using the -> operator,
7592 // the object type is the type that the pointer points to. We might still
7593 // have enough information about that type to do something useful.
7594 if (OpKind
== tok::arrow
)
7595 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>())
7596 BaseType
= Ptr
->getPointeeType();
7598 ObjectType
= ParsedType::make(BaseType
);
7599 MayBePseudoDestructor
= true;
7603 // C++ [over.match.oper]p8:
7604 // [...] When operator->returns, the operator-> is applied to the value
7605 // returned, with the original second operand.
7606 if (OpKind
== tok::arrow
) {
7607 QualType StartingType
= BaseType
;
7608 bool NoArrowOperatorFound
= false;
7609 bool FirstIteration
= true;
7610 FunctionDecl
*CurFD
= dyn_cast
<FunctionDecl
>(CurContext
);
7611 // The set of types we've considered so far.
7612 llvm::SmallPtrSet
<CanQualType
,8> CTypes
;
7613 SmallVector
<FunctionDecl
*, 8> OperatorArrows
;
7614 CTypes
.insert(Context
.getCanonicalType(BaseType
));
7616 while (BaseType
->isRecordType()) {
7617 if (OperatorArrows
.size() >= getLangOpts().ArrowDepth
) {
7618 Diag(OpLoc
, diag::err_operator_arrow_depth_exceeded
)
7619 << StartingType
<< getLangOpts().ArrowDepth
<< Base
->getSourceRange();
7620 noteOperatorArrows(*this, OperatorArrows
);
7621 Diag(OpLoc
, diag::note_operator_arrow_depth
)
7622 << getLangOpts().ArrowDepth
;
7626 Result
= BuildOverloadedArrowExpr(
7628 // When in a template specialization and on the first loop iteration,
7629 // potentially give the default diagnostic (with the fixit in a
7630 // separate note) instead of having the error reported back to here
7631 // and giving a diagnostic with a fixit attached to the error itself.
7632 (FirstIteration
&& CurFD
&& CurFD
->isFunctionTemplateSpecialization())
7634 : &NoArrowOperatorFound
);
7635 if (Result
.isInvalid()) {
7636 if (NoArrowOperatorFound
) {
7637 if (FirstIteration
) {
7638 Diag(OpLoc
, diag::err_typecheck_member_reference_suggestion
)
7639 << BaseType
<< 1 << Base
->getSourceRange()
7640 << FixItHint::CreateReplacement(OpLoc
, ".");
7641 OpKind
= tok::period
;
7644 Diag(OpLoc
, diag::err_typecheck_member_reference_arrow
)
7645 << BaseType
<< Base
->getSourceRange();
7646 CallExpr
*CE
= dyn_cast
<CallExpr
>(Base
);
7647 if (Decl
*CD
= (CE
? CE
->getCalleeDecl() : nullptr)) {
7648 Diag(CD
->getBeginLoc(),
7649 diag::note_member_reference_arrow_from_operator_arrow
);
7654 Base
= Result
.get();
7655 if (CXXOperatorCallExpr
*OpCall
= dyn_cast
<CXXOperatorCallExpr
>(Base
))
7656 OperatorArrows
.push_back(OpCall
->getDirectCallee());
7657 BaseType
= Base
->getType();
7658 CanQualType CBaseType
= Context
.getCanonicalType(BaseType
);
7659 if (!CTypes
.insert(CBaseType
).second
) {
7660 Diag(OpLoc
, diag::err_operator_arrow_circular
) << StartingType
;
7661 noteOperatorArrows(*this, OperatorArrows
);
7664 FirstIteration
= false;
7667 if (OpKind
== tok::arrow
) {
7668 if (BaseType
->isPointerType())
7669 BaseType
= BaseType
->getPointeeType();
7670 else if (auto *AT
= Context
.getAsArrayType(BaseType
))
7671 BaseType
= AT
->getElementType();
7675 // Objective-C properties allow "." access on Objective-C pointer types,
7676 // so adjust the base type to the object type itself.
7677 if (BaseType
->isObjCObjectPointerType())
7678 BaseType
= BaseType
->getPointeeType();
7680 // C++ [basic.lookup.classref]p2:
7681 // [...] If the type of the object expression is of pointer to scalar
7682 // type, the unqualified-id is looked up in the context of the complete
7683 // postfix-expression.
7685 // This also indicates that we could be parsing a pseudo-destructor-name.
7686 // Note that Objective-C class and object types can be pseudo-destructor
7687 // expressions or normal member (ivar or property) access expressions, and
7688 // it's legal for the type to be incomplete if this is a pseudo-destructor
7689 // call. We'll do more incomplete-type checks later in the lookup process,
7690 // so just skip this check for ObjC types.
7691 if (!BaseType
->isRecordType()) {
7692 ObjectType
= ParsedType::make(BaseType
);
7693 MayBePseudoDestructor
= true;
7697 // The object type must be complete (or dependent), or
7698 // C++11 [expr.prim.general]p3:
7699 // Unlike the object expression in other contexts, *this is not required to
7700 // be of complete type for purposes of class member access (5.2.5) outside
7701 // the member function body.
7702 if (!BaseType
->isDependentType() &&
7703 !isThisOutsideMemberFunctionBody(BaseType
) &&
7704 RequireCompleteType(OpLoc
, BaseType
,
7705 diag::err_incomplete_member_access
)) {
7706 return CreateRecoveryExpr(Base
->getBeginLoc(), Base
->getEndLoc(), {Base
});
7709 // C++ [basic.lookup.classref]p2:
7710 // If the id-expression in a class member access (5.2.5) is an
7711 // unqualified-id, and the type of the object expression is of a class
7712 // type C (or of pointer to a class type C), the unqualified-id is looked
7713 // up in the scope of class C. [...]
7714 ObjectType
= ParsedType::make(BaseType
);
7718 static bool CheckArrow(Sema
&S
, QualType
&ObjectType
, Expr
*&Base
,
7719 tok::TokenKind
&OpKind
, SourceLocation OpLoc
) {
7720 if (Base
->hasPlaceholderType()) {
7721 ExprResult result
= S
.CheckPlaceholderExpr(Base
);
7722 if (result
.isInvalid()) return true;
7723 Base
= result
.get();
7725 ObjectType
= Base
->getType();
7727 // C++ [expr.pseudo]p2:
7728 // The left-hand side of the dot operator shall be of scalar type. The
7729 // left-hand side of the arrow operator shall be of pointer to scalar type.
7730 // This scalar type is the object type.
7731 // Note that this is rather different from the normal handling for the
7733 if (OpKind
== tok::arrow
) {
7734 // The operator requires a prvalue, so perform lvalue conversions.
7735 // Only do this if we might plausibly end with a pointer, as otherwise
7736 // this was likely to be intended to be a '.'.
7737 if (ObjectType
->isPointerType() || ObjectType
->isArrayType() ||
7738 ObjectType
->isFunctionType()) {
7739 ExprResult BaseResult
= S
.DefaultFunctionArrayLvalueConversion(Base
);
7740 if (BaseResult
.isInvalid())
7742 Base
= BaseResult
.get();
7743 ObjectType
= Base
->getType();
7746 if (const PointerType
*Ptr
= ObjectType
->getAs
<PointerType
>()) {
7747 ObjectType
= Ptr
->getPointeeType();
7748 } else if (!Base
->isTypeDependent()) {
7749 // The user wrote "p->" when they probably meant "p."; fix it.
7750 S
.Diag(OpLoc
, diag::err_typecheck_member_reference_suggestion
)
7751 << ObjectType
<< true
7752 << FixItHint::CreateReplacement(OpLoc
, ".");
7753 if (S
.isSFINAEContext())
7756 OpKind
= tok::period
;
7763 /// Check if it's ok to try and recover dot pseudo destructor calls on
7764 /// pointer objects.
7766 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema
&SemaRef
,
7767 QualType DestructedType
) {
7768 // If this is a record type, check if its destructor is callable.
7769 if (auto *RD
= DestructedType
->getAsCXXRecordDecl()) {
7770 if (RD
->hasDefinition())
7771 if (CXXDestructorDecl
*D
= SemaRef
.LookupDestructor(RD
))
7772 return SemaRef
.CanUseDecl(D
, /*TreatUnavailableAsInvalid=*/false);
7776 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7777 return DestructedType
->isDependentType() || DestructedType
->isScalarType() ||
7778 DestructedType
->isVectorType();
7781 ExprResult
Sema::BuildPseudoDestructorExpr(Expr
*Base
,
7782 SourceLocation OpLoc
,
7783 tok::TokenKind OpKind
,
7784 const CXXScopeSpec
&SS
,
7785 TypeSourceInfo
*ScopeTypeInfo
,
7786 SourceLocation CCLoc
,
7787 SourceLocation TildeLoc
,
7788 PseudoDestructorTypeStorage Destructed
) {
7789 TypeSourceInfo
*DestructedTypeInfo
= Destructed
.getTypeSourceInfo();
7791 QualType ObjectType
;
7792 if (CheckArrow(*this, ObjectType
, Base
, OpKind
, OpLoc
))
7795 if (!ObjectType
->isDependentType() && !ObjectType
->isScalarType() &&
7796 !ObjectType
->isVectorType()) {
7797 if (getLangOpts().MSVCCompat
&& ObjectType
->isVoidType())
7798 Diag(OpLoc
, diag::ext_pseudo_dtor_on_void
) << Base
->getSourceRange();
7800 Diag(OpLoc
, diag::err_pseudo_dtor_base_not_scalar
)
7801 << ObjectType
<< Base
->getSourceRange();
7806 // C++ [expr.pseudo]p2:
7807 // [...] The cv-unqualified versions of the object type and of the type
7808 // designated by the pseudo-destructor-name shall be the same type.
7809 if (DestructedTypeInfo
) {
7810 QualType DestructedType
= DestructedTypeInfo
->getType();
7811 SourceLocation DestructedTypeStart
=
7812 DestructedTypeInfo
->getTypeLoc().getBeginLoc();
7813 if (!DestructedType
->isDependentType() && !ObjectType
->isDependentType()) {
7814 if (!Context
.hasSameUnqualifiedType(DestructedType
, ObjectType
)) {
7815 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7818 if (OpKind
== tok::period
&& ObjectType
->isPointerType() &&
7819 Context
.hasSameUnqualifiedType(DestructedType
,
7820 ObjectType
->getPointeeType())) {
7822 Diag(OpLoc
, diag::err_typecheck_member_reference_suggestion
)
7823 << ObjectType
<< /*IsArrow=*/0 << Base
->getSourceRange();
7825 // Issue a fixit only when the destructor is valid.
7826 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7827 *this, DestructedType
))
7828 Diagnostic
<< FixItHint::CreateReplacement(OpLoc
, "->");
7830 // Recover by setting the object type to the destructed type and the
7831 // operator to '->'.
7832 ObjectType
= DestructedType
;
7833 OpKind
= tok::arrow
;
7835 Diag(DestructedTypeStart
, diag::err_pseudo_dtor_type_mismatch
)
7836 << ObjectType
<< DestructedType
<< Base
->getSourceRange()
7837 << DestructedTypeInfo
->getTypeLoc().getSourceRange();
7839 // Recover by setting the destructed type to the object type.
7840 DestructedType
= ObjectType
;
7841 DestructedTypeInfo
=
7842 Context
.getTrivialTypeSourceInfo(ObjectType
, DestructedTypeStart
);
7843 Destructed
= PseudoDestructorTypeStorage(DestructedTypeInfo
);
7845 } else if (DestructedType
.getObjCLifetime() !=
7846 ObjectType
.getObjCLifetime()) {
7848 if (DestructedType
.getObjCLifetime() == Qualifiers::OCL_None
) {
7849 // Okay: just pretend that the user provided the correctly-qualified
7852 Diag(DestructedTypeStart
, diag::err_arc_pseudo_dtor_inconstant_quals
)
7853 << ObjectType
<< DestructedType
<< Base
->getSourceRange()
7854 << DestructedTypeInfo
->getTypeLoc().getSourceRange();
7857 // Recover by setting the destructed type to the object type.
7858 DestructedType
= ObjectType
;
7859 DestructedTypeInfo
= Context
.getTrivialTypeSourceInfo(ObjectType
,
7860 DestructedTypeStart
);
7861 Destructed
= PseudoDestructorTypeStorage(DestructedTypeInfo
);
7866 // C++ [expr.pseudo]p2:
7867 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7870 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7872 // shall designate the same scalar type.
7873 if (ScopeTypeInfo
) {
7874 QualType ScopeType
= ScopeTypeInfo
->getType();
7875 if (!ScopeType
->isDependentType() && !ObjectType
->isDependentType() &&
7876 !Context
.hasSameUnqualifiedType(ScopeType
, ObjectType
)) {
7878 Diag(ScopeTypeInfo
->getTypeLoc().getSourceRange().getBegin(),
7879 diag::err_pseudo_dtor_type_mismatch
)
7880 << ObjectType
<< ScopeType
<< Base
->getSourceRange()
7881 << ScopeTypeInfo
->getTypeLoc().getSourceRange();
7883 ScopeType
= QualType();
7884 ScopeTypeInfo
= nullptr;
7889 = new (Context
) CXXPseudoDestructorExpr(Context
, Base
,
7890 OpKind
== tok::arrow
, OpLoc
,
7891 SS
.getWithLocInContext(Context
),
7900 ExprResult
Sema::ActOnPseudoDestructorExpr(Scope
*S
, Expr
*Base
,
7901 SourceLocation OpLoc
,
7902 tok::TokenKind OpKind
,
7904 UnqualifiedId
&FirstTypeName
,
7905 SourceLocation CCLoc
,
7906 SourceLocation TildeLoc
,
7907 UnqualifiedId
&SecondTypeName
) {
7908 assert((FirstTypeName
.getKind() == UnqualifiedIdKind::IK_TemplateId
||
7909 FirstTypeName
.getKind() == UnqualifiedIdKind::IK_Identifier
) &&
7910 "Invalid first type name in pseudo-destructor");
7911 assert((SecondTypeName
.getKind() == UnqualifiedIdKind::IK_TemplateId
||
7912 SecondTypeName
.getKind() == UnqualifiedIdKind::IK_Identifier
) &&
7913 "Invalid second type name in pseudo-destructor");
7915 QualType ObjectType
;
7916 if (CheckArrow(*this, ObjectType
, Base
, OpKind
, OpLoc
))
7919 // Compute the object type that we should use for name lookup purposes. Only
7920 // record types and dependent types matter.
7921 ParsedType ObjectTypePtrForLookup
;
7923 if (ObjectType
->isRecordType())
7924 ObjectTypePtrForLookup
= ParsedType::make(ObjectType
);
7925 else if (ObjectType
->isDependentType())
7926 ObjectTypePtrForLookup
= ParsedType::make(Context
.DependentTy
);
7929 // Convert the name of the type being destructed (following the ~) into a
7930 // type (with source-location information).
7931 QualType DestructedType
;
7932 TypeSourceInfo
*DestructedTypeInfo
= nullptr;
7933 PseudoDestructorTypeStorage Destructed
;
7934 if (SecondTypeName
.getKind() == UnqualifiedIdKind::IK_Identifier
) {
7935 ParsedType T
= getTypeName(*SecondTypeName
.Identifier
,
7936 SecondTypeName
.StartLocation
,
7937 S
, &SS
, true, false, ObjectTypePtrForLookup
,
7938 /*IsCtorOrDtorName*/true);
7940 ((SS
.isSet() && !computeDeclContext(SS
, false)) ||
7941 (!SS
.isSet() && ObjectType
->isDependentType()))) {
7942 // The name of the type being destroyed is a dependent name, and we
7943 // couldn't find anything useful in scope. Just store the identifier and
7944 // it's location, and we'll perform (qualified) name lookup again at
7945 // template instantiation time.
7946 Destructed
= PseudoDestructorTypeStorage(SecondTypeName
.Identifier
,
7947 SecondTypeName
.StartLocation
);
7949 Diag(SecondTypeName
.StartLocation
,
7950 diag::err_pseudo_dtor_destructor_non_type
)
7951 << SecondTypeName
.Identifier
<< ObjectType
;
7952 if (isSFINAEContext())
7955 // Recover by assuming we had the right type all along.
7956 DestructedType
= ObjectType
;
7958 DestructedType
= GetTypeFromParser(T
, &DestructedTypeInfo
);
7960 // Resolve the template-id to a type.
7961 TemplateIdAnnotation
*TemplateId
= SecondTypeName
.TemplateId
;
7962 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
7963 TemplateId
->NumArgs
);
7964 TypeResult T
= ActOnTemplateIdType(S
,
7966 TemplateId
->TemplateKWLoc
,
7967 TemplateId
->Template
,
7969 TemplateId
->TemplateNameLoc
,
7970 TemplateId
->LAngleLoc
,
7972 TemplateId
->RAngleLoc
,
7973 /*IsCtorOrDtorName*/true);
7974 if (T
.isInvalid() || !T
.get()) {
7975 // Recover by assuming we had the right type all along.
7976 DestructedType
= ObjectType
;
7978 DestructedType
= GetTypeFromParser(T
.get(), &DestructedTypeInfo
);
7981 // If we've performed some kind of recovery, (re-)build the type source
7983 if (!DestructedType
.isNull()) {
7984 if (!DestructedTypeInfo
)
7985 DestructedTypeInfo
= Context
.getTrivialTypeSourceInfo(DestructedType
,
7986 SecondTypeName
.StartLocation
);
7987 Destructed
= PseudoDestructorTypeStorage(DestructedTypeInfo
);
7990 // Convert the name of the scope type (the type prior to '::') into a type.
7991 TypeSourceInfo
*ScopeTypeInfo
= nullptr;
7993 if (FirstTypeName
.getKind() == UnqualifiedIdKind::IK_TemplateId
||
7994 FirstTypeName
.Identifier
) {
7995 if (FirstTypeName
.getKind() == UnqualifiedIdKind::IK_Identifier
) {
7996 ParsedType T
= getTypeName(*FirstTypeName
.Identifier
,
7997 FirstTypeName
.StartLocation
,
7998 S
, &SS
, true, false, ObjectTypePtrForLookup
,
7999 /*IsCtorOrDtorName*/true);
8001 Diag(FirstTypeName
.StartLocation
,
8002 diag::err_pseudo_dtor_destructor_non_type
)
8003 << FirstTypeName
.Identifier
<< ObjectType
;
8005 if (isSFINAEContext())
8008 // Just drop this type. It's unnecessary anyway.
8009 ScopeType
= QualType();
8011 ScopeType
= GetTypeFromParser(T
, &ScopeTypeInfo
);
8013 // Resolve the template-id to a type.
8014 TemplateIdAnnotation
*TemplateId
= FirstTypeName
.TemplateId
;
8015 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
8016 TemplateId
->NumArgs
);
8017 TypeResult T
= ActOnTemplateIdType(S
,
8019 TemplateId
->TemplateKWLoc
,
8020 TemplateId
->Template
,
8022 TemplateId
->TemplateNameLoc
,
8023 TemplateId
->LAngleLoc
,
8025 TemplateId
->RAngleLoc
,
8026 /*IsCtorOrDtorName*/true);
8027 if (T
.isInvalid() || !T
.get()) {
8028 // Recover by dropping this type.
8029 ScopeType
= QualType();
8031 ScopeType
= GetTypeFromParser(T
.get(), &ScopeTypeInfo
);
8035 if (!ScopeType
.isNull() && !ScopeTypeInfo
)
8036 ScopeTypeInfo
= Context
.getTrivialTypeSourceInfo(ScopeType
,
8037 FirstTypeName
.StartLocation
);
8040 return BuildPseudoDestructorExpr(Base
, OpLoc
, OpKind
, SS
,
8041 ScopeTypeInfo
, CCLoc
, TildeLoc
,
8045 ExprResult
Sema::ActOnPseudoDestructorExpr(Scope
*S
, Expr
*Base
,
8046 SourceLocation OpLoc
,
8047 tok::TokenKind OpKind
,
8048 SourceLocation TildeLoc
,
8049 const DeclSpec
& DS
) {
8050 QualType ObjectType
;
8051 if (CheckArrow(*this, ObjectType
, Base
, OpKind
, OpLoc
))
8054 if (DS
.getTypeSpecType() == DeclSpec::TST_decltype_auto
) {
8055 Diag(DS
.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid
);
8059 QualType T
= BuildDecltypeType(DS
.getRepAsExpr(), /*AsUnevaluated=*/false);
8062 DecltypeTypeLoc DecltypeTL
= TLB
.push
<DecltypeTypeLoc
>(T
);
8063 DecltypeTL
.setDecltypeLoc(DS
.getTypeSpecTypeLoc());
8064 DecltypeTL
.setRParenLoc(DS
.getTypeofParensRange().getEnd());
8065 TypeSourceInfo
*DestructedTypeInfo
= TLB
.getTypeSourceInfo(Context
, T
);
8066 PseudoDestructorTypeStorage
Destructed(DestructedTypeInfo
);
8068 return BuildPseudoDestructorExpr(Base
, OpLoc
, OpKind
, CXXScopeSpec(),
8069 nullptr, SourceLocation(), TildeLoc
,
8073 ExprResult
Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc
, Expr
*Operand
,
8074 SourceLocation RParen
) {
8075 // If the operand is an unresolved lookup expression, the expression is ill-
8076 // formed per [over.over]p1, because overloaded function names cannot be used
8077 // without arguments except in explicit contexts.
8078 ExprResult R
= CheckPlaceholderExpr(Operand
);
8082 R
= CheckUnevaluatedOperand(R
.get());
8088 if (!inTemplateInstantiation() && !Operand
->isInstantiationDependent() &&
8089 Operand
->HasSideEffects(Context
, false)) {
8090 // The expression operand for noexcept is in an unevaluated expression
8091 // context, so side effects could result in unintended consequences.
8092 Diag(Operand
->getExprLoc(), diag::warn_side_effects_unevaluated_context
);
8095 CanThrowResult CanThrow
= canThrow(Operand
);
8096 return new (Context
)
8097 CXXNoexceptExpr(Context
.BoolTy
, Operand
, CanThrow
, KeyLoc
, RParen
);
8100 ExprResult
Sema::ActOnNoexceptExpr(SourceLocation KeyLoc
, SourceLocation
,
8101 Expr
*Operand
, SourceLocation RParen
) {
8102 return BuildCXXNoexceptExpr(KeyLoc
, Operand
, RParen
);
8105 static void MaybeDecrementCount(
8106 Expr
*E
, llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
8107 DeclRefExpr
*LHS
= nullptr;
8108 bool IsCompoundAssign
= false;
8109 bool isIncrementDecrementUnaryOp
= false;
8110 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
8111 if (BO
->getLHS()->getType()->isDependentType() ||
8112 BO
->getRHS()->getType()->isDependentType()) {
8113 if (BO
->getOpcode() != BO_Assign
)
8115 } else if (!BO
->isAssignmentOp())
8118 IsCompoundAssign
= BO
->isCompoundAssignmentOp();
8119 LHS
= dyn_cast
<DeclRefExpr
>(BO
->getLHS());
8120 } else if (CXXOperatorCallExpr
*COCE
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
8121 if (COCE
->getOperator() != OO_Equal
)
8123 LHS
= dyn_cast
<DeclRefExpr
>(COCE
->getArg(0));
8124 } else if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(E
)) {
8125 if (!UO
->isIncrementDecrementOp())
8127 isIncrementDecrementUnaryOp
= true;
8128 LHS
= dyn_cast
<DeclRefExpr
>(UO
->getSubExpr());
8132 VarDecl
*VD
= dyn_cast
<VarDecl
>(LHS
->getDecl());
8135 // Don't decrement RefsMinusAssignments if volatile variable with compound
8136 // assignment (+=, ...) or increment/decrement unary operator to avoid
8137 // potential unused-but-set-variable warning.
8138 if ((IsCompoundAssign
|| isIncrementDecrementUnaryOp
) &&
8139 VD
->getType().isVolatileQualified())
8141 auto iter
= RefsMinusAssignments
.find(VD
);
8142 if (iter
== RefsMinusAssignments
.end())
8144 iter
->getSecond()--;
8147 /// Perform the conversions required for an expression used in a
8148 /// context that ignores the result.
8149 ExprResult
Sema::IgnoredValueConversions(Expr
*E
) {
8150 MaybeDecrementCount(E
, RefsMinusAssignments
);
8152 if (E
->hasPlaceholderType()) {
8153 ExprResult result
= CheckPlaceholderExpr(E
);
8154 if (result
.isInvalid()) return E
;
8159 // [Except in specific positions,] an lvalue that does not have
8160 // array type is converted to the value stored in the
8161 // designated object (and is no longer an lvalue).
8162 if (E
->isPRValue()) {
8163 // In C, function designators (i.e. expressions of function type)
8164 // are r-values, but we still want to do function-to-pointer decay
8165 // on them. This is both technically correct and convenient for
8167 if (!getLangOpts().CPlusPlus
&& E
->getType()->isFunctionType())
8168 return DefaultFunctionArrayConversion(E
);
8173 if (getLangOpts().CPlusPlus
) {
8174 // The C++11 standard defines the notion of a discarded-value expression;
8175 // normally, we don't need to do anything to handle it, but if it is a
8176 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8178 if (getLangOpts().CPlusPlus11
&& E
->isReadIfDiscardedInCPlusPlus11()) {
8179 ExprResult Res
= DefaultLvalueConversion(E
);
8180 if (Res
.isInvalid())
8184 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8185 // it occurs as a discarded-value expression.
8186 CheckUnusedVolatileAssignment(E
);
8190 // If the expression is a prvalue after this optional conversion, the
8191 // temporary materialization conversion is applied.
8193 // We skip this step: IR generation is able to synthesize the storage for
8194 // itself in the aggregate case, and adding the extra node to the AST is
8196 // FIXME: We don't emit lifetime markers for the temporaries due to this.
8197 // FIXME: Do any other AST consumers care about this?
8201 // GCC seems to also exclude expressions of incomplete enum type.
8202 if (const EnumType
*T
= E
->getType()->getAs
<EnumType
>()) {
8203 if (!T
->getDecl()->isComplete()) {
8204 // FIXME: stupid workaround for a codegen bug!
8205 E
= ImpCastExprToType(E
, Context
.VoidTy
, CK_ToVoid
).get();
8210 ExprResult Res
= DefaultFunctionArrayLvalueConversion(E
);
8211 if (Res
.isInvalid())
8215 if (!E
->getType()->isVoidType())
8216 RequireCompleteType(E
->getExprLoc(), E
->getType(),
8217 diag::err_incomplete_type
);
8221 ExprResult
Sema::CheckUnevaluatedOperand(Expr
*E
) {
8222 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8223 // it occurs as an unevaluated operand.
8224 CheckUnusedVolatileAssignment(E
);
8229 // If we can unambiguously determine whether Var can never be used
8230 // in a constant expression, return true.
8231 // - if the variable and its initializer are non-dependent, then
8232 // we can unambiguously check if the variable is a constant expression.
8233 // - if the initializer is not value dependent - we can determine whether
8234 // it can be used to initialize a constant expression. If Init can not
8235 // be used to initialize a constant expression we conclude that Var can
8236 // never be a constant expression.
8237 // - FXIME: if the initializer is dependent, we can still do some analysis and
8238 // identify certain cases unambiguously as non-const by using a Visitor:
8239 // - such as those that involve odr-use of a ParmVarDecl, involve a new
8240 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8241 static inline bool VariableCanNeverBeAConstantExpression(VarDecl
*Var
,
8242 ASTContext
&Context
) {
8243 if (isa
<ParmVarDecl
>(Var
)) return true;
8244 const VarDecl
*DefVD
= nullptr;
8246 // If there is no initializer - this can not be a constant expression.
8247 const Expr
*Init
= Var
->getAnyInitializer(DefVD
);
8251 if (DefVD
->isWeak())
8254 if (Var
->getType()->isDependentType() || Init
->isValueDependent()) {
8255 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8256 // of value-dependent expressions, and use it here to determine whether the
8257 // initializer is a potential constant expression.
8261 return !Var
->isUsableInConstantExpressions(Context
);
8264 /// Check if the current lambda has any potential captures
8265 /// that must be captured by any of its enclosing lambdas that are ready to
8266 /// capture. If there is a lambda that can capture a nested
8267 /// potential-capture, go ahead and do so. Also, check to see if any
8268 /// variables are uncaptureable or do not involve an odr-use so do not
8269 /// need to be captured.
8271 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8272 Expr
*const FE
, LambdaScopeInfo
*const CurrentLSI
, Sema
&S
) {
8274 assert(!S
.isUnevaluatedContext());
8275 assert(S
.CurContext
->isDependentContext());
8277 DeclContext
*DC
= S
.CurContext
;
8278 while (DC
&& isa
<CapturedDecl
>(DC
))
8279 DC
= DC
->getParent();
8281 CurrentLSI
->CallOperator
== DC
&&
8282 "The current call operator must be synchronized with Sema's CurContext");
8285 const bool IsFullExprInstantiationDependent
= FE
->isInstantiationDependent();
8287 // All the potentially captureable variables in the current nested
8288 // lambda (within a generic outer lambda), must be captured by an
8289 // outer lambda that is enclosed within a non-dependent context.
8290 CurrentLSI
->visitPotentialCaptures([&](ValueDecl
*Var
, Expr
*VarExpr
) {
8291 // If the variable is clearly identified as non-odr-used and the full
8292 // expression is not instantiation dependent, only then do we not
8293 // need to check enclosing lambda's for speculative captures.
8295 // Even though 'x' is not odr-used, it should be captured.
8297 // const int x = 10;
8298 // auto L = [=](auto a) {
8302 if (CurrentLSI
->isVariableExprMarkedAsNonODRUsed(VarExpr
) &&
8303 !IsFullExprInstantiationDependent
)
8306 VarDecl
*UnderlyingVar
= Var
->getPotentiallyDecomposedVarDecl();
8310 // If we have a capture-capable lambda for the variable, go ahead and
8311 // capture the variable in that lambda (and all its enclosing lambdas).
8312 if (const std::optional
<unsigned> Index
=
8313 getStackIndexOfNearestEnclosingCaptureCapableLambda(
8314 S
.FunctionScopes
, Var
, S
))
8315 S
.MarkCaptureUsedInEnclosingContext(Var
, VarExpr
->getExprLoc(), *Index
);
8316 const bool IsVarNeverAConstantExpression
=
8317 VariableCanNeverBeAConstantExpression(UnderlyingVar
, S
.Context
);
8318 if (!IsFullExprInstantiationDependent
|| IsVarNeverAConstantExpression
) {
8319 // This full expression is not instantiation dependent or the variable
8320 // can not be used in a constant expression - which means
8321 // this variable must be odr-used here, so diagnose a
8322 // capture violation early, if the variable is un-captureable.
8323 // This is purely for diagnosing errors early. Otherwise, this
8324 // error would get diagnosed when the lambda becomes capture ready.
8325 QualType CaptureType
, DeclRefType
;
8326 SourceLocation ExprLoc
= VarExpr
->getExprLoc();
8327 if (S
.tryCaptureVariable(Var
, ExprLoc
, S
.TryCapture_Implicit
,
8328 /*EllipsisLoc*/ SourceLocation(),
8329 /*BuildAndDiagnose*/false, CaptureType
,
8330 DeclRefType
, nullptr)) {
8331 // We will never be able to capture this variable, and we need
8332 // to be able to in any and all instantiations, so diagnose it.
8333 S
.tryCaptureVariable(Var
, ExprLoc
, S
.TryCapture_Implicit
,
8334 /*EllipsisLoc*/ SourceLocation(),
8335 /*BuildAndDiagnose*/true, CaptureType
,
8336 DeclRefType
, nullptr);
8341 // Check if 'this' needs to be captured.
8342 if (CurrentLSI
->hasPotentialThisCapture()) {
8343 // If we have a capture-capable lambda for 'this', go ahead and capture
8344 // 'this' in that lambda (and all its enclosing lambdas).
8345 if (const std::optional
<unsigned> Index
=
8346 getStackIndexOfNearestEnclosingCaptureCapableLambda(
8347 S
.FunctionScopes
, /*0 is 'this'*/ nullptr, S
)) {
8348 const unsigned FunctionScopeIndexOfCapturableLambda
= *Index
;
8349 S
.CheckCXXThisCapture(CurrentLSI
->PotentialThisCaptureLocation
,
8350 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8351 &FunctionScopeIndexOfCapturableLambda
);
8355 // Reset all the potential captures at the end of each full-expression.
8356 CurrentLSI
->clearPotentialCaptures();
8359 static ExprResult
attemptRecovery(Sema
&SemaRef
,
8360 const TypoCorrectionConsumer
&Consumer
,
8361 const TypoCorrection
&TC
) {
8362 LookupResult
R(SemaRef
, Consumer
.getLookupResult().getLookupNameInfo(),
8363 Consumer
.getLookupResult().getLookupKind());
8364 const CXXScopeSpec
*SS
= Consumer
.getSS();
8367 // Use an approprate CXXScopeSpec for building the expr.
8368 if (auto *NNS
= TC
.getCorrectionSpecifier())
8369 NewSS
.MakeTrivial(SemaRef
.Context
, NNS
, TC
.getCorrectionRange());
8370 else if (SS
&& !TC
.WillReplaceSpecifier())
8373 if (auto *ND
= TC
.getFoundDecl()) {
8374 R
.setLookupName(ND
->getDeclName());
8376 if (ND
->isCXXClassMember()) {
8377 // Figure out the correct naming class to add to the LookupResult.
8378 CXXRecordDecl
*Record
= nullptr;
8379 if (auto *NNS
= TC
.getCorrectionSpecifier())
8380 Record
= NNS
->getAsType()->getAsCXXRecordDecl();
8383 dyn_cast
<CXXRecordDecl
>(ND
->getDeclContext()->getRedeclContext());
8385 R
.setNamingClass(Record
);
8387 // Detect and handle the case where the decl might be an implicit
8389 bool MightBeImplicitMember
;
8390 if (!Consumer
.isAddressOfOperand())
8391 MightBeImplicitMember
= true;
8392 else if (!NewSS
.isEmpty())
8393 MightBeImplicitMember
= false;
8394 else if (R
.isOverloadedResult())
8395 MightBeImplicitMember
= false;
8396 else if (R
.isUnresolvableResult())
8397 MightBeImplicitMember
= true;
8399 MightBeImplicitMember
= isa
<FieldDecl
>(ND
) ||
8400 isa
<IndirectFieldDecl
>(ND
) ||
8401 isa
<MSPropertyDecl
>(ND
);
8403 if (MightBeImplicitMember
)
8404 return SemaRef
.BuildPossibleImplicitMemberExpr(
8405 NewSS
, /*TemplateKWLoc*/ SourceLocation(), R
,
8406 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8407 } else if (auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(ND
)) {
8408 return SemaRef
.LookupInObjCMethod(R
, Consumer
.getScope(),
8409 Ivar
->getIdentifier());
8413 return SemaRef
.BuildDeclarationNameExpr(NewSS
, R
, /*NeedsADL*/ false,
8414 /*AcceptInvalidDecl*/ true);
8418 class FindTypoExprs
: public RecursiveASTVisitor
<FindTypoExprs
> {
8419 llvm::SmallSetVector
<TypoExpr
*, 2> &TypoExprs
;
8422 explicit FindTypoExprs(llvm::SmallSetVector
<TypoExpr
*, 2> &TypoExprs
)
8423 : TypoExprs(TypoExprs
) {}
8424 bool VisitTypoExpr(TypoExpr
*TE
) {
8425 TypoExprs
.insert(TE
);
8430 class TransformTypos
: public TreeTransform
<TransformTypos
> {
8431 typedef TreeTransform
<TransformTypos
> BaseTransform
;
8433 VarDecl
*InitDecl
; // A decl to avoid as a correction because it is in the
8434 // process of being initialized.
8435 llvm::function_ref
<ExprResult(Expr
*)> ExprFilter
;
8436 llvm::SmallSetVector
<TypoExpr
*, 2> TypoExprs
, AmbiguousTypoExprs
;
8437 llvm::SmallDenseMap
<TypoExpr
*, ExprResult
, 2> TransformCache
;
8438 llvm::SmallDenseMap
<OverloadExpr
*, Expr
*, 4> OverloadResolution
;
8440 /// Emit diagnostics for all of the TypoExprs encountered.
8442 /// If the TypoExprs were successfully corrected, then the diagnostics should
8443 /// suggest the corrections. Otherwise the diagnostics will not suggest
8444 /// anything (having been passed an empty TypoCorrection).
8446 /// If we've failed to correct due to ambiguous corrections, we need to
8447 /// be sure to pass empty corrections and replacements. Otherwise it's
8448 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8449 /// and we don't want to report those diagnostics.
8450 void EmitAllDiagnostics(bool IsAmbiguous
) {
8451 for (TypoExpr
*TE
: TypoExprs
) {
8452 auto &State
= SemaRef
.getTypoExprState(TE
);
8453 if (State
.DiagHandler
) {
8454 TypoCorrection TC
= IsAmbiguous
8455 ? TypoCorrection() : State
.Consumer
->getCurrentCorrection();
8456 ExprResult Replacement
= IsAmbiguous
? ExprError() : TransformCache
[TE
];
8458 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8459 // TypoCorrection, replacing the existing decls. This ensures the right
8460 // NamedDecl is used in diagnostics e.g. in the case where overload
8461 // resolution was used to select one from several possible decls that
8462 // had been stored in the TypoCorrection.
8463 if (auto *ND
= getDeclFromExpr(
8464 Replacement
.isInvalid() ? nullptr : Replacement
.get()))
8465 TC
.setCorrectionDecl(ND
);
8467 State
.DiagHandler(TC
);
8469 SemaRef
.clearDelayedTypo(TE
);
8473 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8474 /// We allow advancement of the correction stream by removing it from the
8475 /// TransformCache which allows `TransformTypoExpr` to advance during the
8476 /// next transformation attempt.
8478 /// Any substitution attempts for the previous TypoExprs (which must have been
8479 /// finished) will need to be retried since it's possible that they will now
8480 /// be invalid given the latest advancement.
8482 /// We need to be sure that we're making progress - it's possible that the
8483 /// tree is so malformed that the transform never makes it to the
8484 /// `TransformTypoExpr`.
8486 /// Returns true if there are any untried correction combinations.
8487 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8488 for (auto *TE
: TypoExprs
) {
8489 auto &State
= SemaRef
.getTypoExprState(TE
);
8490 TransformCache
.erase(TE
);
8491 if (!State
.Consumer
->hasMadeAnyCorrectionProgress())
8493 if (!State
.Consumer
->finished())
8495 State
.Consumer
->resetCorrectionStream();
8500 NamedDecl
*getDeclFromExpr(Expr
*E
) {
8501 if (auto *OE
= dyn_cast_or_null
<OverloadExpr
>(E
))
8502 E
= OverloadResolution
[OE
];
8506 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
))
8507 return DRE
->getFoundDecl();
8508 if (auto *ME
= dyn_cast
<MemberExpr
>(E
))
8509 return ME
->getFoundDecl();
8510 // FIXME: Add any other expr types that could be seen by the delayed typo
8511 // correction TreeTransform for which the corresponding TypoCorrection could
8512 // contain multiple decls.
8516 ExprResult
TryTransform(Expr
*E
) {
8517 Sema::SFINAETrap
Trap(SemaRef
);
8518 ExprResult Res
= TransformExpr(E
);
8519 if (Trap
.hasErrorOccurred() || Res
.isInvalid())
8522 return ExprFilter(Res
.get());
8525 // Since correcting typos may intoduce new TypoExprs, this function
8526 // checks for new TypoExprs and recurses if it finds any. Note that it will
8527 // only succeed if it is able to correct all typos in the given expression.
8528 ExprResult
CheckForRecursiveTypos(ExprResult Res
, bool &IsAmbiguous
) {
8529 if (Res
.isInvalid()) {
8532 // Check to see if any new TypoExprs were created. If so, we need to recurse
8533 // to check their validity.
8534 Expr
*FixedExpr
= Res
.get();
8536 auto SavedTypoExprs
= std::move(TypoExprs
);
8537 auto SavedAmbiguousTypoExprs
= std::move(AmbiguousTypoExprs
);
8539 AmbiguousTypoExprs
.clear();
8541 FindTypoExprs(TypoExprs
).TraverseStmt(FixedExpr
);
8542 if (!TypoExprs
.empty()) {
8543 // Recurse to handle newly created TypoExprs. If we're not able to
8544 // handle them, discard these TypoExprs.
8545 ExprResult RecurResult
=
8546 RecursiveTransformLoop(FixedExpr
, IsAmbiguous
);
8547 if (RecurResult
.isInvalid()) {
8549 // Recursive corrections didn't work, wipe them away and don't add
8550 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8551 // since we don't want to clear them twice. Note: it's possible the
8552 // TypoExprs were created recursively and thus won't be in our
8553 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8554 auto &SemaTypoExprs
= SemaRef
.TypoExprs
;
8555 for (auto *TE
: TypoExprs
) {
8556 TransformCache
.erase(TE
);
8557 SemaRef
.clearDelayedTypo(TE
);
8559 auto SI
= find(SemaTypoExprs
, TE
);
8560 if (SI
!= SemaTypoExprs
.end()) {
8561 SemaTypoExprs
.erase(SI
);
8565 // TypoExpr is valid: add newly created TypoExprs since we were
8566 // able to correct them.
8568 SavedTypoExprs
.set_union(TypoExprs
);
8572 TypoExprs
= std::move(SavedTypoExprs
);
8573 AmbiguousTypoExprs
= std::move(SavedAmbiguousTypoExprs
);
8578 // Try to transform the given expression, looping through the correction
8579 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8581 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8582 // true and this method immediately will return an `ExprError`.
8583 ExprResult
RecursiveTransformLoop(Expr
*E
, bool &IsAmbiguous
) {
8585 auto SavedTypoExprs
= std::move(SemaRef
.TypoExprs
);
8586 SemaRef
.TypoExprs
.clear();
8589 Res
= CheckForRecursiveTypos(TryTransform(E
), IsAmbiguous
);
8591 // Recursion encountered an ambiguous correction. This means that our
8592 // correction itself is ambiguous, so stop now.
8596 // If the transform is still valid after checking for any new typos,
8598 if (!Res
.isInvalid())
8601 // The transform was invalid, see if we have any TypoExprs with untried
8602 // correction candidates.
8603 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8607 // If we found a valid result, double check to make sure it's not ambiguous.
8608 if (!IsAmbiguous
&& !Res
.isInvalid() && !AmbiguousTypoExprs
.empty()) {
8609 auto SavedTransformCache
=
8610 llvm::SmallDenseMap
<TypoExpr
*, ExprResult
, 2>(TransformCache
);
8612 // Ensure none of the TypoExprs have multiple typo correction candidates
8613 // with the same edit length that pass all the checks and filters.
8614 while (!AmbiguousTypoExprs
.empty()) {
8615 auto TE
= AmbiguousTypoExprs
.back();
8617 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8618 // and invalidating our TypoExprState, so always fetch it instead of storing.
8619 SemaRef
.getTypoExprState(TE
).Consumer
->saveCurrentPosition();
8621 TypoCorrection TC
= SemaRef
.getTypoExprState(TE
).Consumer
->peekNextCorrection();
8622 TypoCorrection Next
;
8624 // Fetch the next correction by erasing the typo from the cache and calling
8625 // `TryTransform` which will iterate through corrections in
8626 // `TransformTypoExpr`.
8627 TransformCache
.erase(TE
);
8628 ExprResult AmbigRes
= CheckForRecursiveTypos(TryTransform(E
), IsAmbiguous
);
8630 if (!AmbigRes
.isInvalid() || IsAmbiguous
) {
8631 SemaRef
.getTypoExprState(TE
).Consumer
->resetCorrectionStream();
8632 SavedTransformCache
.erase(TE
);
8637 } while ((Next
= SemaRef
.getTypoExprState(TE
).Consumer
->peekNextCorrection()) &&
8638 Next
.getEditDistance(false) == TC
.getEditDistance(false));
8643 AmbiguousTypoExprs
.remove(TE
);
8644 SemaRef
.getTypoExprState(TE
).Consumer
->restoreSavedPosition();
8645 TransformCache
[TE
] = SavedTransformCache
[TE
];
8647 TransformCache
= std::move(SavedTransformCache
);
8650 // Wipe away any newly created TypoExprs that we don't know about. Since we
8651 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8652 // possible if a `TypoExpr` is created during a transformation but then
8653 // fails before we can discover it.
8654 auto &SemaTypoExprs
= SemaRef
.TypoExprs
;
8655 for (auto Iterator
= SemaTypoExprs
.begin(); Iterator
!= SemaTypoExprs
.end();) {
8656 auto TE
= *Iterator
;
8657 auto FI
= find(TypoExprs
, TE
);
8658 if (FI
!= TypoExprs
.end()) {
8662 SemaRef
.clearDelayedTypo(TE
);
8663 Iterator
= SemaTypoExprs
.erase(Iterator
);
8665 SemaRef
.TypoExprs
= std::move(SavedTypoExprs
);
8671 TransformTypos(Sema
&SemaRef
, VarDecl
*InitDecl
, llvm::function_ref
<ExprResult(Expr
*)> Filter
)
8672 : BaseTransform(SemaRef
), InitDecl(InitDecl
), ExprFilter(Filter
) {}
8674 ExprResult
RebuildCallExpr(Expr
*Callee
, SourceLocation LParenLoc
,
8676 SourceLocation RParenLoc
,
8677 Expr
*ExecConfig
= nullptr) {
8678 auto Result
= BaseTransform::RebuildCallExpr(Callee
, LParenLoc
, Args
,
8679 RParenLoc
, ExecConfig
);
8680 if (auto *OE
= dyn_cast
<OverloadExpr
>(Callee
)) {
8681 if (Result
.isUsable()) {
8682 Expr
*ResultCall
= Result
.get();
8683 if (auto *BE
= dyn_cast
<CXXBindTemporaryExpr
>(ResultCall
))
8684 ResultCall
= BE
->getSubExpr();
8685 if (auto *CE
= dyn_cast
<CallExpr
>(ResultCall
))
8686 OverloadResolution
[OE
] = CE
->getCallee();
8692 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) { return Owned(E
); }
8694 ExprResult
TransformBlockExpr(BlockExpr
*E
) { return Owned(E
); }
8696 ExprResult
Transform(Expr
*E
) {
8697 bool IsAmbiguous
= false;
8698 ExprResult Res
= RecursiveTransformLoop(E
, IsAmbiguous
);
8700 if (!Res
.isUsable())
8701 FindTypoExprs(TypoExprs
).TraverseStmt(E
);
8703 EmitAllDiagnostics(IsAmbiguous
);
8708 ExprResult
TransformTypoExpr(TypoExpr
*E
) {
8709 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8710 // cached transformation result if there is one and the TypoExpr isn't the
8711 // first one that was encountered.
8712 auto &CacheEntry
= TransformCache
[E
];
8713 if (!TypoExprs
.insert(E
) && !CacheEntry
.isUnset()) {
8717 auto &State
= SemaRef
.getTypoExprState(E
);
8718 assert(State
.Consumer
&& "Cannot transform a cleared TypoExpr");
8720 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8721 // typo correction and return it.
8722 while (TypoCorrection TC
= State
.Consumer
->getNextCorrection()) {
8723 if (InitDecl
&& TC
.getFoundDecl() == InitDecl
)
8725 // FIXME: If we would typo-correct to an invalid declaration, it's
8726 // probably best to just suppress all errors from this typo correction.
8727 ExprResult NE
= State
.RecoveryHandler
?
8728 State
.RecoveryHandler(SemaRef
, E
, TC
) :
8729 attemptRecovery(SemaRef
, *State
.Consumer
, TC
);
8730 if (!NE
.isInvalid()) {
8731 // Check whether there may be a second viable correction with the same
8732 // edit distance; if so, remember this TypoExpr may have an ambiguous
8733 // correction so it can be more thoroughly vetted later.
8734 TypoCorrection Next
;
8735 if ((Next
= State
.Consumer
->peekNextCorrection()) &&
8736 Next
.getEditDistance(false) == TC
.getEditDistance(false)) {
8737 AmbiguousTypoExprs
.insert(E
);
8739 AmbiguousTypoExprs
.remove(E
);
8741 assert(!NE
.isUnset() &&
8742 "Typo was transformed into a valid-but-null ExprResult");
8743 return CacheEntry
= NE
;
8746 return CacheEntry
= ExprError();
8752 Sema::CorrectDelayedTyposInExpr(Expr
*E
, VarDecl
*InitDecl
,
8753 bool RecoverUncorrectedTypos
,
8754 llvm::function_ref
<ExprResult(Expr
*)> Filter
) {
8755 // If the current evaluation context indicates there are uncorrected typos
8756 // and the current expression isn't guaranteed to not have typos, try to
8757 // resolve any TypoExpr nodes that might be in the expression.
8758 if (E
&& !ExprEvalContexts
.empty() && ExprEvalContexts
.back().NumTypos
&&
8759 (E
->isTypeDependent() || E
->isValueDependent() ||
8760 E
->isInstantiationDependent())) {
8761 auto TyposResolved
= DelayedTypos
.size();
8762 auto Result
= TransformTypos(*this, InitDecl
, Filter
).Transform(E
);
8763 TyposResolved
-= DelayedTypos
.size();
8764 if (Result
.isInvalid() || Result
.get() != E
) {
8765 ExprEvalContexts
.back().NumTypos
-= TyposResolved
;
8766 if (Result
.isInvalid() && RecoverUncorrectedTypos
) {
8767 struct TyposReplace
: TreeTransform
<TyposReplace
> {
8768 TyposReplace(Sema
&SemaRef
) : TreeTransform(SemaRef
) {}
8769 ExprResult
TransformTypoExpr(clang::TypoExpr
*E
) {
8770 return this->SemaRef
.CreateRecoveryExpr(E
->getBeginLoc(),
8771 E
->getEndLoc(), {});
8774 return TT
.TransformExpr(E
);
8778 assert(TyposResolved
== 0 && "Corrected typo but got same Expr back?");
8783 ExprResult
Sema::ActOnFinishFullExpr(Expr
*FE
, SourceLocation CC
,
8784 bool DiscardedValue
, bool IsConstexpr
,
8785 bool IsTemplateArgument
) {
8786 ExprResult FullExpr
= FE
;
8788 if (!FullExpr
.get())
8791 if (!IsTemplateArgument
&& DiagnoseUnexpandedParameterPack(FullExpr
.get()))
8794 if (DiscardedValue
) {
8795 // Top-level expressions default to 'id' when we're in a debugger.
8796 if (getLangOpts().DebuggerCastResultToId
&&
8797 FullExpr
.get()->getType() == Context
.UnknownAnyTy
) {
8798 FullExpr
= forceUnknownAnyToType(FullExpr
.get(), Context
.getObjCIdType());
8799 if (FullExpr
.isInvalid())
8803 FullExpr
= CheckPlaceholderExpr(FullExpr
.get());
8804 if (FullExpr
.isInvalid())
8807 FullExpr
= IgnoredValueConversions(FullExpr
.get());
8808 if (FullExpr
.isInvalid())
8811 DiagnoseUnusedExprResult(FullExpr
.get(), diag::warn_unused_expr
);
8814 FullExpr
= CorrectDelayedTyposInExpr(FullExpr
.get(), /*InitDecl=*/nullptr,
8815 /*RecoverUncorrectedTypos=*/true);
8816 if (FullExpr
.isInvalid())
8819 CheckCompletedExpr(FullExpr
.get(), CC
, IsConstexpr
);
8821 // At the end of this full expression (which could be a deeply nested
8822 // lambda), if there is a potential capture within the nested lambda,
8823 // have the outer capture-able lambda try and capture it.
8824 // Consider the following code:
8825 // void f(int, int);
8826 // void f(const int&, double);
8828 // const int x = 10, y = 20;
8829 // auto L = [=](auto a) {
8830 // auto M = [=](auto b) {
8831 // f(x, b); <-- requires x to be captured by L and M
8832 // f(y, a); <-- requires y to be captured by L, but not all Ms
8837 // FIXME: Also consider what happens for something like this that involves
8838 // the gnu-extension statement-expressions or even lambda-init-captures:
8841 // auto L = [&](auto a) {
8842 // +n + ({ 0; a; });
8846 // Here, we see +n, and then the full-expression 0; ends, so we don't
8847 // capture n (and instead remove it from our list of potential captures),
8848 // and then the full-expression +n + ({ 0; }); ends, but it's too late
8849 // for us to see that we need to capture n after all.
8851 LambdaScopeInfo
*const CurrentLSI
=
8852 getCurLambda(/*IgnoreCapturedRegions=*/true);
8853 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8854 // even if CurContext is not a lambda call operator. Refer to that Bug Report
8855 // for an example of the code that might cause this asynchrony.
8856 // By ensuring we are in the context of a lambda's call operator
8857 // we can fix the bug (we only need to check whether we need to capture
8858 // if we are within a lambda's body); but per the comments in that
8859 // PR, a proper fix would entail :
8860 // "Alternative suggestion:
8861 // - Add to Sema an integer holding the smallest (outermost) scope
8862 // index that we are *lexically* within, and save/restore/set to
8863 // FunctionScopes.size() in InstantiatingTemplate's
8864 // constructor/destructor.
8865 // - Teach the handful of places that iterate over FunctionScopes to
8866 // stop at the outermost enclosing lexical scope."
8867 DeclContext
*DC
= CurContext
;
8868 while (DC
&& isa
<CapturedDecl
>(DC
))
8869 DC
= DC
->getParent();
8870 const bool IsInLambdaDeclContext
= isLambdaCallOperator(DC
);
8871 if (IsInLambdaDeclContext
&& CurrentLSI
&&
8872 CurrentLSI
->hasPotentialCaptures() && !FullExpr
.isInvalid())
8873 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE
, CurrentLSI
,
8875 return MaybeCreateExprWithCleanups(FullExpr
);
8878 StmtResult
Sema::ActOnFinishFullStmt(Stmt
*FullStmt
) {
8879 if (!FullStmt
) return StmtError();
8881 return MaybeCreateStmtWithCleanups(FullStmt
);
8884 Sema::IfExistsResult
8885 Sema::CheckMicrosoftIfExistsSymbol(Scope
*S
,
8887 const DeclarationNameInfo
&TargetNameInfo
) {
8888 DeclarationName TargetName
= TargetNameInfo
.getName();
8890 return IER_DoesNotExist
;
8892 // If the name itself is dependent, then the result is dependent.
8893 if (TargetName
.isDependentName())
8894 return IER_Dependent
;
8896 // Do the redeclaration lookup in the current scope.
8897 LookupResult
R(*this, TargetNameInfo
, Sema::LookupAnyName
,
8898 Sema::NotForRedeclaration
);
8899 LookupParsedName(R
, S
, &SS
);
8900 R
.suppressDiagnostics();
8902 switch (R
.getResultKind()) {
8903 case LookupResult::Found
:
8904 case LookupResult::FoundOverloaded
:
8905 case LookupResult::FoundUnresolvedValue
:
8906 case LookupResult::Ambiguous
:
8909 case LookupResult::NotFound
:
8910 return IER_DoesNotExist
;
8912 case LookupResult::NotFoundInCurrentInstantiation
:
8913 return IER_Dependent
;
8916 llvm_unreachable("Invalid LookupResult Kind!");
8919 Sema::IfExistsResult
8920 Sema::CheckMicrosoftIfExistsSymbol(Scope
*S
, SourceLocation KeywordLoc
,
8921 bool IsIfExists
, CXXScopeSpec
&SS
,
8922 UnqualifiedId
&Name
) {
8923 DeclarationNameInfo TargetNameInfo
= GetNameFromUnqualifiedId(Name
);
8925 // Check for an unexpanded parameter pack.
8926 auto UPPC
= IsIfExists
? UPPC_IfExists
: UPPC_IfNotExists
;
8927 if (DiagnoseUnexpandedParameterPack(SS
, UPPC
) ||
8928 DiagnoseUnexpandedParameterPack(TargetNameInfo
, UPPC
))
8931 return CheckMicrosoftIfExistsSymbol(S
, SS
, TargetNameInfo
);
8934 concepts::Requirement
*Sema::ActOnSimpleRequirement(Expr
*E
) {
8935 return BuildExprRequirement(E
, /*IsSimple=*/true,
8936 /*NoexceptLoc=*/SourceLocation(),
8937 /*ReturnTypeRequirement=*/{});
8940 concepts::Requirement
*
8941 Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc
, CXXScopeSpec
&SS
,
8942 SourceLocation NameLoc
, IdentifierInfo
*TypeName
,
8943 TemplateIdAnnotation
*TemplateId
) {
8944 assert(((!TypeName
&& TemplateId
) || (TypeName
&& !TemplateId
)) &&
8945 "Exactly one of TypeName and TemplateId must be specified.");
8946 TypeSourceInfo
*TSI
= nullptr;
8949 CheckTypenameType(ElaboratedTypeKeyword::Typename
, TypenameKWLoc
,
8950 SS
.getWithLocInContext(Context
), *TypeName
, NameLoc
,
8951 &TSI
, /*DeducedTSTContext=*/false);
8955 ASTTemplateArgsPtr
ArgsPtr(TemplateId
->getTemplateArgs(),
8956 TemplateId
->NumArgs
);
8957 TypeResult T
= ActOnTypenameType(CurScope
, TypenameKWLoc
, SS
,
8958 TemplateId
->TemplateKWLoc
,
8959 TemplateId
->Template
, TemplateId
->Name
,
8960 TemplateId
->TemplateNameLoc
,
8961 TemplateId
->LAngleLoc
, ArgsPtr
,
8962 TemplateId
->RAngleLoc
);
8965 if (GetTypeFromParser(T
.get(), &TSI
).isNull())
8968 return BuildTypeRequirement(TSI
);
8971 concepts::Requirement
*
8972 Sema::ActOnCompoundRequirement(Expr
*E
, SourceLocation NoexceptLoc
) {
8973 return BuildExprRequirement(E
, /*IsSimple=*/false, NoexceptLoc
,
8974 /*ReturnTypeRequirement=*/{});
8977 concepts::Requirement
*
8978 Sema::ActOnCompoundRequirement(
8979 Expr
*E
, SourceLocation NoexceptLoc
, CXXScopeSpec
&SS
,
8980 TemplateIdAnnotation
*TypeConstraint
, unsigned Depth
) {
8981 // C++2a [expr.prim.req.compound] p1.3.3
8982 // [..] the expression is deduced against an invented function template
8983 // F [...] F is a void function template with a single type template
8984 // parameter T declared with the constrained-parameter. Form a new
8985 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8986 // around the constrained-parameter. F has a single parameter whose
8987 // type-specifier is cv T followed by the abstract-declarator. [...]
8989 // The cv part is done in the calling function - we get the concept with
8990 // arguments and the abstract declarator with the correct CV qualification and
8991 // have to synthesize T and the single parameter of F.
8992 auto &II
= Context
.Idents
.get("expr-type");
8993 auto *TParam
= TemplateTypeParmDecl::Create(Context
, CurContext
,
8995 SourceLocation(), Depth
,
8998 /*ParameterPack=*/false,
8999 /*HasTypeConstraint=*/true);
9001 if (BuildTypeConstraint(SS
, TypeConstraint
, TParam
,
9002 /*EllipsisLoc=*/SourceLocation(),
9003 /*AllowUnexpandedPack=*/true))
9004 // Just produce a requirement with no type requirements.
9005 return BuildExprRequirement(E
, /*IsSimple=*/false, NoexceptLoc
, {});
9007 auto *TPL
= TemplateParameterList::Create(Context
, SourceLocation(),
9009 ArrayRef
<NamedDecl
*>(TParam
),
9011 /*RequiresClause=*/nullptr);
9012 return BuildExprRequirement(
9013 E
, /*IsSimple=*/false, NoexceptLoc
,
9014 concepts::ExprRequirement::ReturnTypeRequirement(TPL
));
9017 concepts::ExprRequirement
*
9018 Sema::BuildExprRequirement(
9019 Expr
*E
, bool IsSimple
, SourceLocation NoexceptLoc
,
9020 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement
) {
9021 auto Status
= concepts::ExprRequirement::SS_Satisfied
;
9022 ConceptSpecializationExpr
*SubstitutedConstraintExpr
= nullptr;
9023 if (E
->isInstantiationDependent() || E
->getType()->isPlaceholderType() ||
9024 ReturnTypeRequirement
.isDependent())
9025 Status
= concepts::ExprRequirement::SS_Dependent
;
9026 else if (NoexceptLoc
.isValid() && canThrow(E
) == CanThrowResult::CT_Can
)
9027 Status
= concepts::ExprRequirement::SS_NoexceptNotMet
;
9028 else if (ReturnTypeRequirement
.isSubstitutionFailure())
9029 Status
= concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure
;
9030 else if (ReturnTypeRequirement
.isTypeConstraint()) {
9031 // C++2a [expr.prim.req]p1.3.3
9032 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9034 TemplateParameterList
*TPL
=
9035 ReturnTypeRequirement
.getTypeConstraintTemplateParameterList();
9036 QualType MatchedType
=
9037 Context
.getReferenceQualifiedType(E
).getCanonicalType();
9038 llvm::SmallVector
<TemplateArgument
, 1> Args
;
9039 Args
.push_back(TemplateArgument(MatchedType
));
9041 auto *Param
= cast
<TemplateTypeParmDecl
>(TPL
->getParam(0));
9043 TemplateArgumentList
TAL(TemplateArgumentList::OnStack
, Args
);
9044 MultiLevelTemplateArgumentList
MLTAL(Param
, TAL
.asArray(),
9046 MLTAL
.addOuterRetainedLevels(TPL
->getDepth());
9047 const TypeConstraint
*TC
= Param
->getTypeConstraint();
9048 assert(TC
&& "Type Constraint cannot be null here");
9049 auto *IDC
= TC
->getImmediatelyDeclaredConstraint();
9050 assert(IDC
&& "ImmediatelyDeclaredConstraint can't be null here.");
9051 ExprResult Constraint
= SubstExpr(IDC
, MLTAL
);
9052 if (Constraint
.isInvalid()) {
9053 return new (Context
) concepts::ExprRequirement(
9054 concepts::createSubstDiagAt(*this, IDC
->getExprLoc(),
9055 [&](llvm::raw_ostream
&OS
) {
9056 IDC
->printPretty(OS
, /*Helper=*/nullptr,
9057 getPrintingPolicy());
9059 IsSimple
, NoexceptLoc
, ReturnTypeRequirement
);
9061 SubstitutedConstraintExpr
=
9062 cast
<ConceptSpecializationExpr
>(Constraint
.get());
9063 if (!SubstitutedConstraintExpr
->isSatisfied())
9064 Status
= concepts::ExprRequirement::SS_ConstraintsNotSatisfied
;
9066 return new (Context
) concepts::ExprRequirement(E
, IsSimple
, NoexceptLoc
,
9067 ReturnTypeRequirement
, Status
,
9068 SubstitutedConstraintExpr
);
9071 concepts::ExprRequirement
*
9072 Sema::BuildExprRequirement(
9073 concepts::Requirement::SubstitutionDiagnostic
*ExprSubstitutionDiagnostic
,
9074 bool IsSimple
, SourceLocation NoexceptLoc
,
9075 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement
) {
9076 return new (Context
) concepts::ExprRequirement(ExprSubstitutionDiagnostic
,
9077 IsSimple
, NoexceptLoc
,
9078 ReturnTypeRequirement
);
9081 concepts::TypeRequirement
*
9082 Sema::BuildTypeRequirement(TypeSourceInfo
*Type
) {
9083 return new (Context
) concepts::TypeRequirement(Type
);
9086 concepts::TypeRequirement
*
9087 Sema::BuildTypeRequirement(
9088 concepts::Requirement::SubstitutionDiagnostic
*SubstDiag
) {
9089 return new (Context
) concepts::TypeRequirement(SubstDiag
);
9092 concepts::Requirement
*Sema::ActOnNestedRequirement(Expr
*Constraint
) {
9093 return BuildNestedRequirement(Constraint
);
9096 concepts::NestedRequirement
*
9097 Sema::BuildNestedRequirement(Expr
*Constraint
) {
9098 ConstraintSatisfaction Satisfaction
;
9099 if (!Constraint
->isInstantiationDependent() &&
9100 CheckConstraintSatisfaction(nullptr, {Constraint
}, /*TemplateArgs=*/{},
9101 Constraint
->getSourceRange(), Satisfaction
))
9103 return new (Context
) concepts::NestedRequirement(Context
, Constraint
,
9107 concepts::NestedRequirement
*
9108 Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity
,
9109 const ASTConstraintSatisfaction
&Satisfaction
) {
9110 return new (Context
) concepts::NestedRequirement(
9111 InvalidConstraintEntity
,
9112 ASTConstraintSatisfaction::Rebuild(Context
, Satisfaction
));
9115 RequiresExprBodyDecl
*
9116 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc
,
9117 ArrayRef
<ParmVarDecl
*> LocalParameters
,
9121 RequiresExprBodyDecl
*Body
= RequiresExprBodyDecl::Create(Context
, CurContext
,
9124 PushDeclContext(BodyScope
, Body
);
9126 for (ParmVarDecl
*Param
: LocalParameters
) {
9127 if (Param
->hasDefaultArg())
9128 // C++2a [expr.prim.req] p4
9129 // [...] A local parameter of a requires-expression shall not have a
9130 // default argument. [...]
9131 Diag(Param
->getDefaultArgRange().getBegin(),
9132 diag::err_requires_expr_local_parameter_default_argument
);
9133 // Ignore default argument and move on
9135 Param
->setDeclContext(Body
);
9136 // If this has an identifier, add it to the scope stack.
9137 if (Param
->getIdentifier()) {
9138 CheckShadow(BodyScope
, Param
);
9139 PushOnScopeChains(Param
, BodyScope
);
9145 void Sema::ActOnFinishRequiresExpr() {
9146 assert(CurContext
&& "DeclContext imbalance!");
9147 CurContext
= CurContext
->getLexicalParent();
9148 assert(CurContext
&& "Popped translation unit!");
9151 ExprResult
Sema::ActOnRequiresExpr(
9152 SourceLocation RequiresKWLoc
, RequiresExprBodyDecl
*Body
,
9153 SourceLocation LParenLoc
, ArrayRef
<ParmVarDecl
*> LocalParameters
,
9154 SourceLocation RParenLoc
, ArrayRef
<concepts::Requirement
*> Requirements
,
9155 SourceLocation ClosingBraceLoc
) {
9156 auto *RE
= RequiresExpr::Create(Context
, RequiresKWLoc
, Body
, LParenLoc
,
9157 LocalParameters
, RParenLoc
, Requirements
,
9159 if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE
))