1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for declarations.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/Randstruct.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/HLSLRuntime.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
38 #include "clang/Sema/CXXFieldCollector.h"
39 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/DelayedDiagnostic.h"
41 #include "clang/Sema/Initialization.h"
42 #include "clang/Sema/Lookup.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/TargetParser/Triple.h"
54 #include <unordered_map>
56 using namespace clang
;
59 Sema::DeclGroupPtrTy
Sema::ConvertDeclToDeclGroup(Decl
*Ptr
, Decl
*OwnedType
) {
61 Decl
*Group
[2] = { OwnedType
, Ptr
};
62 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context
, Group
, 2));
65 return DeclGroupPtrTy::make(DeclGroupRef(Ptr
));
70 class TypeNameValidatorCCC final
: public CorrectionCandidateCallback
{
72 TypeNameValidatorCCC(bool AllowInvalid
, bool WantClass
= false,
73 bool AllowTemplates
= false,
74 bool AllowNonTemplates
= true)
75 : AllowInvalidDecl(AllowInvalid
), WantClassName(WantClass
),
76 AllowTemplates(AllowTemplates
), AllowNonTemplates(AllowNonTemplates
) {
77 WantExpressionKeywords
= false;
78 WantCXXNamedCasts
= false;
79 WantRemainingKeywords
= false;
82 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
83 if (NamedDecl
*ND
= candidate
.getCorrectionDecl()) {
84 if (!AllowInvalidDecl
&& ND
->isInvalidDecl())
87 if (getAsTypeTemplateDecl(ND
))
88 return AllowTemplates
;
90 bool IsType
= isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
);
94 if (AllowNonTemplates
)
97 // An injected-class-name of a class template (specialization) is valid
98 // as a template or as a non-template.
100 auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
);
101 if (!RD
|| !RD
->isInjectedClassName())
103 RD
= cast
<CXXRecordDecl
>(RD
->getDeclContext());
104 return RD
->getDescribedClassTemplate() ||
105 isa
<ClassTemplateSpecializationDecl
>(RD
);
111 return !WantClassName
&& candidate
.isKeyword();
114 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
115 return std::make_unique
<TypeNameValidatorCCC
>(*this);
119 bool AllowInvalidDecl
;
122 bool AllowNonTemplates
;
125 } // end anonymous namespace
127 /// Determine whether the token kind starts a simple-type-specifier.
128 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind
) const {
130 // FIXME: Take into account the current language when deciding whether a
131 // token kind is a valid type specifier
134 case tok::kw___int64
:
135 case tok::kw___int128
:
137 case tok::kw_unsigned
:
145 case tok::kw__Float16
:
146 case tok::kw___float128
:
147 case tok::kw___ibm128
:
148 case tok::kw_wchar_t
:
150 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
151 #include "clang/Basic/TransformTypeTraits.def"
152 case tok::kw___auto_type
:
155 case tok::annot_typename
:
156 case tok::kw_char16_t
:
157 case tok::kw_char32_t
:
159 case tok::annot_decltype
:
160 case tok::kw_decltype
:
161 return getLangOpts().CPlusPlus
;
163 case tok::kw_char8_t
:
164 return getLangOpts().Char8
;
174 enum class UnqualifiedTypeNameLookupResult
{
179 } // end anonymous namespace
181 /// Tries to perform unqualified lookup of the type decls in bases for
183 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
184 /// type decl, \a FoundType if only type decls are found.
185 static UnqualifiedTypeNameLookupResult
186 lookupUnqualifiedTypeNameInBase(Sema
&S
, const IdentifierInfo
&II
,
187 SourceLocation NameLoc
,
188 const CXXRecordDecl
*RD
) {
189 if (!RD
->hasDefinition())
190 return UnqualifiedTypeNameLookupResult::NotFound
;
191 // Look for type decls in base classes.
192 UnqualifiedTypeNameLookupResult FoundTypeDecl
=
193 UnqualifiedTypeNameLookupResult::NotFound
;
194 for (const auto &Base
: RD
->bases()) {
195 const CXXRecordDecl
*BaseRD
= nullptr;
196 if (auto *BaseTT
= Base
.getType()->getAs
<TagType
>())
197 BaseRD
= BaseTT
->getAsCXXRecordDecl();
198 else if (auto *TST
= Base
.getType()->getAs
<TemplateSpecializationType
>()) {
199 // Look for type decls in dependent base classes that have known primary
201 if (!TST
|| !TST
->isDependentType())
203 auto *TD
= TST
->getTemplateName().getAsTemplateDecl();
206 if (auto *BasePrimaryTemplate
=
207 dyn_cast_or_null
<CXXRecordDecl
>(TD
->getTemplatedDecl())) {
208 if (BasePrimaryTemplate
->getCanonicalDecl() != RD
->getCanonicalDecl())
209 BaseRD
= BasePrimaryTemplate
;
210 else if (auto *CTD
= dyn_cast
<ClassTemplateDecl
>(TD
)) {
211 if (const ClassTemplatePartialSpecializationDecl
*PS
=
212 CTD
->findPartialSpecialization(Base
.getType()))
213 if (PS
->getCanonicalDecl() != RD
->getCanonicalDecl())
219 for (NamedDecl
*ND
: BaseRD
->lookup(&II
)) {
220 if (!isa
<TypeDecl
>(ND
))
221 return UnqualifiedTypeNameLookupResult::FoundNonType
;
222 FoundTypeDecl
= UnqualifiedTypeNameLookupResult::FoundType
;
224 if (FoundTypeDecl
== UnqualifiedTypeNameLookupResult::NotFound
) {
225 switch (lookupUnqualifiedTypeNameInBase(S
, II
, NameLoc
, BaseRD
)) {
226 case UnqualifiedTypeNameLookupResult::FoundNonType
:
227 return UnqualifiedTypeNameLookupResult::FoundNonType
;
228 case UnqualifiedTypeNameLookupResult::FoundType
:
229 FoundTypeDecl
= UnqualifiedTypeNameLookupResult::FoundType
;
231 case UnqualifiedTypeNameLookupResult::NotFound
:
238 return FoundTypeDecl
;
241 static ParsedType
recoverFromTypeInKnownDependentBase(Sema
&S
,
242 const IdentifierInfo
&II
,
243 SourceLocation NameLoc
) {
244 // Lookup in the parent class template context, if any.
245 const CXXRecordDecl
*RD
= nullptr;
246 UnqualifiedTypeNameLookupResult FoundTypeDecl
=
247 UnqualifiedTypeNameLookupResult::NotFound
;
248 for (DeclContext
*DC
= S
.CurContext
;
249 DC
&& FoundTypeDecl
== UnqualifiedTypeNameLookupResult::NotFound
;
250 DC
= DC
->getParent()) {
251 // Look for type decls in dependent base classes that have known primary
253 RD
= dyn_cast
<CXXRecordDecl
>(DC
);
254 if (RD
&& RD
->getDescribedClassTemplate())
255 FoundTypeDecl
= lookupUnqualifiedTypeNameInBase(S
, II
, NameLoc
, RD
);
257 if (FoundTypeDecl
!= UnqualifiedTypeNameLookupResult::FoundType
)
260 // We found some types in dependent base classes. Recover as if the user
261 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
262 // lookup during template instantiation.
263 S
.Diag(NameLoc
, diag::ext_found_in_dependent_base
) << &II
;
265 ASTContext
&Context
= S
.Context
;
266 auto *NNS
= NestedNameSpecifier::Create(Context
, nullptr, false,
267 cast
<Type
>(Context
.getRecordType(RD
)));
268 QualType T
= Context
.getDependentNameType(ETK_Typename
, NNS
, &II
);
271 SS
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
273 TypeLocBuilder Builder
;
274 DependentNameTypeLoc DepTL
= Builder
.push
<DependentNameTypeLoc
>(T
);
275 DepTL
.setNameLoc(NameLoc
);
276 DepTL
.setElaboratedKeywordLoc(SourceLocation());
277 DepTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
278 return S
.CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
281 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
282 static ParsedType
buildNamedType(Sema
&S
, const CXXScopeSpec
*SS
, QualType T
,
283 SourceLocation NameLoc
,
284 bool WantNontrivialTypeSourceInfo
= true) {
285 switch (T
->getTypeClass()) {
286 case Type::DeducedTemplateSpecialization
:
288 case Type::InjectedClassName
:
291 case Type::UnresolvedUsing
:
294 // These can never be qualified so an ElaboratedType node
295 // would carry no additional meaning.
296 case Type::ObjCInterface
:
297 case Type::ObjCTypeParam
:
298 case Type::TemplateTypeParm
:
299 return ParsedType::make(T
);
301 llvm_unreachable("Unexpected Type Class");
304 if (!SS
|| SS
->isEmpty())
305 return ParsedType::make(
306 S
.Context
.getElaboratedType(ETK_None
, nullptr, T
, nullptr));
308 QualType ElTy
= S
.getElaboratedType(ETK_None
, *SS
, T
);
309 if (!WantNontrivialTypeSourceInfo
)
310 return ParsedType::make(ElTy
);
312 TypeLocBuilder Builder
;
313 Builder
.pushTypeSpec(T
).setNameLoc(NameLoc
);
314 ElaboratedTypeLoc ElabTL
= Builder
.push
<ElaboratedTypeLoc
>(ElTy
);
315 ElabTL
.setElaboratedKeywordLoc(SourceLocation());
316 ElabTL
.setQualifierLoc(SS
->getWithLocInContext(S
.Context
));
317 return S
.CreateParsedType(ElTy
, Builder
.getTypeSourceInfo(S
.Context
, ElTy
));
320 /// If the identifier refers to a type name within this scope,
321 /// return the declaration of that type.
323 /// This routine performs ordinary name lookup of the identifier II
324 /// within the given scope, with optional C++ scope specifier SS, to
325 /// determine whether the name refers to a type. If so, returns an
326 /// opaque pointer (actually a QualType) corresponding to that
327 /// type. Otherwise, returns NULL.
328 ParsedType
Sema::getTypeName(const IdentifierInfo
&II
, SourceLocation NameLoc
,
329 Scope
*S
, CXXScopeSpec
*SS
, bool isClassName
,
330 bool HasTrailingDot
, ParsedType ObjectTypePtr
,
331 bool IsCtorOrDtorName
,
332 bool WantNontrivialTypeSourceInfo
,
333 bool IsClassTemplateDeductionContext
,
334 ImplicitTypenameContext AllowImplicitTypename
,
335 IdentifierInfo
**CorrectedII
) {
336 // FIXME: Consider allowing this outside C++1z mode as an extension.
337 bool AllowDeducedTemplate
= IsClassTemplateDeductionContext
&&
338 getLangOpts().CPlusPlus17
&& !IsCtorOrDtorName
&&
339 !isClassName
&& !HasTrailingDot
;
341 // Determine where we will perform name lookup.
342 DeclContext
*LookupCtx
= nullptr;
344 QualType ObjectType
= ObjectTypePtr
.get();
345 if (ObjectType
->isRecordType())
346 LookupCtx
= computeDeclContext(ObjectType
);
347 } else if (SS
&& SS
->isNotEmpty()) {
348 LookupCtx
= computeDeclContext(*SS
, false);
351 if (isDependentScopeSpecifier(*SS
)) {
353 // A qualified-id that refers to a type and in which the
354 // nested-name-specifier depends on a template-parameter (14.6.2)
355 // shall be prefixed by the keyword typename to indicate that the
356 // qualified-id denotes a type, forming an
357 // elaborated-type-specifier (7.1.5.3).
359 // We therefore do not perform any name lookup if the result would
360 // refer to a member of an unknown specialization.
361 // In C++2a, in several contexts a 'typename' is not required. Also
362 // allow this as an extension.
363 if (AllowImplicitTypename
== ImplicitTypenameContext::No
&&
364 !isClassName
&& !IsCtorOrDtorName
)
366 bool IsImplicitTypename
= !isClassName
&& !IsCtorOrDtorName
;
367 if (IsImplicitTypename
) {
368 SourceLocation QualifiedLoc
= SS
->getRange().getBegin();
369 if (getLangOpts().CPlusPlus20
)
370 Diag(QualifiedLoc
, diag::warn_cxx17_compat_implicit_typename
);
372 Diag(QualifiedLoc
, diag::ext_implicit_typename
)
373 << SS
->getScopeRep() << II
.getName()
374 << FixItHint::CreateInsertion(QualifiedLoc
, "typename ");
377 // We know from the grammar that this name refers to a type,
378 // so build a dependent node to describe the type.
379 if (WantNontrivialTypeSourceInfo
)
380 return ActOnTypenameType(S
, SourceLocation(), *SS
, II
, NameLoc
,
381 (ImplicitTypenameContext
)IsImplicitTypename
)
384 NestedNameSpecifierLoc QualifierLoc
= SS
->getWithLocInContext(Context
);
386 CheckTypenameType(IsImplicitTypename
? ETK_Typename
: ETK_None
,
387 SourceLocation(), QualifierLoc
, II
, NameLoc
);
388 return ParsedType::make(T
);
394 if (!LookupCtx
->isDependentContext() &&
395 RequireCompleteDeclContext(*SS
, LookupCtx
))
399 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
400 // lookup for class-names.
401 LookupNameKind Kind
= isClassName
? LookupNestedNameSpecifierName
:
403 LookupResult
Result(*this, &II
, NameLoc
, Kind
);
405 // Perform "qualified" name lookup into the declaration context we
406 // computed, which is either the type of the base of a member access
407 // expression or the declaration context associated with a prior
408 // nested-name-specifier.
409 LookupQualifiedName(Result
, LookupCtx
);
411 if (ObjectTypePtr
&& Result
.empty()) {
412 // C++ [basic.lookup.classref]p3:
413 // If the unqualified-id is ~type-name, the type-name is looked up
414 // in the context of the entire postfix-expression. If the type T of
415 // the object expression is of a class type C, the type-name is also
416 // looked up in the scope of class C. At least one of the lookups shall
417 // find a name that refers to (possibly cv-qualified) T.
418 LookupName(Result
, S
);
421 // Perform unqualified name lookup.
422 LookupName(Result
, S
);
424 // For unqualified lookup in a class template in MSVC mode, look into
425 // dependent base classes where the primary class template is known.
426 if (Result
.empty() && getLangOpts().MSVCCompat
&& (!SS
|| SS
->isEmpty())) {
427 if (ParsedType TypeInBase
=
428 recoverFromTypeInKnownDependentBase(*this, II
, NameLoc
))
433 NamedDecl
*IIDecl
= nullptr;
434 UsingShadowDecl
*FoundUsingShadow
= nullptr;
435 switch (Result
.getResultKind()) {
436 case LookupResult::NotFound
:
437 case LookupResult::NotFoundInCurrentInstantiation
:
439 TypeNameValidatorCCC
CCC(/*AllowInvalid=*/true, isClassName
,
440 AllowDeducedTemplate
);
441 TypoCorrection Correction
= CorrectTypo(Result
.getLookupNameInfo(), Kind
,
442 S
, SS
, CCC
, CTK_ErrorRecovery
);
443 IdentifierInfo
*NewII
= Correction
.getCorrectionAsIdentifierInfo();
445 bool MemberOfUnknownSpecialization
;
446 UnqualifiedId TemplateName
;
447 TemplateName
.setIdentifier(NewII
, NameLoc
);
448 NestedNameSpecifier
*NNS
= Correction
.getCorrectionSpecifier();
449 CXXScopeSpec NewSS
, *NewSSPtr
= SS
;
451 NewSS
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
454 if (Correction
&& (NNS
|| NewII
!= &II
) &&
455 // Ignore a correction to a template type as the to-be-corrected
456 // identifier is not a template (typo correction for template names
457 // is handled elsewhere).
458 !(getLangOpts().CPlusPlus
&& NewSSPtr
&&
459 isTemplateName(S
, *NewSSPtr
, false, TemplateName
, nullptr, false,
460 Template
, MemberOfUnknownSpecialization
))) {
461 ParsedType Ty
= getTypeName(*NewII
, NameLoc
, S
, NewSSPtr
,
462 isClassName
, HasTrailingDot
, ObjectTypePtr
,
464 WantNontrivialTypeSourceInfo
,
465 IsClassTemplateDeductionContext
);
467 diagnoseTypo(Correction
,
468 PDiag(diag::err_unknown_type_or_class_name_suggest
)
469 << Result
.getLookupName() << isClassName
);
471 SS
->MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
472 *CorrectedII
= NewII
;
477 // If typo correction failed or was not performed, fall through
479 case LookupResult::FoundOverloaded
:
480 case LookupResult::FoundUnresolvedValue
:
481 Result
.suppressDiagnostics();
484 case LookupResult::Ambiguous
:
485 // Recover from type-hiding ambiguities by hiding the type. We'll
486 // do the lookup again when looking for an object, and we can
487 // diagnose the error then. If we don't do this, then the error
488 // about hiding the type will be immediately followed by an error
489 // that only makes sense if the identifier was treated like a type.
490 if (Result
.getAmbiguityKind() == LookupResult::AmbiguousTagHiding
) {
491 Result
.suppressDiagnostics();
495 // Look to see if we have a type anywhere in the list of results.
496 for (LookupResult::iterator Res
= Result
.begin(), ResEnd
= Result
.end();
497 Res
!= ResEnd
; ++Res
) {
498 NamedDecl
*RealRes
= (*Res
)->getUnderlyingDecl();
499 if (isa
<TypeDecl
, ObjCInterfaceDecl
, UnresolvedUsingIfExistsDecl
>(
501 (AllowDeducedTemplate
&& getAsTypeTemplateDecl(RealRes
))) {
503 // Make the selection of the recovery decl deterministic.
504 RealRes
->getLocation() < IIDecl
->getLocation()) {
506 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*Res
);
512 // None of the entities we found is a type, so there is no way
513 // to even assume that the result is a type. In this case, don't
514 // complain about the ambiguity. The parser will either try to
515 // perform this lookup again (e.g., as an object name), which
516 // will produce the ambiguity, or will complain that it expected
518 Result
.suppressDiagnostics();
522 // We found a type within the ambiguous lookup; diagnose the
523 // ambiguity and then return that type. This might be the right
524 // answer, or it might not be, but it suppresses any attempt to
525 // perform the name lookup again.
528 case LookupResult::Found
:
529 IIDecl
= Result
.getFoundDecl();
530 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*Result
.begin());
534 assert(IIDecl
&& "Didn't find decl");
537 if (TypeDecl
*TD
= dyn_cast
<TypeDecl
>(IIDecl
)) {
538 // C++ [class.qual]p2: A lookup that would find the injected-class-name
539 // instead names the constructors of the class, except when naming a class.
540 // This is ill-formed when we're not actually forming a ctor or dtor name.
541 auto *LookupRD
= dyn_cast_or_null
<CXXRecordDecl
>(LookupCtx
);
542 auto *FoundRD
= dyn_cast
<CXXRecordDecl
>(TD
);
543 if (!isClassName
&& !IsCtorOrDtorName
&& LookupRD
&& FoundRD
&&
544 FoundRD
->isInjectedClassName() &&
545 declaresSameEntity(LookupRD
, cast
<Decl
>(FoundRD
->getParent())))
546 Diag(NameLoc
, diag::err_out_of_line_qualified_id_type_names_constructor
)
549 DiagnoseUseOfDecl(IIDecl
, NameLoc
);
551 T
= Context
.getTypeDeclType(TD
);
552 MarkAnyDeclReferenced(TD
->getLocation(), TD
, /*OdrUse=*/false);
553 } else if (ObjCInterfaceDecl
*IDecl
= dyn_cast
<ObjCInterfaceDecl
>(IIDecl
)) {
554 (void)DiagnoseUseOfDecl(IDecl
, NameLoc
);
556 T
= Context
.getObjCInterfaceType(IDecl
);
557 FoundUsingShadow
= nullptr; // FIXME: Target must be a TypeDecl.
558 } else if (auto *UD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(IIDecl
)) {
559 (void)DiagnoseUseOfDecl(UD
, NameLoc
);
560 // Recover with 'int'
561 return ParsedType::make(Context
.IntTy
);
562 } else if (AllowDeducedTemplate
) {
563 if (auto *TD
= getAsTypeTemplateDecl(IIDecl
)) {
564 assert(!FoundUsingShadow
|| FoundUsingShadow
->getTargetDecl() == TD
);
565 TemplateName Template
=
566 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
567 T
= Context
.getDeducedTemplateSpecializationType(Template
, QualType(),
569 // Don't wrap in a further UsingType.
570 FoundUsingShadow
= nullptr;
575 // If it's not plausibly a type, suppress diagnostics.
576 Result
.suppressDiagnostics();
580 if (FoundUsingShadow
)
581 T
= Context
.getUsingType(FoundUsingShadow
, T
);
583 return buildNamedType(*this, SS
, T
, NameLoc
, WantNontrivialTypeSourceInfo
);
586 // Builds a fake NNS for the given decl context.
587 static NestedNameSpecifier
*
588 synthesizeCurrentNestedNameSpecifier(ASTContext
&Context
, DeclContext
*DC
) {
589 for (;; DC
= DC
->getLookupParent()) {
590 DC
= DC
->getPrimaryContext();
591 auto *ND
= dyn_cast
<NamespaceDecl
>(DC
);
592 if (ND
&& !ND
->isInline() && !ND
->isAnonymousNamespace())
593 return NestedNameSpecifier::Create(Context
, nullptr, ND
);
594 else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
595 return NestedNameSpecifier::Create(Context
, nullptr, RD
->isTemplateDecl(),
596 RD
->getTypeForDecl());
597 else if (isa
<TranslationUnitDecl
>(DC
))
598 return NestedNameSpecifier::GlobalSpecifier(Context
);
600 llvm_unreachable("something isn't in TU scope?");
603 /// Find the parent class with dependent bases of the innermost enclosing method
604 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
605 /// up allowing unqualified dependent type names at class-level, which MSVC
606 /// correctly rejects.
607 static const CXXRecordDecl
*
608 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext
*DC
) {
609 for (; DC
&& DC
->isDependentContext(); DC
= DC
->getLookupParent()) {
610 DC
= DC
->getPrimaryContext();
611 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(DC
))
612 if (MD
->getParent()->hasAnyDependentBases())
613 return MD
->getParent();
618 ParsedType
Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo
&II
,
619 SourceLocation NameLoc
,
620 bool IsTemplateTypeArg
) {
621 assert(getLangOpts().MSVCCompat
&& "shouldn't be called in non-MSVC mode");
623 NestedNameSpecifier
*NNS
= nullptr;
624 if (IsTemplateTypeArg
&& getCurScope()->isTemplateParamScope()) {
625 // If we weren't able to parse a default template argument, delay lookup
626 // until instantiation time by making a non-dependent DependentTypeName. We
627 // pretend we saw a NestedNameSpecifier referring to the current scope, and
628 // lookup is retried.
629 // FIXME: This hurts our diagnostic quality, since we get errors like "no
630 // type named 'Foo' in 'current_namespace'" when the user didn't write any
632 NNS
= synthesizeCurrentNestedNameSpecifier(Context
, CurContext
);
633 Diag(NameLoc
, diag::ext_ms_delayed_template_argument
) << &II
;
634 } else if (const CXXRecordDecl
*RD
=
635 findRecordWithDependentBasesOfEnclosingMethod(CurContext
)) {
636 // Build a DependentNameType that will perform lookup into RD at
637 // instantiation time.
638 NNS
= NestedNameSpecifier::Create(Context
, nullptr, RD
->isTemplateDecl(),
639 RD
->getTypeForDecl());
641 // Diagnose that this identifier was undeclared, and retry the lookup during
642 // template instantiation.
643 Diag(NameLoc
, diag::ext_undeclared_unqual_id_with_dependent_base
) << &II
646 // This is not a situation that we should recover from.
650 QualType T
= Context
.getDependentNameType(ETK_None
, NNS
, &II
);
652 // Build type location information. We synthesized the qualifier, so we have
653 // to build a fake NestedNameSpecifierLoc.
654 NestedNameSpecifierLocBuilder NNSLocBuilder
;
655 NNSLocBuilder
.MakeTrivial(Context
, NNS
, SourceRange(NameLoc
));
656 NestedNameSpecifierLoc QualifierLoc
= NNSLocBuilder
.getWithLocInContext(Context
);
658 TypeLocBuilder Builder
;
659 DependentNameTypeLoc DepTL
= Builder
.push
<DependentNameTypeLoc
>(T
);
660 DepTL
.setNameLoc(NameLoc
);
661 DepTL
.setElaboratedKeywordLoc(SourceLocation());
662 DepTL
.setQualifierLoc(QualifierLoc
);
663 return CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
666 /// isTagName() - This method is called *for error recovery purposes only*
667 /// to determine if the specified name is a valid tag name ("struct foo"). If
668 /// so, this returns the TST for the tag corresponding to it (TST_enum,
669 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
670 /// cases in C where the user forgot to specify the tag.
671 DeclSpec::TST
Sema::isTagName(IdentifierInfo
&II
, Scope
*S
) {
672 // Do a tag name lookup in this scope.
673 LookupResult
R(*this, &II
, SourceLocation(), LookupTagName
);
674 LookupName(R
, S
, false);
675 R
.suppressDiagnostics();
676 if (R
.getResultKind() == LookupResult::Found
)
677 if (const TagDecl
*TD
= R
.getAsSingle
<TagDecl
>()) {
678 switch (TD
->getTagKind()) {
679 case TTK_Struct
: return DeclSpec::TST_struct
;
680 case TTK_Interface
: return DeclSpec::TST_interface
;
681 case TTK_Union
: return DeclSpec::TST_union
;
682 case TTK_Class
: return DeclSpec::TST_class
;
683 case TTK_Enum
: return DeclSpec::TST_enum
;
687 return DeclSpec::TST_unspecified
;
690 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
691 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
692 /// then downgrade the missing typename error to a warning.
693 /// This is needed for MSVC compatibility; Example:
695 /// template<class T> class A {
697 /// typedef int TYPE;
699 /// template<class T> class B : public A<T> {
701 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
704 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec
*SS
, Scope
*S
) {
705 if (CurContext
->isRecord()) {
706 if (SS
->getScopeRep()->getKind() == NestedNameSpecifier::Super
)
709 const Type
*Ty
= SS
->getScopeRep()->getAsType();
711 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(CurContext
);
712 for (const auto &Base
: RD
->bases())
713 if (Ty
&& Context
.hasSameUnqualifiedType(QualType(Ty
, 1), Base
.getType()))
715 return S
->isFunctionPrototypeScope();
717 return CurContext
->isFunctionOrMethod() || S
->isFunctionPrototypeScope();
720 void Sema::DiagnoseUnknownTypeName(IdentifierInfo
*&II
,
721 SourceLocation IILoc
,
724 ParsedType
&SuggestedType
,
725 bool IsTemplateName
) {
726 // Don't report typename errors for editor placeholders.
727 if (II
->isEditorPlaceholder())
729 // We don't have anything to suggest (yet).
730 SuggestedType
= nullptr;
732 // There may have been a typo in the name of the type. Look up typo
733 // results, in case we have something that we can suggest.
734 TypeNameValidatorCCC
CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
735 /*AllowTemplates=*/IsTemplateName
,
736 /*AllowNonTemplates=*/!IsTemplateName
);
737 if (TypoCorrection Corrected
=
738 CorrectTypo(DeclarationNameInfo(II
, IILoc
), LookupOrdinaryName
, S
, SS
,
739 CCC
, CTK_ErrorRecovery
)) {
740 // FIXME: Support error recovery for the template-name case.
741 bool CanRecover
= !IsTemplateName
;
742 if (Corrected
.isKeyword()) {
743 // We corrected to a keyword.
744 diagnoseTypo(Corrected
,
745 PDiag(IsTemplateName
? diag::err_no_template_suggest
746 : diag::err_unknown_typename_suggest
)
748 II
= Corrected
.getCorrectionAsIdentifierInfo();
750 // We found a similarly-named type or interface; suggest that.
751 if (!SS
|| !SS
->isSet()) {
752 diagnoseTypo(Corrected
,
753 PDiag(IsTemplateName
? diag::err_no_template_suggest
754 : diag::err_unknown_typename_suggest
)
756 } else if (DeclContext
*DC
= computeDeclContext(*SS
, false)) {
757 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
758 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
759 II
->getName().equals(CorrectedStr
);
760 diagnoseTypo(Corrected
,
762 ? diag::err_no_member_template_suggest
763 : diag::err_unknown_nested_typename_suggest
)
764 << II
<< DC
<< DroppedSpecifier
<< SS
->getRange(),
767 llvm_unreachable("could not have corrected a typo here");
774 if (Corrected
.getCorrectionSpecifier())
775 tmpSS
.MakeTrivial(Context
, Corrected
.getCorrectionSpecifier(),
777 // FIXME: Support class template argument deduction here.
779 getTypeName(*Corrected
.getCorrectionAsIdentifierInfo(), IILoc
, S
,
780 tmpSS
.isSet() ? &tmpSS
: SS
, false, false, nullptr,
781 /*IsCtorOrDtorName=*/false,
782 /*WantNontrivialTypeSourceInfo=*/true);
787 if (getLangOpts().CPlusPlus
&& !IsTemplateName
) {
788 // See if II is a class template that the user forgot to pass arguments to.
790 Name
.setIdentifier(II
, IILoc
);
791 CXXScopeSpec EmptySS
;
792 TemplateTy TemplateResult
;
793 bool MemberOfUnknownSpecialization
;
794 if (isTemplateName(S
, SS
? *SS
: EmptySS
, /*hasTemplateKeyword=*/false,
795 Name
, nullptr, true, TemplateResult
,
796 MemberOfUnknownSpecialization
) == TNK_Type_template
) {
797 diagnoseMissingTemplateArguments(TemplateResult
.get(), IILoc
);
802 // FIXME: Should we move the logic that tries to recover from a missing tag
803 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
805 if (!SS
|| (!SS
->isSet() && !SS
->isInvalid()))
806 Diag(IILoc
, IsTemplateName
? diag::err_no_template
807 : diag::err_unknown_typename
)
809 else if (DeclContext
*DC
= computeDeclContext(*SS
, false))
810 Diag(IILoc
, IsTemplateName
? diag::err_no_member_template
811 : diag::err_typename_nested_not_found
)
812 << II
<< DC
<< SS
->getRange();
813 else if (SS
->isValid() && SS
->getScopeRep()->containsErrors()) {
815 ActOnTypenameType(S
, SourceLocation(), *SS
, *II
, IILoc
).get();
816 } else if (isDependentScopeSpecifier(*SS
)) {
817 unsigned DiagID
= diag::err_typename_missing
;
818 if (getLangOpts().MSVCCompat
&& isMicrosoftMissingTypename(SS
, S
))
819 DiagID
= diag::ext_typename_missing
;
821 Diag(SS
->getRange().getBegin(), DiagID
)
822 << SS
->getScopeRep() << II
->getName()
823 << SourceRange(SS
->getRange().getBegin(), IILoc
)
824 << FixItHint::CreateInsertion(SS
->getRange().getBegin(), "typename ");
825 SuggestedType
= ActOnTypenameType(S
, SourceLocation(),
826 *SS
, *II
, IILoc
).get();
828 assert(SS
&& SS
->isInvalid() &&
829 "Invalid scope specifier has already been diagnosed");
833 /// Determine whether the given result set contains either a type name
835 static bool isResultTypeOrTemplate(LookupResult
&R
, const Token
&NextToken
) {
836 bool CheckTemplate
= R
.getSema().getLangOpts().CPlusPlus
&&
837 NextToken
.is(tok::less
);
839 for (LookupResult::iterator I
= R
.begin(), IEnd
= R
.end(); I
!= IEnd
; ++I
) {
840 if (isa
<TypeDecl
>(*I
) || isa
<ObjCInterfaceDecl
>(*I
))
843 if (CheckTemplate
&& isa
<TemplateDecl
>(*I
))
850 static bool isTagTypeWithMissingTag(Sema
&SemaRef
, LookupResult
&Result
,
851 Scope
*S
, CXXScopeSpec
&SS
,
852 IdentifierInfo
*&Name
,
853 SourceLocation NameLoc
) {
854 LookupResult
R(SemaRef
, Name
, NameLoc
, Sema::LookupTagName
);
855 SemaRef
.LookupParsedName(R
, S
, &SS
);
856 if (TagDecl
*Tag
= R
.getAsSingle
<TagDecl
>()) {
857 StringRef FixItTagName
;
858 switch (Tag
->getTagKind()) {
860 FixItTagName
= "class ";
864 FixItTagName
= "enum ";
868 FixItTagName
= "struct ";
872 FixItTagName
= "__interface ";
876 FixItTagName
= "union ";
880 StringRef TagName
= FixItTagName
.drop_back();
881 SemaRef
.Diag(NameLoc
, diag::err_use_of_tag_name_without_tag
)
882 << Name
<< TagName
<< SemaRef
.getLangOpts().CPlusPlus
883 << FixItHint::CreateInsertion(NameLoc
, FixItTagName
);
885 for (LookupResult::iterator I
= Result
.begin(), IEnd
= Result
.end();
887 SemaRef
.Diag((*I
)->getLocation(), diag::note_decl_hiding_tag_type
)
890 // Replace lookup results with just the tag decl.
891 Result
.clear(Sema::LookupTagName
);
892 SemaRef
.LookupParsedName(Result
, S
, &SS
);
899 Sema::NameClassification
Sema::ClassifyName(Scope
*S
, CXXScopeSpec
&SS
,
900 IdentifierInfo
*&Name
,
901 SourceLocation NameLoc
,
902 const Token
&NextToken
,
903 CorrectionCandidateCallback
*CCC
) {
904 DeclarationNameInfo
NameInfo(Name
, NameLoc
);
905 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
907 assert(NextToken
.isNot(tok::coloncolon
) &&
908 "parse nested name specifiers before calling ClassifyName");
909 if (getLangOpts().CPlusPlus
&& SS
.isSet() &&
910 isCurrentClassName(*Name
, S
, &SS
)) {
911 // Per [class.qual]p2, this names the constructors of SS, not the
912 // injected-class-name. We don't have a classification for that.
913 // There's not much point caching this result, since the parser
914 // will reject it later.
915 return NameClassification::Unknown();
918 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
919 LookupParsedName(Result
, S
, &SS
, !CurMethod
);
922 return NameClassification::Error();
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result
.empty() && SS
.isEmpty() && getLangOpts().MSVCCompat
) {
927 if (ParsedType TypeInBase
=
928 recoverFromTypeInKnownDependentBase(*this, *Name
, NameLoc
))
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS
.isEmpty() && CurMethod
&& !isResultTypeOrTemplate(Result
, NextToken
)) {
937 DeclResult Ivar
= LookupIvarInObjCMethod(Result
, S
, Name
);
938 if (Ivar
.isInvalid())
939 return NameClassification::Error();
941 return NameClassification::NonType(cast
<NamedDecl
>(Ivar
.get()));
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
945 LookupBuiltin(Result
);
948 bool SecondTry
= false;
949 bool IsFilteredTemplateName
= false;
952 switch (Result
.getResultKind()) {
953 case LookupResult::NotFound
:
954 // If an unqualified-id is followed by a '(', then we have a function
956 if (SS
.isEmpty() && NextToken
.is(tok::l_paren
)) {
957 // In C++, this is an ADL-only call.
959 if (getLangOpts().CPlusPlus
)
960 return NameClassification::UndeclaredNonType();
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
969 // extern int identifier ();
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *Name
, S
))
978 return NameClassification::NonType(D
);
982 if (getLangOpts().CPlusPlus20
&& SS
.isEmpty() && NextToken
.is(tok::less
)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
986 // FIXME: Find a way to still do typo correction in this case.
987 TemplateName Template
=
988 Context
.getAssumedTemplateName(NameInfo
.getName());
989 return NameClassification::UndeclaredTemplate(Template
);
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus
&& !SecondTry
&&
996 isTagTypeWithMissingTag(*this, Result
, S
, SS
, Name
, NameLoc
)) {
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry
&& CCC
) {
1004 if (TypoCorrection Corrected
=
1005 CorrectTypo(Result
.getLookupNameInfo(), Result
.getLookupKind(), S
,
1006 &SS
, *CCC
, CTK_ErrorRecovery
)) {
1007 unsigned UnqualifiedDiag
= diag::err_undeclared_var_use_suggest
;
1008 unsigned QualifiedDiag
= diag::err_no_member_suggest
;
1010 NamedDecl
*FirstDecl
= Corrected
.getFoundDecl();
1011 NamedDecl
*UnderlyingFirstDecl
= Corrected
.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1013 UnderlyingFirstDecl
&& isa
<TemplateDecl
>(UnderlyingFirstDecl
)) {
1014 UnqualifiedDiag
= diag::err_no_template_suggest
;
1015 QualifiedDiag
= diag::err_no_member_template_suggest
;
1016 } else if (UnderlyingFirstDecl
&&
1017 (isa
<TypeDecl
>(UnderlyingFirstDecl
) ||
1018 isa
<ObjCInterfaceDecl
>(UnderlyingFirstDecl
) ||
1019 isa
<ObjCCompatibleAliasDecl
>(UnderlyingFirstDecl
))) {
1020 UnqualifiedDiag
= diag::err_unknown_typename_suggest
;
1021 QualifiedDiag
= diag::err_unknown_nested_typename_suggest
;
1025 diagnoseTypo(Corrected
, PDiag(UnqualifiedDiag
) << Name
);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
1028 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
1029 Name
->getName().equals(CorrectedStr
);
1030 diagnoseTypo(Corrected
, PDiag(QualifiedDiag
)
1031 << Name
<< computeDeclContext(SS
, false)
1032 << DroppedSpecifier
<< SS
.getRange());
1035 // Update the name, so that the caller has the new name.
1036 Name
= Corrected
.getCorrectionAsIdentifierInfo();
1038 // Typo correction corrected to a keyword.
1039 if (Corrected
.isKeyword())
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1045 Result
.setLookupName(Corrected
.getCorrection());
1047 Result
.addDecl(FirstDecl
);
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl
*Ivar
= Result
.getAsSingle
<ObjCIvarDecl
>()) {
1055 LookupIvarInObjCMethod(Result
, S
, Ivar
->getIdentifier());
1057 return NameClassification::Error();
1059 return NameClassification::NonType(Ivar
);
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result
.suppressDiagnostics();
1068 return NameClassification::Unknown();
1070 case LookupResult::NotFoundInCurrentInstantiation
: {
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1085 return NameClassification::DependentNonType();
1088 case LookupResult::Found
:
1089 case LookupResult::FoundOverloaded
:
1090 case LookupResult::FoundUnresolvedValue
:
1093 case LookupResult::Ambiguous
:
1094 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1095 hasAnyAcceptableTemplateNames(Result
, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1108 FilterAcceptableTemplateNames(Result
);
1109 if (!Result
.isAmbiguous()) {
1110 IsFilteredTemplateName
= true;
1115 // Diagnose the ambiguity and return an error.
1116 return NameClassification::Error();
1119 if (getLangOpts().CPlusPlus
&& NextToken
.is(tok::less
) &&
1120 (IsFilteredTemplateName
||
1121 hasAnyAcceptableTemplateNames(
1122 Result
, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS
.isEmpty() &&
1125 getLangOpts().CPlusPlus20
))) {
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName
)
1137 FilterAcceptableTemplateNames(Result
);
1139 bool IsFunctionTemplate
;
1141 TemplateName Template
;
1142 if (Result
.end() - Result
.begin() > 1) {
1143 IsFunctionTemplate
= true;
1144 Template
= Context
.getOverloadedTemplateName(Result
.begin(),
1146 } else if (!Result
.empty()) {
1147 auto *TD
= cast
<TemplateDecl
>(getAsTemplateNameDecl(
1148 *Result
.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate
= isa
<FunctionTemplateDecl
>(TD
);
1151 IsVarTemplate
= isa
<VarTemplateDecl
>(TD
);
1153 UsingShadowDecl
*FoundUsingShadow
=
1154 dyn_cast
<UsingShadowDecl
>(*Result
.begin());
1155 assert(!FoundUsingShadow
||
1156 TD
== cast
<TemplateDecl
>(FoundUsingShadow
->getTargetDecl()));
1158 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
1159 if (SS
.isNotEmpty())
1160 Template
= Context
.getQualifiedTemplateName(SS
.getScopeRep(),
1161 /*TemplateKeyword=*/false,
1164 // All results were non-template functions. This is a function template
1166 IsFunctionTemplate
= true;
1167 Template
= Context
.getAssumedTemplateName(NameInfo
.getName());
1170 if (IsFunctionTemplate
) {
1171 // Function templates always go through overload resolution, at which
1172 // point we'll perform the various checks (e.g., accessibility) we need
1173 // to based on which function we selected.
1174 Result
.suppressDiagnostics();
1176 return NameClassification::FunctionTemplate(Template
);
1179 return IsVarTemplate
? NameClassification::VarTemplate(Template
)
1180 : NameClassification::TypeTemplate(Template
);
1183 auto BuildTypeFor
= [&](TypeDecl
*Type
, NamedDecl
*Found
) {
1184 QualType T
= Context
.getTypeDeclType(Type
);
1185 if (const auto *USD
= dyn_cast
<UsingShadowDecl
>(Found
))
1186 T
= Context
.getUsingType(USD
, T
);
1187 return buildNamedType(*this, &SS
, T
, NameLoc
);
1190 NamedDecl
*FirstDecl
= (*Result
.begin())->getUnderlyingDecl();
1191 if (TypeDecl
*Type
= dyn_cast
<TypeDecl
>(FirstDecl
)) {
1192 DiagnoseUseOfDecl(Type
, NameLoc
);
1193 MarkAnyDeclReferenced(Type
->getLocation(), Type
, /*OdrUse=*/false);
1194 return BuildTypeFor(Type
, *Result
.begin());
1197 ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(FirstDecl
);
1199 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1200 if (ObjCCompatibleAliasDecl
*Alias
=
1201 dyn_cast
<ObjCCompatibleAliasDecl
>(FirstDecl
))
1202 Class
= Alias
->getClassInterface();
1206 DiagnoseUseOfDecl(Class
, NameLoc
);
1208 if (NextToken
.is(tok::period
)) {
1209 // Interface. <something> is parsed as a property reference expression.
1210 // Just return "unknown" as a fall-through for now.
1211 Result
.suppressDiagnostics();
1212 return NameClassification::Unknown();
1215 QualType T
= Context
.getObjCInterfaceType(Class
);
1216 return ParsedType::make(T
);
1219 if (isa
<ConceptDecl
>(FirstDecl
))
1220 return NameClassification::Concept(
1221 TemplateName(cast
<TemplateDecl
>(FirstDecl
)));
1223 if (auto *EmptyD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(FirstDecl
)) {
1224 (void)DiagnoseUseOfDecl(EmptyD
, NameLoc
);
1225 return NameClassification::Error();
1228 // We can have a type template here if we're classifying a template argument.
1229 if (isa
<TemplateDecl
>(FirstDecl
) && !isa
<FunctionTemplateDecl
>(FirstDecl
) &&
1230 !isa
<VarTemplateDecl
>(FirstDecl
))
1231 return NameClassification::TypeTemplate(
1232 TemplateName(cast
<TemplateDecl
>(FirstDecl
)));
1234 // Check for a tag type hidden by a non-type decl in a few cases where it
1235 // seems likely a type is wanted instead of the non-type that was found.
1236 bool NextIsOp
= NextToken
.isOneOf(tok::amp
, tok::star
);
1237 if ((NextToken
.is(tok::identifier
) ||
1239 FirstDecl
->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1240 isTagTypeWithMissingTag(*this, Result
, S
, SS
, Name
, NameLoc
)) {
1241 TypeDecl
*Type
= Result
.getAsSingle
<TypeDecl
>();
1242 DiagnoseUseOfDecl(Type
, NameLoc
);
1243 return BuildTypeFor(Type
, *Result
.begin());
1246 // If we already know which single declaration is referenced, just annotate
1247 // that declaration directly. Defer resolving even non-overloaded class
1248 // member accesses, as we need to defer certain access checks until we know
1250 bool ADL
= UseArgumentDependentLookup(SS
, Result
, NextToken
.is(tok::l_paren
));
1251 if (Result
.isSingleResult() && !ADL
&&
1252 (!FirstDecl
->isCXXClassMember() || isa
<EnumConstantDecl
>(FirstDecl
)))
1253 return NameClassification::NonType(Result
.getRepresentativeDecl());
1255 // Otherwise, this is an overload set that we will need to resolve later.
1256 Result
.suppressDiagnostics();
1257 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1258 Context
, Result
.getNamingClass(), SS
.getWithLocInContext(Context
),
1259 Result
.getLookupNameInfo(), ADL
, Result
.isOverloadedResult(),
1260 Result
.begin(), Result
.end()));
1264 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo
*Name
,
1265 SourceLocation NameLoc
) {
1266 assert(getLangOpts().CPlusPlus
&& "ADL-only call in C?");
1268 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
1269 return BuildDeclarationNameExpr(SS
, Result
, /*ADL=*/true);
1273 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec
&SS
,
1274 IdentifierInfo
*Name
,
1275 SourceLocation NameLoc
,
1276 bool IsAddressOfOperand
) {
1277 DeclarationNameInfo
NameInfo(Name
, NameLoc
);
1278 return ActOnDependentIdExpression(SS
, /*TemplateKWLoc=*/SourceLocation(),
1279 NameInfo
, IsAddressOfOperand
,
1280 /*TemplateArgs=*/nullptr);
1283 ExprResult
Sema::ActOnNameClassifiedAsNonType(Scope
*S
, const CXXScopeSpec
&SS
,
1285 SourceLocation NameLoc
,
1286 const Token
&NextToken
) {
1287 if (getCurMethodDecl() && SS
.isEmpty())
1288 if (auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(Found
->getUnderlyingDecl()))
1289 return BuildIvarRefExpr(S
, NameLoc
, Ivar
);
1291 // Reconstruct the lookup result.
1292 LookupResult
Result(*this, Found
->getDeclName(), NameLoc
, LookupOrdinaryName
);
1293 Result
.addDecl(Found
);
1294 Result
.resolveKind();
1296 bool ADL
= UseArgumentDependentLookup(SS
, Result
, NextToken
.is(tok::l_paren
));
1297 return BuildDeclarationNameExpr(SS
, Result
, ADL
, /*AcceptInvalidDecl=*/true);
1300 ExprResult
Sema::ActOnNameClassifiedAsOverloadSet(Scope
*S
, Expr
*E
) {
1301 // For an implicit class member access, transform the result into a member
1302 // access expression if necessary.
1303 auto *ULE
= cast
<UnresolvedLookupExpr
>(E
);
1304 if ((*ULE
->decls_begin())->isCXXClassMember()) {
1306 SS
.Adopt(ULE
->getQualifierLoc());
1308 // Reconstruct the lookup result.
1309 LookupResult
Result(*this, ULE
->getName(), ULE
->getNameLoc(),
1310 LookupOrdinaryName
);
1311 Result
.setNamingClass(ULE
->getNamingClass());
1312 for (auto I
= ULE
->decls_begin(), E
= ULE
->decls_end(); I
!= E
; ++I
)
1313 Result
.addDecl(*I
, I
.getAccess());
1314 Result
.resolveKind();
1315 return BuildPossibleImplicitMemberExpr(SS
, SourceLocation(), Result
,
1319 // Otherwise, this is already in the form we needed, and no further checks
1324 Sema::TemplateNameKindForDiagnostics
1325 Sema::getTemplateNameKindForDiagnostics(TemplateName Name
) {
1326 auto *TD
= Name
.getAsTemplateDecl();
1328 return TemplateNameKindForDiagnostics::DependentTemplate
;
1329 if (isa
<ClassTemplateDecl
>(TD
))
1330 return TemplateNameKindForDiagnostics::ClassTemplate
;
1331 if (isa
<FunctionTemplateDecl
>(TD
))
1332 return TemplateNameKindForDiagnostics::FunctionTemplate
;
1333 if (isa
<VarTemplateDecl
>(TD
))
1334 return TemplateNameKindForDiagnostics::VarTemplate
;
1335 if (isa
<TypeAliasTemplateDecl
>(TD
))
1336 return TemplateNameKindForDiagnostics::AliasTemplate
;
1337 if (isa
<TemplateTemplateParmDecl
>(TD
))
1338 return TemplateNameKindForDiagnostics::TemplateTemplateParam
;
1339 if (isa
<ConceptDecl
>(TD
))
1340 return TemplateNameKindForDiagnostics::Concept
;
1341 return TemplateNameKindForDiagnostics::DependentTemplate
;
1344 void Sema::PushDeclContext(Scope
*S
, DeclContext
*DC
) {
1345 assert(DC
->getLexicalParent() == CurContext
&&
1346 "The next DeclContext should be lexically contained in the current one.");
1351 void Sema::PopDeclContext() {
1352 assert(CurContext
&& "DeclContext imbalance!");
1354 CurContext
= CurContext
->getLexicalParent();
1355 assert(CurContext
&& "Popped translation unit!");
1358 Sema::SkippedDefinitionContext
Sema::ActOnTagStartSkippedDefinition(Scope
*S
,
1360 // Unlike PushDeclContext, the context to which we return is not necessarily
1361 // the containing DC of TD, because the new context will be some pre-existing
1362 // TagDecl definition instead of a fresh one.
1363 auto Result
= static_cast<SkippedDefinitionContext
>(CurContext
);
1364 CurContext
= cast
<TagDecl
>(D
)->getDefinition();
1365 assert(CurContext
&& "skipping definition of undefined tag");
1366 // Start lookups from the parent of the current context; we don't want to look
1367 // into the pre-existing complete definition.
1368 S
->setEntity(CurContext
->getLookupParent());
1372 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context
) {
1373 CurContext
= static_cast<decltype(CurContext
)>(Context
);
1376 /// EnterDeclaratorContext - Used when we must lookup names in the context
1377 /// of a declarator's nested name specifier.
1379 void Sema::EnterDeclaratorContext(Scope
*S
, DeclContext
*DC
) {
1380 // C++0x [basic.lookup.unqual]p13:
1381 // A name used in the definition of a static data member of class
1382 // X (after the qualified-id of the static member) is looked up as
1383 // if the name was used in a member function of X.
1384 // C++0x [basic.lookup.unqual]p14:
1385 // If a variable member of a namespace is defined outside of the
1386 // scope of its namespace then any name used in the definition of
1387 // the variable member (after the declarator-id) is looked up as
1388 // if the definition of the variable member occurred in its
1390 // Both of these imply that we should push a scope whose context
1391 // is the semantic context of the declaration. We can't use
1392 // PushDeclContext here because that context is not necessarily
1393 // lexically contained in the current context. Fortunately,
1394 // the containing scope should have the appropriate information.
1396 assert(!S
->getEntity() && "scope already has entity");
1399 Scope
*Ancestor
= S
->getParent();
1400 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
1401 assert(Ancestor
->getEntity() == CurContext
&& "ancestor context mismatch");
1407 if (S
->getParent()->isTemplateParamScope()) {
1408 // Also set the corresponding entities for all immediately-enclosing
1409 // template parameter scopes.
1410 EnterTemplatedContext(S
->getParent(), DC
);
1414 void Sema::ExitDeclaratorContext(Scope
*S
) {
1415 assert(S
->getEntity() == CurContext
&& "Context imbalance!");
1417 // Switch back to the lexical context. The safety of this is
1418 // enforced by an assert in EnterDeclaratorContext.
1419 Scope
*Ancestor
= S
->getParent();
1420 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
1421 CurContext
= Ancestor
->getEntity();
1423 // We don't need to do anything with the scope, which is going to
1427 void Sema::EnterTemplatedContext(Scope
*S
, DeclContext
*DC
) {
1428 assert(S
->isTemplateParamScope() &&
1429 "expected to be initializing a template parameter scope");
1431 // C++20 [temp.local]p7:
1432 // In the definition of a member of a class template that appears outside
1433 // of the class template definition, the name of a member of the class
1434 // template hides the name of a template-parameter of any enclosing class
1435 // templates (but not a template-parameter of the member if the member is a
1436 // class or function template).
1437 // C++20 [temp.local]p9:
1438 // In the definition of a class template or in the definition of a member
1439 // of such a template that appears outside of the template definition, for
1440 // each non-dependent base class (13.8.2.1), if the name of the base class
1441 // or the name of a member of the base class is the same as the name of a
1442 // template-parameter, the base class name or member name hides the
1443 // template-parameter name (6.4.10).
1445 // This means that a template parameter scope should be searched immediately
1446 // after searching the DeclContext for which it is a template parameter
1447 // scope. For example, for
1448 // template<typename T> template<typename U> template<typename V>
1449 // void N::A<T>::B<U>::f(...)
1450 // we search V then B<U> (and base classes) then U then A<T> (and base
1451 // classes) then T then N then ::.
1452 unsigned ScopeDepth
= getTemplateDepth(S
);
1453 for (; S
&& S
->isTemplateParamScope(); S
= S
->getParent(), --ScopeDepth
) {
1454 DeclContext
*SearchDCAfterScope
= DC
;
1455 for (; DC
; DC
= DC
->getLookupParent()) {
1456 if (const TemplateParameterList
*TPL
=
1457 cast
<Decl
>(DC
)->getDescribedTemplateParams()) {
1458 unsigned DCDepth
= TPL
->getDepth() + 1;
1459 if (DCDepth
> ScopeDepth
)
1461 if (ScopeDepth
== DCDepth
)
1462 SearchDCAfterScope
= DC
= DC
->getLookupParent();
1466 S
->setLookupEntity(SearchDCAfterScope
);
1470 void Sema::ActOnReenterFunctionContext(Scope
* S
, Decl
*D
) {
1471 // We assume that the caller has already called
1472 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1473 FunctionDecl
*FD
= D
->getAsFunction();
1477 // Same implementation as PushDeclContext, but enters the context
1478 // from the lexical parent, rather than the top-level class.
1479 assert(CurContext
== FD
->getLexicalParent() &&
1480 "The next DeclContext should be lexically contained in the current one.");
1482 S
->setEntity(CurContext
);
1484 for (unsigned P
= 0, NumParams
= FD
->getNumParams(); P
< NumParams
; ++P
) {
1485 ParmVarDecl
*Param
= FD
->getParamDecl(P
);
1486 // If the parameter has an identifier, then add it to the scope
1487 if (Param
->getIdentifier()) {
1489 IdResolver
.AddDecl(Param
);
1494 void Sema::ActOnExitFunctionContext() {
1495 // Same implementation as PopDeclContext, but returns to the lexical parent,
1496 // rather than the top-level class.
1497 assert(CurContext
&& "DeclContext imbalance!");
1498 CurContext
= CurContext
->getLexicalParent();
1499 assert(CurContext
&& "Popped translation unit!");
1502 /// Determine whether overloading is allowed for a new function
1503 /// declaration considering prior declarations of the same name.
1505 /// This routine determines whether overloading is possible, not
1506 /// whether a new declaration actually overloads a previous one.
1507 /// It will return true in C++ (where overloads are alway permitted)
1508 /// or, as a C extension, when either the new declaration or a
1509 /// previous one is declared with the 'overloadable' attribute.
1510 static bool AllowOverloadingOfFunction(const LookupResult
&Previous
,
1511 ASTContext
&Context
,
1512 const FunctionDecl
*New
) {
1513 if (Context
.getLangOpts().CPlusPlus
|| New
->hasAttr
<OverloadableAttr
>())
1516 // Multiversion function declarations are not overloads in the
1517 // usual sense of that term, but lookup will report that an
1518 // overload set was found if more than one multiversion function
1519 // declaration is present for the same name. It is therefore
1520 // inadequate to assume that some prior declaration(s) had
1521 // the overloadable attribute; checking is required. Since one
1522 // declaration is permitted to omit the attribute, it is necessary
1523 // to check at least two; hence the 'any_of' check below. Note that
1524 // the overloadable attribute is implicitly added to declarations
1525 // that were required to have it but did not.
1526 if (Previous
.getResultKind() == LookupResult::FoundOverloaded
) {
1527 return llvm::any_of(Previous
, [](const NamedDecl
*ND
) {
1528 return ND
->hasAttr
<OverloadableAttr
>();
1530 } else if (Previous
.getResultKind() == LookupResult::Found
)
1531 return Previous
.getFoundDecl()->hasAttr
<OverloadableAttr
>();
1536 /// Add this decl to the scope shadowed decl chains.
1537 void Sema::PushOnScopeChains(NamedDecl
*D
, Scope
*S
, bool AddToContext
) {
1538 // Move up the scope chain until we find the nearest enclosing
1539 // non-transparent context. The declaration will be introduced into this
1541 while (S
->getEntity() && S
->getEntity()->isTransparentContext())
1544 // Add scoped declarations into their context, so that they can be
1545 // found later. Declarations without a context won't be inserted
1546 // into any context.
1548 CurContext
->addDecl(D
);
1550 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1551 // are function-local declarations.
1552 if (getLangOpts().CPlusPlus
&& D
->isOutOfLine() && !S
->getFnParent())
1555 // Template instantiations should also not be pushed into scope.
1556 if (isa
<FunctionDecl
>(D
) &&
1557 cast
<FunctionDecl
>(D
)->isFunctionTemplateSpecialization())
1560 // If this replaces anything in the current scope,
1561 IdentifierResolver::iterator I
= IdResolver
.begin(D
->getDeclName()),
1562 IEnd
= IdResolver
.end();
1563 for (; I
!= IEnd
; ++I
) {
1564 if (S
->isDeclScope(*I
) && D
->declarationReplaces(*I
)) {
1566 IdResolver
.RemoveDecl(*I
);
1568 // Should only need to replace one decl.
1575 if (isa
<LabelDecl
>(D
) && !cast
<LabelDecl
>(D
)->isGnuLocal()) {
1576 // Implicitly-generated labels may end up getting generated in an order that
1577 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1578 // the label at the appropriate place in the identifier chain.
1579 for (I
= IdResolver
.begin(D
->getDeclName()); I
!= IEnd
; ++I
) {
1580 DeclContext
*IDC
= (*I
)->getLexicalDeclContext()->getRedeclContext();
1581 if (IDC
== CurContext
) {
1582 if (!S
->isDeclScope(*I
))
1584 } else if (IDC
->Encloses(CurContext
))
1588 IdResolver
.InsertDeclAfter(I
, D
);
1590 IdResolver
.AddDecl(D
);
1592 warnOnReservedIdentifier(D
);
1595 bool Sema::isDeclInScope(NamedDecl
*D
, DeclContext
*Ctx
, Scope
*S
,
1596 bool AllowInlineNamespace
) {
1597 return IdResolver
.isDeclInScope(D
, Ctx
, S
, AllowInlineNamespace
);
1600 Scope
*Sema::getScopeForDeclContext(Scope
*S
, DeclContext
*DC
) {
1601 DeclContext
*TargetDC
= DC
->getPrimaryContext();
1603 if (DeclContext
*ScopeDC
= S
->getEntity())
1604 if (ScopeDC
->getPrimaryContext() == TargetDC
)
1606 } while ((S
= S
->getParent()));
1611 static bool isOutOfScopePreviousDeclaration(NamedDecl
*,
1615 /// Filters out lookup results that don't fall within the given scope
1616 /// as determined by isDeclInScope.
1617 void Sema::FilterLookupForScope(LookupResult
&R
, DeclContext
*Ctx
, Scope
*S
,
1618 bool ConsiderLinkage
,
1619 bool AllowInlineNamespace
) {
1620 LookupResult::Filter F
= R
.makeFilter();
1621 while (F
.hasNext()) {
1622 NamedDecl
*D
= F
.next();
1624 if (isDeclInScope(D
, Ctx
, S
, AllowInlineNamespace
))
1627 if (ConsiderLinkage
&& isOutOfScopePreviousDeclaration(D
, Ctx
, Context
))
1636 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1637 /// have compatible owning modules.
1638 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl
*New
, NamedDecl
*Old
) {
1639 // [module.interface]p7:
1640 // A declaration is attached to a module as follows:
1641 // - If the declaration is a non-dependent friend declaration that nominates a
1642 // function with a declarator-id that is a qualified-id or template-id or that
1643 // nominates a class other than with an elaborated-type-specifier with neither
1644 // a nested-name-specifier nor a simple-template-id, it is attached to the
1645 // module to which the friend is attached ([basic.link]).
1646 if (New
->getFriendObjectKind() &&
1647 Old
->getOwningModuleForLinkage() != New
->getOwningModuleForLinkage()) {
1648 New
->setLocalOwningModule(Old
->getOwningModule());
1649 makeMergedDefinitionVisible(New
);
1653 Module
*NewM
= New
->getOwningModule();
1654 Module
*OldM
= Old
->getOwningModule();
1656 if (NewM
&& NewM
->isPrivateModule())
1657 NewM
= NewM
->Parent
;
1658 if (OldM
&& OldM
->isPrivateModule())
1659 OldM
= OldM
->Parent
;
1664 // Partitions are part of the module, but a partition could import another
1665 // module, so verify that the PMIs agree.
1667 (NewM
->isModulePartition() || OldM
->isModulePartition()) &&
1668 NewM
->getPrimaryModuleInterfaceName() ==
1669 OldM
->getPrimaryModuleInterfaceName())
1672 bool NewIsModuleInterface
= NewM
&& NewM
->isModulePurview();
1673 bool OldIsModuleInterface
= OldM
&& OldM
->isModulePurview();
1674 if (NewIsModuleInterface
|| OldIsModuleInterface
) {
1675 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1676 // if a declaration of D [...] appears in the purview of a module, all
1677 // other such declarations shall appear in the purview of the same module
1678 Diag(New
->getLocation(), diag::err_mismatched_owning_module
)
1680 << NewIsModuleInterface
1681 << (NewIsModuleInterface
? NewM
->getFullModuleName() : "")
1682 << OldIsModuleInterface
1683 << (OldIsModuleInterface
? OldM
->getFullModuleName() : "");
1684 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1685 New
->setInvalidDecl();
1692 // [module.interface]p6:
1693 // A redeclaration of an entity X is implicitly exported if X was introduced by
1694 // an exported declaration; otherwise it shall not be exported.
1695 bool Sema::CheckRedeclarationExported(NamedDecl
*New
, NamedDecl
*Old
) {
1696 // [module.interface]p1:
1697 // An export-declaration shall inhabit a namespace scope.
1699 // So it is meaningless to talk about redeclaration which is not at namespace
1701 if (!New
->getLexicalDeclContext()
1702 ->getNonTransparentContext()
1703 ->isFileContext() ||
1704 !Old
->getLexicalDeclContext()
1705 ->getNonTransparentContext()
1709 bool IsNewExported
= New
->isInExportDeclContext();
1710 bool IsOldExported
= Old
->isInExportDeclContext();
1712 // It should be irrevelant if both of them are not exported.
1713 if (!IsNewExported
&& !IsOldExported
)
1719 assert(IsNewExported
);
1721 auto Lk
= Old
->getFormalLinkage();
1723 if (Lk
== Linkage::InternalLinkage
)
1725 else if (Lk
== Linkage::ModuleLinkage
)
1727 Diag(New
->getLocation(), diag::err_redeclaration_non_exported
) << New
<< S
;
1728 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1732 // A wrapper function for checking the semantic restrictions of
1733 // a redeclaration within a module.
1734 bool Sema::CheckRedeclarationInModule(NamedDecl
*New
, NamedDecl
*Old
) {
1735 if (CheckRedeclarationModuleOwnership(New
, Old
))
1738 if (CheckRedeclarationExported(New
, Old
))
1744 // Check the redefinition in C++20 Modules.
1746 // [basic.def.odr]p14:
1747 // For any definable item D with definitions in multiple translation units,
1748 // - if D is a non-inline non-templated function or variable, or
1749 // - if the definitions in different translation units do not satisfy the
1750 // following requirements,
1751 // the program is ill-formed; a diagnostic is required only if the definable
1752 // item is attached to a named module and a prior definition is reachable at
1753 // the point where a later definition occurs.
1754 // - Each such definition shall not be attached to a named module
1756 // - Each such definition shall consist of the same sequence of tokens, ...
1759 // Return true if the redefinition is not allowed. Return false otherwise.
1760 bool Sema::IsRedefinitionInModule(const NamedDecl
*New
,
1761 const NamedDecl
*Old
) const {
1762 assert(getASTContext().isSameEntity(New
, Old
) &&
1763 "New and Old are not the same definition, we should diagnostic it "
1764 "immediately instead of checking it.");
1765 assert(const_cast<Sema
*>(this)->isReachable(New
) &&
1766 const_cast<Sema
*>(this)->isReachable(Old
) &&
1767 "We shouldn't see unreachable definitions here.");
1769 Module
*NewM
= New
->getOwningModule();
1770 Module
*OldM
= Old
->getOwningModule();
1772 // We only checks for named modules here. The header like modules is skipped.
1773 // FIXME: This is not right if we import the header like modules in the module
1776 // For example, assuming "header.h" provides definition for `D`.
1780 // import "header.h"; // or #include "header.h" but import it by clang modules
1785 // import "header.h"; // or uses clang modules.
1788 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1789 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1790 // reject it. But the current implementation couldn't detect the case since we
1791 // don't record the information about the importee modules.
1793 // But this might not be painful in practice. Since the design of C++20 Named
1794 // Modules suggests us to use headers in global module fragment instead of
1796 if (NewM
&& NewM
->isHeaderLikeModule())
1798 if (OldM
&& OldM
->isHeaderLikeModule())
1804 // [basic.def.odr]p14.3
1805 // Each such definition shall not be attached to a named module
1807 if ((NewM
&& NewM
->isModulePurview()) || (OldM
&& OldM
->isModulePurview()))
1810 // Then New and Old lives in the same TU if their share one same module unit.
1812 NewM
= NewM
->getTopLevelModule();
1814 OldM
= OldM
->getTopLevelModule();
1815 return OldM
== NewM
;
1818 static bool isUsingDecl(NamedDecl
*D
) {
1819 return isa
<UsingShadowDecl
>(D
) ||
1820 isa
<UnresolvedUsingTypenameDecl
>(D
) ||
1821 isa
<UnresolvedUsingValueDecl
>(D
);
1824 /// Removes using shadow declarations from the lookup results.
1825 static void RemoveUsingDecls(LookupResult
&R
) {
1826 LookupResult::Filter F
= R
.makeFilter();
1828 if (isUsingDecl(F
.next()))
1834 /// Check for this common pattern:
1837 /// S(const S&); // DO NOT IMPLEMENT
1838 /// void operator=(const S&); // DO NOT IMPLEMENT
1841 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl
*D
) {
1842 // FIXME: Should check for private access too but access is set after we get
1844 if (D
->doesThisDeclarationHaveABody())
1847 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(D
))
1848 return CD
->isCopyConstructor();
1849 return D
->isCopyAssignmentOperator();
1852 // We need this to handle
1855 // void *foo() { return 0; }
1858 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1859 // for example. If 'A', foo will have external linkage. If we have '*A',
1860 // foo will have no linkage. Since we can't know until we get to the end
1861 // of the typedef, this function finds out if D might have non-external linkage.
1862 // Callers should verify at the end of the TU if it D has external linkage or
1864 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl
*D
) {
1865 const DeclContext
*DC
= D
->getDeclContext();
1866 while (!DC
->isTranslationUnit()) {
1867 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(DC
)){
1868 if (!RD
->hasNameForLinkage())
1871 DC
= DC
->getParent();
1874 return !D
->isExternallyVisible();
1877 // FIXME: This needs to be refactored; some other isInMainFile users want
1879 static bool isMainFileLoc(const Sema
&S
, SourceLocation Loc
) {
1880 if (S
.TUKind
!= TU_Complete
|| S
.getLangOpts().IsHeaderFile
)
1882 return S
.SourceMgr
.isInMainFile(Loc
);
1885 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl
*D
) const {
1888 if (D
->isInvalidDecl() || D
->isUsed() || D
->hasAttr
<UnusedAttr
>())
1891 // Ignore all entities declared within templates, and out-of-line definitions
1892 // of members of class templates.
1893 if (D
->getDeclContext()->isDependentContext() ||
1894 D
->getLexicalDeclContext()->isDependentContext())
1897 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1898 if (FD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
1900 // A non-out-of-line declaration of a member specialization was implicitly
1901 // instantiated; it's the out-of-line declaration that we're interested in.
1902 if (FD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
1903 FD
->getMemberSpecializationInfo() && !FD
->isOutOfLine())
1906 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
1907 if (MD
->isVirtual() || IsDisallowedCopyOrAssign(MD
))
1910 // 'static inline' functions are defined in headers; don't warn.
1911 if (FD
->isInlined() && !isMainFileLoc(*this, FD
->getLocation()))
1915 if (FD
->doesThisDeclarationHaveABody() &&
1916 Context
.DeclMustBeEmitted(FD
))
1918 } else if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1919 // Constants and utility variables are defined in headers with internal
1920 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1922 if (!isMainFileLoc(*this, VD
->getLocation()))
1925 if (Context
.DeclMustBeEmitted(VD
))
1928 if (VD
->isStaticDataMember() &&
1929 VD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
1931 if (VD
->isStaticDataMember() &&
1932 VD
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
1933 VD
->getMemberSpecializationInfo() && !VD
->isOutOfLine())
1936 if (VD
->isInline() && !isMainFileLoc(*this, VD
->getLocation()))
1942 // Only warn for unused decls internal to the translation unit.
1943 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1944 // for inline functions defined in the main source file, for instance.
1945 return mightHaveNonExternalLinkage(D
);
1948 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl
*D
) {
1952 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1953 const FunctionDecl
*First
= FD
->getFirstDecl();
1954 if (FD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
1955 return; // First should already be in the vector.
1958 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
1959 const VarDecl
*First
= VD
->getFirstDecl();
1960 if (VD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
1961 return; // First should already be in the vector.
1964 if (ShouldWarnIfUnusedFileScopedDecl(D
))
1965 UnusedFileScopedDecls
.push_back(D
);
1968 static bool ShouldDiagnoseUnusedDecl(const NamedDecl
*D
) {
1969 if (D
->isInvalidDecl())
1972 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
)) {
1973 // For a decomposition declaration, warn if none of the bindings are
1974 // referenced, instead of if the variable itself is referenced (which
1975 // it is, by the bindings' expressions).
1976 for (auto *BD
: DD
->bindings())
1977 if (BD
->isReferenced())
1979 } else if (!D
->getDeclName()) {
1981 } else if (D
->isReferenced() || D
->isUsed()) {
1985 if (D
->hasAttr
<UnusedAttr
>() || D
->hasAttr
<ObjCPreciseLifetimeAttr
>())
1988 if (isa
<LabelDecl
>(D
))
1991 // Except for labels, we only care about unused decls that are local to
1993 bool WithinFunction
= D
->getDeclContext()->isFunctionOrMethod();
1994 if (const auto *R
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext()))
1995 // For dependent types, the diagnostic is deferred.
1997 WithinFunction
|| (R
->isLocalClass() && !R
->isDependentType());
1998 if (!WithinFunction
)
2001 if (isa
<TypedefNameDecl
>(D
))
2004 // White-list anything that isn't a local variable.
2005 if (!isa
<VarDecl
>(D
) || isa
<ParmVarDecl
>(D
) || isa
<ImplicitParamDecl
>(D
))
2008 // Types of valid local variables should be complete, so this should succeed.
2009 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2011 const Expr
*Init
= VD
->getInit();
2012 if (const auto *Cleanups
= dyn_cast_or_null
<ExprWithCleanups
>(Init
))
2013 Init
= Cleanups
->getSubExpr();
2015 const auto *Ty
= VD
->getType().getTypePtr();
2017 // Only look at the outermost level of typedef.
2018 if (const TypedefType
*TT
= Ty
->getAs
<TypedefType
>()) {
2019 // Allow anything marked with __attribute__((unused)).
2020 if (TT
->getDecl()->hasAttr
<UnusedAttr
>())
2024 // Warn for reference variables whose initializtion performs lifetime
2026 if (const auto *MTE
= dyn_cast_or_null
<MaterializeTemporaryExpr
>(Init
)) {
2027 if (MTE
->getExtendingDecl()) {
2028 Ty
= VD
->getType().getNonReferenceType().getTypePtr();
2029 Init
= MTE
->getSubExpr()->IgnoreImplicitAsWritten();
2033 // If we failed to complete the type for some reason, or if the type is
2034 // dependent, don't diagnose the variable.
2035 if (Ty
->isIncompleteType() || Ty
->isDependentType())
2038 // Look at the element type to ensure that the warning behaviour is
2039 // consistent for both scalars and arrays.
2040 Ty
= Ty
->getBaseElementTypeUnsafe();
2042 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
2043 const TagDecl
*Tag
= TT
->getDecl();
2044 if (Tag
->hasAttr
<UnusedAttr
>())
2047 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
2048 if (!RD
->hasTrivialDestructor() && !RD
->hasAttr
<WarnUnusedAttr
>())
2052 const CXXConstructExpr
*Construct
=
2053 dyn_cast
<CXXConstructExpr
>(Init
);
2054 if (Construct
&& !Construct
->isElidable()) {
2055 CXXConstructorDecl
*CD
= Construct
->getConstructor();
2056 if (!CD
->isTrivial() && !RD
->hasAttr
<WarnUnusedAttr
>() &&
2057 (VD
->getInit()->isValueDependent() || !VD
->evaluateValue()))
2061 // Suppress the warning if we don't know how this is constructed, and
2062 // it could possibly be non-trivial constructor.
2063 if (Init
->isTypeDependent()) {
2064 for (const CXXConstructorDecl
*Ctor
: RD
->ctors())
2065 if (!Ctor
->isTrivial())
2069 // Suppress the warning if the constructor is unresolved because
2070 // its arguments are dependent.
2071 if (isa
<CXXUnresolvedConstructExpr
>(Init
))
2077 // TODO: __attribute__((unused)) templates?
2083 static void GenerateFixForUnusedDecl(const NamedDecl
*D
, ASTContext
&Ctx
,
2085 if (isa
<LabelDecl
>(D
)) {
2086 SourceLocation AfterColon
= Lexer::findLocationAfterToken(
2087 D
->getEndLoc(), tok::colon
, Ctx
.getSourceManager(), Ctx
.getLangOpts(),
2089 if (AfterColon
.isInvalid())
2091 Hint
= FixItHint::CreateRemoval(
2092 CharSourceRange::getCharRange(D
->getBeginLoc(), AfterColon
));
2096 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl
*D
) {
2097 DiagnoseUnusedNestedTypedefs(
2098 D
, [this](SourceLocation Loc
, PartialDiagnostic PD
) { Diag(Loc
, PD
); });
2101 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl
*D
,
2102 DiagReceiverTy DiagReceiver
) {
2103 if (D
->getTypeForDecl()->isDependentType())
2106 for (auto *TmpD
: D
->decls()) {
2107 if (const auto *T
= dyn_cast
<TypedefNameDecl
>(TmpD
))
2108 DiagnoseUnusedDecl(T
, DiagReceiver
);
2109 else if(const auto *R
= dyn_cast
<RecordDecl
>(TmpD
))
2110 DiagnoseUnusedNestedTypedefs(R
, DiagReceiver
);
2114 void Sema::DiagnoseUnusedDecl(const NamedDecl
*D
) {
2116 D
, [this](SourceLocation Loc
, PartialDiagnostic PD
) { Diag(Loc
, PD
); });
2119 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2120 /// unless they are marked attr(unused).
2121 void Sema::DiagnoseUnusedDecl(const NamedDecl
*D
, DiagReceiverTy DiagReceiver
) {
2122 if (!ShouldDiagnoseUnusedDecl(D
))
2125 if (auto *TD
= dyn_cast
<TypedefNameDecl
>(D
)) {
2126 // typedefs can be referenced later on, so the diagnostics are emitted
2127 // at end-of-translation-unit.
2128 UnusedLocalTypedefNameCandidates
.insert(TD
);
2133 GenerateFixForUnusedDecl(D
, Context
, Hint
);
2136 if (isa
<VarDecl
>(D
) && cast
<VarDecl
>(D
)->isExceptionVariable())
2137 DiagID
= diag::warn_unused_exception_param
;
2138 else if (isa
<LabelDecl
>(D
))
2139 DiagID
= diag::warn_unused_label
;
2141 DiagID
= diag::warn_unused_variable
;
2143 DiagReceiver(D
->getLocation(), PDiag(DiagID
) << D
<< Hint
);
2146 void Sema::DiagnoseUnusedButSetDecl(const VarDecl
*VD
,
2147 DiagReceiverTy DiagReceiver
) {
2148 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2149 // it's not really unused.
2150 if (!VD
->isReferenced() || !VD
->getDeclName() || VD
->hasAttr
<UnusedAttr
>() ||
2151 VD
->hasAttr
<CleanupAttr
>())
2154 const auto *Ty
= VD
->getType().getTypePtr()->getBaseElementTypeUnsafe();
2156 if (Ty
->isReferenceType() || Ty
->isDependentType())
2159 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
2160 const TagDecl
*Tag
= TT
->getDecl();
2161 if (Tag
->hasAttr
<UnusedAttr
>())
2163 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2164 // mimic gcc's behavior.
2165 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
2166 if (!RD
->hasAttr
<WarnUnusedAttr
>())
2171 // Don't warn about __block Objective-C pointer variables, as they might
2172 // be assigned in the block but not used elsewhere for the purpose of lifetime
2174 if (VD
->hasAttr
<BlocksAttr
>() && Ty
->isObjCObjectPointerType())
2177 // Don't warn about Objective-C pointer variables with precise lifetime
2178 // semantics; they can be used to ensure ARC releases the object at a known
2179 // time, which may mean assignment but no other references.
2180 if (VD
->hasAttr
<ObjCPreciseLifetimeAttr
>() && Ty
->isObjCObjectPointerType())
2183 auto iter
= RefsMinusAssignments
.find(VD
);
2184 if (iter
== RefsMinusAssignments
.end())
2187 assert(iter
->getSecond() >= 0 &&
2188 "Found a negative number of references to a VarDecl");
2189 if (iter
->getSecond() != 0)
2191 unsigned DiagID
= isa
<ParmVarDecl
>(VD
) ? diag::warn_unused_but_set_parameter
2192 : diag::warn_unused_but_set_variable
;
2193 DiagReceiver(VD
->getLocation(), PDiag(DiagID
) << VD
);
2196 static void CheckPoppedLabel(LabelDecl
*L
, Sema
&S
,
2197 Sema::DiagReceiverTy DiagReceiver
) {
2198 // Verify that we have no forward references left. If so, there was a goto
2199 // or address of a label taken, but no definition of it. Label fwd
2200 // definitions are indicated with a null substmt which is also not a resolved
2201 // MS inline assembly label name.
2202 bool Diagnose
= false;
2203 if (L
->isMSAsmLabel())
2204 Diagnose
= !L
->isResolvedMSAsmLabel();
2206 Diagnose
= L
->getStmt() == nullptr;
2208 DiagReceiver(L
->getLocation(), S
.PDiag(diag::err_undeclared_label_use
)
2212 void Sema::ActOnPopScope(SourceLocation Loc
, Scope
*S
) {
2215 if (S
->decl_empty()) return;
2216 assert((S
->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope
)) &&
2217 "Scope shouldn't contain decls!");
2219 /// We visit the decls in non-deterministic order, but we want diagnostics
2220 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2221 /// and sort the diagnostics before emitting them, after we visited all decls.
2224 std::optional
<SourceLocation
> PreviousDeclLoc
;
2225 PartialDiagnostic PD
;
2227 SmallVector
<LocAndDiag
, 16> DeclDiags
;
2228 auto addDiag
= [&DeclDiags
](SourceLocation Loc
, PartialDiagnostic PD
) {
2229 DeclDiags
.push_back(LocAndDiag
{Loc
, std::nullopt
, std::move(PD
)});
2231 auto addDiagWithPrev
= [&DeclDiags
](SourceLocation Loc
,
2232 SourceLocation PreviousDeclLoc
,
2233 PartialDiagnostic PD
) {
2234 DeclDiags
.push_back(LocAndDiag
{Loc
, PreviousDeclLoc
, std::move(PD
)});
2237 for (auto *TmpD
: S
->decls()) {
2238 assert(TmpD
&& "This decl didn't get pushed??");
2240 assert(isa
<NamedDecl
>(TmpD
) && "Decl isn't NamedDecl?");
2241 NamedDecl
*D
= cast
<NamedDecl
>(TmpD
);
2243 // Diagnose unused variables in this scope.
2244 if (!S
->hasUnrecoverableErrorOccurred()) {
2245 DiagnoseUnusedDecl(D
, addDiag
);
2246 if (const auto *RD
= dyn_cast
<RecordDecl
>(D
))
2247 DiagnoseUnusedNestedTypedefs(RD
, addDiag
);
2248 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2249 DiagnoseUnusedButSetDecl(VD
, addDiag
);
2250 RefsMinusAssignments
.erase(VD
);
2254 if (!D
->getDeclName()) continue;
2256 // If this was a forward reference to a label, verify it was defined.
2257 if (LabelDecl
*LD
= dyn_cast
<LabelDecl
>(D
))
2258 CheckPoppedLabel(LD
, *this, addDiag
);
2260 // Remove this name from our lexical scope, and warn on it if we haven't
2262 IdResolver
.RemoveDecl(D
);
2263 auto ShadowI
= ShadowingDecls
.find(D
);
2264 if (ShadowI
!= ShadowingDecls
.end()) {
2265 if (const auto *FD
= dyn_cast
<FieldDecl
>(ShadowI
->second
)) {
2266 addDiagWithPrev(D
->getLocation(), FD
->getLocation(),
2267 PDiag(diag::warn_ctor_parm_shadows_field
)
2268 << D
<< FD
<< FD
->getParent());
2270 ShadowingDecls
.erase(ShadowI
);
2274 llvm::sort(DeclDiags
,
2275 [](const LocAndDiag
&LHS
, const LocAndDiag
&RHS
) -> bool {
2276 // The particular order for diagnostics is not important, as long
2277 // as the order is deterministic. Using the raw location is going
2278 // to generally be in source order unless there are macro
2279 // expansions involved.
2280 return LHS
.Loc
.getRawEncoding() < RHS
.Loc
.getRawEncoding();
2282 for (const LocAndDiag
&D
: DeclDiags
) {
2284 if (D
.PreviousDeclLoc
)
2285 Diag(*D
.PreviousDeclLoc
, diag::note_previous_declaration
);
2289 /// Look for an Objective-C class in the translation unit.
2291 /// \param Id The name of the Objective-C class we're looking for. If
2292 /// typo-correction fixes this name, the Id will be updated
2293 /// to the fixed name.
2295 /// \param IdLoc The location of the name in the translation unit.
2297 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2298 /// if there is no class with the given name.
2300 /// \returns The declaration of the named Objective-C class, or NULL if the
2301 /// class could not be found.
2302 ObjCInterfaceDecl
*Sema::getObjCInterfaceDecl(IdentifierInfo
*&Id
,
2303 SourceLocation IdLoc
,
2304 bool DoTypoCorrection
) {
2305 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2306 // creation from this context.
2307 NamedDecl
*IDecl
= LookupSingleName(TUScope
, Id
, IdLoc
, LookupOrdinaryName
);
2309 if (!IDecl
&& DoTypoCorrection
) {
2310 // Perform typo correction at the given location, but only if we
2311 // find an Objective-C class name.
2312 DeclFilterCCC
<ObjCInterfaceDecl
> CCC
{};
2313 if (TypoCorrection C
=
2314 CorrectTypo(DeclarationNameInfo(Id
, IdLoc
), LookupOrdinaryName
,
2315 TUScope
, nullptr, CCC
, CTK_ErrorRecovery
)) {
2316 diagnoseTypo(C
, PDiag(diag::err_undef_interface_suggest
) << Id
);
2317 IDecl
= C
.getCorrectionDeclAs
<ObjCInterfaceDecl
>();
2318 Id
= IDecl
->getIdentifier();
2321 ObjCInterfaceDecl
*Def
= dyn_cast_or_null
<ObjCInterfaceDecl
>(IDecl
);
2322 // This routine must always return a class definition, if any.
2323 if (Def
&& Def
->getDefinition())
2324 Def
= Def
->getDefinition();
2328 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2329 /// from S, where a non-field would be declared. This routine copes
2330 /// with the difference between C and C++ scoping rules in structs and
2331 /// unions. For example, the following code is well-formed in C but
2332 /// ill-formed in C++:
2338 /// void test_S6() {
2343 /// For the declaration of BAR, this routine will return a different
2344 /// scope. The scope S will be the scope of the unnamed enumeration
2345 /// within S6. In C++, this routine will return the scope associated
2346 /// with S6, because the enumeration's scope is a transparent
2347 /// context but structures can contain non-field names. In C, this
2348 /// routine will return the translation unit scope, since the
2349 /// enumeration's scope is a transparent context and structures cannot
2350 /// contain non-field names.
2351 Scope
*Sema::getNonFieldDeclScope(Scope
*S
) {
2352 while (((S
->getFlags() & Scope::DeclScope
) == 0) ||
2353 (S
->getEntity() && S
->getEntity()->isTransparentContext()) ||
2354 (S
->isClassScope() && !getLangOpts().CPlusPlus
))
2359 static StringRef
getHeaderName(Builtin::Context
&BuiltinInfo
, unsigned ID
,
2360 ASTContext::GetBuiltinTypeError Error
) {
2362 case ASTContext::GE_None
:
2364 case ASTContext::GE_Missing_type
:
2365 return BuiltinInfo
.getHeaderName(ID
);
2366 case ASTContext::GE_Missing_stdio
:
2368 case ASTContext::GE_Missing_setjmp
:
2370 case ASTContext::GE_Missing_ucontext
:
2371 return "ucontext.h";
2373 llvm_unreachable("unhandled error kind");
2376 FunctionDecl
*Sema::CreateBuiltin(IdentifierInfo
*II
, QualType Type
,
2377 unsigned ID
, SourceLocation Loc
) {
2378 DeclContext
*Parent
= Context
.getTranslationUnitDecl();
2380 if (getLangOpts().CPlusPlus
) {
2381 LinkageSpecDecl
*CLinkageDecl
= LinkageSpecDecl::Create(
2382 Context
, Parent
, Loc
, Loc
, LinkageSpecDecl::lang_c
, false);
2383 CLinkageDecl
->setImplicit();
2384 Parent
->addDecl(CLinkageDecl
);
2385 Parent
= CLinkageDecl
;
2388 FunctionDecl
*New
= FunctionDecl::Create(Context
, Parent
, Loc
, Loc
, II
, Type
,
2389 /*TInfo=*/nullptr, SC_Extern
,
2390 getCurFPFeatures().isFPConstrained(),
2391 false, Type
->isFunctionProtoType());
2393 New
->addAttr(BuiltinAttr::CreateImplicit(Context
, ID
));
2395 // Create Decl objects for each parameter, adding them to the
2397 if (const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(Type
)) {
2398 SmallVector
<ParmVarDecl
*, 16> Params
;
2399 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
2400 ParmVarDecl
*parm
= ParmVarDecl::Create(
2401 Context
, New
, SourceLocation(), SourceLocation(), nullptr,
2402 FT
->getParamType(i
), /*TInfo=*/nullptr, SC_None
, nullptr);
2403 parm
->setScopeInfo(0, i
);
2404 Params
.push_back(parm
);
2406 New
->setParams(Params
);
2409 AddKnownFunctionAttributes(New
);
2413 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2414 /// file scope. lazily create a decl for it. ForRedeclaration is true
2415 /// if we're creating this built-in in anticipation of redeclaring the
2417 NamedDecl
*Sema::LazilyCreateBuiltin(IdentifierInfo
*II
, unsigned ID
,
2418 Scope
*S
, bool ForRedeclaration
,
2419 SourceLocation Loc
) {
2420 LookupNecessaryTypesForBuiltin(S
, ID
);
2422 ASTContext::GetBuiltinTypeError Error
;
2423 QualType R
= Context
.GetBuiltinType(ID
, Error
);
2425 if (!ForRedeclaration
)
2428 // If we have a builtin without an associated type we should not emit a
2429 // warning when we were not able to find a type for it.
2430 if (Error
== ASTContext::GE_Missing_type
||
2431 Context
.BuiltinInfo
.allowTypeMismatch(ID
))
2434 // If we could not find a type for setjmp it is because the jmp_buf type was
2435 // not defined prior to the setjmp declaration.
2436 if (Error
== ASTContext::GE_Missing_setjmp
) {
2437 Diag(Loc
, diag::warn_implicit_decl_no_jmp_buf
)
2438 << Context
.BuiltinInfo
.getName(ID
);
2442 // Generally, we emit a warning that the declaration requires the
2443 // appropriate header.
2444 Diag(Loc
, diag::warn_implicit_decl_requires_sysheader
)
2445 << getHeaderName(Context
.BuiltinInfo
, ID
, Error
)
2446 << Context
.BuiltinInfo
.getName(ID
);
2450 if (!ForRedeclaration
&&
2451 (Context
.BuiltinInfo
.isPredefinedLibFunction(ID
) ||
2452 Context
.BuiltinInfo
.isHeaderDependentFunction(ID
))) {
2453 Diag(Loc
, LangOpts
.C99
? diag::ext_implicit_lib_function_decl_c99
2454 : diag::ext_implicit_lib_function_decl
)
2455 << Context
.BuiltinInfo
.getName(ID
) << R
;
2456 if (const char *Header
= Context
.BuiltinInfo
.getHeaderName(ID
))
2457 Diag(Loc
, diag::note_include_header_or_declare
)
2458 << Header
<< Context
.BuiltinInfo
.getName(ID
);
2464 FunctionDecl
*New
= CreateBuiltin(II
, R
, ID
, Loc
);
2465 RegisterLocallyScopedExternCDecl(New
, S
);
2467 // TUScope is the translation-unit scope to insert this function into.
2468 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2469 // relate Scopes to DeclContexts, and probably eliminate CurContext
2470 // entirely, but we're not there yet.
2471 DeclContext
*SavedContext
= CurContext
;
2472 CurContext
= New
->getDeclContext();
2473 PushOnScopeChains(New
, TUScope
);
2474 CurContext
= SavedContext
;
2478 /// Typedef declarations don't have linkage, but they still denote the same
2479 /// entity if their types are the same.
2480 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2482 static void filterNonConflictingPreviousTypedefDecls(Sema
&S
,
2483 TypedefNameDecl
*Decl
,
2484 LookupResult
&Previous
) {
2485 // This is only interesting when modules are enabled.
2486 if (!S
.getLangOpts().Modules
&& !S
.getLangOpts().ModulesLocalVisibility
)
2489 // Empty sets are uninteresting.
2490 if (Previous
.empty())
2493 LookupResult::Filter Filter
= Previous
.makeFilter();
2494 while (Filter
.hasNext()) {
2495 NamedDecl
*Old
= Filter
.next();
2497 // Non-hidden declarations are never ignored.
2498 if (S
.isVisible(Old
))
2501 // Declarations of the same entity are not ignored, even if they have
2502 // different linkages.
2503 if (auto *OldTD
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2504 if (S
.Context
.hasSameType(OldTD
->getUnderlyingType(),
2505 Decl
->getUnderlyingType()))
2508 // If both declarations give a tag declaration a typedef name for linkage
2509 // purposes, then they declare the same entity.
2510 if (OldTD
->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2511 Decl
->getAnonDeclWithTypedefName())
2521 bool Sema::isIncompatibleTypedef(TypeDecl
*Old
, TypedefNameDecl
*New
) {
2523 if (TypedefNameDecl
*OldTypedef
= dyn_cast
<TypedefNameDecl
>(Old
))
2524 OldType
= OldTypedef
->getUnderlyingType();
2526 OldType
= Context
.getTypeDeclType(Old
);
2527 QualType NewType
= New
->getUnderlyingType();
2529 if (NewType
->isVariablyModifiedType()) {
2530 // Must not redefine a typedef with a variably-modified type.
2531 int Kind
= isa
<TypeAliasDecl
>(Old
) ? 1 : 0;
2532 Diag(New
->getLocation(), diag::err_redefinition_variably_modified_typedef
)
2534 if (Old
->getLocation().isValid())
2535 notePreviousDefinition(Old
, New
->getLocation());
2536 New
->setInvalidDecl();
2540 if (OldType
!= NewType
&&
2541 !OldType
->isDependentType() &&
2542 !NewType
->isDependentType() &&
2543 !Context
.hasSameType(OldType
, NewType
)) {
2544 int Kind
= isa
<TypeAliasDecl
>(Old
) ? 1 : 0;
2545 Diag(New
->getLocation(), diag::err_redefinition_different_typedef
)
2546 << Kind
<< NewType
<< OldType
;
2547 if (Old
->getLocation().isValid())
2548 notePreviousDefinition(Old
, New
->getLocation());
2549 New
->setInvalidDecl();
2555 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2556 /// same name and scope as a previous declaration 'Old'. Figure out
2557 /// how to resolve this situation, merging decls or emitting
2558 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2560 void Sema::MergeTypedefNameDecl(Scope
*S
, TypedefNameDecl
*New
,
2561 LookupResult
&OldDecls
) {
2562 // If the new decl is known invalid already, don't bother doing any
2564 if (New
->isInvalidDecl()) return;
2566 // Allow multiple definitions for ObjC built-in typedefs.
2567 // FIXME: Verify the underlying types are equivalent!
2568 if (getLangOpts().ObjC
) {
2569 const IdentifierInfo
*TypeID
= New
->getIdentifier();
2570 switch (TypeID
->getLength()) {
2574 if (!TypeID
->isStr("id"))
2576 QualType T
= New
->getUnderlyingType();
2577 if (!T
->isPointerType())
2579 if (!T
->isVoidPointerType()) {
2580 QualType PT
= T
->castAs
<PointerType
>()->getPointeeType();
2581 if (!PT
->isStructureType())
2584 Context
.setObjCIdRedefinitionType(T
);
2585 // Install the built-in type for 'id', ignoring the current definition.
2586 New
->setTypeForDecl(Context
.getObjCIdType().getTypePtr());
2590 if (!TypeID
->isStr("Class"))
2592 Context
.setObjCClassRedefinitionType(New
->getUnderlyingType());
2593 // Install the built-in type for 'Class', ignoring the current definition.
2594 New
->setTypeForDecl(Context
.getObjCClassType().getTypePtr());
2597 if (!TypeID
->isStr("SEL"))
2599 Context
.setObjCSelRedefinitionType(New
->getUnderlyingType());
2600 // Install the built-in type for 'SEL', ignoring the current definition.
2601 New
->setTypeForDecl(Context
.getObjCSelType().getTypePtr());
2604 // Fall through - the typedef name was not a builtin type.
2607 // Verify the old decl was also a type.
2608 TypeDecl
*Old
= OldDecls
.getAsSingle
<TypeDecl
>();
2610 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
2611 << New
->getDeclName();
2613 NamedDecl
*OldD
= OldDecls
.getRepresentativeDecl();
2614 if (OldD
->getLocation().isValid())
2615 notePreviousDefinition(OldD
, New
->getLocation());
2617 return New
->setInvalidDecl();
2620 // If the old declaration is invalid, just give up here.
2621 if (Old
->isInvalidDecl())
2622 return New
->setInvalidDecl();
2624 if (auto *OldTD
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2625 auto *OldTag
= OldTD
->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2626 auto *NewTag
= New
->getAnonDeclWithTypedefName();
2627 NamedDecl
*Hidden
= nullptr;
2628 if (OldTag
&& NewTag
&&
2629 OldTag
->getCanonicalDecl() != NewTag
->getCanonicalDecl() &&
2630 !hasVisibleDefinition(OldTag
, &Hidden
)) {
2631 // There is a definition of this tag, but it is not visible. Use it
2632 // instead of our tag.
2633 New
->setTypeForDecl(OldTD
->getTypeForDecl());
2634 if (OldTD
->isModed())
2635 New
->setModedTypeSourceInfo(OldTD
->getTypeSourceInfo(),
2636 OldTD
->getUnderlyingType());
2638 New
->setTypeSourceInfo(OldTD
->getTypeSourceInfo());
2640 // Make the old tag definition visible.
2641 makeMergedDefinitionVisible(Hidden
);
2643 // If this was an unscoped enumeration, yank all of its enumerators
2644 // out of the scope.
2645 if (isa
<EnumDecl
>(NewTag
)) {
2646 Scope
*EnumScope
= getNonFieldDeclScope(S
);
2647 for (auto *D
: NewTag
->decls()) {
2648 auto *ED
= cast
<EnumConstantDecl
>(D
);
2649 assert(EnumScope
->isDeclScope(ED
));
2650 EnumScope
->RemoveDecl(ED
);
2651 IdResolver
.RemoveDecl(ED
);
2652 ED
->getLexicalDeclContext()->removeDecl(ED
);
2658 // If the typedef types are not identical, reject them in all languages and
2659 // with any extensions enabled.
2660 if (isIncompatibleTypedef(Old
, New
))
2663 // The types match. Link up the redeclaration chain and merge attributes if
2664 // the old declaration was a typedef.
2665 if (TypedefNameDecl
*Typedef
= dyn_cast
<TypedefNameDecl
>(Old
)) {
2666 New
->setPreviousDecl(Typedef
);
2667 mergeDeclAttributes(New
, Old
);
2670 if (getLangOpts().MicrosoftExt
)
2673 if (getLangOpts().CPlusPlus
) {
2674 // C++ [dcl.typedef]p2:
2675 // In a given non-class scope, a typedef specifier can be used to
2676 // redefine the name of any type declared in that scope to refer
2677 // to the type to which it already refers.
2678 if (!isa
<CXXRecordDecl
>(CurContext
))
2681 // C++0x [dcl.typedef]p4:
2682 // In a given class scope, a typedef specifier can be used to redefine
2683 // any class-name declared in that scope that is not also a typedef-name
2684 // to refer to the type to which it already refers.
2686 // This wording came in via DR424, which was a correction to the
2687 // wording in DR56, which accidentally banned code like:
2690 // typedef struct A { } A;
2693 // in the C++03 standard. We implement the C++0x semantics, which
2694 // allow the above but disallow
2701 // since that was the intent of DR56.
2702 if (!isa
<TypedefNameDecl
>(Old
))
2705 Diag(New
->getLocation(), diag::err_redefinition
)
2706 << New
->getDeclName();
2707 notePreviousDefinition(Old
, New
->getLocation());
2708 return New
->setInvalidDecl();
2711 // Modules always permit redefinition of typedefs, as does C11.
2712 if (getLangOpts().Modules
|| getLangOpts().C11
)
2715 // If we have a redefinition of a typedef in C, emit a warning. This warning
2716 // is normally mapped to an error, but can be controlled with
2717 // -Wtypedef-redefinition. If either the original or the redefinition is
2718 // in a system header, don't emit this for compatibility with GCC.
2719 if (getDiagnostics().getSuppressSystemWarnings() &&
2720 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2721 (Old
->isImplicit() ||
2722 Context
.getSourceManager().isInSystemHeader(Old
->getLocation()) ||
2723 Context
.getSourceManager().isInSystemHeader(New
->getLocation())))
2726 Diag(New
->getLocation(), diag::ext_redefinition_of_typedef
)
2727 << New
->getDeclName();
2728 notePreviousDefinition(Old
, New
->getLocation());
2731 /// DeclhasAttr - returns true if decl Declaration already has the target
2733 static bool DeclHasAttr(const Decl
*D
, const Attr
*A
) {
2734 const OwnershipAttr
*OA
= dyn_cast
<OwnershipAttr
>(A
);
2735 const AnnotateAttr
*Ann
= dyn_cast
<AnnotateAttr
>(A
);
2736 for (const auto *i
: D
->attrs())
2737 if (i
->getKind() == A
->getKind()) {
2739 if (Ann
->getAnnotation() == cast
<AnnotateAttr
>(i
)->getAnnotation())
2743 // FIXME: Don't hardcode this check
2744 if (OA
&& isa
<OwnershipAttr
>(i
))
2745 return OA
->getOwnKind() == cast
<OwnershipAttr
>(i
)->getOwnKind();
2752 static bool isAttributeTargetADefinition(Decl
*D
) {
2753 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
))
2754 return VD
->isThisDeclarationADefinition();
2755 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(D
))
2756 return TD
->isCompleteDefinition() || TD
->isBeingDefined();
2760 /// Merge alignment attributes from \p Old to \p New, taking into account the
2761 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2763 /// \return \c true if any attributes were added to \p New.
2764 static bool mergeAlignedAttrs(Sema
&S
, NamedDecl
*New
, Decl
*Old
) {
2765 // Look for alignas attributes on Old, and pick out whichever attribute
2766 // specifies the strictest alignment requirement.
2767 AlignedAttr
*OldAlignasAttr
= nullptr;
2768 AlignedAttr
*OldStrictestAlignAttr
= nullptr;
2769 unsigned OldAlign
= 0;
2770 for (auto *I
: Old
->specific_attrs
<AlignedAttr
>()) {
2771 // FIXME: We have no way of representing inherited dependent alignments
2773 // template<int A, int B> struct alignas(A) X;
2774 // template<int A, int B> struct alignas(B) X {};
2775 // For now, we just ignore any alignas attributes which are not on the
2776 // definition in such a case.
2777 if (I
->isAlignmentDependent())
2783 unsigned Align
= I
->getAlignment(S
.Context
);
2784 if (Align
> OldAlign
) {
2786 OldStrictestAlignAttr
= I
;
2790 // Look for alignas attributes on New.
2791 AlignedAttr
*NewAlignasAttr
= nullptr;
2792 unsigned NewAlign
= 0;
2793 for (auto *I
: New
->specific_attrs
<AlignedAttr
>()) {
2794 if (I
->isAlignmentDependent())
2800 unsigned Align
= I
->getAlignment(S
.Context
);
2801 if (Align
> NewAlign
)
2805 if (OldAlignasAttr
&& NewAlignasAttr
&& OldAlign
!= NewAlign
) {
2806 // Both declarations have 'alignas' attributes. We require them to match.
2807 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2808 // fall short. (If two declarations both have alignas, they must both match
2809 // every definition, and so must match each other if there is a definition.)
2811 // If either declaration only contains 'alignas(0)' specifiers, then it
2812 // specifies the natural alignment for the type.
2813 if (OldAlign
== 0 || NewAlign
== 0) {
2815 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(New
))
2818 Ty
= S
.Context
.getTagDeclType(cast
<TagDecl
>(New
));
2821 OldAlign
= S
.Context
.getTypeAlign(Ty
);
2823 NewAlign
= S
.Context
.getTypeAlign(Ty
);
2826 if (OldAlign
!= NewAlign
) {
2827 S
.Diag(NewAlignasAttr
->getLocation(), diag::err_alignas_mismatch
)
2828 << (unsigned)S
.Context
.toCharUnitsFromBits(OldAlign
).getQuantity()
2829 << (unsigned)S
.Context
.toCharUnitsFromBits(NewAlign
).getQuantity();
2830 S
.Diag(OldAlignasAttr
->getLocation(), diag::note_previous_declaration
);
2834 if (OldAlignasAttr
&& !NewAlignasAttr
&& isAttributeTargetADefinition(New
)) {
2835 // C++11 [dcl.align]p6:
2836 // if any declaration of an entity has an alignment-specifier,
2837 // every defining declaration of that entity shall specify an
2838 // equivalent alignment.
2840 // If the definition of an object does not have an alignment
2841 // specifier, any other declaration of that object shall also
2842 // have no alignment specifier.
2843 S
.Diag(New
->getLocation(), diag::err_alignas_missing_on_definition
)
2845 S
.Diag(OldAlignasAttr
->getLocation(), diag::note_alignas_on_declaration
)
2849 bool AnyAdded
= false;
2851 // Ensure we have an attribute representing the strictest alignment.
2852 if (OldAlign
> NewAlign
) {
2853 AlignedAttr
*Clone
= OldStrictestAlignAttr
->clone(S
.Context
);
2854 Clone
->setInherited(true);
2855 New
->addAttr(Clone
);
2859 // Ensure we have an alignas attribute if the old declaration had one.
2860 if (OldAlignasAttr
&& !NewAlignasAttr
&&
2861 !(AnyAdded
&& OldStrictestAlignAttr
->isAlignas())) {
2862 AlignedAttr
*Clone
= OldAlignasAttr
->clone(S
.Context
);
2863 Clone
->setInherited(true);
2864 New
->addAttr(Clone
);
2871 #define WANT_DECL_MERGE_LOGIC
2872 #include "clang/Sema/AttrParsedAttrImpl.inc"
2873 #undef WANT_DECL_MERGE_LOGIC
2875 static bool mergeDeclAttribute(Sema
&S
, NamedDecl
*D
,
2876 const InheritableAttr
*Attr
,
2877 Sema::AvailabilityMergeKind AMK
) {
2878 // Diagnose any mutual exclusions between the attribute that we want to add
2879 // and attributes that already exist on the declaration.
2880 if (!DiagnoseMutualExclusions(S
, D
, Attr
))
2883 // This function copies an attribute Attr from a previous declaration to the
2884 // new declaration D if the new declaration doesn't itself have that attribute
2885 // yet or if that attribute allows duplicates.
2886 // If you're adding a new attribute that requires logic different from
2887 // "use explicit attribute on decl if present, else use attribute from
2888 // previous decl", for example if the attribute needs to be consistent
2889 // between redeclarations, you need to call a custom merge function here.
2890 InheritableAttr
*NewAttr
= nullptr;
2891 if (const auto *AA
= dyn_cast
<AvailabilityAttr
>(Attr
))
2892 NewAttr
= S
.mergeAvailabilityAttr(
2893 D
, *AA
, AA
->getPlatform(), AA
->isImplicit(), AA
->getIntroduced(),
2894 AA
->getDeprecated(), AA
->getObsoleted(), AA
->getUnavailable(),
2895 AA
->getMessage(), AA
->getStrict(), AA
->getReplacement(), AMK
,
2897 else if (const auto *VA
= dyn_cast
<VisibilityAttr
>(Attr
))
2898 NewAttr
= S
.mergeVisibilityAttr(D
, *VA
, VA
->getVisibility());
2899 else if (const auto *VA
= dyn_cast
<TypeVisibilityAttr
>(Attr
))
2900 NewAttr
= S
.mergeTypeVisibilityAttr(D
, *VA
, VA
->getVisibility());
2901 else if (const auto *ImportA
= dyn_cast
<DLLImportAttr
>(Attr
))
2902 NewAttr
= S
.mergeDLLImportAttr(D
, *ImportA
);
2903 else if (const auto *ExportA
= dyn_cast
<DLLExportAttr
>(Attr
))
2904 NewAttr
= S
.mergeDLLExportAttr(D
, *ExportA
);
2905 else if (const auto *EA
= dyn_cast
<ErrorAttr
>(Attr
))
2906 NewAttr
= S
.mergeErrorAttr(D
, *EA
, EA
->getUserDiagnostic());
2907 else if (const auto *FA
= dyn_cast
<FormatAttr
>(Attr
))
2908 NewAttr
= S
.mergeFormatAttr(D
, *FA
, FA
->getType(), FA
->getFormatIdx(),
2910 else if (const auto *SA
= dyn_cast
<SectionAttr
>(Attr
))
2911 NewAttr
= S
.mergeSectionAttr(D
, *SA
, SA
->getName());
2912 else if (const auto *CSA
= dyn_cast
<CodeSegAttr
>(Attr
))
2913 NewAttr
= S
.mergeCodeSegAttr(D
, *CSA
, CSA
->getName());
2914 else if (const auto *IA
= dyn_cast
<MSInheritanceAttr
>(Attr
))
2915 NewAttr
= S
.mergeMSInheritanceAttr(D
, *IA
, IA
->getBestCase(),
2916 IA
->getInheritanceModel());
2917 else if (const auto *AA
= dyn_cast
<AlwaysInlineAttr
>(Attr
))
2918 NewAttr
= S
.mergeAlwaysInlineAttr(D
, *AA
,
2919 &S
.Context
.Idents
.get(AA
->getSpelling()));
2920 else if (S
.getLangOpts().CUDA
&& isa
<FunctionDecl
>(D
) &&
2921 (isa
<CUDAHostAttr
>(Attr
) || isa
<CUDADeviceAttr
>(Attr
) ||
2922 isa
<CUDAGlobalAttr
>(Attr
))) {
2923 // CUDA target attributes are part of function signature for
2924 // overloading purposes and must not be merged.
2926 } else if (const auto *MA
= dyn_cast
<MinSizeAttr
>(Attr
))
2927 NewAttr
= S
.mergeMinSizeAttr(D
, *MA
);
2928 else if (const auto *SNA
= dyn_cast
<SwiftNameAttr
>(Attr
))
2929 NewAttr
= S
.mergeSwiftNameAttr(D
, *SNA
, SNA
->getName());
2930 else if (const auto *OA
= dyn_cast
<OptimizeNoneAttr
>(Attr
))
2931 NewAttr
= S
.mergeOptimizeNoneAttr(D
, *OA
);
2932 else if (const auto *InternalLinkageA
= dyn_cast
<InternalLinkageAttr
>(Attr
))
2933 NewAttr
= S
.mergeInternalLinkageAttr(D
, *InternalLinkageA
);
2934 else if (isa
<AlignedAttr
>(Attr
))
2935 // AlignedAttrs are handled separately, because we need to handle all
2936 // such attributes on a declaration at the same time.
2938 else if ((isa
<DeprecatedAttr
>(Attr
) || isa
<UnavailableAttr
>(Attr
)) &&
2939 (AMK
== Sema::AMK_Override
||
2940 AMK
== Sema::AMK_ProtocolImplementation
||
2941 AMK
== Sema::AMK_OptionalProtocolImplementation
))
2943 else if (const auto *UA
= dyn_cast
<UuidAttr
>(Attr
))
2944 NewAttr
= S
.mergeUuidAttr(D
, *UA
, UA
->getGuid(), UA
->getGuidDecl());
2945 else if (const auto *IMA
= dyn_cast
<WebAssemblyImportModuleAttr
>(Attr
))
2946 NewAttr
= S
.mergeImportModuleAttr(D
, *IMA
);
2947 else if (const auto *INA
= dyn_cast
<WebAssemblyImportNameAttr
>(Attr
))
2948 NewAttr
= S
.mergeImportNameAttr(D
, *INA
);
2949 else if (const auto *TCBA
= dyn_cast
<EnforceTCBAttr
>(Attr
))
2950 NewAttr
= S
.mergeEnforceTCBAttr(D
, *TCBA
);
2951 else if (const auto *TCBLA
= dyn_cast
<EnforceTCBLeafAttr
>(Attr
))
2952 NewAttr
= S
.mergeEnforceTCBLeafAttr(D
, *TCBLA
);
2953 else if (const auto *BTFA
= dyn_cast
<BTFDeclTagAttr
>(Attr
))
2954 NewAttr
= S
.mergeBTFDeclTagAttr(D
, *BTFA
);
2955 else if (const auto *NT
= dyn_cast
<HLSLNumThreadsAttr
>(Attr
))
2957 S
.mergeHLSLNumThreadsAttr(D
, *NT
, NT
->getX(), NT
->getY(), NT
->getZ());
2958 else if (const auto *SA
= dyn_cast
<HLSLShaderAttr
>(Attr
))
2959 NewAttr
= S
.mergeHLSLShaderAttr(D
, *SA
, SA
->getType());
2960 else if (Attr
->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D
, Attr
))
2961 NewAttr
= cast
<InheritableAttr
>(Attr
->clone(S
.Context
));
2964 NewAttr
->setInherited(true);
2965 D
->addAttr(NewAttr
);
2966 if (isa
<MSInheritanceAttr
>(NewAttr
))
2967 S
.Consumer
.AssignInheritanceModel(cast
<CXXRecordDecl
>(D
));
2974 static const NamedDecl
*getDefinition(const Decl
*D
) {
2975 if (const TagDecl
*TD
= dyn_cast
<TagDecl
>(D
))
2976 return TD
->getDefinition();
2977 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2978 const VarDecl
*Def
= VD
->getDefinition();
2981 return VD
->getActingDefinition();
2983 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
2984 const FunctionDecl
*Def
= nullptr;
2985 if (FD
->isDefined(Def
, true))
2991 static bool hasAttribute(const Decl
*D
, attr::Kind Kind
) {
2992 for (const auto *Attribute
: D
->attrs())
2993 if (Attribute
->getKind() == Kind
)
2998 /// checkNewAttributesAfterDef - If we already have a definition, check that
2999 /// there are no new attributes in this declaration.
3000 static void checkNewAttributesAfterDef(Sema
&S
, Decl
*New
, const Decl
*Old
) {
3001 if (!New
->hasAttrs())
3004 const NamedDecl
*Def
= getDefinition(Old
);
3005 if (!Def
|| Def
== New
)
3008 AttrVec
&NewAttributes
= New
->getAttrs();
3009 for (unsigned I
= 0, E
= NewAttributes
.size(); I
!= E
;) {
3010 const Attr
*NewAttribute
= NewAttributes
[I
];
3012 if (isa
<AliasAttr
>(NewAttribute
) || isa
<IFuncAttr
>(NewAttribute
)) {
3013 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(New
)) {
3014 Sema::SkipBodyInfo SkipBody
;
3015 S
.CheckForFunctionRedefinition(FD
, cast
<FunctionDecl
>(Def
), &SkipBody
);
3017 // If we're skipping this definition, drop the "alias" attribute.
3018 if (SkipBody
.ShouldSkip
) {
3019 NewAttributes
.erase(NewAttributes
.begin() + I
);
3024 VarDecl
*VD
= cast
<VarDecl
>(New
);
3025 unsigned Diag
= cast
<VarDecl
>(Def
)->isThisDeclarationADefinition() ==
3026 VarDecl::TentativeDefinition
3027 ? diag::err_alias_after_tentative
3028 : diag::err_redefinition
;
3029 S
.Diag(VD
->getLocation(), Diag
) << VD
->getDeclName();
3030 if (Diag
== diag::err_redefinition
)
3031 S
.notePreviousDefinition(Def
, VD
->getLocation());
3033 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3034 VD
->setInvalidDecl();
3040 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(Def
)) {
3041 // Tentative definitions are only interesting for the alias check above.
3042 if (VD
->isThisDeclarationADefinition() != VarDecl::Definition
) {
3048 if (hasAttribute(Def
, NewAttribute
->getKind())) {
3050 continue; // regular attr merging will take care of validating this.
3053 if (isa
<C11NoReturnAttr
>(NewAttribute
)) {
3054 // C's _Noreturn is allowed to be added to a function after it is defined.
3057 } else if (isa
<UuidAttr
>(NewAttribute
)) {
3058 // msvc will allow a subsequent definition to add an uuid to a class
3061 } else if (const AlignedAttr
*AA
= dyn_cast
<AlignedAttr
>(NewAttribute
)) {
3062 if (AA
->isAlignas()) {
3063 // C++11 [dcl.align]p6:
3064 // if any declaration of an entity has an alignment-specifier,
3065 // every defining declaration of that entity shall specify an
3066 // equivalent alignment.
3068 // If the definition of an object does not have an alignment
3069 // specifier, any other declaration of that object shall also
3070 // have no alignment specifier.
3071 S
.Diag(Def
->getLocation(), diag::err_alignas_missing_on_definition
)
3073 S
.Diag(NewAttribute
->getLocation(), diag::note_alignas_on_declaration
)
3075 NewAttributes
.erase(NewAttributes
.begin() + I
);
3079 } else if (isa
<LoaderUninitializedAttr
>(NewAttribute
)) {
3080 // If there is a C definition followed by a redeclaration with this
3081 // attribute then there are two different definitions. In C++, prefer the
3082 // standard diagnostics.
3083 if (!S
.getLangOpts().CPlusPlus
) {
3084 S
.Diag(NewAttribute
->getLocation(),
3085 diag::err_loader_uninitialized_redeclaration
);
3086 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3087 NewAttributes
.erase(NewAttributes
.begin() + I
);
3091 } else if (isa
<SelectAnyAttr
>(NewAttribute
) &&
3092 cast
<VarDecl
>(New
)->isInline() &&
3093 !cast
<VarDecl
>(New
)->isInlineSpecified()) {
3094 // Don't warn about applying selectany to implicitly inline variables.
3095 // Older compilers and language modes would require the use of selectany
3096 // to make such variables inline, and it would have no effect if we
3100 } else if (isa
<OMPDeclareVariantAttr
>(NewAttribute
)) {
3101 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3102 // declarations after definitions.
3107 S
.Diag(NewAttribute
->getLocation(),
3108 diag::warn_attribute_precede_definition
);
3109 S
.Diag(Def
->getLocation(), diag::note_previous_definition
);
3110 NewAttributes
.erase(NewAttributes
.begin() + I
);
3115 static void diagnoseMissingConstinit(Sema
&S
, const VarDecl
*InitDecl
,
3116 const ConstInitAttr
*CIAttr
,
3117 bool AttrBeforeInit
) {
3118 SourceLocation InsertLoc
= InitDecl
->getInnerLocStart();
3120 // Figure out a good way to write this specifier on the old declaration.
3121 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3122 // enough of the attribute list spelling information to extract that without
3124 std::string SuitableSpelling
;
3125 if (S
.getLangOpts().CPlusPlus20
)
3126 SuitableSpelling
= std::string(
3127 S
.PP
.getLastMacroWithSpelling(InsertLoc
, {tok::kw_constinit
}));
3128 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus11
)
3129 SuitableSpelling
= std::string(S
.PP
.getLastMacroWithSpelling(
3130 InsertLoc
, {tok::l_square
, tok::l_square
,
3131 S
.PP
.getIdentifierInfo("clang"), tok::coloncolon
,
3132 S
.PP
.getIdentifierInfo("require_constant_initialization"),
3133 tok::r_square
, tok::r_square
}));
3134 if (SuitableSpelling
.empty())
3135 SuitableSpelling
= std::string(S
.PP
.getLastMacroWithSpelling(
3136 InsertLoc
, {tok::kw___attribute
, tok::l_paren
, tok::r_paren
,
3137 S
.PP
.getIdentifierInfo("require_constant_initialization"),
3138 tok::r_paren
, tok::r_paren
}));
3139 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus20
)
3140 SuitableSpelling
= "constinit";
3141 if (SuitableSpelling
.empty() && S
.getLangOpts().CPlusPlus11
)
3142 SuitableSpelling
= "[[clang::require_constant_initialization]]";
3143 if (SuitableSpelling
.empty())
3144 SuitableSpelling
= "__attribute__((require_constant_initialization))";
3145 SuitableSpelling
+= " ";
3147 if (AttrBeforeInit
) {
3148 // extern constinit int a;
3149 // int a = 0; // error (missing 'constinit'), accepted as extension
3150 assert(CIAttr
->isConstinit() && "should not diagnose this for attribute");
3151 S
.Diag(InitDecl
->getLocation(), diag::ext_constinit_missing
)
3152 << InitDecl
<< FixItHint::CreateInsertion(InsertLoc
, SuitableSpelling
);
3153 S
.Diag(CIAttr
->getLocation(), diag::note_constinit_specified_here
);
3156 // constinit extern int a; // error (missing 'constinit')
3157 S
.Diag(CIAttr
->getLocation(),
3158 CIAttr
->isConstinit() ? diag::err_constinit_added_too_late
3159 : diag::warn_require_const_init_added_too_late
)
3160 << FixItHint::CreateRemoval(SourceRange(CIAttr
->getLocation()));
3161 S
.Diag(InitDecl
->getLocation(), diag::note_constinit_missing_here
)
3162 << CIAttr
->isConstinit()
3163 << FixItHint::CreateInsertion(InsertLoc
, SuitableSpelling
);
3167 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3168 void Sema::mergeDeclAttributes(NamedDecl
*New
, Decl
*Old
,
3169 AvailabilityMergeKind AMK
) {
3170 if (UsedAttr
*OldAttr
= Old
->getMostRecentDecl()->getAttr
<UsedAttr
>()) {
3171 UsedAttr
*NewAttr
= OldAttr
->clone(Context
);
3172 NewAttr
->setInherited(true);
3173 New
->addAttr(NewAttr
);
3175 if (RetainAttr
*OldAttr
= Old
->getMostRecentDecl()->getAttr
<RetainAttr
>()) {
3176 RetainAttr
*NewAttr
= OldAttr
->clone(Context
);
3177 NewAttr
->setInherited(true);
3178 New
->addAttr(NewAttr
);
3181 if (!Old
->hasAttrs() && !New
->hasAttrs())
3184 // [dcl.constinit]p1:
3185 // If the [constinit] specifier is applied to any declaration of a
3186 // variable, it shall be applied to the initializing declaration.
3187 const auto *OldConstInit
= Old
->getAttr
<ConstInitAttr
>();
3188 const auto *NewConstInit
= New
->getAttr
<ConstInitAttr
>();
3189 if (bool(OldConstInit
) != bool(NewConstInit
)) {
3190 const auto *OldVD
= cast
<VarDecl
>(Old
);
3191 auto *NewVD
= cast
<VarDecl
>(New
);
3193 // Find the initializing declaration. Note that we might not have linked
3194 // the new declaration into the redeclaration chain yet.
3195 const VarDecl
*InitDecl
= OldVD
->getInitializingDeclaration();
3197 (NewVD
->hasInit() || NewVD
->isThisDeclarationADefinition()))
3200 if (InitDecl
== NewVD
) {
3201 // This is the initializing declaration. If it would inherit 'constinit',
3202 // that's ill-formed. (Note that we do not apply this to the attribute
3204 if (OldConstInit
&& OldConstInit
->isConstinit())
3205 diagnoseMissingConstinit(*this, NewVD
, OldConstInit
,
3206 /*AttrBeforeInit=*/true);
3207 } else if (NewConstInit
) {
3208 // This is the first time we've been told that this declaration should
3209 // have a constant initializer. If we already saw the initializing
3210 // declaration, this is too late.
3211 if (InitDecl
&& InitDecl
!= NewVD
) {
3212 diagnoseMissingConstinit(*this, InitDecl
, NewConstInit
,
3213 /*AttrBeforeInit=*/false);
3214 NewVD
->dropAttr
<ConstInitAttr
>();
3219 // Attributes declared post-definition are currently ignored.
3220 checkNewAttributesAfterDef(*this, New
, Old
);
3222 if (AsmLabelAttr
*NewA
= New
->getAttr
<AsmLabelAttr
>()) {
3223 if (AsmLabelAttr
*OldA
= Old
->getAttr
<AsmLabelAttr
>()) {
3224 if (!OldA
->isEquivalent(NewA
)) {
3225 // This redeclaration changes __asm__ label.
3226 Diag(New
->getLocation(), diag::err_different_asm_label
);
3227 Diag(OldA
->getLocation(), diag::note_previous_declaration
);
3229 } else if (Old
->isUsed()) {
3230 // This redeclaration adds an __asm__ label to a declaration that has
3231 // already been ODR-used.
3232 Diag(New
->getLocation(), diag::err_late_asm_label_name
)
3233 << isa
<FunctionDecl
>(Old
) << New
->getAttr
<AsmLabelAttr
>()->getRange();
3237 // Re-declaration cannot add abi_tag's.
3238 if (const auto *NewAbiTagAttr
= New
->getAttr
<AbiTagAttr
>()) {
3239 if (const auto *OldAbiTagAttr
= Old
->getAttr
<AbiTagAttr
>()) {
3240 for (const auto &NewTag
: NewAbiTagAttr
->tags()) {
3241 if (!llvm::is_contained(OldAbiTagAttr
->tags(), NewTag
)) {
3242 Diag(NewAbiTagAttr
->getLocation(),
3243 diag::err_new_abi_tag_on_redeclaration
)
3245 Diag(OldAbiTagAttr
->getLocation(), diag::note_previous_declaration
);
3249 Diag(NewAbiTagAttr
->getLocation(), diag::err_abi_tag_on_redeclaration
);
3250 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3254 // This redeclaration adds a section attribute.
3255 if (New
->hasAttr
<SectionAttr
>() && !Old
->hasAttr
<SectionAttr
>()) {
3256 if (auto *VD
= dyn_cast
<VarDecl
>(New
)) {
3257 if (VD
->isThisDeclarationADefinition() == VarDecl::DeclarationOnly
) {
3258 Diag(New
->getLocation(), diag::warn_attribute_section_on_redeclaration
);
3259 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3264 // Redeclaration adds code-seg attribute.
3265 const auto *NewCSA
= New
->getAttr
<CodeSegAttr
>();
3266 if (NewCSA
&& !Old
->hasAttr
<CodeSegAttr
>() &&
3267 !NewCSA
->isImplicit() && isa
<CXXMethodDecl
>(New
)) {
3268 Diag(New
->getLocation(), diag::warn_mismatched_section
)
3270 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3273 if (!Old
->hasAttrs())
3276 bool foundAny
= New
->hasAttrs();
3278 // Ensure that any moving of objects within the allocated map is done before
3280 if (!foundAny
) New
->setAttrs(AttrVec());
3282 for (auto *I
: Old
->specific_attrs
<InheritableAttr
>()) {
3283 // Ignore deprecated/unavailable/availability attributes if requested.
3284 AvailabilityMergeKind LocalAMK
= AMK_None
;
3285 if (isa
<DeprecatedAttr
>(I
) ||
3286 isa
<UnavailableAttr
>(I
) ||
3287 isa
<AvailabilityAttr
>(I
)) {
3292 case AMK_Redeclaration
:
3294 case AMK_ProtocolImplementation
:
3295 case AMK_OptionalProtocolImplementation
:
3302 if (isa
<UsedAttr
>(I
) || isa
<RetainAttr
>(I
))
3305 if (mergeDeclAttribute(*this, New
, I
, LocalAMK
))
3309 if (mergeAlignedAttrs(*this, New
, Old
))
3312 if (!foundAny
) New
->dropAttrs();
3315 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3317 static void mergeParamDeclAttributes(ParmVarDecl
*newDecl
,
3318 const ParmVarDecl
*oldDecl
,
3320 // C++11 [dcl.attr.depend]p2:
3321 // The first declaration of a function shall specify the
3322 // carries_dependency attribute for its declarator-id if any declaration
3323 // of the function specifies the carries_dependency attribute.
3324 const CarriesDependencyAttr
*CDA
= newDecl
->getAttr
<CarriesDependencyAttr
>();
3325 if (CDA
&& !oldDecl
->hasAttr
<CarriesDependencyAttr
>()) {
3326 S
.Diag(CDA
->getLocation(),
3327 diag::err_carries_dependency_missing_on_first_decl
) << 1/*Param*/;
3328 // Find the first declaration of the parameter.
3329 // FIXME: Should we build redeclaration chains for function parameters?
3330 const FunctionDecl
*FirstFD
=
3331 cast
<FunctionDecl
>(oldDecl
->getDeclContext())->getFirstDecl();
3332 const ParmVarDecl
*FirstVD
=
3333 FirstFD
->getParamDecl(oldDecl
->getFunctionScopeIndex());
3334 S
.Diag(FirstVD
->getLocation(),
3335 diag::note_carries_dependency_missing_first_decl
) << 1/*Param*/;
3338 if (!oldDecl
->hasAttrs())
3341 bool foundAny
= newDecl
->hasAttrs();
3343 // Ensure that any moving of objects within the allocated map is
3344 // done before we process them.
3345 if (!foundAny
) newDecl
->setAttrs(AttrVec());
3347 for (const auto *I
: oldDecl
->specific_attrs
<InheritableParamAttr
>()) {
3348 if (!DeclHasAttr(newDecl
, I
)) {
3349 InheritableAttr
*newAttr
=
3350 cast
<InheritableParamAttr
>(I
->clone(S
.Context
));
3351 newAttr
->setInherited(true);
3352 newDecl
->addAttr(newAttr
);
3357 if (!foundAny
) newDecl
->dropAttrs();
3360 static bool EquivalentArrayTypes(QualType Old
, QualType New
,
3361 const ASTContext
&Ctx
) {
3363 auto NoSizeInfo
= [&Ctx
](QualType Ty
) {
3364 if (Ty
->isIncompleteArrayType() || Ty
->isPointerType())
3366 if (const auto *VAT
= Ctx
.getAsVariableArrayType(Ty
))
3367 return VAT
->getSizeModifier() == ArrayType::ArraySizeModifier::Star
;
3371 // `type[]` is equivalent to `type *` and `type[*]`.
3372 if (NoSizeInfo(Old
) && NoSizeInfo(New
))
3375 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3376 if (Old
->isVariableArrayType() && New
->isVariableArrayType()) {
3377 const auto *OldVAT
= Ctx
.getAsVariableArrayType(Old
);
3378 const auto *NewVAT
= Ctx
.getAsVariableArrayType(New
);
3379 if ((OldVAT
->getSizeModifier() == ArrayType::ArraySizeModifier::Star
) ^
3380 (NewVAT
->getSizeModifier() == ArrayType::ArraySizeModifier::Star
))
3385 // Only compare size, ignore Size modifiers and CVR.
3386 if (Old
->isConstantArrayType() && New
->isConstantArrayType()) {
3387 return Ctx
.getAsConstantArrayType(Old
)->getSize() ==
3388 Ctx
.getAsConstantArrayType(New
)->getSize();
3391 // Don't try to compare dependent sized array
3392 if (Old
->isDependentSizedArrayType() && New
->isDependentSizedArrayType()) {
3399 static void mergeParamDeclTypes(ParmVarDecl
*NewParam
,
3400 const ParmVarDecl
*OldParam
,
3402 if (auto Oldnullability
= OldParam
->getType()->getNullability()) {
3403 if (auto Newnullability
= NewParam
->getType()->getNullability()) {
3404 if (*Oldnullability
!= *Newnullability
) {
3405 S
.Diag(NewParam
->getLocation(), diag::warn_mismatched_nullability_attr
)
3406 << DiagNullabilityKind(
3408 ((NewParam
->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
3410 << DiagNullabilityKind(
3412 ((OldParam
->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
3414 S
.Diag(OldParam
->getLocation(), diag::note_previous_declaration
);
3417 QualType NewT
= NewParam
->getType();
3418 NewT
= S
.Context
.getAttributedType(
3419 AttributedType::getNullabilityAttrKind(*Oldnullability
),
3421 NewParam
->setType(NewT
);
3424 const auto *OldParamDT
= dyn_cast
<DecayedType
>(OldParam
->getType());
3425 const auto *NewParamDT
= dyn_cast
<DecayedType
>(NewParam
->getType());
3426 if (OldParamDT
&& NewParamDT
&&
3427 OldParamDT
->getPointeeType() == NewParamDT
->getPointeeType()) {
3428 QualType OldParamOT
= OldParamDT
->getOriginalType();
3429 QualType NewParamOT
= NewParamDT
->getOriginalType();
3430 if (!EquivalentArrayTypes(OldParamOT
, NewParamOT
, S
.getASTContext())) {
3431 S
.Diag(NewParam
->getLocation(), diag::warn_inconsistent_array_form
)
3432 << NewParam
<< NewParamOT
;
3433 S
.Diag(OldParam
->getLocation(), diag::note_previous_declaration_as
)
3441 /// Used in MergeFunctionDecl to keep track of function parameters in
3443 struct GNUCompatibleParamWarning
{
3444 ParmVarDecl
*OldParm
;
3445 ParmVarDecl
*NewParm
;
3446 QualType PromotedType
;
3449 } // end anonymous namespace
3451 // Determine whether the previous declaration was a definition, implicit
3452 // declaration, or a declaration.
3453 template <typename T
>
3454 static std::pair
<diag::kind
, SourceLocation
>
3455 getNoteDiagForInvalidRedeclaration(const T
*Old
, const T
*New
) {
3456 diag::kind PrevDiag
;
3457 SourceLocation OldLocation
= Old
->getLocation();
3458 if (Old
->isThisDeclarationADefinition())
3459 PrevDiag
= diag::note_previous_definition
;
3460 else if (Old
->isImplicit()) {
3461 PrevDiag
= diag::note_previous_implicit_declaration
;
3462 if (const auto *FD
= dyn_cast
<FunctionDecl
>(Old
)) {
3463 if (FD
->getBuiltinID())
3464 PrevDiag
= diag::note_previous_builtin_declaration
;
3466 if (OldLocation
.isInvalid())
3467 OldLocation
= New
->getLocation();
3469 PrevDiag
= diag::note_previous_declaration
;
3470 return std::make_pair(PrevDiag
, OldLocation
);
3473 /// canRedefineFunction - checks if a function can be redefined. Currently,
3474 /// only extern inline functions can be redefined, and even then only in
3476 static bool canRedefineFunction(const FunctionDecl
*FD
,
3477 const LangOptions
& LangOpts
) {
3478 return ((FD
->hasAttr
<GNUInlineAttr
>() || LangOpts
.GNUInline
) &&
3479 !LangOpts
.CPlusPlus
&&
3480 FD
->isInlineSpecified() &&
3481 FD
->getStorageClass() == SC_Extern
);
3484 const AttributedType
*Sema::getCallingConvAttributedType(QualType T
) const {
3485 const AttributedType
*AT
= T
->getAs
<AttributedType
>();
3486 while (AT
&& !AT
->isCallingConv())
3487 AT
= AT
->getModifiedType()->getAs
<AttributedType
>();
3491 template <typename T
>
3492 static bool haveIncompatibleLanguageLinkages(const T
*Old
, const T
*New
) {
3493 const DeclContext
*DC
= Old
->getDeclContext();
3497 LanguageLinkage OldLinkage
= Old
->getLanguageLinkage();
3498 if (OldLinkage
== CXXLanguageLinkage
&& New
->isInExternCContext())
3500 if (OldLinkage
== CLanguageLinkage
&& New
->isInExternCXXContext())
3505 template<typename T
> static bool isExternC(T
*D
) { return D
->isExternC(); }
3506 static bool isExternC(VarTemplateDecl
*) { return false; }
3507 static bool isExternC(FunctionTemplateDecl
*) { return false; }
3509 /// Check whether a redeclaration of an entity introduced by a
3510 /// using-declaration is valid, given that we know it's not an overload
3511 /// (nor a hidden tag declaration).
3512 template<typename ExpectedDecl
>
3513 static bool checkUsingShadowRedecl(Sema
&S
, UsingShadowDecl
*OldS
,
3514 ExpectedDecl
*New
) {
3515 // C++11 [basic.scope.declarative]p4:
3516 // Given a set of declarations in a single declarative region, each of
3517 // which specifies the same unqualified name,
3518 // -- they shall all refer to the same entity, or all refer to functions
3519 // and function templates; or
3520 // -- exactly one declaration shall declare a class name or enumeration
3521 // name that is not a typedef name and the other declarations shall all
3522 // refer to the same variable or enumerator, or all refer to functions
3523 // and function templates; in this case the class name or enumeration
3524 // name is hidden (3.3.10).
3526 // C++11 [namespace.udecl]p14:
3527 // If a function declaration in namespace scope or block scope has the
3528 // same name and the same parameter-type-list as a function introduced
3529 // by a using-declaration, and the declarations do not declare the same
3530 // function, the program is ill-formed.
3532 auto *Old
= dyn_cast
<ExpectedDecl
>(OldS
->getTargetDecl());
3534 !Old
->getDeclContext()->getRedeclContext()->Equals(
3535 New
->getDeclContext()->getRedeclContext()) &&
3536 !(isExternC(Old
) && isExternC(New
)))
3540 S
.Diag(New
->getLocation(), diag::err_using_decl_conflict_reverse
);
3541 S
.Diag(OldS
->getTargetDecl()->getLocation(), diag::note_using_decl_target
);
3542 S
.Diag(OldS
->getIntroducer()->getLocation(), diag::note_using_decl
) << 0;
3548 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl
*A
,
3549 const FunctionDecl
*B
) {
3550 assert(A
->getNumParams() == B
->getNumParams());
3552 auto AttrEq
= [](const ParmVarDecl
*A
, const ParmVarDecl
*B
) {
3553 const auto *AttrA
= A
->getAttr
<PassObjectSizeAttr
>();
3554 const auto *AttrB
= B
->getAttr
<PassObjectSizeAttr
>();
3557 return AttrA
&& AttrB
&& AttrA
->getType() == AttrB
->getType() &&
3558 AttrA
->isDynamic() == AttrB
->isDynamic();
3561 return std::equal(A
->param_begin(), A
->param_end(), B
->param_begin(), AttrEq
);
3564 /// If necessary, adjust the semantic declaration context for a qualified
3565 /// declaration to name the correct inline namespace within the qualifier.
3566 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl
*NewD
,
3567 DeclaratorDecl
*OldD
) {
3568 // The only case where we need to update the DeclContext is when
3569 // redeclaration lookup for a qualified name finds a declaration
3570 // in an inline namespace within the context named by the qualifier:
3572 // inline namespace N { int f(); }
3573 // int ::f(); // Sema DC needs adjusting from :: to N::.
3575 // For unqualified declarations, the semantic context *can* change
3576 // along the redeclaration chain (for local extern declarations,
3577 // extern "C" declarations, and friend declarations in particular).
3578 if (!NewD
->getQualifier())
3581 // NewD is probably already in the right context.
3582 auto *NamedDC
= NewD
->getDeclContext()->getRedeclContext();
3583 auto *SemaDC
= OldD
->getDeclContext()->getRedeclContext();
3584 if (NamedDC
->Equals(SemaDC
))
3587 assert((NamedDC
->InEnclosingNamespaceSetOf(SemaDC
) ||
3588 NewD
->isInvalidDecl() || OldD
->isInvalidDecl()) &&
3589 "unexpected context for redeclaration");
3591 auto *LexDC
= NewD
->getLexicalDeclContext();
3592 auto FixSemaDC
= [=](NamedDecl
*D
) {
3595 D
->setDeclContext(SemaDC
);
3596 D
->setLexicalDeclContext(LexDC
);
3600 if (auto *FD
= dyn_cast
<FunctionDecl
>(NewD
))
3601 FixSemaDC(FD
->getDescribedFunctionTemplate());
3602 else if (auto *VD
= dyn_cast
<VarDecl
>(NewD
))
3603 FixSemaDC(VD
->getDescribedVarTemplate());
3606 /// MergeFunctionDecl - We just parsed a function 'New' from
3607 /// declarator D which has the same name and scope as a previous
3608 /// declaration 'Old'. Figure out how to resolve this situation,
3609 /// merging decls or emitting diagnostics as appropriate.
3611 /// In C++, New and Old must be declarations that are not
3612 /// overloaded. Use IsOverload to determine whether New and Old are
3613 /// overloaded, and to select the Old declaration that New should be
3616 /// Returns true if there was an error, false otherwise.
3617 bool Sema::MergeFunctionDecl(FunctionDecl
*New
, NamedDecl
*&OldD
, Scope
*S
,
3618 bool MergeTypeWithOld
, bool NewDeclIsDefn
) {
3619 // Verify the old decl was also a function.
3620 FunctionDecl
*Old
= OldD
->getAsFunction();
3622 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(OldD
)) {
3623 if (New
->getFriendObjectKind()) {
3624 Diag(New
->getLocation(), diag::err_using_decl_friend
);
3625 Diag(Shadow
->getTargetDecl()->getLocation(),
3626 diag::note_using_decl_target
);
3627 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
)
3632 // Check whether the two declarations might declare the same function or
3633 // function template.
3634 if (FunctionTemplateDecl
*NewTemplate
=
3635 New
->getDescribedFunctionTemplate()) {
3636 if (checkUsingShadowRedecl
<FunctionTemplateDecl
>(*this, Shadow
,
3639 OldD
= Old
= cast
<FunctionTemplateDecl
>(Shadow
->getTargetDecl())
3642 if (checkUsingShadowRedecl
<FunctionDecl
>(*this, Shadow
, New
))
3644 OldD
= Old
= cast
<FunctionDecl
>(Shadow
->getTargetDecl());
3647 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
3648 << New
->getDeclName();
3649 notePreviousDefinition(OldD
, New
->getLocation());
3654 // If the old declaration was found in an inline namespace and the new
3655 // declaration was qualified, update the DeclContext to match.
3656 adjustDeclContextForDeclaratorDecl(New
, Old
);
3658 // If the old declaration is invalid, just give up here.
3659 if (Old
->isInvalidDecl())
3662 // Disallow redeclaration of some builtins.
3663 if (!getASTContext().canBuiltinBeRedeclared(Old
)) {
3664 Diag(New
->getLocation(), diag::err_builtin_redeclare
) << Old
->getDeclName();
3665 Diag(Old
->getLocation(), diag::note_previous_builtin_declaration
)
3666 << Old
<< Old
->getType();
3670 diag::kind PrevDiag
;
3671 SourceLocation OldLocation
;
3672 std::tie(PrevDiag
, OldLocation
) =
3673 getNoteDiagForInvalidRedeclaration(Old
, New
);
3675 // Don't complain about this if we're in GNU89 mode and the old function
3676 // is an extern inline function.
3677 // Don't complain about specializations. They are not supposed to have
3679 if (!isa
<CXXMethodDecl
>(New
) && !isa
<CXXMethodDecl
>(Old
) &&
3680 New
->getStorageClass() == SC_Static
&&
3681 Old
->hasExternalFormalLinkage() &&
3682 !New
->getTemplateSpecializationInfo() &&
3683 !canRedefineFunction(Old
, getLangOpts())) {
3684 if (getLangOpts().MicrosoftExt
) {
3685 Diag(New
->getLocation(), diag::ext_static_non_static
) << New
;
3686 Diag(OldLocation
, PrevDiag
);
3688 Diag(New
->getLocation(), diag::err_static_non_static
) << New
;
3689 Diag(OldLocation
, PrevDiag
);
3694 if (const auto *ILA
= New
->getAttr
<InternalLinkageAttr
>())
3695 if (!Old
->hasAttr
<InternalLinkageAttr
>()) {
3696 Diag(New
->getLocation(), diag::err_attribute_missing_on_first_decl
)
3698 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3699 New
->dropAttr
<InternalLinkageAttr
>();
3702 if (auto *EA
= New
->getAttr
<ErrorAttr
>()) {
3703 if (!Old
->hasAttr
<ErrorAttr
>()) {
3704 Diag(EA
->getLocation(), diag::err_attribute_missing_on_first_decl
) << EA
;
3705 Diag(Old
->getLocation(), diag::note_previous_declaration
);
3706 New
->dropAttr
<ErrorAttr
>();
3710 if (CheckRedeclarationInModule(New
, Old
))
3713 if (!getLangOpts().CPlusPlus
) {
3714 bool OldOvl
= Old
->hasAttr
<OverloadableAttr
>();
3715 if (OldOvl
!= New
->hasAttr
<OverloadableAttr
>() && !Old
->isImplicit()) {
3716 Diag(New
->getLocation(), diag::err_attribute_overloadable_mismatch
)
3719 // Try our best to find a decl that actually has the overloadable
3720 // attribute for the note. In most cases (e.g. programs with only one
3721 // broken declaration/definition), this won't matter.
3723 // FIXME: We could do this if we juggled some extra state in
3724 // OverloadableAttr, rather than just removing it.
3725 const Decl
*DiagOld
= Old
;
3727 auto OldIter
= llvm::find_if(Old
->redecls(), [](const Decl
*D
) {
3728 const auto *A
= D
->getAttr
<OverloadableAttr
>();
3729 return A
&& !A
->isImplicit();
3731 // If we've implicitly added *all* of the overloadable attrs to this
3732 // chain, emitting a "previous redecl" note is pointless.
3733 DiagOld
= OldIter
== Old
->redecls_end() ? nullptr : *OldIter
;
3737 Diag(DiagOld
->getLocation(),
3738 diag::note_attribute_overloadable_prev_overload
)
3742 New
->addAttr(OverloadableAttr::CreateImplicit(Context
));
3744 New
->dropAttr
<OverloadableAttr
>();
3748 // If a function is first declared with a calling convention, but is later
3749 // declared or defined without one, all following decls assume the calling
3750 // convention of the first.
3752 // It's OK if a function is first declared without a calling convention,
3753 // but is later declared or defined with the default calling convention.
3755 // To test if either decl has an explicit calling convention, we look for
3756 // AttributedType sugar nodes on the type as written. If they are missing or
3757 // were canonicalized away, we assume the calling convention was implicit.
3759 // Note also that we DO NOT return at this point, because we still have
3760 // other tests to run.
3761 QualType OldQType
= Context
.getCanonicalType(Old
->getType());
3762 QualType NewQType
= Context
.getCanonicalType(New
->getType());
3763 const FunctionType
*OldType
= cast
<FunctionType
>(OldQType
);
3764 const FunctionType
*NewType
= cast
<FunctionType
>(NewQType
);
3765 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
3766 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
3767 bool RequiresAdjustment
= false;
3769 if (OldTypeInfo
.getCC() != NewTypeInfo
.getCC()) {
3770 FunctionDecl
*First
= Old
->getFirstDecl();
3771 const FunctionType
*FT
=
3772 First
->getType().getCanonicalType()->castAs
<FunctionType
>();
3773 FunctionType::ExtInfo FI
= FT
->getExtInfo();
3774 bool NewCCExplicit
= getCallingConvAttributedType(New
->getType());
3775 if (!NewCCExplicit
) {
3776 // Inherit the CC from the previous declaration if it was specified
3777 // there but not here.
3778 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
3779 RequiresAdjustment
= true;
3780 } else if (Old
->getBuiltinID()) {
3781 // Builtin attribute isn't propagated to the new one yet at this point,
3782 // so we check if the old one is a builtin.
3784 // Calling Conventions on a Builtin aren't really useful and setting a
3785 // default calling convention and cdecl'ing some builtin redeclarations is
3786 // common, so warn and ignore the calling convention on the redeclaration.
3787 Diag(New
->getLocation(), diag::warn_cconv_unsupported
)
3788 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
3789 << (int)CallingConventionIgnoredReason::BuiltinFunction
;
3790 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
3791 RequiresAdjustment
= true;
3793 // Calling conventions aren't compatible, so complain.
3794 bool FirstCCExplicit
= getCallingConvAttributedType(First
->getType());
3795 Diag(New
->getLocation(), diag::err_cconv_change
)
3796 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
3798 << (!FirstCCExplicit
? "" :
3799 FunctionType::getNameForCallConv(FI
.getCC()));
3801 // Put the note on the first decl, since it is the one that matters.
3802 Diag(First
->getLocation(), diag::note_previous_declaration
);
3807 // FIXME: diagnose the other way around?
3808 if (OldTypeInfo
.getNoReturn() && !NewTypeInfo
.getNoReturn()) {
3809 NewTypeInfo
= NewTypeInfo
.withNoReturn(true);
3810 RequiresAdjustment
= true;
3813 // Merge regparm attribute.
3814 if (OldTypeInfo
.getHasRegParm() != NewTypeInfo
.getHasRegParm() ||
3815 OldTypeInfo
.getRegParm() != NewTypeInfo
.getRegParm()) {
3816 if (NewTypeInfo
.getHasRegParm()) {
3817 Diag(New
->getLocation(), diag::err_regparm_mismatch
)
3818 << NewType
->getRegParmType()
3819 << OldType
->getRegParmType();
3820 Diag(OldLocation
, diag::note_previous_declaration
);
3824 NewTypeInfo
= NewTypeInfo
.withRegParm(OldTypeInfo
.getRegParm());
3825 RequiresAdjustment
= true;
3828 // Merge ns_returns_retained attribute.
3829 if (OldTypeInfo
.getProducesResult() != NewTypeInfo
.getProducesResult()) {
3830 if (NewTypeInfo
.getProducesResult()) {
3831 Diag(New
->getLocation(), diag::err_function_attribute_mismatch
)
3832 << "'ns_returns_retained'";
3833 Diag(OldLocation
, diag::note_previous_declaration
);
3837 NewTypeInfo
= NewTypeInfo
.withProducesResult(true);
3838 RequiresAdjustment
= true;
3841 if (OldTypeInfo
.getNoCallerSavedRegs() !=
3842 NewTypeInfo
.getNoCallerSavedRegs()) {
3843 if (NewTypeInfo
.getNoCallerSavedRegs()) {
3844 AnyX86NoCallerSavedRegistersAttr
*Attr
=
3845 New
->getAttr
<AnyX86NoCallerSavedRegistersAttr
>();
3846 Diag(New
->getLocation(), diag::err_function_attribute_mismatch
) << Attr
;
3847 Diag(OldLocation
, diag::note_previous_declaration
);
3851 NewTypeInfo
= NewTypeInfo
.withNoCallerSavedRegs(true);
3852 RequiresAdjustment
= true;
3855 if (RequiresAdjustment
) {
3856 const FunctionType
*AdjustedType
= New
->getType()->getAs
<FunctionType
>();
3857 AdjustedType
= Context
.adjustFunctionType(AdjustedType
, NewTypeInfo
);
3858 New
->setType(QualType(AdjustedType
, 0));
3859 NewQType
= Context
.getCanonicalType(New
->getType());
3862 // If this redeclaration makes the function inline, we may need to add it to
3863 // UndefinedButUsed.
3864 if (!Old
->isInlined() && New
->isInlined() &&
3865 !New
->hasAttr
<GNUInlineAttr
>() &&
3866 !getLangOpts().GNUInline
&&
3867 Old
->isUsed(false) &&
3868 !Old
->isDefined() && !New
->isThisDeclarationADefinition())
3869 UndefinedButUsed
.insert(std::make_pair(Old
->getCanonicalDecl(),
3872 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3874 if (New
->hasAttr
<GNUInlineAttr
>() &&
3875 Old
->isInlined() && !Old
->hasAttr
<GNUInlineAttr
>()) {
3876 UndefinedButUsed
.erase(Old
->getCanonicalDecl());
3879 // If pass_object_size params don't match up perfectly, this isn't a valid
3881 if (Old
->getNumParams() > 0 && Old
->getNumParams() == New
->getNumParams() &&
3882 !hasIdenticalPassObjectSizeAttrs(Old
, New
)) {
3883 Diag(New
->getLocation(), diag::err_different_pass_object_size_params
)
3884 << New
->getDeclName();
3885 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3889 if (getLangOpts().CPlusPlus
) {
3890 // C++1z [over.load]p2
3891 // Certain function declarations cannot be overloaded:
3892 // -- Function declarations that differ only in the return type,
3893 // the exception specification, or both cannot be overloaded.
3895 // Check the exception specifications match. This may recompute the type of
3896 // both Old and New if it resolved exception specifications, so grab the
3897 // types again after this. Because this updates the type, we do this before
3898 // any of the other checks below, which may update the "de facto" NewQType
3899 // but do not necessarily update the type of New.
3900 if (CheckEquivalentExceptionSpec(Old
, New
))
3902 OldQType
= Context
.getCanonicalType(Old
->getType());
3903 NewQType
= Context
.getCanonicalType(New
->getType());
3905 // Go back to the type source info to compare the declared return types,
3906 // per C++1y [dcl.type.auto]p13:
3907 // Redeclarations or specializations of a function or function template
3908 // with a declared return type that uses a placeholder type shall also
3909 // use that placeholder, not a deduced type.
3910 QualType OldDeclaredReturnType
= Old
->getDeclaredReturnType();
3911 QualType NewDeclaredReturnType
= New
->getDeclaredReturnType();
3912 if (!Context
.hasSameType(OldDeclaredReturnType
, NewDeclaredReturnType
) &&
3913 canFullyTypeCheckRedeclaration(New
, Old
, NewDeclaredReturnType
,
3914 OldDeclaredReturnType
)) {
3916 if (NewDeclaredReturnType
->isObjCObjectPointerType() &&
3917 OldDeclaredReturnType
->isObjCObjectPointerType())
3918 // FIXME: This does the wrong thing for a deduced return type.
3919 ResQT
= Context
.mergeObjCGCQualifiers(NewQType
, OldQType
);
3920 if (ResQT
.isNull()) {
3921 if (New
->isCXXClassMember() && New
->isOutOfLine())
3922 Diag(New
->getLocation(), diag::err_member_def_does_not_match_ret_type
)
3923 << New
<< New
->getReturnTypeSourceRange();
3925 Diag(New
->getLocation(), diag::err_ovl_diff_return_type
)
3926 << New
->getReturnTypeSourceRange();
3927 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType()
3928 << Old
->getReturnTypeSourceRange();
3935 QualType OldReturnType
= OldType
->getReturnType();
3936 QualType NewReturnType
= cast
<FunctionType
>(NewQType
)->getReturnType();
3937 if (OldReturnType
!= NewReturnType
) {
3938 // If this function has a deduced return type and has already been
3939 // defined, copy the deduced value from the old declaration.
3940 AutoType
*OldAT
= Old
->getReturnType()->getContainedAutoType();
3941 if (OldAT
&& OldAT
->isDeduced()) {
3942 QualType DT
= OldAT
->getDeducedType();
3944 New
->setType(SubstAutoTypeDependent(New
->getType()));
3945 NewQType
= Context
.getCanonicalType(SubstAutoTypeDependent(NewQType
));
3947 New
->setType(SubstAutoType(New
->getType(), DT
));
3948 NewQType
= Context
.getCanonicalType(SubstAutoType(NewQType
, DT
));
3953 const CXXMethodDecl
*OldMethod
= dyn_cast
<CXXMethodDecl
>(Old
);
3954 CXXMethodDecl
*NewMethod
= dyn_cast
<CXXMethodDecl
>(New
);
3955 if (OldMethod
&& NewMethod
) {
3956 // Preserve triviality.
3957 NewMethod
->setTrivial(OldMethod
->isTrivial());
3959 // MSVC allows explicit template specialization at class scope:
3960 // 2 CXXMethodDecls referring to the same function will be injected.
3961 // We don't want a redeclaration error.
3962 bool IsClassScopeExplicitSpecialization
=
3963 OldMethod
->isFunctionTemplateSpecialization() &&
3964 NewMethod
->isFunctionTemplateSpecialization();
3965 bool isFriend
= NewMethod
->getFriendObjectKind();
3967 if (!isFriend
&& NewMethod
->getLexicalDeclContext()->isRecord() &&
3968 !IsClassScopeExplicitSpecialization
) {
3969 // -- Member function declarations with the same name and the
3970 // same parameter types cannot be overloaded if any of them
3971 // is a static member function declaration.
3972 if (OldMethod
->isStatic() != NewMethod
->isStatic()) {
3973 Diag(New
->getLocation(), diag::err_ovl_static_nonstatic_member
);
3974 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
3978 // C++ [class.mem]p1:
3979 // [...] A member shall not be declared twice in the
3980 // member-specification, except that a nested class or member
3981 // class template can be declared and then later defined.
3982 if (!inTemplateInstantiation()) {
3984 if (isa
<CXXConstructorDecl
>(OldMethod
))
3985 NewDiag
= diag::err_constructor_redeclared
;
3986 else if (isa
<CXXDestructorDecl
>(NewMethod
))
3987 NewDiag
= diag::err_destructor_redeclared
;
3988 else if (isa
<CXXConversionDecl
>(NewMethod
))
3989 NewDiag
= diag::err_conv_function_redeclared
;
3991 NewDiag
= diag::err_member_redeclared
;
3993 Diag(New
->getLocation(), NewDiag
);
3995 Diag(New
->getLocation(), diag::err_member_redeclared_in_instantiation
)
3996 << New
<< New
->getType();
3998 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4001 // Complain if this is an explicit declaration of a special
4002 // member that was initially declared implicitly.
4004 // As an exception, it's okay to befriend such methods in order
4005 // to permit the implicit constructor/destructor/operator calls.
4006 } else if (OldMethod
->isImplicit()) {
4008 NewMethod
->setImplicit();
4010 Diag(NewMethod
->getLocation(),
4011 diag::err_definition_of_implicitly_declared_member
)
4012 << New
<< getSpecialMember(OldMethod
);
4015 } else if (OldMethod
->getFirstDecl()->isExplicitlyDefaulted() && !isFriend
) {
4016 Diag(NewMethod
->getLocation(),
4017 diag::err_definition_of_explicitly_defaulted_member
)
4018 << getSpecialMember(OldMethod
);
4023 // C++11 [dcl.attr.noreturn]p1:
4024 // The first declaration of a function shall specify the noreturn
4025 // attribute if any declaration of that function specifies the noreturn
4027 if (const auto *NRA
= New
->getAttr
<CXX11NoReturnAttr
>())
4028 if (!Old
->hasAttr
<CXX11NoReturnAttr
>()) {
4029 Diag(NRA
->getLocation(), diag::err_attribute_missing_on_first_decl
)
4031 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4034 // C++11 [dcl.attr.depend]p2:
4035 // The first declaration of a function shall specify the
4036 // carries_dependency attribute for its declarator-id if any declaration
4037 // of the function specifies the carries_dependency attribute.
4038 const CarriesDependencyAttr
*CDA
= New
->getAttr
<CarriesDependencyAttr
>();
4039 if (CDA
&& !Old
->hasAttr
<CarriesDependencyAttr
>()) {
4040 Diag(CDA
->getLocation(),
4041 diag::err_carries_dependency_missing_on_first_decl
) << 0/*Function*/;
4042 Diag(Old
->getFirstDecl()->getLocation(),
4043 diag::note_carries_dependency_missing_first_decl
) << 0/*Function*/;
4047 // All declarations for a function shall agree exactly in both the
4048 // return type and the parameter-type-list.
4049 // We also want to respect all the extended bits except noreturn.
4051 // noreturn should now match unless the old type info didn't have it.
4052 QualType OldQTypeForComparison
= OldQType
;
4053 if (!OldTypeInfo
.getNoReturn() && NewTypeInfo
.getNoReturn()) {
4054 auto *OldType
= OldQType
->castAs
<FunctionProtoType
>();
4055 const FunctionType
*OldTypeForComparison
4056 = Context
.adjustFunctionType(OldType
, OldTypeInfo
.withNoReturn(true));
4057 OldQTypeForComparison
= QualType(OldTypeForComparison
, 0);
4058 assert(OldQTypeForComparison
.isCanonical());
4061 if (haveIncompatibleLanguageLinkages(Old
, New
)) {
4062 // As a special case, retain the language linkage from previous
4063 // declarations of a friend function as an extension.
4065 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4066 // and is useful because there's otherwise no way to specify language
4067 // linkage within class scope.
4069 // Check cautiously as the friend object kind isn't yet complete.
4070 if (New
->getFriendObjectKind() != Decl::FOK_None
) {
4071 Diag(New
->getLocation(), diag::ext_retained_language_linkage
) << New
;
4072 Diag(OldLocation
, PrevDiag
);
4074 Diag(New
->getLocation(), diag::err_different_language_linkage
) << New
;
4075 Diag(OldLocation
, PrevDiag
);
4080 // If the function types are compatible, merge the declarations. Ignore the
4081 // exception specifier because it was already checked above in
4082 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4083 // about incompatible types under -fms-compatibility.
4084 if (Context
.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison
,
4086 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4088 // If the types are imprecise (due to dependent constructs in friends or
4089 // local extern declarations), it's OK if they differ. We'll check again
4090 // during instantiation.
4091 if (!canFullyTypeCheckRedeclaration(New
, Old
, NewQType
, OldQType
))
4094 // Fall through for conflicting redeclarations and redefinitions.
4097 // C: Function types need to be compatible, not identical. This handles
4098 // duplicate function decls like "void f(int); void f(enum X);" properly.
4099 if (!getLangOpts().CPlusPlus
) {
4100 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4101 // type is specified by a function definition that contains a (possibly
4102 // empty) identifier list, both shall agree in the number of parameters
4103 // and the type of each parameter shall be compatible with the type that
4104 // results from the application of default argument promotions to the
4105 // type of the corresponding identifier. ...
4106 // This cannot be handled by ASTContext::typesAreCompatible() because that
4107 // doesn't know whether the function type is for a definition or not when
4108 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4109 // we need to cover here is that the number of arguments agree as the
4110 // default argument promotion rules were already checked by
4111 // ASTContext::typesAreCompatible().
4112 if (Old
->hasPrototype() && !New
->hasWrittenPrototype() && NewDeclIsDefn
&&
4113 Old
->getNumParams() != New
->getNumParams() && !Old
->isImplicit()) {
4114 if (Old
->hasInheritedPrototype())
4115 Old
= Old
->getCanonicalDecl();
4116 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
;
4117 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
4121 // If we are merging two functions where only one of them has a prototype,
4122 // we may have enough information to decide to issue a diagnostic that the
4123 // function without a protoype will change behavior in C2x. This handles
4125 // void i(); void i(int j);
4126 // void i(int j); void i();
4127 // void i(); void i(int j) {}
4128 // See ActOnFinishFunctionBody() for other cases of the behavior change
4129 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4130 // type without a prototype.
4131 if (New
->hasWrittenPrototype() != Old
->hasWrittenPrototype() &&
4132 !New
->isImplicit() && !Old
->isImplicit()) {
4133 const FunctionDecl
*WithProto
, *WithoutProto
;
4134 if (New
->hasWrittenPrototype()) {
4142 if (WithProto
->getNumParams() != 0) {
4143 if (WithoutProto
->getBuiltinID() == 0 && !WithoutProto
->isImplicit()) {
4144 // The one without the prototype will be changing behavior in C2x, so
4145 // warn about that one so long as it's a user-visible declaration.
4146 bool IsWithoutProtoADef
= false, IsWithProtoADef
= false;
4147 if (WithoutProto
== New
)
4148 IsWithoutProtoADef
= NewDeclIsDefn
;
4150 IsWithProtoADef
= NewDeclIsDefn
;
4151 Diag(WithoutProto
->getLocation(),
4152 diag::warn_non_prototype_changes_behavior
)
4153 << IsWithoutProtoADef
<< (WithoutProto
->getNumParams() ? 0 : 1)
4154 << (WithoutProto
== Old
) << IsWithProtoADef
;
4156 // The reason the one without the prototype will be changing behavior
4157 // is because of the one with the prototype, so note that so long as
4158 // it's a user-visible declaration. There is one exception to this:
4159 // when the new declaration is a definition without a prototype, the
4160 // old declaration with a prototype is not the cause of the issue,
4161 // and that does not need to be noted because the one with a
4162 // prototype will not change behavior in C2x.
4163 if (WithProto
->getBuiltinID() == 0 && !WithProto
->isImplicit() &&
4164 !IsWithoutProtoADef
)
4165 Diag(WithProto
->getLocation(), diag::note_conflicting_prototype
);
4170 if (Context
.typesAreCompatible(OldQType
, NewQType
)) {
4171 const FunctionType
*OldFuncType
= OldQType
->getAs
<FunctionType
>();
4172 const FunctionType
*NewFuncType
= NewQType
->getAs
<FunctionType
>();
4173 const FunctionProtoType
*OldProto
= nullptr;
4174 if (MergeTypeWithOld
&& isa
<FunctionNoProtoType
>(NewFuncType
) &&
4175 (OldProto
= dyn_cast
<FunctionProtoType
>(OldFuncType
))) {
4176 // The old declaration provided a function prototype, but the
4177 // new declaration does not. Merge in the prototype.
4178 assert(!OldProto
->hasExceptionSpec() && "Exception spec in C");
4179 NewQType
= Context
.getFunctionType(NewFuncType
->getReturnType(),
4180 OldProto
->getParamTypes(),
4181 OldProto
->getExtProtoInfo());
4182 New
->setType(NewQType
);
4183 New
->setHasInheritedPrototype();
4185 // Synthesize parameters with the same types.
4186 SmallVector
<ParmVarDecl
*, 16> Params
;
4187 for (const auto &ParamType
: OldProto
->param_types()) {
4188 ParmVarDecl
*Param
= ParmVarDecl::Create(
4189 Context
, New
, SourceLocation(), SourceLocation(), nullptr,
4190 ParamType
, /*TInfo=*/nullptr, SC_None
, nullptr);
4191 Param
->setScopeInfo(0, Params
.size());
4192 Param
->setImplicit();
4193 Params
.push_back(Param
);
4196 New
->setParams(Params
);
4199 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4203 // Check if the function types are compatible when pointer size address
4204 // spaces are ignored.
4205 if (Context
.hasSameFunctionTypeIgnoringPtrSizes(OldQType
, NewQType
))
4208 // GNU C permits a K&R definition to follow a prototype declaration
4209 // if the declared types of the parameters in the K&R definition
4210 // match the types in the prototype declaration, even when the
4211 // promoted types of the parameters from the K&R definition differ
4212 // from the types in the prototype. GCC then keeps the types from
4215 // If a variadic prototype is followed by a non-variadic K&R definition,
4216 // the K&R definition becomes variadic. This is sort of an edge case, but
4217 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4219 if (!getLangOpts().CPlusPlus
&&
4220 Old
->hasPrototype() && !New
->hasPrototype() &&
4221 New
->getType()->getAs
<FunctionProtoType
>() &&
4222 Old
->getNumParams() == New
->getNumParams()) {
4223 SmallVector
<QualType
, 16> ArgTypes
;
4224 SmallVector
<GNUCompatibleParamWarning
, 16> Warnings
;
4225 const FunctionProtoType
*OldProto
4226 = Old
->getType()->getAs
<FunctionProtoType
>();
4227 const FunctionProtoType
*NewProto
4228 = New
->getType()->getAs
<FunctionProtoType
>();
4230 // Determine whether this is the GNU C extension.
4231 QualType MergedReturn
= Context
.mergeTypes(OldProto
->getReturnType(),
4232 NewProto
->getReturnType());
4233 bool LooseCompatible
= !MergedReturn
.isNull();
4234 for (unsigned Idx
= 0, End
= Old
->getNumParams();
4235 LooseCompatible
&& Idx
!= End
; ++Idx
) {
4236 ParmVarDecl
*OldParm
= Old
->getParamDecl(Idx
);
4237 ParmVarDecl
*NewParm
= New
->getParamDecl(Idx
);
4238 if (Context
.typesAreCompatible(OldParm
->getType(),
4239 NewProto
->getParamType(Idx
))) {
4240 ArgTypes
.push_back(NewParm
->getType());
4241 } else if (Context
.typesAreCompatible(OldParm
->getType(),
4243 /*CompareUnqualified=*/true)) {
4244 GNUCompatibleParamWarning Warn
= { OldParm
, NewParm
,
4245 NewProto
->getParamType(Idx
) };
4246 Warnings
.push_back(Warn
);
4247 ArgTypes
.push_back(NewParm
->getType());
4249 LooseCompatible
= false;
4252 if (LooseCompatible
) {
4253 for (unsigned Warn
= 0; Warn
< Warnings
.size(); ++Warn
) {
4254 Diag(Warnings
[Warn
].NewParm
->getLocation(),
4255 diag::ext_param_promoted_not_compatible_with_prototype
)
4256 << Warnings
[Warn
].PromotedType
4257 << Warnings
[Warn
].OldParm
->getType();
4258 if (Warnings
[Warn
].OldParm
->getLocation().isValid())
4259 Diag(Warnings
[Warn
].OldParm
->getLocation(),
4260 diag::note_previous_declaration
);
4263 if (MergeTypeWithOld
)
4264 New
->setType(Context
.getFunctionType(MergedReturn
, ArgTypes
,
4265 OldProto
->getExtProtoInfo()));
4266 return MergeCompatibleFunctionDecls(New
, Old
, S
, MergeTypeWithOld
);
4269 // Fall through to diagnose conflicting types.
4272 // A function that has already been declared has been redeclared or
4273 // defined with a different type; show an appropriate diagnostic.
4275 // If the previous declaration was an implicitly-generated builtin
4276 // declaration, then at the very least we should use a specialized note.
4278 if (Old
->isImplicit() && (BuiltinID
= Old
->getBuiltinID())) {
4279 // If it's actually a library-defined builtin function like 'malloc'
4280 // or 'printf', just warn about the incompatible redeclaration.
4281 if (Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
)) {
4282 Diag(New
->getLocation(), diag::warn_redecl_library_builtin
) << New
;
4283 Diag(OldLocation
, diag::note_previous_builtin_declaration
)
4284 << Old
<< Old
->getType();
4288 PrevDiag
= diag::note_previous_builtin_declaration
;
4291 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
->getDeclName();
4292 Diag(OldLocation
, PrevDiag
) << Old
<< Old
->getType();
4296 /// Completes the merge of two function declarations that are
4297 /// known to be compatible.
4299 /// This routine handles the merging of attributes and other
4300 /// properties of function declarations from the old declaration to
4301 /// the new declaration, once we know that New is in fact a
4302 /// redeclaration of Old.
4305 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl
*New
, FunctionDecl
*Old
,
4306 Scope
*S
, bool MergeTypeWithOld
) {
4307 // Merge the attributes
4308 mergeDeclAttributes(New
, Old
);
4310 // Merge "pure" flag.
4314 // Merge "used" flag.
4315 if (Old
->getMostRecentDecl()->isUsed(false))
4318 // Merge attributes from the parameters. These can mismatch with K&R
4320 if (New
->getNumParams() == Old
->getNumParams())
4321 for (unsigned i
= 0, e
= New
->getNumParams(); i
!= e
; ++i
) {
4322 ParmVarDecl
*NewParam
= New
->getParamDecl(i
);
4323 ParmVarDecl
*OldParam
= Old
->getParamDecl(i
);
4324 mergeParamDeclAttributes(NewParam
, OldParam
, *this);
4325 mergeParamDeclTypes(NewParam
, OldParam
, *this);
4328 if (getLangOpts().CPlusPlus
)
4329 return MergeCXXFunctionDecl(New
, Old
, S
);
4331 // Merge the function types so the we get the composite types for the return
4332 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4334 QualType Merged
= Context
.mergeTypes(Old
->getType(), New
->getType());
4335 if (!Merged
.isNull() && MergeTypeWithOld
)
4336 New
->setType(Merged
);
4341 void Sema::mergeObjCMethodDecls(ObjCMethodDecl
*newMethod
,
4342 ObjCMethodDecl
*oldMethod
) {
4343 // Merge the attributes, including deprecated/unavailable
4344 AvailabilityMergeKind MergeKind
=
4345 isa
<ObjCProtocolDecl
>(oldMethod
->getDeclContext())
4346 ? (oldMethod
->isOptional() ? AMK_OptionalProtocolImplementation
4347 : AMK_ProtocolImplementation
)
4348 : isa
<ObjCImplDecl
>(newMethod
->getDeclContext()) ? AMK_Redeclaration
4351 mergeDeclAttributes(newMethod
, oldMethod
, MergeKind
);
4353 // Merge attributes from the parameters.
4354 ObjCMethodDecl::param_const_iterator oi
= oldMethod
->param_begin(),
4355 oe
= oldMethod
->param_end();
4356 for (ObjCMethodDecl::param_iterator
4357 ni
= newMethod
->param_begin(), ne
= newMethod
->param_end();
4358 ni
!= ne
&& oi
!= oe
; ++ni
, ++oi
)
4359 mergeParamDeclAttributes(*ni
, *oi
, *this);
4361 CheckObjCMethodOverride(newMethod
, oldMethod
);
4364 static void diagnoseVarDeclTypeMismatch(Sema
&S
, VarDecl
*New
, VarDecl
* Old
) {
4365 assert(!S
.Context
.hasSameType(New
->getType(), Old
->getType()));
4367 S
.Diag(New
->getLocation(), New
->isThisDeclarationADefinition()
4368 ? diag::err_redefinition_different_type
4369 : diag::err_redeclaration_different_type
)
4370 << New
->getDeclName() << New
->getType() << Old
->getType();
4372 diag::kind PrevDiag
;
4373 SourceLocation OldLocation
;
4374 std::tie(PrevDiag
, OldLocation
)
4375 = getNoteDiagForInvalidRedeclaration(Old
, New
);
4376 S
.Diag(OldLocation
, PrevDiag
);
4377 New
->setInvalidDecl();
4380 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4381 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4382 /// emitting diagnostics as appropriate.
4384 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4385 /// to here in AddInitializerToDecl. We can't check them before the initializer
4387 void Sema::MergeVarDeclTypes(VarDecl
*New
, VarDecl
*Old
,
4388 bool MergeTypeWithOld
) {
4389 if (New
->isInvalidDecl() || Old
->isInvalidDecl())
4393 if (getLangOpts().CPlusPlus
) {
4394 if (New
->getType()->isUndeducedType()) {
4395 // We don't know what the new type is until the initializer is attached.
4397 } else if (Context
.hasSameType(New
->getType(), Old
->getType())) {
4398 // These could still be something that needs exception specs checked.
4399 return MergeVarDeclExceptionSpecs(New
, Old
);
4401 // C++ [basic.link]p10:
4402 // [...] the types specified by all declarations referring to a given
4403 // object or function shall be identical, except that declarations for an
4404 // array object can specify array types that differ by the presence or
4405 // absence of a major array bound (8.3.4).
4406 else if (Old
->getType()->isArrayType() && New
->getType()->isArrayType()) {
4407 const ArrayType
*OldArray
= Context
.getAsArrayType(Old
->getType());
4408 const ArrayType
*NewArray
= Context
.getAsArrayType(New
->getType());
4410 // We are merging a variable declaration New into Old. If it has an array
4411 // bound, and that bound differs from Old's bound, we should diagnose the
4413 if (!NewArray
->isIncompleteArrayType() && !NewArray
->isDependentType()) {
4414 for (VarDecl
*PrevVD
= Old
->getMostRecentDecl(); PrevVD
;
4415 PrevVD
= PrevVD
->getPreviousDecl()) {
4416 QualType PrevVDTy
= PrevVD
->getType();
4417 if (PrevVDTy
->isIncompleteArrayType() || PrevVDTy
->isDependentType())
4420 if (!Context
.hasSameType(New
->getType(), PrevVDTy
))
4421 return diagnoseVarDeclTypeMismatch(*this, New
, PrevVD
);
4425 if (OldArray
->isIncompleteArrayType() && NewArray
->isArrayType()) {
4426 if (Context
.hasSameType(OldArray
->getElementType(),
4427 NewArray
->getElementType()))
4428 MergedT
= New
->getType();
4430 // FIXME: Check visibility. New is hidden but has a complete type. If New
4431 // has no array bound, it should not inherit one from Old, if Old is not
4433 else if (OldArray
->isArrayType() && NewArray
->isIncompleteArrayType()) {
4434 if (Context
.hasSameType(OldArray
->getElementType(),
4435 NewArray
->getElementType()))
4436 MergedT
= Old
->getType();
4439 else if (New
->getType()->isObjCObjectPointerType() &&
4440 Old
->getType()->isObjCObjectPointerType()) {
4441 MergedT
= Context
.mergeObjCGCQualifiers(New
->getType(),
4446 // All declarations that refer to the same object or function shall have
4448 MergedT
= Context
.mergeTypes(New
->getType(), Old
->getType());
4450 if (MergedT
.isNull()) {
4451 // It's OK if we couldn't merge types if either type is dependent, for a
4452 // block-scope variable. In other cases (static data members of class
4453 // templates, variable templates, ...), we require the types to be
4455 // FIXME: The C++ standard doesn't say anything about this.
4456 if ((New
->getType()->isDependentType() ||
4457 Old
->getType()->isDependentType()) && New
->isLocalVarDecl()) {
4458 // If the old type was dependent, we can't merge with it, so the new type
4459 // becomes dependent for now. We'll reproduce the original type when we
4460 // instantiate the TypeSourceInfo for the variable.
4461 if (!New
->getType()->isDependentType() && MergeTypeWithOld
)
4462 New
->setType(Context
.DependentTy
);
4465 return diagnoseVarDeclTypeMismatch(*this, New
, Old
);
4468 // Don't actually update the type on the new declaration if the old
4469 // declaration was an extern declaration in a different scope.
4470 if (MergeTypeWithOld
)
4471 New
->setType(MergedT
);
4474 static bool mergeTypeWithPrevious(Sema
&S
, VarDecl
*NewVD
, VarDecl
*OldVD
,
4475 LookupResult
&Previous
) {
4477 // For an identifier with internal or external linkage declared
4478 // in a scope in which a prior declaration of that identifier is
4479 // visible, if the prior declaration specifies internal or
4480 // external linkage, the type of the identifier at the later
4481 // declaration becomes the composite type.
4483 // If the variable isn't visible, we do not merge with its type.
4484 if (Previous
.isShadowed())
4487 if (S
.getLangOpts().CPlusPlus
) {
4488 // C++11 [dcl.array]p3:
4489 // If there is a preceding declaration of the entity in the same
4490 // scope in which the bound was specified, an omitted array bound
4491 // is taken to be the same as in that earlier declaration.
4492 return NewVD
->isPreviousDeclInSameBlockScope() ||
4493 (!OldVD
->getLexicalDeclContext()->isFunctionOrMethod() &&
4494 !NewVD
->getLexicalDeclContext()->isFunctionOrMethod());
4496 // If the old declaration was function-local, don't merge with its
4497 // type unless we're in the same function.
4498 return !OldVD
->getLexicalDeclContext()->isFunctionOrMethod() ||
4499 OldVD
->getLexicalDeclContext() == NewVD
->getLexicalDeclContext();
4503 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4504 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4505 /// situation, merging decls or emitting diagnostics as appropriate.
4507 /// Tentative definition rules (C99 6.9.2p2) are checked by
4508 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4509 /// definitions here, since the initializer hasn't been attached.
4511 void Sema::MergeVarDecl(VarDecl
*New
, LookupResult
&Previous
) {
4512 // If the new decl is already invalid, don't do any other checking.
4513 if (New
->isInvalidDecl())
4516 if (!shouldLinkPossiblyHiddenDecl(Previous
, New
))
4519 VarTemplateDecl
*NewTemplate
= New
->getDescribedVarTemplate();
4521 // Verify the old decl was also a variable or variable template.
4522 VarDecl
*Old
= nullptr;
4523 VarTemplateDecl
*OldTemplate
= nullptr;
4524 if (Previous
.isSingleResult()) {
4526 OldTemplate
= dyn_cast
<VarTemplateDecl
>(Previous
.getFoundDecl());
4527 Old
= OldTemplate
? OldTemplate
->getTemplatedDecl() : nullptr;
4530 dyn_cast
<UsingShadowDecl
>(Previous
.getRepresentativeDecl()))
4531 if (checkUsingShadowRedecl
<VarTemplateDecl
>(*this, Shadow
, NewTemplate
))
4532 return New
->setInvalidDecl();
4534 Old
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl());
4537 dyn_cast
<UsingShadowDecl
>(Previous
.getRepresentativeDecl()))
4538 if (checkUsingShadowRedecl
<VarDecl
>(*this, Shadow
, New
))
4539 return New
->setInvalidDecl();
4543 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
4544 << New
->getDeclName();
4545 notePreviousDefinition(Previous
.getRepresentativeDecl(),
4546 New
->getLocation());
4547 return New
->setInvalidDecl();
4550 // If the old declaration was found in an inline namespace and the new
4551 // declaration was qualified, update the DeclContext to match.
4552 adjustDeclContextForDeclaratorDecl(New
, Old
);
4554 // Ensure the template parameters are compatible.
4556 !TemplateParameterListsAreEqual(NewTemplate
->getTemplateParameters(),
4557 OldTemplate
->getTemplateParameters(),
4558 /*Complain=*/true, TPL_TemplateMatch
))
4559 return New
->setInvalidDecl();
4561 // C++ [class.mem]p1:
4562 // A member shall not be declared twice in the member-specification [...]
4564 // Here, we need only consider static data members.
4565 if (Old
->isStaticDataMember() && !New
->isOutOfLine()) {
4566 Diag(New
->getLocation(), diag::err_duplicate_member
)
4567 << New
->getIdentifier();
4568 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4569 New
->setInvalidDecl();
4572 mergeDeclAttributes(New
, Old
);
4573 // Warn if an already-declared variable is made a weak_import in a subsequent
4575 if (New
->hasAttr
<WeakImportAttr
>() &&
4576 Old
->getStorageClass() == SC_None
&&
4577 !Old
->hasAttr
<WeakImportAttr
>()) {
4578 Diag(New
->getLocation(), diag::warn_weak_import
) << New
->getDeclName();
4579 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4580 // Remove weak_import attribute on new declaration.
4581 New
->dropAttr
<WeakImportAttr
>();
4584 if (const auto *ILA
= New
->getAttr
<InternalLinkageAttr
>())
4585 if (!Old
->hasAttr
<InternalLinkageAttr
>()) {
4586 Diag(New
->getLocation(), diag::err_attribute_missing_on_first_decl
)
4588 Diag(Old
->getLocation(), diag::note_previous_declaration
);
4589 New
->dropAttr
<InternalLinkageAttr
>();
4593 VarDecl
*MostRecent
= Old
->getMostRecentDecl();
4594 if (MostRecent
!= Old
) {
4595 MergeVarDeclTypes(New
, MostRecent
,
4596 mergeTypeWithPrevious(*this, New
, MostRecent
, Previous
));
4597 if (New
->isInvalidDecl())
4601 MergeVarDeclTypes(New
, Old
, mergeTypeWithPrevious(*this, New
, Old
, Previous
));
4602 if (New
->isInvalidDecl())
4605 diag::kind PrevDiag
;
4606 SourceLocation OldLocation
;
4607 std::tie(PrevDiag
, OldLocation
) =
4608 getNoteDiagForInvalidRedeclaration(Old
, New
);
4610 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4611 if (New
->getStorageClass() == SC_Static
&&
4612 !New
->isStaticDataMember() &&
4613 Old
->hasExternalFormalLinkage()) {
4614 if (getLangOpts().MicrosoftExt
) {
4615 Diag(New
->getLocation(), diag::ext_static_non_static
)
4616 << New
->getDeclName();
4617 Diag(OldLocation
, PrevDiag
);
4619 Diag(New
->getLocation(), diag::err_static_non_static
)
4620 << New
->getDeclName();
4621 Diag(OldLocation
, PrevDiag
);
4622 return New
->setInvalidDecl();
4626 // For an identifier declared with the storage-class specifier
4627 // extern in a scope in which a prior declaration of that
4628 // identifier is visible,23) if the prior declaration specifies
4629 // internal or external linkage, the linkage of the identifier at
4630 // the later declaration is the same as the linkage specified at
4631 // the prior declaration. If no prior declaration is visible, or
4632 // if the prior declaration specifies no linkage, then the
4633 // identifier has external linkage.
4634 if (New
->hasExternalStorage() && Old
->hasLinkage())
4636 else if (New
->getCanonicalDecl()->getStorageClass() != SC_Static
&&
4637 !New
->isStaticDataMember() &&
4638 Old
->getCanonicalDecl()->getStorageClass() == SC_Static
) {
4639 Diag(New
->getLocation(), diag::err_non_static_static
) << New
->getDeclName();
4640 Diag(OldLocation
, PrevDiag
);
4641 return New
->setInvalidDecl();
4644 // Check if extern is followed by non-extern and vice-versa.
4645 if (New
->hasExternalStorage() &&
4646 !Old
->hasLinkage() && Old
->isLocalVarDeclOrParm()) {
4647 Diag(New
->getLocation(), diag::err_extern_non_extern
) << New
->getDeclName();
4648 Diag(OldLocation
, PrevDiag
);
4649 return New
->setInvalidDecl();
4651 if (Old
->hasLinkage() && New
->isLocalVarDeclOrParm() &&
4652 !New
->hasExternalStorage()) {
4653 Diag(New
->getLocation(), diag::err_non_extern_extern
) << New
->getDeclName();
4654 Diag(OldLocation
, PrevDiag
);
4655 return New
->setInvalidDecl();
4658 if (CheckRedeclarationInModule(New
, Old
))
4661 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4663 // FIXME: The test for external storage here seems wrong? We still
4664 // need to check for mismatches.
4665 if (!New
->hasExternalStorage() && !New
->isFileVarDecl() &&
4666 // Don't complain about out-of-line definitions of static members.
4667 !(Old
->getLexicalDeclContext()->isRecord() &&
4668 !New
->getLexicalDeclContext()->isRecord())) {
4669 Diag(New
->getLocation(), diag::err_redefinition
) << New
->getDeclName();
4670 Diag(OldLocation
, PrevDiag
);
4671 return New
->setInvalidDecl();
4674 if (New
->isInline() && !Old
->getMostRecentDecl()->isInline()) {
4675 if (VarDecl
*Def
= Old
->getDefinition()) {
4676 // C++1z [dcl.fcn.spec]p4:
4677 // If the definition of a variable appears in a translation unit before
4678 // its first declaration as inline, the program is ill-formed.
4679 Diag(New
->getLocation(), diag::err_inline_decl_follows_def
) << New
;
4680 Diag(Def
->getLocation(), diag::note_previous_definition
);
4684 // If this redeclaration makes the variable inline, we may need to add it to
4685 // UndefinedButUsed.
4686 if (!Old
->isInline() && New
->isInline() && Old
->isUsed(false) &&
4687 !Old
->getDefinition() && !New
->isThisDeclarationADefinition())
4688 UndefinedButUsed
.insert(std::make_pair(Old
->getCanonicalDecl(),
4691 if (New
->getTLSKind() != Old
->getTLSKind()) {
4692 if (!Old
->getTLSKind()) {
4693 Diag(New
->getLocation(), diag::err_thread_non_thread
) << New
->getDeclName();
4694 Diag(OldLocation
, PrevDiag
);
4695 } else if (!New
->getTLSKind()) {
4696 Diag(New
->getLocation(), diag::err_non_thread_thread
) << New
->getDeclName();
4697 Diag(OldLocation
, PrevDiag
);
4699 // Do not allow redeclaration to change the variable between requiring
4700 // static and dynamic initialization.
4701 // FIXME: GCC allows this, but uses the TLS keyword on the first
4702 // declaration to determine the kind. Do we need to be compatible here?
4703 Diag(New
->getLocation(), diag::err_thread_thread_different_kind
)
4704 << New
->getDeclName() << (New
->getTLSKind() == VarDecl::TLS_Dynamic
);
4705 Diag(OldLocation
, PrevDiag
);
4709 // C++ doesn't have tentative definitions, so go right ahead and check here.
4710 if (getLangOpts().CPlusPlus
) {
4711 if (Old
->isStaticDataMember() && Old
->getCanonicalDecl()->isInline() &&
4712 Old
->getCanonicalDecl()->isConstexpr()) {
4713 // This definition won't be a definition any more once it's been merged.
4714 Diag(New
->getLocation(),
4715 diag::warn_deprecated_redundant_constexpr_static_def
);
4716 } else if (New
->isThisDeclarationADefinition() == VarDecl::Definition
) {
4717 VarDecl
*Def
= Old
->getDefinition();
4718 if (Def
&& checkVarDeclRedefinition(Def
, New
))
4723 if (haveIncompatibleLanguageLinkages(Old
, New
)) {
4724 Diag(New
->getLocation(), diag::err_different_language_linkage
) << New
;
4725 Diag(OldLocation
, PrevDiag
);
4726 New
->setInvalidDecl();
4730 // Merge "used" flag.
4731 if (Old
->getMostRecentDecl()->isUsed(false))
4734 // Keep a chain of previous declarations.
4735 New
->setPreviousDecl(Old
);
4737 NewTemplate
->setPreviousDecl(OldTemplate
);
4739 // Inherit access appropriately.
4740 New
->setAccess(Old
->getAccess());
4742 NewTemplate
->setAccess(New
->getAccess());
4744 if (Old
->isInline())
4745 New
->setImplicitlyInline();
4748 void Sema::notePreviousDefinition(const NamedDecl
*Old
, SourceLocation New
) {
4749 SourceManager
&SrcMgr
= getSourceManager();
4750 auto FNewDecLoc
= SrcMgr
.getDecomposedLoc(New
);
4751 auto FOldDecLoc
= SrcMgr
.getDecomposedLoc(Old
->getLocation());
4752 auto *FNew
= SrcMgr
.getFileEntryForID(FNewDecLoc
.first
);
4753 auto *FOld
= SrcMgr
.getFileEntryForID(FOldDecLoc
.first
);
4754 auto &HSI
= PP
.getHeaderSearchInfo();
4755 StringRef HdrFilename
=
4756 SrcMgr
.getFilename(SrcMgr
.getSpellingLoc(Old
->getLocation()));
4758 auto noteFromModuleOrInclude
= [&](Module
*Mod
,
4759 SourceLocation IncLoc
) -> bool {
4760 // Redefinition errors with modules are common with non modular mapped
4761 // headers, example: a non-modular header H in module A that also gets
4762 // included directly in a TU. Pointing twice to the same header/definition
4763 // is confusing, try to get better diagnostics when modules is on.
4764 if (IncLoc
.isValid()) {
4766 Diag(IncLoc
, diag::note_redefinition_modules_same_file
)
4767 << HdrFilename
.str() << Mod
->getFullModuleName();
4768 if (!Mod
->DefinitionLoc
.isInvalid())
4769 Diag(Mod
->DefinitionLoc
, diag::note_defined_here
)
4770 << Mod
->getFullModuleName();
4772 Diag(IncLoc
, diag::note_redefinition_include_same_file
)
4773 << HdrFilename
.str();
4781 // Is it the same file and same offset? Provide more information on why
4782 // this leads to a redefinition error.
4783 if (FNew
== FOld
&& FNewDecLoc
.second
== FOldDecLoc
.second
) {
4784 SourceLocation OldIncLoc
= SrcMgr
.getIncludeLoc(FOldDecLoc
.first
);
4785 SourceLocation NewIncLoc
= SrcMgr
.getIncludeLoc(FNewDecLoc
.first
);
4787 noteFromModuleOrInclude(Old
->getOwningModule(), OldIncLoc
);
4788 EmittedDiag
|= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc
);
4790 // If the header has no guards, emit a note suggesting one.
4791 if (FOld
&& !HSI
.isFileMultipleIncludeGuarded(FOld
))
4792 Diag(Old
->getLocation(), diag::note_use_ifdef_guards
);
4798 // Redefinition coming from different files or couldn't do better above.
4799 if (Old
->getLocation().isValid())
4800 Diag(Old
->getLocation(), diag::note_previous_definition
);
4803 /// We've just determined that \p Old and \p New both appear to be definitions
4804 /// of the same variable. Either diagnose or fix the problem.
4805 bool Sema::checkVarDeclRedefinition(VarDecl
*Old
, VarDecl
*New
) {
4806 if (!hasVisibleDefinition(Old
) &&
4807 (New
->getFormalLinkage() == InternalLinkage
||
4809 isa
<VarTemplateSpecializationDecl
>(New
) ||
4810 New
->getDescribedVarTemplate() ||
4811 New
->getNumTemplateParameterLists() ||
4812 New
->getDeclContext()->isDependentContext())) {
4813 // The previous definition is hidden, and multiple definitions are
4814 // permitted (in separate TUs). Demote this to a declaration.
4815 New
->demoteThisDefinitionToDeclaration();
4817 // Make the canonical definition visible.
4818 if (auto *OldTD
= Old
->getDescribedVarTemplate())
4819 makeMergedDefinitionVisible(OldTD
);
4820 makeMergedDefinitionVisible(Old
);
4823 Diag(New
->getLocation(), diag::err_redefinition
) << New
;
4824 notePreviousDefinition(Old
, New
->getLocation());
4825 New
->setInvalidDecl();
4830 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4831 /// no declarator (e.g. "struct foo;") is parsed.
4832 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
4834 const ParsedAttributesView
&DeclAttrs
,
4835 RecordDecl
*&AnonRecord
) {
4836 return ParsedFreeStandingDeclSpec(
4837 S
, AS
, DS
, DeclAttrs
, MultiTemplateParamsArg(), false, AnonRecord
);
4840 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4841 // disambiguate entities defined in different scopes.
4842 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4844 // We will pick our mangling number depending on which version of MSVC is being
4846 static unsigned getMSManglingNumber(const LangOptions
&LO
, Scope
*S
) {
4847 return LO
.isCompatibleWithMSVC(LangOptions::MSVC2015
)
4848 ? S
->getMSCurManglingNumber()
4849 : S
->getMSLastManglingNumber();
4852 void Sema::handleTagNumbering(const TagDecl
*Tag
, Scope
*TagScope
) {
4853 if (!Context
.getLangOpts().CPlusPlus
)
4856 if (isa
<CXXRecordDecl
>(Tag
->getParent())) {
4857 // If this tag is the direct child of a class, number it if
4859 if (!Tag
->getName().empty() || Tag
->getTypedefNameForAnonDecl())
4861 MangleNumberingContext
&MCtx
=
4862 Context
.getManglingNumberContext(Tag
->getParent());
4863 Context
.setManglingNumber(
4864 Tag
, MCtx
.getManglingNumber(
4865 Tag
, getMSManglingNumber(getLangOpts(), TagScope
)));
4869 // If this tag isn't a direct child of a class, number it if it is local.
4870 MangleNumberingContext
*MCtx
;
4871 Decl
*ManglingContextDecl
;
4872 std::tie(MCtx
, ManglingContextDecl
) =
4873 getCurrentMangleNumberContext(Tag
->getDeclContext());
4875 Context
.setManglingNumber(
4876 Tag
, MCtx
->getManglingNumber(
4877 Tag
, getMSManglingNumber(getLangOpts(), TagScope
)));
4882 struct NonCLikeKind
{
4894 explicit operator bool() { return Kind
!= None
; }
4898 /// Determine whether a class is C-like, according to the rules of C++
4899 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4900 static NonCLikeKind
getNonCLikeKindForAnonymousStruct(const CXXRecordDecl
*RD
) {
4901 if (RD
->isInvalidDecl())
4902 return {NonCLikeKind::Invalid
, {}};
4904 // C++ [dcl.typedef]p9: [P1766R1]
4905 // An unnamed class with a typedef name for linkage purposes shall not
4907 // -- have any base classes
4908 if (RD
->getNumBases())
4909 return {NonCLikeKind::BaseClass
,
4910 SourceRange(RD
->bases_begin()->getBeginLoc(),
4911 RD
->bases_end()[-1].getEndLoc())};
4912 bool Invalid
= false;
4913 for (Decl
*D
: RD
->decls()) {
4914 // Don't complain about things we already diagnosed.
4915 if (D
->isInvalidDecl()) {
4920 // -- have any [...] default member initializers
4921 if (auto *FD
= dyn_cast
<FieldDecl
>(D
)) {
4922 if (FD
->hasInClassInitializer()) {
4923 auto *Init
= FD
->getInClassInitializer();
4924 return {NonCLikeKind::DefaultMemberInit
,
4925 Init
? Init
->getSourceRange() : D
->getSourceRange()};
4930 // FIXME: We don't allow friend declarations. This violates the wording of
4931 // P1766, but not the intent.
4932 if (isa
<FriendDecl
>(D
))
4933 return {NonCLikeKind::Friend
, D
->getSourceRange()};
4935 // -- declare any members other than non-static data members, member
4936 // enumerations, or member classes,
4937 if (isa
<StaticAssertDecl
>(D
) || isa
<IndirectFieldDecl
>(D
) ||
4940 auto *MemberRD
= dyn_cast
<CXXRecordDecl
>(D
);
4942 if (D
->isImplicit())
4944 return {NonCLikeKind::OtherMember
, D
->getSourceRange()};
4947 // -- contain a lambda-expression,
4948 if (MemberRD
->isLambda())
4949 return {NonCLikeKind::Lambda
, MemberRD
->getSourceRange()};
4951 // and all member classes shall also satisfy these requirements
4953 if (MemberRD
->isThisDeclarationADefinition()) {
4954 if (auto Kind
= getNonCLikeKindForAnonymousStruct(MemberRD
))
4959 return {Invalid
? NonCLikeKind::Invalid
: NonCLikeKind::None
, {}};
4962 void Sema::setTagNameForLinkagePurposes(TagDecl
*TagFromDeclSpec
,
4963 TypedefNameDecl
*NewTD
) {
4964 if (TagFromDeclSpec
->isInvalidDecl())
4967 // Do nothing if the tag already has a name for linkage purposes.
4968 if (TagFromDeclSpec
->hasNameForLinkage())
4971 // A well-formed anonymous tag must always be a TUK_Definition.
4972 assert(TagFromDeclSpec
->isThisDeclarationADefinition());
4974 // The type must match the tag exactly; no qualifiers allowed.
4975 if (!Context
.hasSameType(NewTD
->getUnderlyingType(),
4976 Context
.getTagDeclType(TagFromDeclSpec
))) {
4977 if (getLangOpts().CPlusPlus
)
4978 Context
.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec
, NewTD
);
4982 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4983 // An unnamed class with a typedef name for linkage purposes shall [be
4986 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4987 // shouldn't happen, but there are constructs that the language rule doesn't
4988 // disallow for which we can't reasonably avoid computing linkage early.
4989 const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(TagFromDeclSpec
);
4990 NonCLikeKind NonCLike
= RD
? getNonCLikeKindForAnonymousStruct(RD
)
4992 bool ChangesLinkage
= TagFromDeclSpec
->hasLinkageBeenComputed();
4993 if (NonCLike
|| ChangesLinkage
) {
4994 if (NonCLike
.Kind
== NonCLikeKind::Invalid
)
4997 unsigned DiagID
= diag::ext_non_c_like_anon_struct_in_typedef
;
4998 if (ChangesLinkage
) {
4999 // If the linkage changes, we can't accept this as an extension.
5000 if (NonCLike
.Kind
== NonCLikeKind::None
)
5001 DiagID
= diag::err_typedef_changes_linkage
;
5003 DiagID
= diag::err_non_c_like_anon_struct_in_typedef
;
5006 SourceLocation FixitLoc
=
5007 getLocForEndOfToken(TagFromDeclSpec
->getInnerLocStart());
5008 llvm::SmallString
<40> TextToInsert
;
5009 TextToInsert
+= ' ';
5010 TextToInsert
+= NewTD
->getIdentifier()->getName();
5012 Diag(FixitLoc
, DiagID
)
5013 << isa
<TypeAliasDecl
>(NewTD
)
5014 << FixItHint::CreateInsertion(FixitLoc
, TextToInsert
);
5015 if (NonCLike
.Kind
!= NonCLikeKind::None
) {
5016 Diag(NonCLike
.Range
.getBegin(), diag::note_non_c_like_anon_struct
)
5017 << NonCLike
.Kind
- 1 << NonCLike
.Range
;
5019 Diag(NewTD
->getLocation(), diag::note_typedef_for_linkage_here
)
5020 << NewTD
<< isa
<TypeAliasDecl
>(NewTD
);
5026 // Otherwise, set this as the anon-decl typedef for the tag.
5027 TagFromDeclSpec
->setTypedefNameForAnonDecl(NewTD
);
5030 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T
) {
5032 case DeclSpec::TST_class
:
5034 case DeclSpec::TST_struct
:
5036 case DeclSpec::TST_interface
:
5038 case DeclSpec::TST_union
:
5040 case DeclSpec::TST_enum
:
5043 llvm_unreachable("unexpected type specifier");
5047 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5048 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5049 /// parameters to cope with template friend declarations.
5050 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
5052 const ParsedAttributesView
&DeclAttrs
,
5053 MultiTemplateParamsArg TemplateParams
,
5054 bool IsExplicitInstantiation
,
5055 RecordDecl
*&AnonRecord
) {
5056 Decl
*TagD
= nullptr;
5057 TagDecl
*Tag
= nullptr;
5058 if (DS
.getTypeSpecType() == DeclSpec::TST_class
||
5059 DS
.getTypeSpecType() == DeclSpec::TST_struct
||
5060 DS
.getTypeSpecType() == DeclSpec::TST_interface
||
5061 DS
.getTypeSpecType() == DeclSpec::TST_union
||
5062 DS
.getTypeSpecType() == DeclSpec::TST_enum
) {
5063 TagD
= DS
.getRepAsDecl();
5065 if (!TagD
) // We probably had an error
5068 // Note that the above type specs guarantee that the
5069 // type rep is a Decl, whereas in many of the others
5071 if (isa
<TagDecl
>(TagD
))
5072 Tag
= cast
<TagDecl
>(TagD
);
5073 else if (ClassTemplateDecl
*CTD
= dyn_cast
<ClassTemplateDecl
>(TagD
))
5074 Tag
= CTD
->getTemplatedDecl();
5078 handleTagNumbering(Tag
, S
);
5079 Tag
->setFreeStanding();
5080 if (Tag
->isInvalidDecl())
5084 if (unsigned TypeQuals
= DS
.getTypeQualifiers()) {
5085 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5086 // or incomplete types shall not be restrict-qualified."
5087 if (TypeQuals
& DeclSpec::TQ_restrict
)
5088 Diag(DS
.getRestrictSpecLoc(),
5089 diag::err_typecheck_invalid_restrict_not_pointer_noarg
)
5090 << DS
.getSourceRange();
5093 if (DS
.isInlineSpecified())
5094 Diag(DS
.getInlineSpecLoc(), diag::err_inline_non_function
)
5095 << getLangOpts().CPlusPlus17
;
5097 if (DS
.hasConstexprSpecifier()) {
5098 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5099 // and definitions of functions and variables.
5100 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5101 // the declaration of a function or function template
5103 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_tag
)
5104 << GetDiagnosticTypeSpecifierID(DS
.getTypeSpecType())
5105 << static_cast<int>(DS
.getConstexprSpecifier());
5107 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind
)
5108 << static_cast<int>(DS
.getConstexprSpecifier());
5109 // Don't emit warnings after this error.
5113 DiagnoseFunctionSpecifiers(DS
);
5115 if (DS
.isFriendSpecified()) {
5116 // If we're dealing with a decl but not a TagDecl, assume that
5117 // whatever routines created it handled the friendship aspect.
5120 return ActOnFriendTypeDecl(S
, DS
, TemplateParams
);
5123 const CXXScopeSpec
&SS
= DS
.getTypeSpecScope();
5124 bool IsExplicitSpecialization
=
5125 !TemplateParams
.empty() && TemplateParams
.back()->size() == 0;
5126 if (Tag
&& SS
.isNotEmpty() && !Tag
->isCompleteDefinition() &&
5127 !IsExplicitInstantiation
&& !IsExplicitSpecialization
&&
5128 !isa
<ClassTemplatePartialSpecializationDecl
>(Tag
)) {
5129 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5130 // nested-name-specifier unless it is an explicit instantiation
5131 // or an explicit specialization.
5133 // FIXME: We allow class template partial specializations here too, per the
5134 // obvious intent of DR1819.
5136 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5137 Diag(SS
.getBeginLoc(), diag::err_standalone_class_nested_name_specifier
)
5138 << GetDiagnosticTypeSpecifierID(DS
.getTypeSpecType()) << SS
.getRange();
5142 // Track whether this decl-specifier declares anything.
5143 bool DeclaresAnything
= true;
5145 // Handle anonymous struct definitions.
5146 if (RecordDecl
*Record
= dyn_cast_or_null
<RecordDecl
>(Tag
)) {
5147 if (!Record
->getDeclName() && Record
->isCompleteDefinition() &&
5148 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
) {
5149 if (getLangOpts().CPlusPlus
||
5150 Record
->getDeclContext()->isRecord()) {
5151 // If CurContext is a DeclContext that can contain statements,
5152 // RecursiveASTVisitor won't visit the decls that
5153 // BuildAnonymousStructOrUnion() will put into CurContext.
5154 // Also store them here so that they can be part of the
5155 // DeclStmt that gets created in this case.
5156 // FIXME: Also return the IndirectFieldDecls created by
5157 // BuildAnonymousStructOr union, for the same reason?
5158 if (CurContext
->isFunctionOrMethod())
5159 AnonRecord
= Record
;
5160 return BuildAnonymousStructOrUnion(S
, DS
, AS
, Record
,
5161 Context
.getPrintingPolicy());
5164 DeclaresAnything
= false;
5169 // A struct-declaration that does not declare an anonymous structure or
5170 // anonymous union shall contain a struct-declarator-list.
5172 // This rule also existed in C89 and C99; the grammar for struct-declaration
5173 // did not permit a struct-declaration without a struct-declarator-list.
5174 if (!getLangOpts().CPlusPlus
&& CurContext
->isRecord() &&
5175 DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
) {
5176 // Check for Microsoft C extension: anonymous struct/union member.
5177 // Handle 2 kinds of anonymous struct/union:
5181 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5182 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5183 if ((Tag
&& Tag
->getDeclName()) ||
5184 DS
.getTypeSpecType() == DeclSpec::TST_typename
) {
5185 RecordDecl
*Record
= nullptr;
5187 Record
= dyn_cast
<RecordDecl
>(Tag
);
5188 else if (const RecordType
*RT
=
5189 DS
.getRepAsType().get()->getAsStructureType())
5190 Record
= RT
->getDecl();
5191 else if (const RecordType
*UT
= DS
.getRepAsType().get()->getAsUnionType())
5192 Record
= UT
->getDecl();
5194 if (Record
&& getLangOpts().MicrosoftExt
) {
5195 Diag(DS
.getBeginLoc(), diag::ext_ms_anonymous_record
)
5196 << Record
->isUnion() << DS
.getSourceRange();
5197 return BuildMicrosoftCAnonymousStruct(S
, DS
, Record
);
5200 DeclaresAnything
= false;
5204 // Skip all the checks below if we have a type error.
5205 if (DS
.getTypeSpecType() == DeclSpec::TST_error
||
5206 (TagD
&& TagD
->isInvalidDecl()))
5209 if (getLangOpts().CPlusPlus
&&
5210 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
)
5211 if (EnumDecl
*Enum
= dyn_cast_or_null
<EnumDecl
>(Tag
))
5212 if (Enum
->enumerator_begin() == Enum
->enumerator_end() &&
5213 !Enum
->getIdentifier() && !Enum
->isInvalidDecl())
5214 DeclaresAnything
= false;
5216 if (!DS
.isMissingDeclaratorOk()) {
5217 // Customize diagnostic for a typedef missing a name.
5218 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
)
5219 Diag(DS
.getBeginLoc(), diag::ext_typedef_without_a_name
)
5220 << DS
.getSourceRange();
5222 DeclaresAnything
= false;
5225 if (DS
.isModulePrivateSpecified() &&
5226 Tag
&& Tag
->getDeclContext()->isFunctionOrMethod())
5227 Diag(DS
.getModulePrivateSpecLoc(), diag::err_module_private_local_class
)
5228 << Tag
->getTagKind()
5229 << FixItHint::CreateRemoval(DS
.getModulePrivateSpecLoc());
5231 ActOnDocumentableDecl(TagD
);
5234 // A declaration [...] shall declare at least a declarator [...], a tag,
5235 // or the members of an enumeration.
5237 // [If there are no declarators], and except for the declaration of an
5238 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5239 // names into the program, or shall redeclare a name introduced by a
5240 // previous declaration.
5241 if (!DeclaresAnything
) {
5242 // In C, we allow this as a (popular) extension / bug. Don't bother
5243 // producing further diagnostics for redundant qualifiers after this.
5244 Diag(DS
.getBeginLoc(), (IsExplicitInstantiation
|| !TemplateParams
.empty())
5245 ? diag::err_no_declarators
5246 : diag::ext_no_declarators
)
5247 << DS
.getSourceRange();
5252 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5253 // init-declarator-list of the declaration shall not be empty.
5254 // C++ [dcl.fct.spec]p1:
5255 // If a cv-qualifier appears in a decl-specifier-seq, the
5256 // init-declarator-list of the declaration shall not be empty.
5258 // Spurious qualifiers here appear to be valid in C.
5259 unsigned DiagID
= diag::warn_standalone_specifier
;
5260 if (getLangOpts().CPlusPlus
)
5261 DiagID
= diag::ext_standalone_specifier
;
5263 // Note that a linkage-specification sets a storage class, but
5264 // 'extern "C" struct foo;' is actually valid and not theoretically
5266 if (DeclSpec::SCS SCS
= DS
.getStorageClassSpec()) {
5267 if (SCS
== DeclSpec::SCS_mutable
)
5268 // Since mutable is not a viable storage class specifier in C, there is
5269 // no reason to treat it as an extension. Instead, diagnose as an error.
5270 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_nonmember
);
5271 else if (!DS
.isExternInLinkageSpec() && SCS
!= DeclSpec::SCS_typedef
)
5272 Diag(DS
.getStorageClassSpecLoc(), DiagID
)
5273 << DeclSpec::getSpecifierName(SCS
);
5276 if (DeclSpec::TSCS TSCS
= DS
.getThreadStorageClassSpec())
5277 Diag(DS
.getThreadStorageClassSpecLoc(), DiagID
)
5278 << DeclSpec::getSpecifierName(TSCS
);
5279 if (DS
.getTypeQualifiers()) {
5280 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
5281 Diag(DS
.getConstSpecLoc(), DiagID
) << "const";
5282 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
5283 Diag(DS
.getConstSpecLoc(), DiagID
) << "volatile";
5284 // Restrict is covered above.
5285 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
5286 Diag(DS
.getAtomicSpecLoc(), DiagID
) << "_Atomic";
5287 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
5288 Diag(DS
.getUnalignedSpecLoc(), DiagID
) << "__unaligned";
5291 // Warn about ignored type attributes, for example:
5292 // __attribute__((aligned)) struct A;
5293 // Attributes should be placed after tag to apply to type declaration.
5294 if (!DS
.getAttributes().empty() || !DeclAttrs
.empty()) {
5295 DeclSpec::TST TypeSpecType
= DS
.getTypeSpecType();
5296 if (TypeSpecType
== DeclSpec::TST_class
||
5297 TypeSpecType
== DeclSpec::TST_struct
||
5298 TypeSpecType
== DeclSpec::TST_interface
||
5299 TypeSpecType
== DeclSpec::TST_union
||
5300 TypeSpecType
== DeclSpec::TST_enum
) {
5301 for (const ParsedAttr
&AL
: DS
.getAttributes())
5302 Diag(AL
.getLoc(), diag::warn_declspec_attribute_ignored
)
5303 << AL
<< GetDiagnosticTypeSpecifierID(TypeSpecType
);
5304 for (const ParsedAttr
&AL
: DeclAttrs
)
5305 Diag(AL
.getLoc(), diag::warn_declspec_attribute_ignored
)
5306 << AL
<< GetDiagnosticTypeSpecifierID(TypeSpecType
);
5313 /// We are trying to inject an anonymous member into the given scope;
5314 /// check if there's an existing declaration that can't be overloaded.
5316 /// \return true if this is a forbidden redeclaration
5317 static bool CheckAnonMemberRedeclaration(Sema
&SemaRef
,
5320 DeclarationName Name
,
5321 SourceLocation NameLoc
,
5323 LookupResult
R(SemaRef
, Name
, NameLoc
, Sema::LookupMemberName
,
5324 Sema::ForVisibleRedeclaration
);
5325 if (!SemaRef
.LookupName(R
, S
)) return false;
5327 // Pick a representative declaration.
5328 NamedDecl
*PrevDecl
= R
.getRepresentativeDecl()->getUnderlyingDecl();
5329 assert(PrevDecl
&& "Expected a non-null Decl");
5331 if (!SemaRef
.isDeclInScope(PrevDecl
, Owner
, S
))
5334 SemaRef
.Diag(NameLoc
, diag::err_anonymous_record_member_redecl
)
5336 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
5341 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5342 /// anonymous struct or union AnonRecord into the owning context Owner
5343 /// and scope S. This routine will be invoked just after we realize
5344 /// that an unnamed union or struct is actually an anonymous union or
5351 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5352 /// // f into the surrounding scope.x
5355 /// This routine is recursive, injecting the names of nested anonymous
5356 /// structs/unions into the owning context and scope as well.
5358 InjectAnonymousStructOrUnionMembers(Sema
&SemaRef
, Scope
*S
, DeclContext
*Owner
,
5359 RecordDecl
*AnonRecord
, AccessSpecifier AS
,
5360 SmallVectorImpl
<NamedDecl
*> &Chaining
) {
5361 bool Invalid
= false;
5363 // Look every FieldDecl and IndirectFieldDecl with a name.
5364 for (auto *D
: AnonRecord
->decls()) {
5365 if ((isa
<FieldDecl
>(D
) || isa
<IndirectFieldDecl
>(D
)) &&
5366 cast
<NamedDecl
>(D
)->getDeclName()) {
5367 ValueDecl
*VD
= cast
<ValueDecl
>(D
);
5368 if (CheckAnonMemberRedeclaration(SemaRef
, S
, Owner
, VD
->getDeclName(),
5370 AnonRecord
->isUnion())) {
5371 // C++ [class.union]p2:
5372 // The names of the members of an anonymous union shall be
5373 // distinct from the names of any other entity in the
5374 // scope in which the anonymous union is declared.
5377 // C++ [class.union]p2:
5378 // For the purpose of name lookup, after the anonymous union
5379 // definition, the members of the anonymous union are
5380 // considered to have been defined in the scope in which the
5381 // anonymous union is declared.
5382 unsigned OldChainingSize
= Chaining
.size();
5383 if (IndirectFieldDecl
*IF
= dyn_cast
<IndirectFieldDecl
>(VD
))
5384 Chaining
.append(IF
->chain_begin(), IF
->chain_end());
5386 Chaining
.push_back(VD
);
5388 assert(Chaining
.size() >= 2);
5389 NamedDecl
**NamedChain
=
5390 new (SemaRef
.Context
)NamedDecl
*[Chaining
.size()];
5391 for (unsigned i
= 0; i
< Chaining
.size(); i
++)
5392 NamedChain
[i
] = Chaining
[i
];
5394 IndirectFieldDecl
*IndirectField
= IndirectFieldDecl::Create(
5395 SemaRef
.Context
, Owner
, VD
->getLocation(), VD
->getIdentifier(),
5396 VD
->getType(), {NamedChain
, Chaining
.size()});
5398 for (const auto *Attr
: VD
->attrs())
5399 IndirectField
->addAttr(Attr
->clone(SemaRef
.Context
));
5401 IndirectField
->setAccess(AS
);
5402 IndirectField
->setImplicit();
5403 SemaRef
.PushOnScopeChains(IndirectField
, S
);
5405 // That includes picking up the appropriate access specifier.
5406 if (AS
!= AS_none
) IndirectField
->setAccess(AS
);
5408 Chaining
.resize(OldChainingSize
);
5416 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5417 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5418 /// illegal input values are mapped to SC_None.
5420 StorageClassSpecToVarDeclStorageClass(const DeclSpec
&DS
) {
5421 DeclSpec::SCS StorageClassSpec
= DS
.getStorageClassSpec();
5422 assert(StorageClassSpec
!= DeclSpec::SCS_typedef
&&
5423 "Parser allowed 'typedef' as storage class VarDecl.");
5424 switch (StorageClassSpec
) {
5425 case DeclSpec::SCS_unspecified
: return SC_None
;
5426 case DeclSpec::SCS_extern
:
5427 if (DS
.isExternInLinkageSpec())
5430 case DeclSpec::SCS_static
: return SC_Static
;
5431 case DeclSpec::SCS_auto
: return SC_Auto
;
5432 case DeclSpec::SCS_register
: return SC_Register
;
5433 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
5434 // Illegal SCSs map to None: error reporting is up to the caller.
5435 case DeclSpec::SCS_mutable
: // Fall through.
5436 case DeclSpec::SCS_typedef
: return SC_None
;
5438 llvm_unreachable("unknown storage class specifier");
5441 static SourceLocation
findDefaultInitializer(const CXXRecordDecl
*Record
) {
5442 assert(Record
->hasInClassInitializer());
5444 for (const auto *I
: Record
->decls()) {
5445 const auto *FD
= dyn_cast
<FieldDecl
>(I
);
5446 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
))
5447 FD
= IFD
->getAnonField();
5448 if (FD
&& FD
->hasInClassInitializer())
5449 return FD
->getLocation();
5452 llvm_unreachable("couldn't find in-class initializer");
5455 static void checkDuplicateDefaultInit(Sema
&S
, CXXRecordDecl
*Parent
,
5456 SourceLocation DefaultInitLoc
) {
5457 if (!Parent
->isUnion() || !Parent
->hasInClassInitializer())
5460 S
.Diag(DefaultInitLoc
, diag::err_multiple_mem_union_initialization
);
5461 S
.Diag(findDefaultInitializer(Parent
), diag::note_previous_initializer
) << 0;
5464 static void checkDuplicateDefaultInit(Sema
&S
, CXXRecordDecl
*Parent
,
5465 CXXRecordDecl
*AnonUnion
) {
5466 if (!Parent
->isUnion() || !Parent
->hasInClassInitializer())
5469 checkDuplicateDefaultInit(S
, Parent
, findDefaultInitializer(AnonUnion
));
5472 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5473 /// anonymous structure or union. Anonymous unions are a C++ feature
5474 /// (C++ [class.union]) and a C11 feature; anonymous structures
5475 /// are a C11 feature and GNU C++ extension.
5476 Decl
*Sema::BuildAnonymousStructOrUnion(Scope
*S
, DeclSpec
&DS
,
5479 const PrintingPolicy
&Policy
) {
5480 DeclContext
*Owner
= Record
->getDeclContext();
5482 // Diagnose whether this anonymous struct/union is an extension.
5483 if (Record
->isUnion() && !getLangOpts().CPlusPlus
&& !getLangOpts().C11
)
5484 Diag(Record
->getLocation(), diag::ext_anonymous_union
);
5485 else if (!Record
->isUnion() && getLangOpts().CPlusPlus
)
5486 Diag(Record
->getLocation(), diag::ext_gnu_anonymous_struct
);
5487 else if (!Record
->isUnion() && !getLangOpts().C11
)
5488 Diag(Record
->getLocation(), diag::ext_c11_anonymous_struct
);
5490 // C and C++ require different kinds of checks for anonymous
5492 bool Invalid
= false;
5493 if (getLangOpts().CPlusPlus
) {
5494 const char *PrevSpec
= nullptr;
5495 if (Record
->isUnion()) {
5496 // C++ [class.union]p6:
5497 // C++17 [class.union.anon]p2:
5498 // Anonymous unions declared in a named namespace or in the
5499 // global namespace shall be declared static.
5501 DeclContext
*OwnerScope
= Owner
->getRedeclContext();
5502 if (DS
.getStorageClassSpec() != DeclSpec::SCS_static
&&
5503 (OwnerScope
->isTranslationUnit() ||
5504 (OwnerScope
->isNamespace() &&
5505 !cast
<NamespaceDecl
>(OwnerScope
)->isAnonymousNamespace()))) {
5506 Diag(Record
->getLocation(), diag::err_anonymous_union_not_static
)
5507 << FixItHint::CreateInsertion(Record
->getLocation(), "static ");
5509 // Recover by adding 'static'.
5510 DS
.SetStorageClassSpec(*this, DeclSpec::SCS_static
, SourceLocation(),
5511 PrevSpec
, DiagID
, Policy
);
5513 // C++ [class.union]p6:
5514 // A storage class is not allowed in a declaration of an
5515 // anonymous union in a class scope.
5516 else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
&&
5517 isa
<RecordDecl
>(Owner
)) {
5518 Diag(DS
.getStorageClassSpecLoc(),
5519 diag::err_anonymous_union_with_storage_spec
)
5520 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
5522 // Recover by removing the storage specifier.
5523 DS
.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified
,
5525 PrevSpec
, DiagID
, Context
.getPrintingPolicy());
5529 // Ignore const/volatile/restrict qualifiers.
5530 if (DS
.getTypeQualifiers()) {
5531 if (DS
.getTypeQualifiers() & DeclSpec::TQ_const
)
5532 Diag(DS
.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified
)
5533 << Record
->isUnion() << "const"
5534 << FixItHint::CreateRemoval(DS
.getConstSpecLoc());
5535 if (DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
)
5536 Diag(DS
.getVolatileSpecLoc(),
5537 diag::ext_anonymous_struct_union_qualified
)
5538 << Record
->isUnion() << "volatile"
5539 << FixItHint::CreateRemoval(DS
.getVolatileSpecLoc());
5540 if (DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
)
5541 Diag(DS
.getRestrictSpecLoc(),
5542 diag::ext_anonymous_struct_union_qualified
)
5543 << Record
->isUnion() << "restrict"
5544 << FixItHint::CreateRemoval(DS
.getRestrictSpecLoc());
5545 if (DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
)
5546 Diag(DS
.getAtomicSpecLoc(),
5547 diag::ext_anonymous_struct_union_qualified
)
5548 << Record
->isUnion() << "_Atomic"
5549 << FixItHint::CreateRemoval(DS
.getAtomicSpecLoc());
5550 if (DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
)
5551 Diag(DS
.getUnalignedSpecLoc(),
5552 diag::ext_anonymous_struct_union_qualified
)
5553 << Record
->isUnion() << "__unaligned"
5554 << FixItHint::CreateRemoval(DS
.getUnalignedSpecLoc());
5556 DS
.ClearTypeQualifiers();
5559 // C++ [class.union]p2:
5560 // The member-specification of an anonymous union shall only
5561 // define non-static data members. [Note: nested types and
5562 // functions cannot be declared within an anonymous union. ]
5563 for (auto *Mem
: Record
->decls()) {
5564 // Ignore invalid declarations; we already diagnosed them.
5565 if (Mem
->isInvalidDecl())
5568 if (auto *FD
= dyn_cast
<FieldDecl
>(Mem
)) {
5569 // C++ [class.union]p3:
5570 // An anonymous union shall not have private or protected
5571 // members (clause 11).
5572 assert(FD
->getAccess() != AS_none
);
5573 if (FD
->getAccess() != AS_public
) {
5574 Diag(FD
->getLocation(), diag::err_anonymous_record_nonpublic_member
)
5575 << Record
->isUnion() << (FD
->getAccess() == AS_protected
);
5579 // C++ [class.union]p1
5580 // An object of a class with a non-trivial constructor, a non-trivial
5581 // copy constructor, a non-trivial destructor, or a non-trivial copy
5582 // assignment operator cannot be a member of a union, nor can an
5583 // array of such objects.
5584 if (CheckNontrivialField(FD
))
5586 } else if (Mem
->isImplicit()) {
5587 // Any implicit members are fine.
5588 } else if (isa
<TagDecl
>(Mem
) && Mem
->getDeclContext() != Record
) {
5589 // This is a type that showed up in an
5590 // elaborated-type-specifier inside the anonymous struct or
5591 // union, but which actually declares a type outside of the
5592 // anonymous struct or union. It's okay.
5593 } else if (auto *MemRecord
= dyn_cast
<RecordDecl
>(Mem
)) {
5594 if (!MemRecord
->isAnonymousStructOrUnion() &&
5595 MemRecord
->getDeclName()) {
5596 // Visual C++ allows type definition in anonymous struct or union.
5597 if (getLangOpts().MicrosoftExt
)
5598 Diag(MemRecord
->getLocation(), diag::ext_anonymous_record_with_type
)
5599 << Record
->isUnion();
5601 // This is a nested type declaration.
5602 Diag(MemRecord
->getLocation(), diag::err_anonymous_record_with_type
)
5603 << Record
->isUnion();
5607 // This is an anonymous type definition within another anonymous type.
5608 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5609 // not part of standard C++.
5610 Diag(MemRecord
->getLocation(),
5611 diag::ext_anonymous_record_with_anonymous_type
)
5612 << Record
->isUnion();
5614 } else if (isa
<AccessSpecDecl
>(Mem
)) {
5615 // Any access specifier is fine.
5616 } else if (isa
<StaticAssertDecl
>(Mem
)) {
5617 // In C++1z, static_assert declarations are also fine.
5619 // We have something that isn't a non-static data
5620 // member. Complain about it.
5621 unsigned DK
= diag::err_anonymous_record_bad_member
;
5622 if (isa
<TypeDecl
>(Mem
))
5623 DK
= diag::err_anonymous_record_with_type
;
5624 else if (isa
<FunctionDecl
>(Mem
))
5625 DK
= diag::err_anonymous_record_with_function
;
5626 else if (isa
<VarDecl
>(Mem
))
5627 DK
= diag::err_anonymous_record_with_static
;
5629 // Visual C++ allows type definition in anonymous struct or union.
5630 if (getLangOpts().MicrosoftExt
&&
5631 DK
== diag::err_anonymous_record_with_type
)
5632 Diag(Mem
->getLocation(), diag::ext_anonymous_record_with_type
)
5633 << Record
->isUnion();
5635 Diag(Mem
->getLocation(), DK
) << Record
->isUnion();
5641 // C++11 [class.union]p8 (DR1460):
5642 // At most one variant member of a union may have a
5643 // brace-or-equal-initializer.
5644 if (cast
<CXXRecordDecl
>(Record
)->hasInClassInitializer() &&
5646 checkDuplicateDefaultInit(*this, cast
<CXXRecordDecl
>(Owner
),
5647 cast
<CXXRecordDecl
>(Record
));
5650 if (!Record
->isUnion() && !Owner
->isRecord()) {
5651 Diag(Record
->getLocation(), diag::err_anonymous_struct_not_member
)
5652 << getLangOpts().CPlusPlus
;
5657 // [If there are no declarators], and except for the declaration of an
5658 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5659 // names into the program
5660 // C++ [class.mem]p2:
5661 // each such member-declaration shall either declare at least one member
5662 // name of the class or declare at least one unnamed bit-field
5664 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5665 if (getLangOpts().CPlusPlus
&& Record
->field_empty())
5666 Diag(DS
.getBeginLoc(), diag::ext_no_declarators
) << DS
.getSourceRange();
5668 // Mock up a declarator.
5669 Declarator
Dc(DS
, ParsedAttributesView::none(), DeclaratorContext::Member
);
5670 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
5671 assert(TInfo
&& "couldn't build declarator info for anonymous struct/union");
5673 // Create a declaration for this anonymous struct/union.
5674 NamedDecl
*Anon
= nullptr;
5675 if (RecordDecl
*OwningClass
= dyn_cast
<RecordDecl
>(Owner
)) {
5676 Anon
= FieldDecl::Create(
5677 Context
, OwningClass
, DS
.getBeginLoc(), Record
->getLocation(),
5678 /*IdentifierInfo=*/nullptr, Context
.getTypeDeclType(Record
), TInfo
,
5679 /*BitWidth=*/nullptr, /*Mutable=*/false,
5680 /*InitStyle=*/ICIS_NoInit
);
5681 Anon
->setAccess(AS
);
5682 ProcessDeclAttributes(S
, Anon
, Dc
);
5684 if (getLangOpts().CPlusPlus
)
5685 FieldCollector
->Add(cast
<FieldDecl
>(Anon
));
5687 DeclSpec::SCS SCSpec
= DS
.getStorageClassSpec();
5688 StorageClass SC
= StorageClassSpecToVarDeclStorageClass(DS
);
5689 if (SCSpec
== DeclSpec::SCS_mutable
) {
5690 // mutable can only appear on non-static class members, so it's always
5692 Diag(Record
->getLocation(), diag::err_mutable_nonmember
);
5697 assert(DS
.getAttributes().empty() && "No attribute expected");
5698 Anon
= VarDecl::Create(Context
, Owner
, DS
.getBeginLoc(),
5699 Record
->getLocation(), /*IdentifierInfo=*/nullptr,
5700 Context
.getTypeDeclType(Record
), TInfo
, SC
);
5702 // Default-initialize the implicit variable. This initialization will be
5703 // trivial in almost all cases, except if a union member has an in-class
5705 // union { int n = 0; };
5706 ActOnUninitializedDecl(Anon
);
5708 Anon
->setImplicit();
5710 // Mark this as an anonymous struct/union type.
5711 Record
->setAnonymousStructOrUnion(true);
5713 // Add the anonymous struct/union object to the current
5714 // context. We'll be referencing this object when we refer to one of
5716 Owner
->addDecl(Anon
);
5718 // Inject the members of the anonymous struct/union into the owning
5719 // context and into the identifier resolver chain for name lookup
5721 SmallVector
<NamedDecl
*, 2> Chain
;
5722 Chain
.push_back(Anon
);
5724 if (InjectAnonymousStructOrUnionMembers(*this, S
, Owner
, Record
, AS
, Chain
))
5727 if (VarDecl
*NewVD
= dyn_cast
<VarDecl
>(Anon
)) {
5728 if (getLangOpts().CPlusPlus
&& NewVD
->isStaticLocal()) {
5729 MangleNumberingContext
*MCtx
;
5730 Decl
*ManglingContextDecl
;
5731 std::tie(MCtx
, ManglingContextDecl
) =
5732 getCurrentMangleNumberContext(NewVD
->getDeclContext());
5734 Context
.setManglingNumber(
5735 NewVD
, MCtx
->getManglingNumber(
5736 NewVD
, getMSManglingNumber(getLangOpts(), S
)));
5737 Context
.setStaticLocalNumber(NewVD
, MCtx
->getStaticLocalNumber(NewVD
));
5743 Anon
->setInvalidDecl();
5748 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5749 /// Microsoft C anonymous structure.
5750 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5753 /// struct A { int a; };
5754 /// struct B { struct A; int b; };
5761 Decl
*Sema::BuildMicrosoftCAnonymousStruct(Scope
*S
, DeclSpec
&DS
,
5762 RecordDecl
*Record
) {
5763 assert(Record
&& "expected a record!");
5765 // Mock up a declarator.
5766 Declarator
Dc(DS
, ParsedAttributesView::none(), DeclaratorContext::TypeName
);
5767 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
5768 assert(TInfo
&& "couldn't build declarator info for anonymous struct");
5770 auto *ParentDecl
= cast
<RecordDecl
>(CurContext
);
5771 QualType RecTy
= Context
.getTypeDeclType(Record
);
5773 // Create a declaration for this anonymous struct.
5775 FieldDecl::Create(Context
, ParentDecl
, DS
.getBeginLoc(), DS
.getBeginLoc(),
5776 /*IdentifierInfo=*/nullptr, RecTy
, TInfo
,
5777 /*BitWidth=*/nullptr, /*Mutable=*/false,
5778 /*InitStyle=*/ICIS_NoInit
);
5779 Anon
->setImplicit();
5781 // Add the anonymous struct object to the current context.
5782 CurContext
->addDecl(Anon
);
5784 // Inject the members of the anonymous struct into the current
5785 // context and into the identifier resolver chain for name lookup
5787 SmallVector
<NamedDecl
*, 2> Chain
;
5788 Chain
.push_back(Anon
);
5790 RecordDecl
*RecordDef
= Record
->getDefinition();
5791 if (RequireCompleteSizedType(Anon
->getLocation(), RecTy
,
5792 diag::err_field_incomplete_or_sizeless
) ||
5793 InjectAnonymousStructOrUnionMembers(*this, S
, CurContext
, RecordDef
,
5795 Anon
->setInvalidDecl();
5796 ParentDecl
->setInvalidDecl();
5802 /// GetNameForDeclarator - Determine the full declaration name for the
5803 /// given Declarator.
5804 DeclarationNameInfo
Sema::GetNameForDeclarator(Declarator
&D
) {
5805 return GetNameFromUnqualifiedId(D
.getName());
5808 /// Retrieves the declaration name from a parsed unqualified-id.
5810 Sema::GetNameFromUnqualifiedId(const UnqualifiedId
&Name
) {
5811 DeclarationNameInfo NameInfo
;
5812 NameInfo
.setLoc(Name
.StartLocation
);
5814 switch (Name
.getKind()) {
5816 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
5817 case UnqualifiedIdKind::IK_Identifier
:
5818 NameInfo
.setName(Name
.Identifier
);
5821 case UnqualifiedIdKind::IK_DeductionGuideName
: {
5822 // C++ [temp.deduct.guide]p3:
5823 // The simple-template-id shall name a class template specialization.
5824 // The template-name shall be the same identifier as the template-name
5825 // of the simple-template-id.
5826 // These together intend to imply that the template-name shall name a
5828 // FIXME: template<typename T> struct X {};
5829 // template<typename T> using Y = X<T>;
5830 // Y(int) -> Y<int>;
5831 // satisfies these rules but does not name a class template.
5832 TemplateName TN
= Name
.TemplateName
.get().get();
5833 auto *Template
= TN
.getAsTemplateDecl();
5834 if (!Template
|| !isa
<ClassTemplateDecl
>(Template
)) {
5835 Diag(Name
.StartLocation
,
5836 diag::err_deduction_guide_name_not_class_template
)
5837 << (int)getTemplateNameKindForDiagnostics(TN
) << TN
;
5839 Diag(Template
->getLocation(), diag::note_template_decl_here
);
5840 return DeclarationNameInfo();
5844 Context
.DeclarationNames
.getCXXDeductionGuideName(Template
));
5848 case UnqualifiedIdKind::IK_OperatorFunctionId
:
5849 NameInfo
.setName(Context
.DeclarationNames
.getCXXOperatorName(
5850 Name
.OperatorFunctionId
.Operator
));
5851 NameInfo
.setCXXOperatorNameRange(SourceRange(
5852 Name
.OperatorFunctionId
.SymbolLocations
[0], Name
.EndLocation
));
5855 case UnqualifiedIdKind::IK_LiteralOperatorId
:
5856 NameInfo
.setName(Context
.DeclarationNames
.getCXXLiteralOperatorName(
5858 NameInfo
.setCXXLiteralOperatorNameLoc(Name
.EndLocation
);
5861 case UnqualifiedIdKind::IK_ConversionFunctionId
: {
5862 TypeSourceInfo
*TInfo
;
5863 QualType Ty
= GetTypeFromParser(Name
.ConversionFunctionId
, &TInfo
);
5865 return DeclarationNameInfo();
5866 NameInfo
.setName(Context
.DeclarationNames
.getCXXConversionFunctionName(
5867 Context
.getCanonicalType(Ty
)));
5868 NameInfo
.setNamedTypeInfo(TInfo
);
5872 case UnqualifiedIdKind::IK_ConstructorName
: {
5873 TypeSourceInfo
*TInfo
;
5874 QualType Ty
= GetTypeFromParser(Name
.ConstructorName
, &TInfo
);
5876 return DeclarationNameInfo();
5877 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
5878 Context
.getCanonicalType(Ty
)));
5879 NameInfo
.setNamedTypeInfo(TInfo
);
5883 case UnqualifiedIdKind::IK_ConstructorTemplateId
: {
5884 // In well-formed code, we can only have a constructor
5885 // template-id that refers to the current context, so go there
5886 // to find the actual type being constructed.
5887 CXXRecordDecl
*CurClass
= dyn_cast
<CXXRecordDecl
>(CurContext
);
5888 if (!CurClass
|| CurClass
->getIdentifier() != Name
.TemplateId
->Name
)
5889 return DeclarationNameInfo();
5891 // Determine the type of the class being constructed.
5892 QualType CurClassType
= Context
.getTypeDeclType(CurClass
);
5894 // FIXME: Check two things: that the template-id names the same type as
5895 // CurClassType, and that the template-id does not occur when the name
5898 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
5899 Context
.getCanonicalType(CurClassType
)));
5900 // FIXME: should we retrieve TypeSourceInfo?
5901 NameInfo
.setNamedTypeInfo(nullptr);
5905 case UnqualifiedIdKind::IK_DestructorName
: {
5906 TypeSourceInfo
*TInfo
;
5907 QualType Ty
= GetTypeFromParser(Name
.DestructorName
, &TInfo
);
5909 return DeclarationNameInfo();
5910 NameInfo
.setName(Context
.DeclarationNames
.getCXXDestructorName(
5911 Context
.getCanonicalType(Ty
)));
5912 NameInfo
.setNamedTypeInfo(TInfo
);
5916 case UnqualifiedIdKind::IK_TemplateId
: {
5917 TemplateName TName
= Name
.TemplateId
->Template
.get();
5918 SourceLocation TNameLoc
= Name
.TemplateId
->TemplateNameLoc
;
5919 return Context
.getNameForTemplate(TName
, TNameLoc
);
5922 } // switch (Name.getKind())
5924 llvm_unreachable("Unknown name kind");
5927 static QualType
getCoreType(QualType Ty
) {
5929 if (Ty
->isPointerType() || Ty
->isReferenceType())
5930 Ty
= Ty
->getPointeeType();
5931 else if (Ty
->isArrayType())
5932 Ty
= Ty
->castAsArrayTypeUnsafe()->getElementType();
5934 return Ty
.withoutLocalFastQualifiers();
5938 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5939 /// and Definition have "nearly" matching parameters. This heuristic is
5940 /// used to improve diagnostics in the case where an out-of-line function
5941 /// definition doesn't match any declaration within the class or namespace.
5942 /// Also sets Params to the list of indices to the parameters that differ
5943 /// between the declaration and the definition. If hasSimilarParameters
5944 /// returns true and Params is empty, then all of the parameters match.
5945 static bool hasSimilarParameters(ASTContext
&Context
,
5946 FunctionDecl
*Declaration
,
5947 FunctionDecl
*Definition
,
5948 SmallVectorImpl
<unsigned> &Params
) {
5950 if (Declaration
->param_size() != Definition
->param_size())
5952 for (unsigned Idx
= 0; Idx
< Declaration
->param_size(); ++Idx
) {
5953 QualType DeclParamTy
= Declaration
->getParamDecl(Idx
)->getType();
5954 QualType DefParamTy
= Definition
->getParamDecl(Idx
)->getType();
5956 // The parameter types are identical
5957 if (Context
.hasSameUnqualifiedType(DefParamTy
, DeclParamTy
))
5960 QualType DeclParamBaseTy
= getCoreType(DeclParamTy
);
5961 QualType DefParamBaseTy
= getCoreType(DefParamTy
);
5962 const IdentifierInfo
*DeclTyName
= DeclParamBaseTy
.getBaseTypeIdentifier();
5963 const IdentifierInfo
*DefTyName
= DefParamBaseTy
.getBaseTypeIdentifier();
5965 if (Context
.hasSameUnqualifiedType(DeclParamBaseTy
, DefParamBaseTy
) ||
5966 (DeclTyName
&& DeclTyName
== DefTyName
))
5967 Params
.push_back(Idx
);
5968 else // The two parameters aren't even close
5975 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5976 /// declarator needs to be rebuilt in the current instantiation.
5977 /// Any bits of declarator which appear before the name are valid for
5978 /// consideration here. That's specifically the type in the decl spec
5979 /// and the base type in any member-pointer chunks.
5980 static bool RebuildDeclaratorInCurrentInstantiation(Sema
&S
, Declarator
&D
,
5981 DeclarationName Name
) {
5982 // The types we specifically need to rebuild are:
5983 // - typenames, typeofs, and decltypes
5984 // - types which will become injected class names
5985 // Of course, we also need to rebuild any type referencing such a
5986 // type. It's safest to just say "dependent", but we call out a
5989 DeclSpec
&DS
= D
.getMutableDeclSpec();
5990 switch (DS
.getTypeSpecType()) {
5991 case DeclSpec::TST_typename
:
5992 case DeclSpec::TST_typeofType
:
5993 case DeclSpec::TST_typeof_unqualType
:
5994 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5995 #include "clang/Basic/TransformTypeTraits.def"
5996 case DeclSpec::TST_atomic
: {
5997 // Grab the type from the parser.
5998 TypeSourceInfo
*TSI
= nullptr;
5999 QualType T
= S
.GetTypeFromParser(DS
.getRepAsType(), &TSI
);
6000 if (T
.isNull() || !T
->isInstantiationDependentType()) break;
6002 // Make sure there's a type source info. This isn't really much
6003 // of a waste; most dependent types should have type source info
6004 // attached already.
6006 TSI
= S
.Context
.getTrivialTypeSourceInfo(T
, DS
.getTypeSpecTypeLoc());
6008 // Rebuild the type in the current instantiation.
6009 TSI
= S
.RebuildTypeInCurrentInstantiation(TSI
, D
.getIdentifierLoc(), Name
);
6010 if (!TSI
) return true;
6012 // Store the new type back in the decl spec.
6013 ParsedType LocType
= S
.CreateParsedType(TSI
->getType(), TSI
);
6014 DS
.UpdateTypeRep(LocType
);
6018 case DeclSpec::TST_decltype
:
6019 case DeclSpec::TST_typeof_unqualExpr
:
6020 case DeclSpec::TST_typeofExpr
: {
6021 Expr
*E
= DS
.getRepAsExpr();
6022 ExprResult Result
= S
.RebuildExprInCurrentInstantiation(E
);
6023 if (Result
.isInvalid()) return true;
6024 DS
.UpdateExprRep(Result
.get());
6029 // Nothing to do for these decl specs.
6033 // It doesn't matter what order we do this in.
6034 for (unsigned I
= 0, E
= D
.getNumTypeObjects(); I
!= E
; ++I
) {
6035 DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
6037 // The only type information in the declarator which can come
6038 // before the declaration name is the base type of a member
6040 if (Chunk
.Kind
!= DeclaratorChunk::MemberPointer
)
6043 // Rebuild the scope specifier in-place.
6044 CXXScopeSpec
&SS
= Chunk
.Mem
.Scope();
6045 if (S
.RebuildNestedNameSpecifierInCurrentInstantiation(SS
))
6052 /// Returns true if the declaration is declared in a system header or from a
6054 static bool isFromSystemHeader(SourceManager
&SM
, const Decl
*D
) {
6055 return SM
.isInSystemHeader(D
->getLocation()) ||
6056 SM
.isInSystemMacro(D
->getLocation());
6059 void Sema::warnOnReservedIdentifier(const NamedDecl
*D
) {
6060 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6062 if (D
->getPreviousDecl() || D
->isImplicit())
6064 ReservedIdentifierStatus Status
= D
->isReserved(getLangOpts());
6065 if (Status
!= ReservedIdentifierStatus::NotReserved
&&
6066 !isFromSystemHeader(Context
.getSourceManager(), D
)) {
6067 Diag(D
->getLocation(), diag::warn_reserved_extern_symbol
)
6068 << D
<< static_cast<int>(Status
);
6072 Decl
*Sema::ActOnDeclarator(Scope
*S
, Declarator
&D
) {
6073 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration
);
6075 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6076 // declaration only if the `bind_to_declaration` extension is set.
6077 SmallVector
<FunctionDecl
*, 4> Bases
;
6078 if (LangOpts
.OpenMP
&& isInOpenMPDeclareVariantScope())
6079 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6080 implementation_extension_bind_to_declaration
))
6081 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6082 S
, D
, MultiTemplateParamsArg(), Bases
);
6084 Decl
*Dcl
= HandleDeclarator(S
, D
, MultiTemplateParamsArg());
6086 if (OriginalLexicalContext
&& OriginalLexicalContext
->isObjCContainer() &&
6087 Dcl
&& Dcl
->getDeclContext()->isFileContext())
6088 Dcl
->setTopLevelDeclInObjCContainer();
6091 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl
, Bases
);
6096 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6097 /// If T is the name of a class, then each of the following shall have a
6098 /// name different from T:
6099 /// - every static data member of class T;
6100 /// - every member function of class T
6101 /// - every member of class T that is itself a type;
6102 /// \returns true if the declaration name violates these rules.
6103 bool Sema::DiagnoseClassNameShadow(DeclContext
*DC
,
6104 DeclarationNameInfo NameInfo
) {
6105 DeclarationName Name
= NameInfo
.getName();
6107 CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
);
6108 while (Record
&& Record
->isAnonymousStructOrUnion())
6109 Record
= dyn_cast
<CXXRecordDecl
>(Record
->getParent());
6110 if (Record
&& Record
->getIdentifier() && Record
->getDeclName() == Name
) {
6111 Diag(NameInfo
.getLoc(), diag::err_member_name_of_class
) << Name
;
6118 /// Diagnose a declaration whose declarator-id has the given
6119 /// nested-name-specifier.
6121 /// \param SS The nested-name-specifier of the declarator-id.
6123 /// \param DC The declaration context to which the nested-name-specifier
6126 /// \param Name The name of the entity being declared.
6128 /// \param Loc The location of the name of the entity being declared.
6130 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6131 /// we're declaring an explicit / partial specialization / instantiation.
6133 /// \returns true if we cannot safely recover from this error, false otherwise.
6134 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec
&SS
, DeclContext
*DC
,
6135 DeclarationName Name
,
6136 SourceLocation Loc
, bool IsTemplateId
) {
6137 DeclContext
*Cur
= CurContext
;
6138 while (isa
<LinkageSpecDecl
>(Cur
) || isa
<CapturedDecl
>(Cur
))
6139 Cur
= Cur
->getParent();
6141 // If the user provided a superfluous scope specifier that refers back to the
6142 // class in which the entity is already declared, diagnose and ignore it.
6148 // Note, it was once ill-formed to give redundant qualification in all
6149 // contexts, but that rule was removed by DR482.
6150 if (Cur
->Equals(DC
)) {
6151 if (Cur
->isRecord()) {
6152 Diag(Loc
, LangOpts
.MicrosoftExt
? diag::warn_member_extra_qualification
6153 : diag::err_member_extra_qualification
)
6154 << Name
<< FixItHint::CreateRemoval(SS
.getRange());
6157 Diag(Loc
, diag::warn_namespace_member_extra_qualification
) << Name
;
6162 // Check whether the qualifying scope encloses the scope of the original
6163 // declaration. For a template-id, we perform the checks in
6164 // CheckTemplateSpecializationScope.
6165 if (!Cur
->Encloses(DC
) && !IsTemplateId
) {
6166 if (Cur
->isRecord())
6167 Diag(Loc
, diag::err_member_qualification
)
6168 << Name
<< SS
.getRange();
6169 else if (isa
<TranslationUnitDecl
>(DC
))
6170 Diag(Loc
, diag::err_invalid_declarator_global_scope
)
6171 << Name
<< SS
.getRange();
6172 else if (isa
<FunctionDecl
>(Cur
))
6173 Diag(Loc
, diag::err_invalid_declarator_in_function
)
6174 << Name
<< SS
.getRange();
6175 else if (isa
<BlockDecl
>(Cur
))
6176 Diag(Loc
, diag::err_invalid_declarator_in_block
)
6177 << Name
<< SS
.getRange();
6178 else if (isa
<ExportDecl
>(Cur
)) {
6179 if (!isa
<NamespaceDecl
>(DC
))
6180 Diag(Loc
, diag::err_export_non_namespace_scope_name
)
6181 << Name
<< SS
.getRange();
6183 // The cases that DC is not NamespaceDecl should be handled in
6184 // CheckRedeclarationExported.
6187 Diag(Loc
, diag::err_invalid_declarator_scope
)
6188 << Name
<< cast
<NamedDecl
>(Cur
) << cast
<NamedDecl
>(DC
) << SS
.getRange();
6193 if (Cur
->isRecord()) {
6194 // Cannot qualify members within a class.
6195 Diag(Loc
, diag::err_member_qualification
)
6196 << Name
<< SS
.getRange();
6199 // C++ constructors and destructors with incorrect scopes can break
6200 // our AST invariants by having the wrong underlying types. If
6201 // that's the case, then drop this declaration entirely.
6202 if ((Name
.getNameKind() == DeclarationName::CXXConstructorName
||
6203 Name
.getNameKind() == DeclarationName::CXXDestructorName
) &&
6204 !Context
.hasSameType(Name
.getCXXNameType(),
6205 Context
.getTypeDeclType(cast
<CXXRecordDecl
>(Cur
))))
6211 // C++11 [dcl.meaning]p1:
6212 // [...] "The nested-name-specifier of the qualified declarator-id shall
6213 // not begin with a decltype-specifer"
6214 NestedNameSpecifierLoc
SpecLoc(SS
.getScopeRep(), SS
.location_data());
6215 while (SpecLoc
.getPrefix())
6216 SpecLoc
= SpecLoc
.getPrefix();
6217 if (isa_and_nonnull
<DecltypeType
>(
6218 SpecLoc
.getNestedNameSpecifier()->getAsType()))
6219 Diag(Loc
, diag::err_decltype_in_declarator
)
6220 << SpecLoc
.getTypeLoc().getSourceRange();
6225 NamedDecl
*Sema::HandleDeclarator(Scope
*S
, Declarator
&D
,
6226 MultiTemplateParamsArg TemplateParamLists
) {
6227 // TODO: consider using NameInfo for diagnostic.
6228 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
6229 DeclarationName Name
= NameInfo
.getName();
6231 // All of these full declarators require an identifier. If it doesn't have
6232 // one, the ParsedFreeStandingDeclSpec action should be used.
6233 if (D
.isDecompositionDeclarator()) {
6234 return ActOnDecompositionDeclarator(S
, D
, TemplateParamLists
);
6236 if (!D
.isInvalidType()) // Reject this if we think it is valid.
6237 Diag(D
.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident
)
6238 << D
.getDeclSpec().getSourceRange() << D
.getSourceRange();
6240 } else if (DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_DeclarationType
))
6243 // The scope passed in may not be a decl scope. Zip up the scope tree until
6244 // we find one that is.
6245 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
6246 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
6249 DeclContext
*DC
= CurContext
;
6250 if (D
.getCXXScopeSpec().isInvalid())
6252 else if (D
.getCXXScopeSpec().isSet()) {
6253 if (DiagnoseUnexpandedParameterPack(D
.getCXXScopeSpec(),
6254 UPPC_DeclarationQualifier
))
6257 bool EnteringContext
= !D
.getDeclSpec().isFriendSpecified();
6258 DC
= computeDeclContext(D
.getCXXScopeSpec(), EnteringContext
);
6259 if (!DC
|| isa
<EnumDecl
>(DC
)) {
6260 // If we could not compute the declaration context, it's because the
6261 // declaration context is dependent but does not refer to a class,
6262 // class template, or class template partial specialization. Complain
6263 // and return early, to avoid the coming semantic disaster.
6264 Diag(D
.getIdentifierLoc(),
6265 diag::err_template_qualified_declarator_no_match
)
6266 << D
.getCXXScopeSpec().getScopeRep()
6267 << D
.getCXXScopeSpec().getRange();
6270 bool IsDependentContext
= DC
->isDependentContext();
6272 if (!IsDependentContext
&&
6273 RequireCompleteDeclContext(D
.getCXXScopeSpec(), DC
))
6276 // If a class is incomplete, do not parse entities inside it.
6277 if (isa
<CXXRecordDecl
>(DC
) && !cast
<CXXRecordDecl
>(DC
)->hasDefinition()) {
6278 Diag(D
.getIdentifierLoc(),
6279 diag::err_member_def_undefined_record
)
6280 << Name
<< DC
<< D
.getCXXScopeSpec().getRange();
6283 if (!D
.getDeclSpec().isFriendSpecified()) {
6284 if (diagnoseQualifiedDeclaration(
6285 D
.getCXXScopeSpec(), DC
, Name
, D
.getIdentifierLoc(),
6286 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
)) {
6294 // Check whether we need to rebuild the type of the given
6295 // declaration in the current instantiation.
6296 if (EnteringContext
&& IsDependentContext
&&
6297 TemplateParamLists
.size() != 0) {
6298 ContextRAII
SavedContext(*this, DC
);
6299 if (RebuildDeclaratorInCurrentInstantiation(*this, D
, Name
))
6304 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6305 QualType R
= TInfo
->getType();
6307 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
6308 UPPC_DeclarationType
))
6311 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
6312 forRedeclarationInCurContext());
6314 // See if this is a redefinition of a variable in the same scope.
6315 if (!D
.getCXXScopeSpec().isSet()) {
6316 bool IsLinkageLookup
= false;
6317 bool CreateBuiltins
= false;
6319 // If the declaration we're planning to build will be a function
6320 // or object with linkage, then look for another declaration with
6321 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6323 // If the declaration we're planning to build will be declared with
6324 // external linkage in the translation unit, create any builtin with
6326 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
)
6328 else if (CurContext
->isFunctionOrMethod() &&
6329 (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern
||
6330 R
->isFunctionType())) {
6331 IsLinkageLookup
= true;
6333 CurContext
->getEnclosingNamespaceContext()->isTranslationUnit();
6334 } else if (CurContext
->getRedeclContext()->isTranslationUnit() &&
6335 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static
)
6336 CreateBuiltins
= true;
6338 if (IsLinkageLookup
) {
6339 Previous
.clear(LookupRedeclarationWithLinkage
);
6340 Previous
.setRedeclarationKind(ForExternalRedeclaration
);
6343 LookupName(Previous
, S
, CreateBuiltins
);
6344 } else { // Something like "int foo::x;"
6345 LookupQualifiedName(Previous
, DC
);
6347 // C++ [dcl.meaning]p1:
6348 // When the declarator-id is qualified, the declaration shall refer to a
6349 // previously declared member of the class or namespace to which the
6350 // qualifier refers (or, in the case of a namespace, of an element of the
6351 // inline namespace set of that namespace (7.3.1)) or to a specialization
6354 // Note that we already checked the context above, and that we do not have
6355 // enough information to make sure that Previous contains the declaration
6356 // we want to match. For example, given:
6363 // void X::f(int) { } // ill-formed
6365 // In this case, Previous will point to the overload set
6366 // containing the two f's declared in X, but neither of them
6369 // C++ [dcl.meaning]p1:
6370 // [...] the member shall not merely have been introduced by a
6371 // using-declaration in the scope of the class or namespace nominated by
6372 // the nested-name-specifier of the declarator-id.
6373 RemoveUsingDecls(Previous
);
6376 if (Previous
.isSingleResult() &&
6377 Previous
.getFoundDecl()->isTemplateParameter()) {
6378 // Maybe we will complain about the shadowed template parameter.
6379 if (!D
.isInvalidType())
6380 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(),
6381 Previous
.getFoundDecl());
6383 // Just pretend that we didn't see the previous declaration.
6387 if (!R
->isFunctionType() && DiagnoseClassNameShadow(DC
, NameInfo
))
6388 // Forget that the previous declaration is the injected-class-name.
6391 // In C++, the previous declaration we find might be a tag type
6392 // (class or enum). In this case, the new declaration will hide the
6393 // tag type. Note that this applies to functions, function templates, and
6394 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6395 if (Previous
.isSingleTagDecl() &&
6396 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
6397 (TemplateParamLists
.size() == 0 || R
->isFunctionType()))
6400 // Check that there are no default arguments other than in the parameters
6401 // of a function declaration (C++ only).
6402 if (getLangOpts().CPlusPlus
)
6403 CheckExtraCXXDefaultArguments(D
);
6407 bool AddToScope
= true;
6408 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
) {
6409 if (TemplateParamLists
.size()) {
6410 Diag(D
.getIdentifierLoc(), diag::err_template_typedef
);
6414 New
= ActOnTypedefDeclarator(S
, D
, DC
, TInfo
, Previous
);
6415 } else if (R
->isFunctionType()) {
6416 New
= ActOnFunctionDeclarator(S
, D
, DC
, TInfo
, Previous
,
6420 New
= ActOnVariableDeclarator(S
, D
, DC
, TInfo
, Previous
, TemplateParamLists
,
6427 // If this has an identifier and is not a function template specialization,
6428 // add it to the scope stack.
6429 if (New
->getDeclName() && AddToScope
)
6430 PushOnScopeChains(New
, S
);
6432 if (isInOpenMPDeclareTargetContext())
6433 checkDeclIsAllowedInOpenMPTarget(nullptr, New
);
6438 /// Helper method to turn variable array types into constant array
6439 /// types in certain situations which would otherwise be errors (for
6440 /// GCC compatibility).
6441 static QualType
TryToFixInvalidVariablyModifiedType(QualType T
,
6442 ASTContext
&Context
,
6443 bool &SizeIsNegative
,
6444 llvm::APSInt
&Oversized
) {
6445 // This method tries to turn a variable array into a constant
6446 // array even when the size isn't an ICE. This is necessary
6447 // for compatibility with code that depends on gcc's buggy
6448 // constant expression folding, like struct {char x[(int)(char*)2];}
6449 SizeIsNegative
= false;
6452 if (T
->isDependentType())
6455 QualifierCollector Qs
;
6456 const Type
*Ty
= Qs
.strip(T
);
6458 if (const PointerType
* PTy
= dyn_cast
<PointerType
>(Ty
)) {
6459 QualType Pointee
= PTy
->getPointeeType();
6460 QualType FixedType
=
6461 TryToFixInvalidVariablyModifiedType(Pointee
, Context
, SizeIsNegative
,
6463 if (FixedType
.isNull()) return FixedType
;
6464 FixedType
= Context
.getPointerType(FixedType
);
6465 return Qs
.apply(Context
, FixedType
);
6467 if (const ParenType
* PTy
= dyn_cast
<ParenType
>(Ty
)) {
6468 QualType Inner
= PTy
->getInnerType();
6469 QualType FixedType
=
6470 TryToFixInvalidVariablyModifiedType(Inner
, Context
, SizeIsNegative
,
6472 if (FixedType
.isNull()) return FixedType
;
6473 FixedType
= Context
.getParenType(FixedType
);
6474 return Qs
.apply(Context
, FixedType
);
6477 const VariableArrayType
* VLATy
= dyn_cast
<VariableArrayType
>(T
);
6481 QualType ElemTy
= VLATy
->getElementType();
6482 if (ElemTy
->isVariablyModifiedType()) {
6483 ElemTy
= TryToFixInvalidVariablyModifiedType(ElemTy
, Context
,
6484 SizeIsNegative
, Oversized
);
6485 if (ElemTy
.isNull())
6489 Expr::EvalResult Result
;
6490 if (!VLATy
->getSizeExpr() ||
6491 !VLATy
->getSizeExpr()->EvaluateAsInt(Result
, Context
))
6494 llvm::APSInt Res
= Result
.Val
.getInt();
6496 // Check whether the array size is negative.
6497 if (Res
.isSigned() && Res
.isNegative()) {
6498 SizeIsNegative
= true;
6502 // Check whether the array is too large to be addressed.
6503 unsigned ActiveSizeBits
=
6504 (!ElemTy
->isDependentType() && !ElemTy
->isVariablyModifiedType() &&
6505 !ElemTy
->isIncompleteType() && !ElemTy
->isUndeducedType())
6506 ? ConstantArrayType::getNumAddressingBits(Context
, ElemTy
, Res
)
6507 : Res
.getActiveBits();
6508 if (ActiveSizeBits
> ConstantArrayType::getMaxSizeBits(Context
)) {
6513 QualType FoldedArrayType
= Context
.getConstantArrayType(
6514 ElemTy
, Res
, VLATy
->getSizeExpr(), ArrayType::Normal
, 0);
6515 return Qs
.apply(Context
, FoldedArrayType
);
6519 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL
, TypeLoc DstTL
) {
6520 SrcTL
= SrcTL
.getUnqualifiedLoc();
6521 DstTL
= DstTL
.getUnqualifiedLoc();
6522 if (PointerTypeLoc SrcPTL
= SrcTL
.getAs
<PointerTypeLoc
>()) {
6523 PointerTypeLoc DstPTL
= DstTL
.castAs
<PointerTypeLoc
>();
6524 FixInvalidVariablyModifiedTypeLoc(SrcPTL
.getPointeeLoc(),
6525 DstPTL
.getPointeeLoc());
6526 DstPTL
.setStarLoc(SrcPTL
.getStarLoc());
6529 if (ParenTypeLoc SrcPTL
= SrcTL
.getAs
<ParenTypeLoc
>()) {
6530 ParenTypeLoc DstPTL
= DstTL
.castAs
<ParenTypeLoc
>();
6531 FixInvalidVariablyModifiedTypeLoc(SrcPTL
.getInnerLoc(),
6532 DstPTL
.getInnerLoc());
6533 DstPTL
.setLParenLoc(SrcPTL
.getLParenLoc());
6534 DstPTL
.setRParenLoc(SrcPTL
.getRParenLoc());
6537 ArrayTypeLoc SrcATL
= SrcTL
.castAs
<ArrayTypeLoc
>();
6538 ArrayTypeLoc DstATL
= DstTL
.castAs
<ArrayTypeLoc
>();
6539 TypeLoc SrcElemTL
= SrcATL
.getElementLoc();
6540 TypeLoc DstElemTL
= DstATL
.getElementLoc();
6541 if (VariableArrayTypeLoc SrcElemATL
=
6542 SrcElemTL
.getAs
<VariableArrayTypeLoc
>()) {
6543 ConstantArrayTypeLoc DstElemATL
= DstElemTL
.castAs
<ConstantArrayTypeLoc
>();
6544 FixInvalidVariablyModifiedTypeLoc(SrcElemATL
, DstElemATL
);
6546 DstElemTL
.initializeFullCopy(SrcElemTL
);
6548 DstATL
.setLBracketLoc(SrcATL
.getLBracketLoc());
6549 DstATL
.setSizeExpr(SrcATL
.getSizeExpr());
6550 DstATL
.setRBracketLoc(SrcATL
.getRBracketLoc());
6553 /// Helper method to turn variable array types into constant array
6554 /// types in certain situations which would otherwise be errors (for
6555 /// GCC compatibility).
6556 static TypeSourceInfo
*
6557 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo
*TInfo
,
6558 ASTContext
&Context
,
6559 bool &SizeIsNegative
,
6560 llvm::APSInt
&Oversized
) {
6562 = TryToFixInvalidVariablyModifiedType(TInfo
->getType(), Context
,
6563 SizeIsNegative
, Oversized
);
6564 if (FixedTy
.isNull())
6566 TypeSourceInfo
*FixedTInfo
= Context
.getTrivialTypeSourceInfo(FixedTy
);
6567 FixInvalidVariablyModifiedTypeLoc(TInfo
->getTypeLoc(),
6568 FixedTInfo
->getTypeLoc());
6572 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6573 /// true if we were successful.
6574 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo
*&TInfo
,
6575 QualType
&T
, SourceLocation Loc
,
6576 unsigned FailedFoldDiagID
) {
6577 bool SizeIsNegative
;
6578 llvm::APSInt Oversized
;
6579 TypeSourceInfo
*FixedTInfo
= TryToFixInvalidVariablyModifiedTypeSourceInfo(
6580 TInfo
, Context
, SizeIsNegative
, Oversized
);
6582 Diag(Loc
, diag::ext_vla_folded_to_constant
);
6584 T
= FixedTInfo
->getType();
6589 Diag(Loc
, diag::err_typecheck_negative_array_size
);
6590 else if (Oversized
.getBoolValue())
6591 Diag(Loc
, diag::err_array_too_large
) << toString(Oversized
, 10);
6592 else if (FailedFoldDiagID
)
6593 Diag(Loc
, FailedFoldDiagID
);
6597 /// Register the given locally-scoped extern "C" declaration so
6598 /// that it can be found later for redeclarations. We include any extern "C"
6599 /// declaration that is not visible in the translation unit here, not just
6600 /// function-scope declarations.
6602 Sema::RegisterLocallyScopedExternCDecl(NamedDecl
*ND
, Scope
*S
) {
6603 if (!getLangOpts().CPlusPlus
&&
6604 ND
->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6605 // Don't need to track declarations in the TU in C.
6608 // Note that we have a locally-scoped external with this name.
6609 Context
.getExternCContextDecl()->makeDeclVisibleInContext(ND
);
6612 NamedDecl
*Sema::findLocallyScopedExternCDecl(DeclarationName Name
) {
6613 // FIXME: We can have multiple results via __attribute__((overloadable)).
6614 auto Result
= Context
.getExternCContextDecl()->lookup(Name
);
6615 return Result
.empty() ? nullptr : *Result
.begin();
6618 /// Diagnose function specifiers on a declaration of an identifier that
6619 /// does not identify a function.
6620 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec
&DS
) {
6621 // FIXME: We should probably indicate the identifier in question to avoid
6622 // confusion for constructs like "virtual int a(), b;"
6623 if (DS
.isVirtualSpecified())
6624 Diag(DS
.getVirtualSpecLoc(),
6625 diag::err_virtual_non_function
);
6627 if (DS
.hasExplicitSpecifier())
6628 Diag(DS
.getExplicitSpecLoc(),
6629 diag::err_explicit_non_function
);
6631 if (DS
.isNoreturnSpecified())
6632 Diag(DS
.getNoreturnSpecLoc(),
6633 diag::err_noreturn_non_function
);
6637 Sema::ActOnTypedefDeclarator(Scope
* S
, Declarator
& D
, DeclContext
* DC
,
6638 TypeSourceInfo
*TInfo
, LookupResult
&Previous
) {
6639 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6640 if (D
.getCXXScopeSpec().isSet()) {
6641 Diag(D
.getIdentifierLoc(), diag::err_qualified_typedef_declarator
)
6642 << D
.getCXXScopeSpec().getRange();
6644 // Pretend we didn't see the scope specifier.
6649 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
6651 if (D
.getDeclSpec().isInlineSpecified())
6652 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
6653 << getLangOpts().CPlusPlus17
;
6654 if (D
.getDeclSpec().hasConstexprSpecifier())
6655 Diag(D
.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr
)
6656 << 1 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
6658 if (D
.getName().getKind() != UnqualifiedIdKind::IK_Identifier
) {
6659 if (D
.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName
)
6660 Diag(D
.getName().StartLocation
,
6661 diag::err_deduction_guide_invalid_specifier
)
6664 Diag(D
.getName().StartLocation
, diag::err_typedef_not_identifier
)
6665 << D
.getName().getSourceRange();
6669 TypedefDecl
*NewTD
= ParseTypedefDecl(S
, D
, TInfo
->getType(), TInfo
);
6670 if (!NewTD
) return nullptr;
6672 // Handle attributes prior to checking for duplicates in MergeVarDecl
6673 ProcessDeclAttributes(S
, NewTD
, D
);
6675 CheckTypedefForVariablyModifiedType(S
, NewTD
);
6677 bool Redeclaration
= D
.isRedeclaration();
6678 NamedDecl
*ND
= ActOnTypedefNameDecl(S
, DC
, NewTD
, Previous
, Redeclaration
);
6679 D
.setRedeclaration(Redeclaration
);
6684 Sema::CheckTypedefForVariablyModifiedType(Scope
*S
, TypedefNameDecl
*NewTD
) {
6685 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6686 // then it shall have block scope.
6687 // Note that variably modified types must be fixed before merging the decl so
6688 // that redeclarations will match.
6689 TypeSourceInfo
*TInfo
= NewTD
->getTypeSourceInfo();
6690 QualType T
= TInfo
->getType();
6691 if (T
->isVariablyModifiedType()) {
6692 setFunctionHasBranchProtectedScope();
6694 if (S
->getFnParent() == nullptr) {
6695 bool SizeIsNegative
;
6696 llvm::APSInt Oversized
;
6697 TypeSourceInfo
*FixedTInfo
=
6698 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo
, Context
,
6702 Diag(NewTD
->getLocation(), diag::ext_vla_folded_to_constant
);
6703 NewTD
->setTypeSourceInfo(FixedTInfo
);
6706 Diag(NewTD
->getLocation(), diag::err_typecheck_negative_array_size
);
6707 else if (T
->isVariableArrayType())
6708 Diag(NewTD
->getLocation(), diag::err_vla_decl_in_file_scope
);
6709 else if (Oversized
.getBoolValue())
6710 Diag(NewTD
->getLocation(), diag::err_array_too_large
)
6711 << toString(Oversized
, 10);
6713 Diag(NewTD
->getLocation(), diag::err_vm_decl_in_file_scope
);
6714 NewTD
->setInvalidDecl();
6720 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6721 /// declares a typedef-name, either using the 'typedef' type specifier or via
6722 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6724 Sema::ActOnTypedefNameDecl(Scope
*S
, DeclContext
*DC
, TypedefNameDecl
*NewTD
,
6725 LookupResult
&Previous
, bool &Redeclaration
) {
6727 // Find the shadowed declaration before filtering for scope.
6728 NamedDecl
*ShadowedDecl
= getShadowedDeclaration(NewTD
, Previous
);
6730 // Merge the decl with the existing one if appropriate. If the decl is
6731 // in an outer scope, it isn't the same thing.
6732 FilterLookupForScope(Previous
, DC
, S
, /*ConsiderLinkage*/false,
6733 /*AllowInlineNamespace*/false);
6734 filterNonConflictingPreviousTypedefDecls(*this, NewTD
, Previous
);
6735 if (!Previous
.empty()) {
6736 Redeclaration
= true;
6737 MergeTypedefNameDecl(S
, NewTD
, Previous
);
6739 inferGslPointerAttribute(NewTD
);
6742 if (ShadowedDecl
&& !Redeclaration
)
6743 CheckShadow(NewTD
, ShadowedDecl
, Previous
);
6745 // If this is the C FILE type, notify the AST context.
6746 if (IdentifierInfo
*II
= NewTD
->getIdentifier())
6747 if (!NewTD
->isInvalidDecl() &&
6748 NewTD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6749 if (II
->isStr("FILE"))
6750 Context
.setFILEDecl(NewTD
);
6751 else if (II
->isStr("jmp_buf"))
6752 Context
.setjmp_bufDecl(NewTD
);
6753 else if (II
->isStr("sigjmp_buf"))
6754 Context
.setsigjmp_bufDecl(NewTD
);
6755 else if (II
->isStr("ucontext_t"))
6756 Context
.setucontext_tDecl(NewTD
);
6762 /// Determines whether the given declaration is an out-of-scope
6763 /// previous declaration.
6765 /// This routine should be invoked when name lookup has found a
6766 /// previous declaration (PrevDecl) that is not in the scope where a
6767 /// new declaration by the same name is being introduced. If the new
6768 /// declaration occurs in a local scope, previous declarations with
6769 /// linkage may still be considered previous declarations (C99
6770 /// 6.2.2p4-5, C++ [basic.link]p6).
6772 /// \param PrevDecl the previous declaration found by name
6775 /// \param DC the context in which the new declaration is being
6778 /// \returns true if PrevDecl is an out-of-scope previous declaration
6779 /// for a new delcaration with the same name.
6781 isOutOfScopePreviousDeclaration(NamedDecl
*PrevDecl
, DeclContext
*DC
,
6782 ASTContext
&Context
) {
6786 if (!PrevDecl
->hasLinkage())
6789 if (Context
.getLangOpts().CPlusPlus
) {
6790 // C++ [basic.link]p6:
6791 // If there is a visible declaration of an entity with linkage
6792 // having the same name and type, ignoring entities declared
6793 // outside the innermost enclosing namespace scope, the block
6794 // scope declaration declares that same entity and receives the
6795 // linkage of the previous declaration.
6796 DeclContext
*OuterContext
= DC
->getRedeclContext();
6797 if (!OuterContext
->isFunctionOrMethod())
6798 // This rule only applies to block-scope declarations.
6801 DeclContext
*PrevOuterContext
= PrevDecl
->getDeclContext();
6802 if (PrevOuterContext
->isRecord())
6803 // We found a member function: ignore it.
6806 // Find the innermost enclosing namespace for the new and
6807 // previous declarations.
6808 OuterContext
= OuterContext
->getEnclosingNamespaceContext();
6809 PrevOuterContext
= PrevOuterContext
->getEnclosingNamespaceContext();
6811 // The previous declaration is in a different namespace, so it
6812 // isn't the same function.
6813 if (!OuterContext
->Equals(PrevOuterContext
))
6820 static void SetNestedNameSpecifier(Sema
&S
, DeclaratorDecl
*DD
, Declarator
&D
) {
6821 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
6822 if (!SS
.isSet()) return;
6823 DD
->setQualifierInfo(SS
.getWithLocInContext(S
.Context
));
6826 bool Sema::inferObjCARCLifetime(ValueDecl
*decl
) {
6827 QualType type
= decl
->getType();
6828 Qualifiers::ObjCLifetime lifetime
= type
.getObjCLifetime();
6829 if (lifetime
== Qualifiers::OCL_Autoreleasing
) {
6830 // Various kinds of declaration aren't allowed to be __autoreleasing.
6831 unsigned kind
= -1U;
6832 if (VarDecl
*var
= dyn_cast
<VarDecl
>(decl
)) {
6833 if (var
->hasAttr
<BlocksAttr
>())
6834 kind
= 0; // __block
6835 else if (!var
->hasLocalStorage())
6837 } else if (isa
<ObjCIvarDecl
>(decl
)) {
6839 } else if (isa
<FieldDecl
>(decl
)) {
6844 Diag(decl
->getLocation(), diag::err_arc_autoreleasing_var
)
6847 } else if (lifetime
== Qualifiers::OCL_None
) {
6848 // Try to infer lifetime.
6849 if (!type
->isObjCLifetimeType())
6852 lifetime
= type
->getObjCARCImplicitLifetime();
6853 type
= Context
.getLifetimeQualifiedType(type
, lifetime
);
6854 decl
->setType(type
);
6857 if (VarDecl
*var
= dyn_cast
<VarDecl
>(decl
)) {
6858 // Thread-local variables cannot have lifetime.
6859 if (lifetime
&& lifetime
!= Qualifiers::OCL_ExplicitNone
&&
6860 var
->getTLSKind()) {
6861 Diag(var
->getLocation(), diag::err_arc_thread_ownership
)
6870 void Sema::deduceOpenCLAddressSpace(ValueDecl
*Decl
) {
6871 if (Decl
->getType().hasAddressSpace())
6873 if (Decl
->getType()->isDependentType())
6875 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(Decl
)) {
6876 QualType Type
= Var
->getType();
6877 if (Type
->isSamplerT() || Type
->isVoidType())
6879 LangAS ImplAS
= LangAS::opencl_private
;
6880 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6881 // __opencl_c_program_scope_global_variables feature, the address space
6882 // for a variable at program scope or a static or extern variable inside
6883 // a function are inferred to be __global.
6884 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6885 Var
->hasGlobalStorage())
6886 ImplAS
= LangAS::opencl_global
;
6887 // If the original type from a decayed type is an array type and that array
6888 // type has no address space yet, deduce it now.
6889 if (auto DT
= dyn_cast
<DecayedType
>(Type
)) {
6890 auto OrigTy
= DT
->getOriginalType();
6891 if (!OrigTy
.hasAddressSpace() && OrigTy
->isArrayType()) {
6892 // Add the address space to the original array type and then propagate
6893 // that to the element type through `getAsArrayType`.
6894 OrigTy
= Context
.getAddrSpaceQualType(OrigTy
, ImplAS
);
6895 OrigTy
= QualType(Context
.getAsArrayType(OrigTy
), 0);
6896 // Re-generate the decayed type.
6897 Type
= Context
.getDecayedType(OrigTy
);
6900 Type
= Context
.getAddrSpaceQualType(Type
, ImplAS
);
6901 // Apply any qualifiers (including address space) from the array type to
6902 // the element type. This implements C99 6.7.3p8: "If the specification of
6903 // an array type includes any type qualifiers, the element type is so
6904 // qualified, not the array type."
6905 if (Type
->isArrayType())
6906 Type
= QualType(Context
.getAsArrayType(Type
), 0);
6907 Decl
->setType(Type
);
6911 static void checkAttributesAfterMerging(Sema
&S
, NamedDecl
&ND
) {
6912 // Ensure that an auto decl is deduced otherwise the checks below might cache
6913 // the wrong linkage.
6914 assert(S
.ParsingInitForAutoVars
.count(&ND
) == 0);
6916 // 'weak' only applies to declarations with external linkage.
6917 if (WeakAttr
*Attr
= ND
.getAttr
<WeakAttr
>()) {
6918 if (!ND
.isExternallyVisible()) {
6919 S
.Diag(Attr
->getLocation(), diag::err_attribute_weak_static
);
6920 ND
.dropAttr
<WeakAttr
>();
6923 if (WeakRefAttr
*Attr
= ND
.getAttr
<WeakRefAttr
>()) {
6924 if (ND
.isExternallyVisible()) {
6925 S
.Diag(Attr
->getLocation(), diag::err_attribute_weakref_not_static
);
6926 ND
.dropAttr
<WeakRefAttr
>();
6927 ND
.dropAttr
<AliasAttr
>();
6931 if (auto *VD
= dyn_cast
<VarDecl
>(&ND
)) {
6932 if (VD
->hasInit()) {
6933 if (const auto *Attr
= VD
->getAttr
<AliasAttr
>()) {
6934 assert(VD
->isThisDeclarationADefinition() &&
6935 !VD
->isExternallyVisible() && "Broken AliasAttr handled late!");
6936 S
.Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << VD
<< 0;
6937 VD
->dropAttr
<AliasAttr
>();
6942 // 'selectany' only applies to externally visible variable declarations.
6943 // It does not apply to functions.
6944 if (SelectAnyAttr
*Attr
= ND
.getAttr
<SelectAnyAttr
>()) {
6945 if (isa
<FunctionDecl
>(ND
) || !ND
.isExternallyVisible()) {
6946 S
.Diag(Attr
->getLocation(),
6947 diag::err_attribute_selectany_non_extern_data
);
6948 ND
.dropAttr
<SelectAnyAttr
>();
6952 if (const InheritableAttr
*Attr
= getDLLAttr(&ND
)) {
6953 auto *VD
= dyn_cast
<VarDecl
>(&ND
);
6954 bool IsAnonymousNS
= false;
6955 bool IsMicrosoft
= S
.Context
.getTargetInfo().getCXXABI().isMicrosoft();
6957 const NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(VD
->getDeclContext());
6958 while (NS
&& !IsAnonymousNS
) {
6959 IsAnonymousNS
= NS
->isAnonymousNamespace();
6960 NS
= dyn_cast
<NamespaceDecl
>(NS
->getParent());
6963 // dll attributes require external linkage. Static locals may have external
6964 // linkage but still cannot be explicitly imported or exported.
6965 // In Microsoft mode, a variable defined in anonymous namespace must have
6966 // external linkage in order to be exported.
6967 bool AnonNSInMicrosoftMode
= IsAnonymousNS
&& IsMicrosoft
;
6968 if ((ND
.isExternallyVisible() && AnonNSInMicrosoftMode
) ||
6969 (!AnonNSInMicrosoftMode
&&
6970 (!ND
.isExternallyVisible() || (VD
&& VD
->isStaticLocal())))) {
6971 S
.Diag(ND
.getLocation(), diag::err_attribute_dll_not_extern
)
6973 ND
.setInvalidDecl();
6977 // Check the attributes on the function type, if any.
6978 if (const auto *FD
= dyn_cast
<FunctionDecl
>(&ND
)) {
6979 // Don't declare this variable in the second operand of the for-statement;
6980 // GCC miscompiles that by ending its lifetime before evaluating the
6981 // third operand. See gcc.gnu.org/PR86769.
6982 AttributedTypeLoc ATL
;
6983 for (TypeLoc TL
= FD
->getTypeSourceInfo()->getTypeLoc();
6984 (ATL
= TL
.getAsAdjusted
<AttributedTypeLoc
>());
6985 TL
= ATL
.getModifiedLoc()) {
6986 // The [[lifetimebound]] attribute can be applied to the implicit object
6987 // parameter of a non-static member function (other than a ctor or dtor)
6988 // by applying it to the function type.
6989 if (const auto *A
= ATL
.getAttrAs
<LifetimeBoundAttr
>()) {
6990 const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
);
6991 if (!MD
|| MD
->isStatic()) {
6992 S
.Diag(A
->getLocation(), diag::err_lifetimebound_no_object_param
)
6993 << !MD
<< A
->getRange();
6994 } else if (isa
<CXXConstructorDecl
>(MD
) || isa
<CXXDestructorDecl
>(MD
)) {
6995 S
.Diag(A
->getLocation(), diag::err_lifetimebound_ctor_dtor
)
6996 << isa
<CXXDestructorDecl
>(MD
) << A
->getRange();
7003 static void checkDLLAttributeRedeclaration(Sema
&S
, NamedDecl
*OldDecl
,
7005 bool IsSpecialization
,
7006 bool IsDefinition
) {
7007 if (OldDecl
->isInvalidDecl() || NewDecl
->isInvalidDecl())
7010 bool IsTemplate
= false;
7011 if (TemplateDecl
*OldTD
= dyn_cast
<TemplateDecl
>(OldDecl
)) {
7012 OldDecl
= OldTD
->getTemplatedDecl();
7014 if (!IsSpecialization
)
7015 IsDefinition
= false;
7017 if (TemplateDecl
*NewTD
= dyn_cast
<TemplateDecl
>(NewDecl
)) {
7018 NewDecl
= NewTD
->getTemplatedDecl();
7022 if (!OldDecl
|| !NewDecl
)
7025 const DLLImportAttr
*OldImportAttr
= OldDecl
->getAttr
<DLLImportAttr
>();
7026 const DLLExportAttr
*OldExportAttr
= OldDecl
->getAttr
<DLLExportAttr
>();
7027 const DLLImportAttr
*NewImportAttr
= NewDecl
->getAttr
<DLLImportAttr
>();
7028 const DLLExportAttr
*NewExportAttr
= NewDecl
->getAttr
<DLLExportAttr
>();
7030 // dllimport and dllexport are inheritable attributes so we have to exclude
7031 // inherited attribute instances.
7032 bool HasNewAttr
= (NewImportAttr
&& !NewImportAttr
->isInherited()) ||
7033 (NewExportAttr
&& !NewExportAttr
->isInherited());
7035 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7036 // the only exception being explicit specializations.
7037 // Implicitly generated declarations are also excluded for now because there
7038 // is no other way to switch these to use dllimport or dllexport.
7039 bool AddsAttr
= !(OldImportAttr
|| OldExportAttr
) && HasNewAttr
;
7041 if (AddsAttr
&& !IsSpecialization
&& !OldDecl
->isImplicit()) {
7042 // Allow with a warning for free functions and global variables.
7043 bool JustWarn
= false;
7044 if (!OldDecl
->isCXXClassMember()) {
7045 auto *VD
= dyn_cast
<VarDecl
>(OldDecl
);
7046 if (VD
&& !VD
->getDescribedVarTemplate())
7048 auto *FD
= dyn_cast
<FunctionDecl
>(OldDecl
);
7049 if (FD
&& FD
->getTemplatedKind() == FunctionDecl::TK_NonTemplate
)
7053 // We cannot change a declaration that's been used because IR has already
7054 // been emitted. Dllimported functions will still work though (modulo
7055 // address equality) as they can use the thunk.
7056 if (OldDecl
->isUsed())
7057 if (!isa
<FunctionDecl
>(OldDecl
) || !NewImportAttr
)
7060 unsigned DiagID
= JustWarn
? diag::warn_attribute_dll_redeclaration
7061 : diag::err_attribute_dll_redeclaration
;
7062 S
.Diag(NewDecl
->getLocation(), DiagID
)
7064 << (NewImportAttr
? (const Attr
*)NewImportAttr
: NewExportAttr
);
7065 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7067 NewDecl
->setInvalidDecl();
7072 // A redeclaration is not allowed to drop a dllimport attribute, the only
7073 // exceptions being inline function definitions (except for function
7074 // templates), local extern declarations, qualified friend declarations or
7075 // special MSVC extension: in the last case, the declaration is treated as if
7076 // it were marked dllexport.
7077 bool IsInline
= false, IsStaticDataMember
= false, IsQualifiedFriend
= false;
7078 bool IsMicrosoftABI
= S
.Context
.getTargetInfo().shouldDLLImportComdatSymbols();
7079 if (const auto *VD
= dyn_cast
<VarDecl
>(NewDecl
)) {
7080 // Ignore static data because out-of-line definitions are diagnosed
7082 IsStaticDataMember
= VD
->isStaticDataMember();
7083 IsDefinition
= VD
->isThisDeclarationADefinition(S
.Context
) !=
7084 VarDecl::DeclarationOnly
;
7085 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(NewDecl
)) {
7086 IsInline
= FD
->isInlined();
7087 IsQualifiedFriend
= FD
->getQualifier() &&
7088 FD
->getFriendObjectKind() == Decl::FOK_Declared
;
7091 if (OldImportAttr
&& !HasNewAttr
&&
7092 (!IsInline
|| (IsMicrosoftABI
&& IsTemplate
)) && !IsStaticDataMember
&&
7093 !NewDecl
->isLocalExternDecl() && !IsQualifiedFriend
) {
7094 if (IsMicrosoftABI
&& IsDefinition
) {
7095 if (IsSpecialization
) {
7097 NewDecl
->getLocation(),
7098 diag::err_attribute_dllimport_function_specialization_definition
);
7099 S
.Diag(OldImportAttr
->getLocation(), diag::note_attribute
);
7100 NewDecl
->dropAttr
<DLLImportAttr
>();
7102 S
.Diag(NewDecl
->getLocation(),
7103 diag::warn_redeclaration_without_import_attribute
)
7105 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7106 NewDecl
->dropAttr
<DLLImportAttr
>();
7107 NewDecl
->addAttr(DLLExportAttr::CreateImplicit(
7108 S
.Context
, NewImportAttr
->getRange()));
7110 } else if (IsMicrosoftABI
&& IsSpecialization
) {
7111 assert(!IsDefinition
);
7112 // MSVC allows this. Keep the inherited attribute.
7114 S
.Diag(NewDecl
->getLocation(),
7115 diag::warn_redeclaration_without_attribute_prev_attribute_ignored
)
7116 << NewDecl
<< OldImportAttr
;
7117 S
.Diag(OldDecl
->getLocation(), diag::note_previous_declaration
);
7118 S
.Diag(OldImportAttr
->getLocation(), diag::note_previous_attribute
);
7119 OldDecl
->dropAttr
<DLLImportAttr
>();
7120 NewDecl
->dropAttr
<DLLImportAttr
>();
7122 } else if (IsInline
&& OldImportAttr
&& !IsMicrosoftABI
) {
7123 // In MinGW, seeing a function declared inline drops the dllimport
7125 OldDecl
->dropAttr
<DLLImportAttr
>();
7126 NewDecl
->dropAttr
<DLLImportAttr
>();
7127 S
.Diag(NewDecl
->getLocation(),
7128 diag::warn_dllimport_dropped_from_inline_function
)
7129 << NewDecl
<< OldImportAttr
;
7132 // A specialization of a class template member function is processed here
7133 // since it's a redeclaration. If the parent class is dllexport, the
7134 // specialization inherits that attribute. This doesn't happen automatically
7135 // since the parent class isn't instantiated until later.
7136 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewDecl
)) {
7137 if (MD
->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
&&
7138 !NewImportAttr
&& !NewExportAttr
) {
7139 if (const DLLExportAttr
*ParentExportAttr
=
7140 MD
->getParent()->getAttr
<DLLExportAttr
>()) {
7141 DLLExportAttr
*NewAttr
= ParentExportAttr
->clone(S
.Context
);
7142 NewAttr
->setInherited(true);
7143 NewDecl
->addAttr(NewAttr
);
7149 /// Given that we are within the definition of the given function,
7150 /// will that definition behave like C99's 'inline', where the
7151 /// definition is discarded except for optimization purposes?
7152 static bool isFunctionDefinitionDiscarded(Sema
&S
, FunctionDecl
*FD
) {
7153 // Try to avoid calling GetGVALinkageForFunction.
7155 // All cases of this require the 'inline' keyword.
7156 if (!FD
->isInlined()) return false;
7158 // This is only possible in C++ with the gnu_inline attribute.
7159 if (S
.getLangOpts().CPlusPlus
&& !FD
->hasAttr
<GNUInlineAttr
>())
7162 // Okay, go ahead and call the relatively-more-expensive function.
7163 return S
.Context
.GetGVALinkageForFunction(FD
) == GVA_AvailableExternally
;
7166 /// Determine whether a variable is extern "C" prior to attaching
7167 /// an initializer. We can't just call isExternC() here, because that
7168 /// will also compute and cache whether the declaration is externally
7169 /// visible, which might change when we attach the initializer.
7171 /// This can only be used if the declaration is known to not be a
7172 /// redeclaration of an internal linkage declaration.
7178 /// Attaching the initializer here makes this declaration not externally
7179 /// visible, because its type has internal linkage.
7181 /// FIXME: This is a hack.
7182 template<typename T
>
7183 static bool isIncompleteDeclExternC(Sema
&S
, const T
*D
) {
7184 if (S
.getLangOpts().CPlusPlus
) {
7185 // In C++, the overloadable attribute negates the effects of extern "C".
7186 if (!D
->isInExternCContext() || D
->template hasAttr
<OverloadableAttr
>())
7189 // So do CUDA's host/device attributes.
7190 if (S
.getLangOpts().CUDA
&& (D
->template hasAttr
<CUDADeviceAttr
>() ||
7191 D
->template hasAttr
<CUDAHostAttr
>()))
7194 return D
->isExternC();
7197 static bool shouldConsiderLinkage(const VarDecl
*VD
) {
7198 const DeclContext
*DC
= VD
->getDeclContext()->getRedeclContext();
7199 if (DC
->isFunctionOrMethod() || isa
<OMPDeclareReductionDecl
>(DC
) ||
7200 isa
<OMPDeclareMapperDecl
>(DC
))
7201 return VD
->hasExternalStorage();
7202 if (DC
->isFileContext())
7206 if (DC
->getDeclKind() == Decl::HLSLBuffer
)
7209 if (isa
<RequiresExprBodyDecl
>(DC
))
7211 llvm_unreachable("Unexpected context");
7214 static bool shouldConsiderLinkage(const FunctionDecl
*FD
) {
7215 const DeclContext
*DC
= FD
->getDeclContext()->getRedeclContext();
7216 if (DC
->isFileContext() || DC
->isFunctionOrMethod() ||
7217 isa
<OMPDeclareReductionDecl
>(DC
) || isa
<OMPDeclareMapperDecl
>(DC
))
7221 llvm_unreachable("Unexpected context");
7224 static bool hasParsedAttr(Scope
*S
, const Declarator
&PD
,
7225 ParsedAttr::Kind Kind
) {
7226 // Check decl attributes on the DeclSpec.
7227 if (PD
.getDeclSpec().getAttributes().hasAttribute(Kind
))
7230 // Walk the declarator structure, checking decl attributes that were in a type
7231 // position to the decl itself.
7232 for (unsigned I
= 0, E
= PD
.getNumTypeObjects(); I
!= E
; ++I
) {
7233 if (PD
.getTypeObject(I
).getAttrs().hasAttribute(Kind
))
7237 // Finally, check attributes on the decl itself.
7238 return PD
.getAttributes().hasAttribute(Kind
) ||
7239 PD
.getDeclarationAttributes().hasAttribute(Kind
);
7242 /// Adjust the \c DeclContext for a function or variable that might be a
7243 /// function-local external declaration.
7244 bool Sema::adjustContextForLocalExternDecl(DeclContext
*&DC
) {
7245 if (!DC
->isFunctionOrMethod())
7248 // If this is a local extern function or variable declared within a function
7249 // template, don't add it into the enclosing namespace scope until it is
7250 // instantiated; it might have a dependent type right now.
7251 if (DC
->isDependentContext())
7254 // C++11 [basic.link]p7:
7255 // When a block scope declaration of an entity with linkage is not found to
7256 // refer to some other declaration, then that entity is a member of the
7257 // innermost enclosing namespace.
7259 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7260 // semantically-enclosing namespace, not a lexically-enclosing one.
7261 while (!DC
->isFileContext() && !isa
<LinkageSpecDecl
>(DC
))
7262 DC
= DC
->getParent();
7266 /// Returns true if given declaration has external C language linkage.
7267 static bool isDeclExternC(const Decl
*D
) {
7268 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
7269 return FD
->isExternC();
7270 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
7271 return VD
->isExternC();
7273 llvm_unreachable("Unknown type of decl!");
7276 /// Returns true if there hasn't been any invalid type diagnosed.
7277 static bool diagnoseOpenCLTypes(Sema
&Se
, VarDecl
*NewVD
) {
7278 DeclContext
*DC
= NewVD
->getDeclContext();
7279 QualType R
= NewVD
->getType();
7281 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7282 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7284 if (R
->isImageType() || R
->isPipeType()) {
7285 Se
.Diag(NewVD
->getLocation(),
7286 diag::err_opencl_type_can_only_be_used_as_function_parameter
)
7288 NewVD
->setInvalidDecl();
7292 // OpenCL v1.2 s6.9.r:
7293 // The event type cannot be used to declare a program scope variable.
7294 // OpenCL v2.0 s6.9.q:
7295 // The clk_event_t and reserve_id_t types cannot be declared in program
7297 if (NewVD
->hasGlobalStorage() && !NewVD
->isStaticLocal()) {
7298 if (R
->isReserveIDT() || R
->isClkEventT() || R
->isEventT()) {
7299 Se
.Diag(NewVD
->getLocation(),
7300 diag::err_invalid_type_for_program_scope_var
)
7302 NewVD
->setInvalidDecl();
7307 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7308 if (!Se
.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7309 Se
.getLangOpts())) {
7310 QualType NR
= R
.getCanonicalType();
7311 while (NR
->isPointerType() || NR
->isMemberFunctionPointerType() ||
7312 NR
->isReferenceType()) {
7313 if (NR
->isFunctionPointerType() || NR
->isMemberFunctionPointerType() ||
7314 NR
->isFunctionReferenceType()) {
7315 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_function_pointer
)
7316 << NR
->isReferenceType();
7317 NewVD
->setInvalidDecl();
7320 NR
= NR
->getPointeeType();
7324 if (!Se
.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7325 Se
.getLangOpts())) {
7326 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7327 // half array type (unless the cl_khr_fp16 extension is enabled).
7328 if (Se
.Context
.getBaseElementType(R
)->isHalfType()) {
7329 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_half_declaration
) << R
;
7330 NewVD
->setInvalidDecl();
7335 // OpenCL v1.2 s6.9.r:
7336 // The event type cannot be used with the __local, __constant and __global
7337 // address space qualifiers.
7338 if (R
->isEventT()) {
7339 if (R
.getAddressSpace() != LangAS::opencl_private
) {
7340 Se
.Diag(NewVD
->getBeginLoc(), diag::err_event_t_addr_space_qual
);
7341 NewVD
->setInvalidDecl();
7346 if (R
->isSamplerT()) {
7347 // OpenCL v1.2 s6.9.b p4:
7348 // The sampler type cannot be used with the __local and __global address
7349 // space qualifiers.
7350 if (R
.getAddressSpace() == LangAS::opencl_local
||
7351 R
.getAddressSpace() == LangAS::opencl_global
) {
7352 Se
.Diag(NewVD
->getLocation(), diag::err_wrong_sampler_addressspace
);
7353 NewVD
->setInvalidDecl();
7356 // OpenCL v1.2 s6.12.14.1:
7357 // A global sampler must be declared with either the constant address
7358 // space qualifier or with the const qualifier.
7359 if (DC
->isTranslationUnit() &&
7360 !(R
.getAddressSpace() == LangAS::opencl_constant
||
7361 R
.isConstQualified())) {
7362 Se
.Diag(NewVD
->getLocation(), diag::err_opencl_nonconst_global_sampler
);
7363 NewVD
->setInvalidDecl();
7365 if (NewVD
->isInvalidDecl())
7372 template <typename AttrTy
>
7373 static void copyAttrFromTypedefToDecl(Sema
&S
, Decl
*D
, const TypedefType
*TT
) {
7374 const TypedefNameDecl
*TND
= TT
->getDecl();
7375 if (const auto *Attribute
= TND
->getAttr
<AttrTy
>()) {
7376 AttrTy
*Clone
= Attribute
->clone(S
.Context
);
7377 Clone
->setInherited(true);
7382 // This function emits warning and a corresponding note based on the
7383 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7384 // declarations of an annotated type must be const qualified.
7385 void emitReadOnlyPlacementAttrWarning(Sema
&S
, const VarDecl
*VD
) {
7386 QualType VarType
= VD
->getType().getCanonicalType();
7388 // Ignore local declarations (for now) and those with const qualification.
7389 // TODO: Local variables should not be allowed if their type declaration has
7390 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7391 if (!VD
|| VD
->hasLocalStorage() || VD
->getType().isConstQualified())
7394 if (VarType
->isArrayType()) {
7395 // Retrieve element type for array declarations.
7396 VarType
= S
.getASTContext().getBaseElementType(VarType
);
7399 const RecordDecl
*RD
= VarType
->getAsRecordDecl();
7401 // Check if the record declaration is present and if it has any attributes.
7405 if (const auto *ConstDecl
= RD
->getAttr
<ReadOnlyPlacementAttr
>()) {
7406 S
.Diag(VD
->getLocation(), diag::warn_var_decl_not_read_only
) << RD
;
7407 S
.Diag(ConstDecl
->getLocation(), diag::note_enforce_read_only_placement
);
7412 NamedDecl
*Sema::ActOnVariableDeclarator(
7413 Scope
*S
, Declarator
&D
, DeclContext
*DC
, TypeSourceInfo
*TInfo
,
7414 LookupResult
&Previous
, MultiTemplateParamsArg TemplateParamLists
,
7415 bool &AddToScope
, ArrayRef
<BindingDecl
*> Bindings
) {
7416 QualType R
= TInfo
->getType();
7417 DeclarationName Name
= GetNameForDeclarator(D
).getName();
7419 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
7421 if (D
.isDecompositionDeclarator()) {
7422 // Take the name of the first declarator as our name for diagnostic
7424 auto &Decomp
= D
.getDecompositionDeclarator();
7425 if (!Decomp
.bindings().empty()) {
7426 II
= Decomp
.bindings()[0].Name
;
7430 Diag(D
.getIdentifierLoc(), diag::err_bad_variable_name
) << Name
;
7435 DeclSpec::SCS SCSpec
= D
.getDeclSpec().getStorageClassSpec();
7436 StorageClass SC
= StorageClassSpecToVarDeclStorageClass(D
.getDeclSpec());
7438 // dllimport globals without explicit storage class are treated as extern. We
7439 // have to change the storage class this early to get the right DeclContext.
7440 if (SC
== SC_None
&& !DC
->isRecord() &&
7441 hasParsedAttr(S
, D
, ParsedAttr::AT_DLLImport
) &&
7442 !hasParsedAttr(S
, D
, ParsedAttr::AT_DLLExport
))
7445 DeclContext
*OriginalDC
= DC
;
7446 bool IsLocalExternDecl
= SC
== SC_Extern
&&
7447 adjustContextForLocalExternDecl(DC
);
7449 if (SCSpec
== DeclSpec::SCS_mutable
) {
7450 // mutable can only appear on non-static class members, so it's always
7452 Diag(D
.getIdentifierLoc(), diag::err_mutable_nonmember
);
7457 if (getLangOpts().CPlusPlus11
&& SCSpec
== DeclSpec::SCS_register
&&
7458 !D
.getAsmLabel() && !getSourceManager().isInSystemMacro(
7459 D
.getDeclSpec().getStorageClassSpecLoc())) {
7460 // In C++11, the 'register' storage class specifier is deprecated.
7461 // Suppress the warning in system macros, it's used in macros in some
7462 // popular C system headers, such as in glibc's htonl() macro.
7463 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7464 getLangOpts().CPlusPlus17
? diag::ext_register_storage_class
7465 : diag::warn_deprecated_register
)
7466 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7469 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
7471 if (!DC
->isRecord() && S
->getFnParent() == nullptr) {
7472 // C99 6.9p2: The storage-class specifiers auto and register shall not
7473 // appear in the declaration specifiers in an external declaration.
7474 // Global Register+Asm is a GNU extension we support.
7475 if (SC
== SC_Auto
|| (SC
== SC_Register
&& !D
.getAsmLabel())) {
7476 Diag(D
.getIdentifierLoc(), diag::err_typecheck_sclass_fscope
);
7481 // If this variable has a VLA type and an initializer, try to
7482 // fold to a constant-sized type. This is otherwise invalid.
7483 if (D
.hasInitializer() && R
->isVariableArrayType())
7484 tryToFixVariablyModifiedVarType(TInfo
, R
, D
.getIdentifierLoc(),
7487 bool IsMemberSpecialization
= false;
7488 bool IsVariableTemplateSpecialization
= false;
7489 bool IsPartialSpecialization
= false;
7490 bool IsVariableTemplate
= false;
7491 VarDecl
*NewVD
= nullptr;
7492 VarTemplateDecl
*NewTemplate
= nullptr;
7493 TemplateParameterList
*TemplateParams
= nullptr;
7494 if (!getLangOpts().CPlusPlus
) {
7495 NewVD
= VarDecl::Create(Context
, DC
, D
.getBeginLoc(), D
.getIdentifierLoc(),
7498 if (R
->getContainedDeducedType())
7499 ParsingInitForAutoVars
.insert(NewVD
);
7501 if (D
.isInvalidType())
7502 NewVD
->setInvalidDecl();
7504 if (NewVD
->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7505 NewVD
->hasLocalStorage())
7506 checkNonTrivialCUnion(NewVD
->getType(), NewVD
->getLocation(),
7507 NTCUC_AutoVar
, NTCUK_Destruct
);
7509 bool Invalid
= false;
7511 if (DC
->isRecord() && !CurContext
->isRecord()) {
7512 // This is an out-of-line definition of a static data member.
7517 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7518 diag::err_static_out_of_line
)
7519 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7524 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7525 // to names of variables declared in a block or to function parameters.
7526 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7529 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7530 diag::err_storage_class_for_static_member
)
7531 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
7533 case SC_PrivateExtern
:
7534 llvm_unreachable("C storage class in c++!");
7538 if (SC
== SC_Static
&& CurContext
->isRecord()) {
7539 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(DC
)) {
7540 // Walk up the enclosing DeclContexts to check for any that are
7541 // incompatible with static data members.
7542 const DeclContext
*FunctionOrMethod
= nullptr;
7543 const CXXRecordDecl
*AnonStruct
= nullptr;
7544 for (DeclContext
*Ctxt
= DC
; Ctxt
; Ctxt
= Ctxt
->getParent()) {
7545 if (Ctxt
->isFunctionOrMethod()) {
7546 FunctionOrMethod
= Ctxt
;
7549 const CXXRecordDecl
*ParentDecl
= dyn_cast
<CXXRecordDecl
>(Ctxt
);
7550 if (ParentDecl
&& !ParentDecl
->getDeclName()) {
7551 AnonStruct
= ParentDecl
;
7555 if (FunctionOrMethod
) {
7556 // C++ [class.static.data]p5: A local class shall not have static data
7558 Diag(D
.getIdentifierLoc(),
7559 diag::err_static_data_member_not_allowed_in_local_class
)
7560 << Name
<< RD
->getDeclName() << RD
->getTagKind();
7561 } else if (AnonStruct
) {
7562 // C++ [class.static.data]p4: Unnamed classes and classes contained
7563 // directly or indirectly within unnamed classes shall not contain
7564 // static data members.
7565 Diag(D
.getIdentifierLoc(),
7566 diag::err_static_data_member_not_allowed_in_anon_struct
)
7567 << Name
<< AnonStruct
->getTagKind();
7569 } else if (RD
->isUnion()) {
7570 // C++98 [class.union]p1: If a union contains a static data member,
7571 // the program is ill-formed. C++11 drops this restriction.
7572 Diag(D
.getIdentifierLoc(),
7573 getLangOpts().CPlusPlus11
7574 ? diag::warn_cxx98_compat_static_data_member_in_union
7575 : diag::ext_static_data_member_in_union
) << Name
;
7580 // Match up the template parameter lists with the scope specifier, then
7581 // determine whether we have a template or a template specialization.
7582 bool InvalidScope
= false;
7583 TemplateParams
= MatchTemplateParametersToScopeSpecifier(
7584 D
.getDeclSpec().getBeginLoc(), D
.getIdentifierLoc(),
7585 D
.getCXXScopeSpec(),
7586 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7587 ? D
.getName().TemplateId
7590 /*never a friend*/ false, IsMemberSpecialization
, InvalidScope
);
7591 Invalid
|= InvalidScope
;
7593 if (TemplateParams
) {
7594 if (!TemplateParams
->size() &&
7595 D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
7596 // There is an extraneous 'template<>' for this variable. Complain
7597 // about it, but allow the declaration of the variable.
7598 Diag(TemplateParams
->getTemplateLoc(),
7599 diag::err_template_variable_noparams
)
7601 << SourceRange(TemplateParams
->getTemplateLoc(),
7602 TemplateParams
->getRAngleLoc());
7603 TemplateParams
= nullptr;
7605 // Check that we can declare a template here.
7606 if (CheckTemplateDeclScope(S
, TemplateParams
))
7609 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
7610 // This is an explicit specialization or a partial specialization.
7611 IsVariableTemplateSpecialization
= true;
7612 IsPartialSpecialization
= TemplateParams
->size() > 0;
7613 } else { // if (TemplateParams->size() > 0)
7614 // This is a template declaration.
7615 IsVariableTemplate
= true;
7617 // Only C++1y supports variable templates (N3651).
7618 Diag(D
.getIdentifierLoc(),
7619 getLangOpts().CPlusPlus14
7620 ? diag::warn_cxx11_compat_variable_template
7621 : diag::ext_variable_template
);
7625 // Check that we can declare a member specialization here.
7626 if (!TemplateParamLists
.empty() && IsMemberSpecialization
&&
7627 CheckTemplateDeclScope(S
, TemplateParamLists
.back()))
7630 D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) &&
7631 "should have a 'template<>' for this decl");
7634 if (IsVariableTemplateSpecialization
) {
7635 SourceLocation TemplateKWLoc
=
7636 TemplateParamLists
.size() > 0
7637 ? TemplateParamLists
[0]->getTemplateLoc()
7639 DeclResult Res
= ActOnVarTemplateSpecialization(
7640 S
, D
, TInfo
, TemplateKWLoc
, TemplateParams
, SC
,
7641 IsPartialSpecialization
);
7642 if (Res
.isInvalid())
7644 NewVD
= cast
<VarDecl
>(Res
.get());
7646 } else if (D
.isDecompositionDeclarator()) {
7647 NewVD
= DecompositionDecl::Create(Context
, DC
, D
.getBeginLoc(),
7648 D
.getIdentifierLoc(), R
, TInfo
, SC
,
7651 NewVD
= VarDecl::Create(Context
, DC
, D
.getBeginLoc(),
7652 D
.getIdentifierLoc(), II
, R
, TInfo
, SC
);
7654 // If this is supposed to be a variable template, create it as such.
7655 if (IsVariableTemplate
) {
7657 VarTemplateDecl::Create(Context
, DC
, D
.getIdentifierLoc(), Name
,
7658 TemplateParams
, NewVD
);
7659 NewVD
->setDescribedVarTemplate(NewTemplate
);
7662 // If this decl has an auto type in need of deduction, make a note of the
7663 // Decl so we can diagnose uses of it in its own initializer.
7664 if (R
->getContainedDeducedType())
7665 ParsingInitForAutoVars
.insert(NewVD
);
7667 if (D
.isInvalidType() || Invalid
) {
7668 NewVD
->setInvalidDecl();
7670 NewTemplate
->setInvalidDecl();
7673 SetNestedNameSpecifier(*this, NewVD
, D
);
7675 // If we have any template parameter lists that don't directly belong to
7676 // the variable (matching the scope specifier), store them.
7677 unsigned VDTemplateParamLists
= TemplateParams
? 1 : 0;
7678 if (TemplateParamLists
.size() > VDTemplateParamLists
)
7679 NewVD
->setTemplateParameterListsInfo(
7680 Context
, TemplateParamLists
.drop_back(VDTemplateParamLists
));
7683 if (D
.getDeclSpec().isInlineSpecified()) {
7684 if (!getLangOpts().CPlusPlus
) {
7685 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
7687 } else if (CurContext
->isFunctionOrMethod()) {
7688 // 'inline' is not allowed on block scope variable declaration.
7689 Diag(D
.getDeclSpec().getInlineSpecLoc(),
7690 diag::err_inline_declaration_block_scope
) << Name
7691 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
7693 Diag(D
.getDeclSpec().getInlineSpecLoc(),
7694 getLangOpts().CPlusPlus17
? diag::warn_cxx14_compat_inline_variable
7695 : diag::ext_inline_variable
);
7696 NewVD
->setInlineSpecified();
7700 // Set the lexical context. If the declarator has a C++ scope specifier, the
7701 // lexical context will be different from the semantic context.
7702 NewVD
->setLexicalDeclContext(CurContext
);
7704 NewTemplate
->setLexicalDeclContext(CurContext
);
7706 if (IsLocalExternDecl
) {
7707 if (D
.isDecompositionDeclarator())
7708 for (auto *B
: Bindings
)
7709 B
->setLocalExternDecl();
7711 NewVD
->setLocalExternDecl();
7714 bool EmitTLSUnsupportedError
= false;
7715 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec()) {
7716 // C++11 [dcl.stc]p4:
7717 // When thread_local is applied to a variable of block scope the
7718 // storage-class-specifier static is implied if it does not appear
7720 // Core issue: 'static' is not implied if the variable is declared
7722 if (NewVD
->hasLocalStorage() &&
7723 (SCSpec
!= DeclSpec::SCS_unspecified
||
7724 TSCS
!= DeclSpec::TSCS_thread_local
||
7725 !DC
->isFunctionOrMethod()))
7726 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7727 diag::err_thread_non_global
)
7728 << DeclSpec::getSpecifierName(TSCS
);
7729 else if (!Context
.getTargetInfo().isTLSSupported()) {
7730 if (getLangOpts().CUDA
|| getLangOpts().OpenMPIsDevice
||
7731 getLangOpts().SYCLIsDevice
) {
7732 // Postpone error emission until we've collected attributes required to
7733 // figure out whether it's a host or device variable and whether the
7734 // error should be ignored.
7735 EmitTLSUnsupportedError
= true;
7736 // We still need to mark the variable as TLS so it shows up in AST with
7737 // proper storage class for other tools to use even if we're not going
7738 // to emit any code for it.
7739 NewVD
->setTSCSpec(TSCS
);
7741 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7742 diag::err_thread_unsupported
);
7744 NewVD
->setTSCSpec(TSCS
);
7747 switch (D
.getDeclSpec().getConstexprSpecifier()) {
7748 case ConstexprSpecKind::Unspecified
:
7751 case ConstexprSpecKind::Consteval
:
7752 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
7753 diag::err_constexpr_wrong_decl_kind
)
7754 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
7757 case ConstexprSpecKind::Constexpr
:
7758 NewVD
->setConstexpr(true);
7759 // C++1z [dcl.spec.constexpr]p1:
7760 // A static data member declared with the constexpr specifier is
7761 // implicitly an inline variable.
7762 if (NewVD
->isStaticDataMember() &&
7763 (getLangOpts().CPlusPlus17
||
7764 Context
.getTargetInfo().getCXXABI().isMicrosoft()))
7765 NewVD
->setImplicitlyInline();
7768 case ConstexprSpecKind::Constinit
:
7769 if (!NewVD
->hasGlobalStorage())
7770 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
7771 diag::err_constinit_local_variable
);
7773 NewVD
->addAttr(ConstInitAttr::Create(
7774 Context
, D
.getDeclSpec().getConstexprSpecLoc(),
7775 AttributeCommonInfo::AS_Keyword
, ConstInitAttr::Keyword_constinit
));
7780 // An inline definition of a function with external linkage shall
7781 // not contain a definition of a modifiable object with static or
7782 // thread storage duration...
7783 // We only apply this when the function is required to be defined
7784 // elsewhere, i.e. when the function is not 'extern inline'. Note
7785 // that a local variable with thread storage duration still has to
7786 // be marked 'static'. Also note that it's possible to get these
7787 // semantics in C++ using __attribute__((gnu_inline)).
7788 if (SC
== SC_Static
&& S
->getFnParent() != nullptr &&
7789 !NewVD
->getType().isConstQualified()) {
7790 FunctionDecl
*CurFD
= getCurFunctionDecl();
7791 if (CurFD
&& isFunctionDefinitionDiscarded(*this, CurFD
)) {
7792 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
7793 diag::warn_static_local_in_extern_inline
);
7794 MaybeSuggestAddingStaticToDecl(CurFD
);
7798 if (D
.getDeclSpec().isModulePrivateSpecified()) {
7799 if (IsVariableTemplateSpecialization
)
7800 Diag(NewVD
->getLocation(), diag::err_module_private_specialization
)
7801 << (IsPartialSpecialization
? 1 : 0)
7802 << FixItHint::CreateRemoval(
7803 D
.getDeclSpec().getModulePrivateSpecLoc());
7804 else if (IsMemberSpecialization
)
7805 Diag(NewVD
->getLocation(), diag::err_module_private_specialization
)
7807 << FixItHint::CreateRemoval(D
.getDeclSpec().getModulePrivateSpecLoc());
7808 else if (NewVD
->hasLocalStorage())
7809 Diag(NewVD
->getLocation(), diag::err_module_private_local
)
7811 << SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
7812 << FixItHint::CreateRemoval(
7813 D
.getDeclSpec().getModulePrivateSpecLoc());
7815 NewVD
->setModulePrivate();
7817 NewTemplate
->setModulePrivate();
7818 for (auto *B
: Bindings
)
7819 B
->setModulePrivate();
7823 if (getLangOpts().OpenCL
) {
7824 deduceOpenCLAddressSpace(NewVD
);
7826 DeclSpec::TSCS TSC
= D
.getDeclSpec().getThreadStorageClassSpec();
7827 if (TSC
!= TSCS_unspecified
) {
7828 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7829 diag::err_opencl_unknown_type_specifier
)
7830 << getLangOpts().getOpenCLVersionString()
7831 << DeclSpec::getSpecifierName(TSC
) << 1;
7832 NewVD
->setInvalidDecl();
7836 // Handle attributes prior to checking for duplicates in MergeVarDecl
7837 ProcessDeclAttributes(S
, NewVD
, D
);
7839 // FIXME: This is probably the wrong location to be doing this and we should
7840 // probably be doing this for more attributes (especially for function
7841 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7842 // the code to copy attributes would be generated by TableGen.
7843 if (R
->isFunctionPointerType())
7844 if (const auto *TT
= R
->getAs
<TypedefType
>())
7845 copyAttrFromTypedefToDecl
<AllocSizeAttr
>(*this, NewVD
, TT
);
7847 if (getLangOpts().CUDA
|| getLangOpts().OpenMPIsDevice
||
7848 getLangOpts().SYCLIsDevice
) {
7849 if (EmitTLSUnsupportedError
&&
7850 ((getLangOpts().CUDA
&& DeclAttrsMatchCUDAMode(getLangOpts(), NewVD
)) ||
7851 (getLangOpts().OpenMPIsDevice
&&
7852 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD
))))
7853 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
7854 diag::err_thread_unsupported
);
7856 if (EmitTLSUnsupportedError
&&
7857 (LangOpts
.SYCLIsDevice
|| (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsDevice
)))
7858 targetDiag(D
.getIdentifierLoc(), diag::err_thread_unsupported
);
7859 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7860 // storage [duration]."
7861 if (SC
== SC_None
&& S
->getFnParent() != nullptr &&
7862 (NewVD
->hasAttr
<CUDASharedAttr
>() ||
7863 NewVD
->hasAttr
<CUDAConstantAttr
>())) {
7864 NewVD
->setStorageClass(SC_Static
);
7868 // Ensure that dllimport globals without explicit storage class are treated as
7869 // extern. The storage class is set above using parsed attributes. Now we can
7870 // check the VarDecl itself.
7871 assert(!NewVD
->hasAttr
<DLLImportAttr
>() ||
7872 NewVD
->getAttr
<DLLImportAttr
>()->isInherited() ||
7873 NewVD
->isStaticDataMember() || NewVD
->getStorageClass() != SC_None
);
7875 // In auto-retain/release, infer strong retension for variables of
7877 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewVD
))
7878 NewVD
->setInvalidDecl();
7880 // Handle GNU asm-label extension (encoded as an attribute).
7881 if (Expr
*E
= (Expr
*)D
.getAsmLabel()) {
7882 // The parser guarantees this is a string.
7883 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
7884 StringRef Label
= SE
->getString();
7885 if (S
->getFnParent() != nullptr) {
7889 Diag(E
->getExprLoc(), diag::warn_asm_label_on_auto_decl
) << Label
;
7892 // Local Named register
7893 if (!Context
.getTargetInfo().isValidGCCRegisterName(Label
) &&
7894 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7895 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
7899 case SC_PrivateExtern
:
7902 } else if (SC
== SC_Register
) {
7903 // Global Named register
7904 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD
)) {
7905 const auto &TI
= Context
.getTargetInfo();
7906 bool HasSizeMismatch
;
7908 if (!TI
.isValidGCCRegisterName(Label
))
7909 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
7910 else if (!TI
.validateGlobalRegisterVariable(Label
,
7911 Context
.getTypeSize(R
),
7913 Diag(E
->getExprLoc(), diag::err_asm_invalid_global_var_reg
) << Label
;
7914 else if (HasSizeMismatch
)
7915 Diag(E
->getExprLoc(), diag::err_asm_register_size_mismatch
) << Label
;
7918 if (!R
->isIntegralType(Context
) && !R
->isPointerType()) {
7919 Diag(D
.getBeginLoc(), diag::err_asm_bad_register_type
);
7920 NewVD
->setInvalidDecl(true);
7924 NewVD
->addAttr(AsmLabelAttr::Create(Context
, Label
,
7925 /*IsLiteralLabel=*/true,
7926 SE
->getStrTokenLoc(0)));
7927 } else if (!ExtnameUndeclaredIdentifiers
.empty()) {
7928 llvm::DenseMap
<IdentifierInfo
*,AsmLabelAttr
*>::iterator I
=
7929 ExtnameUndeclaredIdentifiers
.find(NewVD
->getIdentifier());
7930 if (I
!= ExtnameUndeclaredIdentifiers
.end()) {
7931 if (isDeclExternC(NewVD
)) {
7932 NewVD
->addAttr(I
->second
);
7933 ExtnameUndeclaredIdentifiers
.erase(I
);
7935 Diag(NewVD
->getLocation(), diag::warn_redefine_extname_not_applied
)
7936 << /*Variable*/1 << NewVD
;
7940 // Find the shadowed declaration before filtering for scope.
7941 NamedDecl
*ShadowedDecl
= D
.getCXXScopeSpec().isEmpty()
7942 ? getShadowedDeclaration(NewVD
, Previous
)
7945 // Don't consider existing declarations that are in a different
7946 // scope and are out-of-semantic-context declarations (if the new
7947 // declaration has linkage).
7948 FilterLookupForScope(Previous
, OriginalDC
, S
, shouldConsiderLinkage(NewVD
),
7949 D
.getCXXScopeSpec().isNotEmpty() ||
7950 IsMemberSpecialization
||
7951 IsVariableTemplateSpecialization
);
7953 // Check whether the previous declaration is in the same block scope. This
7954 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7955 if (getLangOpts().CPlusPlus
&&
7956 NewVD
->isLocalVarDecl() && NewVD
->hasExternalStorage())
7957 NewVD
->setPreviousDeclInSameBlockScope(
7958 Previous
.isSingleResult() && !Previous
.isShadowed() &&
7959 isDeclInScope(Previous
.getFoundDecl(), OriginalDC
, S
, false));
7961 if (!getLangOpts().CPlusPlus
) {
7962 D
.setRedeclaration(CheckVariableDeclaration(NewVD
, Previous
));
7964 // If this is an explicit specialization of a static data member, check it.
7965 if (IsMemberSpecialization
&& !NewVD
->isInvalidDecl() &&
7966 CheckMemberSpecialization(NewVD
, Previous
))
7967 NewVD
->setInvalidDecl();
7969 // Merge the decl with the existing one if appropriate.
7970 if (!Previous
.empty()) {
7971 if (Previous
.isSingleResult() &&
7972 isa
<FieldDecl
>(Previous
.getFoundDecl()) &&
7973 D
.getCXXScopeSpec().isSet()) {
7974 // The user tried to define a non-static data member
7975 // out-of-line (C++ [dcl.meaning]p1).
7976 Diag(NewVD
->getLocation(), diag::err_nonstatic_member_out_of_line
)
7977 << D
.getCXXScopeSpec().getRange();
7979 NewVD
->setInvalidDecl();
7981 } else if (D
.getCXXScopeSpec().isSet()) {
7982 // No previous declaration in the qualifying scope.
7983 Diag(D
.getIdentifierLoc(), diag::err_no_member
)
7984 << Name
<< computeDeclContext(D
.getCXXScopeSpec(), true)
7985 << D
.getCXXScopeSpec().getRange();
7986 NewVD
->setInvalidDecl();
7989 if (!IsVariableTemplateSpecialization
)
7990 D
.setRedeclaration(CheckVariableDeclaration(NewVD
, Previous
));
7993 VarTemplateDecl
*PrevVarTemplate
=
7994 NewVD
->getPreviousDecl()
7995 ? NewVD
->getPreviousDecl()->getDescribedVarTemplate()
7998 // Check the template parameter list of this declaration, possibly
7999 // merging in the template parameter list from the previous variable
8000 // template declaration.
8001 if (CheckTemplateParameterList(
8003 PrevVarTemplate
? PrevVarTemplate
->getTemplateParameters()
8005 (D
.getCXXScopeSpec().isSet() && DC
&& DC
->isRecord() &&
8006 DC
->isDependentContext())
8007 ? TPC_ClassTemplateMember
8009 NewVD
->setInvalidDecl();
8011 // If we are providing an explicit specialization of a static variable
8012 // template, make a note of that.
8013 if (PrevVarTemplate
&&
8014 PrevVarTemplate
->getInstantiatedFromMemberTemplate())
8015 PrevVarTemplate
->setMemberSpecialization();
8019 // Diagnose shadowed variables iff this isn't a redeclaration.
8020 if (ShadowedDecl
&& !D
.isRedeclaration())
8021 CheckShadow(NewVD
, ShadowedDecl
, Previous
);
8023 ProcessPragmaWeak(S
, NewVD
);
8025 // If this is the first declaration of an extern C variable, update
8026 // the map of such variables.
8027 if (NewVD
->isFirstDecl() && !NewVD
->isInvalidDecl() &&
8028 isIncompleteDeclExternC(*this, NewVD
))
8029 RegisterLocallyScopedExternCDecl(NewVD
, S
);
8031 if (getLangOpts().CPlusPlus
&& NewVD
->isStaticLocal()) {
8032 MangleNumberingContext
*MCtx
;
8033 Decl
*ManglingContextDecl
;
8034 std::tie(MCtx
, ManglingContextDecl
) =
8035 getCurrentMangleNumberContext(NewVD
->getDeclContext());
8037 Context
.setManglingNumber(
8038 NewVD
, MCtx
->getManglingNumber(
8039 NewVD
, getMSManglingNumber(getLangOpts(), S
)));
8040 Context
.setStaticLocalNumber(NewVD
, MCtx
->getStaticLocalNumber(NewVD
));
8044 // Special handling of variable named 'main'.
8045 if (Name
.getAsIdentifierInfo() && Name
.getAsIdentifierInfo()->isStr("main") &&
8046 NewVD
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8047 !getLangOpts().Freestanding
&& !NewVD
->getDescribedVarTemplate()) {
8049 // C++ [basic.start.main]p3
8050 // A program that declares a variable main at global scope is ill-formed.
8051 if (getLangOpts().CPlusPlus
)
8052 Diag(D
.getBeginLoc(), diag::err_main_global_variable
);
8054 // In C, and external-linkage variable named main results in undefined
8056 else if (NewVD
->hasExternalFormalLinkage())
8057 Diag(D
.getBeginLoc(), diag::warn_main_redefined
);
8060 if (D
.isRedeclaration() && !Previous
.empty()) {
8061 NamedDecl
*Prev
= Previous
.getRepresentativeDecl();
8062 checkDLLAttributeRedeclaration(*this, Prev
, NewVD
, IsMemberSpecialization
,
8063 D
.isFunctionDefinition());
8067 if (NewVD
->isInvalidDecl())
8068 NewTemplate
->setInvalidDecl();
8069 ActOnDocumentableDecl(NewTemplate
);
8073 if (IsMemberSpecialization
&& !NewVD
->isInvalidDecl())
8074 CompleteMemberSpecialization(NewVD
, Previous
);
8076 emitReadOnlyPlacementAttrWarning(*this, NewVD
);
8081 /// Enum describing the %select options in diag::warn_decl_shadow.
8082 enum ShadowedDeclKind
{
8089 SDK_StructuredBinding
8092 /// Determine what kind of declaration we're shadowing.
8093 static ShadowedDeclKind
computeShadowedDeclKind(const NamedDecl
*ShadowedDecl
,
8094 const DeclContext
*OldDC
) {
8095 if (isa
<TypeAliasDecl
>(ShadowedDecl
))
8097 else if (isa
<TypedefDecl
>(ShadowedDecl
))
8099 else if (isa
<BindingDecl
>(ShadowedDecl
))
8100 return SDK_StructuredBinding
;
8101 else if (isa
<RecordDecl
>(OldDC
))
8102 return isa
<FieldDecl
>(ShadowedDecl
) ? SDK_Field
: SDK_StaticMember
;
8104 return OldDC
->isFileContext() ? SDK_Global
: SDK_Local
;
8107 /// Return the location of the capture if the given lambda captures the given
8108 /// variable \p VD, or an invalid source location otherwise.
8109 static SourceLocation
getCaptureLocation(const LambdaScopeInfo
*LSI
,
8110 const VarDecl
*VD
) {
8111 for (const Capture
&Capture
: LSI
->Captures
) {
8112 if (Capture
.isVariableCapture() && Capture
.getVariable() == VD
)
8113 return Capture
.getLocation();
8115 return SourceLocation();
8118 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine
&Diags
,
8119 const LookupResult
&R
) {
8120 // Only diagnose if we're shadowing an unambiguous field or variable.
8121 if (R
.getResultKind() != LookupResult::Found
)
8124 // Return false if warning is ignored.
8125 return !Diags
.isIgnored(diag::warn_decl_shadow
, R
.getNameLoc());
8128 /// Return the declaration shadowed by the given variable \p D, or null
8129 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8130 NamedDecl
*Sema::getShadowedDeclaration(const VarDecl
*D
,
8131 const LookupResult
&R
) {
8132 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8135 // Don't diagnose declarations at file scope.
8136 if (D
->hasGlobalStorage())
8139 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8140 return isa
<VarDecl
, FieldDecl
, BindingDecl
>(ShadowedDecl
) ? ShadowedDecl
8144 /// Return the declaration shadowed by the given typedef \p D, or null
8145 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8146 NamedDecl
*Sema::getShadowedDeclaration(const TypedefNameDecl
*D
,
8147 const LookupResult
&R
) {
8148 // Don't warn if typedef declaration is part of a class
8149 if (D
->getDeclContext()->isRecord())
8152 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8155 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8156 return isa
<TypedefNameDecl
>(ShadowedDecl
) ? ShadowedDecl
: nullptr;
8159 /// Return the declaration shadowed by the given variable \p D, or null
8160 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8161 NamedDecl
*Sema::getShadowedDeclaration(const BindingDecl
*D
,
8162 const LookupResult
&R
) {
8163 if (!shouldWarnIfShadowedDecl(Diags
, R
))
8166 NamedDecl
*ShadowedDecl
= R
.getFoundDecl();
8167 return isa
<VarDecl
, FieldDecl
, BindingDecl
>(ShadowedDecl
) ? ShadowedDecl
8171 /// Diagnose variable or built-in function shadowing. Implements
8174 /// This method is called whenever a VarDecl is added to a "useful"
8177 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8178 /// \param R the lookup of the name
8180 void Sema::CheckShadow(NamedDecl
*D
, NamedDecl
*ShadowedDecl
,
8181 const LookupResult
&R
) {
8182 DeclContext
*NewDC
= D
->getDeclContext();
8184 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ShadowedDecl
)) {
8185 // Fields are not shadowed by variables in C++ static methods.
8186 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewDC
))
8190 // Fields shadowed by constructor parameters are a special case. Usually
8191 // the constructor initializes the field with the parameter.
8192 if (isa
<CXXConstructorDecl
>(NewDC
))
8193 if (const auto PVD
= dyn_cast
<ParmVarDecl
>(D
)) {
8194 // Remember that this was shadowed so we can either warn about its
8195 // modification or its existence depending on warning settings.
8196 ShadowingDecls
.insert({PVD
->getCanonicalDecl(), FD
});
8201 if (VarDecl
*shadowedVar
= dyn_cast
<VarDecl
>(ShadowedDecl
))
8202 if (shadowedVar
->isExternC()) {
8203 // For shadowing external vars, make sure that we point to the global
8204 // declaration, not a locally scoped extern declaration.
8205 for (auto *I
: shadowedVar
->redecls())
8206 if (I
->isFileVarDecl()) {
8212 DeclContext
*OldDC
= ShadowedDecl
->getDeclContext()->getRedeclContext();
8214 unsigned WarningDiag
= diag::warn_decl_shadow
;
8215 SourceLocation CaptureLoc
;
8216 if (isa
<VarDecl
>(D
) && isa
<VarDecl
>(ShadowedDecl
) && NewDC
&&
8217 isa
<CXXMethodDecl
>(NewDC
)) {
8218 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(NewDC
->getParent())) {
8219 if (RD
->isLambda() && OldDC
->Encloses(NewDC
->getLexicalParent())) {
8220 if (RD
->getLambdaCaptureDefault() == LCD_None
) {
8221 // Try to avoid warnings for lambdas with an explicit capture list.
8222 const auto *LSI
= cast
<LambdaScopeInfo
>(getCurFunction());
8223 // Warn only when the lambda captures the shadowed decl explicitly.
8224 CaptureLoc
= getCaptureLocation(LSI
, cast
<VarDecl
>(ShadowedDecl
));
8225 if (CaptureLoc
.isInvalid())
8226 WarningDiag
= diag::warn_decl_shadow_uncaptured_local
;
8228 // Remember that this was shadowed so we can avoid the warning if the
8229 // shadowed decl isn't captured and the warning settings allow it.
8230 cast
<LambdaScopeInfo
>(getCurFunction())
8231 ->ShadowingDecls
.push_back(
8232 {cast
<VarDecl
>(D
), cast
<VarDecl
>(ShadowedDecl
)});
8237 if (cast
<VarDecl
>(ShadowedDecl
)->hasLocalStorage()) {
8238 // A variable can't shadow a local variable in an enclosing scope, if
8239 // they are separated by a non-capturing declaration context.
8240 for (DeclContext
*ParentDC
= NewDC
;
8241 ParentDC
&& !ParentDC
->Equals(OldDC
);
8242 ParentDC
= getLambdaAwareParentOfDeclContext(ParentDC
)) {
8243 // Only block literals, captured statements, and lambda expressions
8244 // can capture; other scopes don't.
8245 if (!isa
<BlockDecl
>(ParentDC
) && !isa
<CapturedDecl
>(ParentDC
) &&
8246 !isLambdaCallOperator(ParentDC
)) {
8254 // Only warn about certain kinds of shadowing for class members.
8255 if (NewDC
&& NewDC
->isRecord()) {
8256 // In particular, don't warn about shadowing non-class members.
8257 if (!OldDC
->isRecord())
8260 // TODO: should we warn about static data members shadowing
8261 // static data members from base classes?
8263 // TODO: don't diagnose for inaccessible shadowed members.
8264 // This is hard to do perfectly because we might friend the
8265 // shadowing context, but that's just a false negative.
8269 DeclarationName Name
= R
.getLookupName();
8271 // Emit warning and note.
8272 ShadowedDeclKind Kind
= computeShadowedDeclKind(ShadowedDecl
, OldDC
);
8273 Diag(R
.getNameLoc(), WarningDiag
) << Name
<< Kind
<< OldDC
;
8274 if (!CaptureLoc
.isInvalid())
8275 Diag(CaptureLoc
, diag::note_var_explicitly_captured_here
)
8276 << Name
<< /*explicitly*/ 1;
8277 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8280 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8281 /// when these variables are captured by the lambda.
8282 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo
*LSI
) {
8283 for (const auto &Shadow
: LSI
->ShadowingDecls
) {
8284 const VarDecl
*ShadowedDecl
= Shadow
.ShadowedDecl
;
8285 // Try to avoid the warning when the shadowed decl isn't captured.
8286 SourceLocation CaptureLoc
= getCaptureLocation(LSI
, ShadowedDecl
);
8287 const DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
8288 Diag(Shadow
.VD
->getLocation(), CaptureLoc
.isInvalid()
8289 ? diag::warn_decl_shadow_uncaptured_local
8290 : diag::warn_decl_shadow
)
8291 << Shadow
.VD
->getDeclName()
8292 << computeShadowedDeclKind(ShadowedDecl
, OldDC
) << OldDC
;
8293 if (!CaptureLoc
.isInvalid())
8294 Diag(CaptureLoc
, diag::note_var_explicitly_captured_here
)
8295 << Shadow
.VD
->getDeclName() << /*explicitly*/ 0;
8296 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8300 /// Check -Wshadow without the advantage of a previous lookup.
8301 void Sema::CheckShadow(Scope
*S
, VarDecl
*D
) {
8302 if (Diags
.isIgnored(diag::warn_decl_shadow
, D
->getLocation()))
8305 LookupResult
R(*this, D
->getDeclName(), D
->getLocation(),
8306 Sema::LookupOrdinaryName
, Sema::ForVisibleRedeclaration
);
8308 if (NamedDecl
*ShadowedDecl
= getShadowedDeclaration(D
, R
))
8309 CheckShadow(D
, ShadowedDecl
, R
);
8312 /// Check if 'E', which is an expression that is about to be modified, refers
8313 /// to a constructor parameter that shadows a field.
8314 void Sema::CheckShadowingDeclModification(Expr
*E
, SourceLocation Loc
) {
8315 // Quickly ignore expressions that can't be shadowing ctor parameters.
8316 if (!getLangOpts().CPlusPlus
|| ShadowingDecls
.empty())
8318 E
= E
->IgnoreParenImpCasts();
8319 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
);
8322 const NamedDecl
*D
= cast
<NamedDecl
>(DRE
->getDecl()->getCanonicalDecl());
8323 auto I
= ShadowingDecls
.find(D
);
8324 if (I
== ShadowingDecls
.end())
8326 const NamedDecl
*ShadowedDecl
= I
->second
;
8327 const DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
8328 Diag(Loc
, diag::warn_modifying_shadowing_decl
) << D
<< OldDC
;
8329 Diag(D
->getLocation(), diag::note_var_declared_here
) << D
;
8330 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
8332 // Avoid issuing multiple warnings about the same decl.
8333 ShadowingDecls
.erase(I
);
8336 /// Check for conflict between this global or extern "C" declaration and
8337 /// previous global or extern "C" declarations. This is only used in C++.
8338 template<typename T
>
8339 static bool checkGlobalOrExternCConflict(
8340 Sema
&S
, const T
*ND
, bool IsGlobal
, LookupResult
&Previous
) {
8341 assert(S
.getLangOpts().CPlusPlus
&& "only C++ has extern \"C\"");
8342 NamedDecl
*Prev
= S
.findLocallyScopedExternCDecl(ND
->getDeclName());
8344 if (!Prev
&& IsGlobal
&& !isIncompleteDeclExternC(S
, ND
)) {
8345 // The common case: this global doesn't conflict with any extern "C"
8351 if (!IsGlobal
|| isIncompleteDeclExternC(S
, ND
)) {
8352 // Both the old and new declarations have C language linkage. This is a
8355 Previous
.addDecl(Prev
);
8359 // This is a global, non-extern "C" declaration, and there is a previous
8360 // non-global extern "C" declaration. Diagnose if this is a variable
8362 if (!isa
<VarDecl
>(ND
))
8365 // The declaration is extern "C". Check for any declaration in the
8366 // translation unit which might conflict.
8368 // We have already performed the lookup into the translation unit.
8370 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
8372 if (isa
<VarDecl
>(*I
)) {
8378 DeclContext::lookup_result R
=
8379 S
.Context
.getTranslationUnitDecl()->lookup(ND
->getDeclName());
8380 for (DeclContext::lookup_result::iterator I
= R
.begin(), E
= R
.end();
8382 if (isa
<VarDecl
>(*I
)) {
8386 // FIXME: If we have any other entity with this name in global scope,
8387 // the declaration is ill-formed, but that is a defect: it breaks the
8388 // 'stat' hack, for instance. Only variables can have mangled name
8389 // clashes with extern "C" declarations, so only they deserve a
8398 // Use the first declaration's location to ensure we point at something which
8399 // is lexically inside an extern "C" linkage-spec.
8400 assert(Prev
&& "should have found a previous declaration to diagnose");
8401 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(Prev
))
8402 Prev
= FD
->getFirstDecl();
8404 Prev
= cast
<VarDecl
>(Prev
)->getFirstDecl();
8406 S
.Diag(ND
->getLocation(), diag::err_extern_c_global_conflict
)
8408 S
.Diag(Prev
->getLocation(), diag::note_extern_c_global_conflict
)
8413 /// Apply special rules for handling extern "C" declarations. Returns \c true
8414 /// if we have found that this is a redeclaration of some prior entity.
8416 /// Per C++ [dcl.link]p6:
8417 /// Two declarations [for a function or variable] with C language linkage
8418 /// with the same name that appear in different scopes refer to the same
8419 /// [entity]. An entity with C language linkage shall not be declared with
8420 /// the same name as an entity in global scope.
8421 template<typename T
>
8422 static bool checkForConflictWithNonVisibleExternC(Sema
&S
, const T
*ND
,
8423 LookupResult
&Previous
) {
8424 if (!S
.getLangOpts().CPlusPlus
) {
8425 // In C, when declaring a global variable, look for a corresponding 'extern'
8426 // variable declared in function scope. We don't need this in C++, because
8427 // we find local extern decls in the surrounding file-scope DeclContext.
8428 if (ND
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8429 if (NamedDecl
*Prev
= S
.findLocallyScopedExternCDecl(ND
->getDeclName())) {
8431 Previous
.addDecl(Prev
);
8438 // A declaration in the translation unit can conflict with an extern "C"
8440 if (ND
->getDeclContext()->getRedeclContext()->isTranslationUnit())
8441 return checkGlobalOrExternCConflict(S
, ND
, /*IsGlobal*/true, Previous
);
8443 // An extern "C" declaration can conflict with a declaration in the
8444 // translation unit or can be a redeclaration of an extern "C" declaration
8445 // in another scope.
8446 if (isIncompleteDeclExternC(S
,ND
))
8447 return checkGlobalOrExternCConflict(S
, ND
, /*IsGlobal*/false, Previous
);
8449 // Neither global nor extern "C": nothing to do.
8453 void Sema::CheckVariableDeclarationType(VarDecl
*NewVD
) {
8454 // If the decl is already known invalid, don't check it.
8455 if (NewVD
->isInvalidDecl())
8458 QualType T
= NewVD
->getType();
8460 // Defer checking an 'auto' type until its initializer is attached.
8461 if (T
->isUndeducedType())
8464 if (NewVD
->hasAttrs())
8465 CheckAlignasUnderalignment(NewVD
);
8467 if (T
->isObjCObjectType()) {
8468 Diag(NewVD
->getLocation(), diag::err_statically_allocated_object
)
8469 << FixItHint::CreateInsertion(NewVD
->getLocation(), "*");
8470 T
= Context
.getObjCObjectPointerType(T
);
8474 // Emit an error if an address space was applied to decl with local storage.
8475 // This includes arrays of objects with address space qualifiers, but not
8476 // automatic variables that point to other address spaces.
8477 // ISO/IEC TR 18037 S5.1.2
8478 if (!getLangOpts().OpenCL
&& NewVD
->hasLocalStorage() &&
8479 T
.getAddressSpace() != LangAS::Default
) {
8480 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
) << 0;
8481 NewVD
->setInvalidDecl();
8485 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8487 if (getLangOpts().OpenCLVersion
== 120 &&
8488 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8490 NewVD
->isStaticLocal()) {
8491 Diag(NewVD
->getLocation(), diag::err_static_function_scope
);
8492 NewVD
->setInvalidDecl();
8496 if (getLangOpts().OpenCL
) {
8497 if (!diagnoseOpenCLTypes(*this, NewVD
))
8500 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8501 if (NewVD
->hasAttr
<BlocksAttr
>()) {
8502 Diag(NewVD
->getLocation(), diag::err_opencl_block_storage_type
);
8506 if (T
->isBlockPointerType()) {
8507 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8508 // can't use 'extern' storage class.
8509 if (!T
.isConstQualified()) {
8510 Diag(NewVD
->getLocation(), diag::err_opencl_invalid_block_declaration
)
8512 NewVD
->setInvalidDecl();
8515 if (NewVD
->hasExternalStorage()) {
8516 Diag(NewVD
->getLocation(), diag::err_opencl_extern_block_declaration
);
8517 NewVD
->setInvalidDecl();
8522 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8523 if (NewVD
->isFileVarDecl() || NewVD
->isStaticLocal() ||
8524 NewVD
->hasExternalStorage()) {
8525 if (!T
->isSamplerT() && !T
->isDependentType() &&
8526 !(T
.getAddressSpace() == LangAS::opencl_constant
||
8527 (T
.getAddressSpace() == LangAS::opencl_global
&&
8528 getOpenCLOptions().areProgramScopeVariablesSupported(
8530 int Scope
= NewVD
->isStaticLocal() | NewVD
->hasExternalStorage() << 1;
8531 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8532 Diag(NewVD
->getLocation(), diag::err_opencl_global_invalid_addr_space
)
8533 << Scope
<< "global or constant";
8535 Diag(NewVD
->getLocation(), diag::err_opencl_global_invalid_addr_space
)
8536 << Scope
<< "constant";
8537 NewVD
->setInvalidDecl();
8541 if (T
.getAddressSpace() == LangAS::opencl_global
) {
8542 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8543 << 1 /*is any function*/ << "global";
8544 NewVD
->setInvalidDecl();
8547 if (T
.getAddressSpace() == LangAS::opencl_constant
||
8548 T
.getAddressSpace() == LangAS::opencl_local
) {
8549 FunctionDecl
*FD
= getCurFunctionDecl();
8550 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8552 if (FD
&& !FD
->hasAttr
<OpenCLKernelAttr
>()) {
8553 if (T
.getAddressSpace() == LangAS::opencl_constant
)
8554 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8555 << 0 /*non-kernel only*/ << "constant";
8557 Diag(NewVD
->getLocation(), diag::err_opencl_function_variable
)
8558 << 0 /*non-kernel only*/ << "local";
8559 NewVD
->setInvalidDecl();
8562 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8563 // in the outermost scope of a kernel function.
8564 if (FD
&& FD
->hasAttr
<OpenCLKernelAttr
>()) {
8565 if (!getCurScope()->isFunctionScope()) {
8566 if (T
.getAddressSpace() == LangAS::opencl_constant
)
8567 Diag(NewVD
->getLocation(), diag::err_opencl_addrspace_scope
)
8570 Diag(NewVD
->getLocation(), diag::err_opencl_addrspace_scope
)
8572 NewVD
->setInvalidDecl();
8576 } else if (T
.getAddressSpace() != LangAS::opencl_private
&&
8577 // If we are parsing a template we didn't deduce an addr
8579 T
.getAddressSpace() != LangAS::Default
) {
8580 // Do not allow other address spaces on automatic variable.
8581 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
) << 1;
8582 NewVD
->setInvalidDecl();
8588 if (NewVD
->hasLocalStorage() && T
.isObjCGCWeak()
8589 && !NewVD
->hasAttr
<BlocksAttr
>()) {
8590 if (getLangOpts().getGC() != LangOptions::NonGC
)
8591 Diag(NewVD
->getLocation(), diag::warn_gc_attribute_weak_on_local
);
8593 assert(!getLangOpts().ObjCAutoRefCount
);
8594 Diag(NewVD
->getLocation(), diag::warn_attribute_weak_on_local
);
8598 bool isVM
= T
->isVariablyModifiedType();
8599 if (isVM
|| NewVD
->hasAttr
<CleanupAttr
>() ||
8600 NewVD
->hasAttr
<BlocksAttr
>())
8601 setFunctionHasBranchProtectedScope();
8603 if ((isVM
&& NewVD
->hasLinkage()) ||
8604 (T
->isVariableArrayType() && NewVD
->hasGlobalStorage())) {
8605 bool SizeIsNegative
;
8606 llvm::APSInt Oversized
;
8607 TypeSourceInfo
*FixedTInfo
= TryToFixInvalidVariablyModifiedTypeSourceInfo(
8608 NewVD
->getTypeSourceInfo(), Context
, SizeIsNegative
, Oversized
);
8610 if (FixedTInfo
&& T
== NewVD
->getTypeSourceInfo()->getType())
8611 FixedT
= FixedTInfo
->getType();
8612 else if (FixedTInfo
) {
8613 // Type and type-as-written are canonically different. We need to fix up
8614 // both types separately.
8615 FixedT
= TryToFixInvalidVariablyModifiedType(T
, Context
, SizeIsNegative
,
8618 if ((!FixedTInfo
|| FixedT
.isNull()) && T
->isVariableArrayType()) {
8619 const VariableArrayType
*VAT
= Context
.getAsVariableArrayType(T
);
8620 // FIXME: This won't give the correct result for
8622 SourceRange SizeRange
= VAT
->getSizeExpr()->getSourceRange();
8624 if (NewVD
->isFileVarDecl())
8625 Diag(NewVD
->getLocation(), diag::err_vla_decl_in_file_scope
)
8627 else if (NewVD
->isStaticLocal())
8628 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_static_storage
)
8631 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_extern_linkage
)
8633 NewVD
->setInvalidDecl();
8638 if (NewVD
->isFileVarDecl())
8639 Diag(NewVD
->getLocation(), diag::err_vm_decl_in_file_scope
);
8641 Diag(NewVD
->getLocation(), diag::err_vm_decl_has_extern_linkage
);
8642 NewVD
->setInvalidDecl();
8646 Diag(NewVD
->getLocation(), diag::ext_vla_folded_to_constant
);
8647 NewVD
->setType(FixedT
);
8648 NewVD
->setTypeSourceInfo(FixedTInfo
);
8651 if (T
->isVoidType()) {
8652 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8653 // of objects and functions.
8654 if (NewVD
->isThisDeclarationADefinition() || getLangOpts().CPlusPlus
) {
8655 Diag(NewVD
->getLocation(), diag::err_typecheck_decl_incomplete_type
)
8657 NewVD
->setInvalidDecl();
8662 if (!NewVD
->hasLocalStorage() && NewVD
->hasAttr
<BlocksAttr
>()) {
8663 Diag(NewVD
->getLocation(), diag::err_block_on_nonlocal
);
8664 NewVD
->setInvalidDecl();
8668 if (!NewVD
->hasLocalStorage() && T
->isSizelessType()) {
8669 Diag(NewVD
->getLocation(), diag::err_sizeless_nonlocal
) << T
;
8670 NewVD
->setInvalidDecl();
8674 if (isVM
&& NewVD
->hasAttr
<BlocksAttr
>()) {
8675 Diag(NewVD
->getLocation(), diag::err_block_on_vm
);
8676 NewVD
->setInvalidDecl();
8680 if (NewVD
->isConstexpr() && !T
->isDependentType() &&
8681 RequireLiteralType(NewVD
->getLocation(), T
,
8682 diag::err_constexpr_var_non_literal
)) {
8683 NewVD
->setInvalidDecl();
8687 // PPC MMA non-pointer types are not allowed as non-local variable types.
8688 if (Context
.getTargetInfo().getTriple().isPPC64() &&
8689 !NewVD
->isLocalVarDecl() &&
8690 CheckPPCMMAType(T
, NewVD
->getLocation())) {
8691 NewVD
->setInvalidDecl();
8695 // Check that SVE types are only used in functions with SVE available.
8696 if (T
->isSVESizelessBuiltinType() && CurContext
->isFunctionOrMethod()) {
8697 const FunctionDecl
*FD
= cast
<FunctionDecl
>(CurContext
);
8698 llvm::StringMap
<bool> CallerFeatureMap
;
8699 Context
.getFunctionFeatureMap(CallerFeatureMap
, FD
);
8700 if (!Builtin::evaluateRequiredTargetFeatures(
8701 "sve", CallerFeatureMap
)) {
8702 Diag(NewVD
->getLocation(), diag::err_sve_vector_in_non_sve_target
) << T
;
8703 NewVD
->setInvalidDecl();
8709 /// Perform semantic checking on a newly-created variable
8712 /// This routine performs all of the type-checking required for a
8713 /// variable declaration once it has been built. It is used both to
8714 /// check variables after they have been parsed and their declarators
8715 /// have been translated into a declaration, and to check variables
8716 /// that have been instantiated from a template.
8718 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8720 /// Returns true if the variable declaration is a redeclaration.
8721 bool Sema::CheckVariableDeclaration(VarDecl
*NewVD
, LookupResult
&Previous
) {
8722 CheckVariableDeclarationType(NewVD
);
8724 // If the decl is already known invalid, don't check it.
8725 if (NewVD
->isInvalidDecl())
8728 // If we did not find anything by this name, look for a non-visible
8729 // extern "C" declaration with the same name.
8730 if (Previous
.empty() &&
8731 checkForConflictWithNonVisibleExternC(*this, NewVD
, Previous
))
8732 Previous
.setShadowed();
8734 if (!Previous
.empty()) {
8735 MergeVarDecl(NewVD
, Previous
);
8741 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8742 /// and if so, check that it's a valid override and remember it.
8743 bool Sema::AddOverriddenMethods(CXXRecordDecl
*DC
, CXXMethodDecl
*MD
) {
8744 llvm::SmallPtrSet
<const CXXMethodDecl
*, 4> Overridden
;
8746 // Look for methods in base classes that this method might override.
8747 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8748 /*DetectVirtual=*/false);
8749 auto VisitBase
= [&] (const CXXBaseSpecifier
*Specifier
, CXXBasePath
&Path
) {
8750 CXXRecordDecl
*BaseRecord
= Specifier
->getType()->getAsCXXRecordDecl();
8751 DeclarationName Name
= MD
->getDeclName();
8753 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
8754 // We really want to find the base class destructor here.
8755 QualType T
= Context
.getTypeDeclType(BaseRecord
);
8756 CanQualType CT
= Context
.getCanonicalType(T
);
8757 Name
= Context
.DeclarationNames
.getCXXDestructorName(CT
);
8760 for (NamedDecl
*BaseND
: BaseRecord
->lookup(Name
)) {
8761 CXXMethodDecl
*BaseMD
=
8762 dyn_cast
<CXXMethodDecl
>(BaseND
->getCanonicalDecl());
8763 if (!BaseMD
|| !BaseMD
->isVirtual() ||
8764 IsOverload(MD
, BaseMD
, /*UseMemberUsingDeclRules=*/false,
8765 /*ConsiderCudaAttrs=*/true,
8766 // C++2a [class.virtual]p2 does not consider requires
8767 // clauses when overriding.
8768 /*ConsiderRequiresClauses=*/false))
8771 if (Overridden
.insert(BaseMD
).second
) {
8772 MD
->addOverriddenMethod(BaseMD
);
8773 CheckOverridingFunctionReturnType(MD
, BaseMD
);
8774 CheckOverridingFunctionAttributes(MD
, BaseMD
);
8775 CheckOverridingFunctionExceptionSpec(MD
, BaseMD
);
8776 CheckIfOverriddenFunctionIsMarkedFinal(MD
, BaseMD
);
8779 // A method can only override one function from each base class. We
8780 // don't track indirectly overridden methods from bases of bases.
8787 DC
->lookupInBases(VisitBase
, Paths
);
8788 return !Overridden
.empty();
8792 // Struct for holding all of the extra arguments needed by
8793 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8794 struct ActOnFDArgs
{
8797 MultiTemplateParamsArg TemplateParamLists
;
8800 } // end anonymous namespace
8804 // Callback to only accept typo corrections that have a non-zero edit distance.
8805 // Also only accept corrections that have the same parent decl.
8806 class DifferentNameValidatorCCC final
: public CorrectionCandidateCallback
{
8808 DifferentNameValidatorCCC(ASTContext
&Context
, FunctionDecl
*TypoFD
,
8809 CXXRecordDecl
*Parent
)
8810 : Context(Context
), OriginalFD(TypoFD
),
8811 ExpectedParent(Parent
? Parent
->getCanonicalDecl() : nullptr) {}
8813 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
8814 if (candidate
.getEditDistance() == 0)
8817 SmallVector
<unsigned, 1> MismatchedParams
;
8818 for (TypoCorrection::const_decl_iterator CDecl
= candidate
.begin(),
8819 CDeclEnd
= candidate
.end();
8820 CDecl
!= CDeclEnd
; ++CDecl
) {
8821 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*CDecl
);
8823 if (FD
&& !FD
->hasBody() &&
8824 hasSimilarParameters(Context
, FD
, OriginalFD
, MismatchedParams
)) {
8825 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
8826 CXXRecordDecl
*Parent
= MD
->getParent();
8827 if (Parent
&& Parent
->getCanonicalDecl() == ExpectedParent
)
8829 } else if (!ExpectedParent
) {
8838 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
8839 return std::make_unique
<DifferentNameValidatorCCC
>(*this);
8843 ASTContext
&Context
;
8844 FunctionDecl
*OriginalFD
;
8845 CXXRecordDecl
*ExpectedParent
;
8848 } // end anonymous namespace
8850 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl
*F
) {
8851 TypoCorrectedFunctionDefinitions
.insert(F
);
8854 /// Generate diagnostics for an invalid function redeclaration.
8856 /// This routine handles generating the diagnostic messages for an invalid
8857 /// function redeclaration, including finding possible similar declarations
8858 /// or performing typo correction if there are no previous declarations with
8861 /// Returns a NamedDecl iff typo correction was performed and substituting in
8862 /// the new declaration name does not cause new errors.
8863 static NamedDecl
*DiagnoseInvalidRedeclaration(
8864 Sema
&SemaRef
, LookupResult
&Previous
, FunctionDecl
*NewFD
,
8865 ActOnFDArgs
&ExtraArgs
, bool IsLocalFriend
, Scope
*S
) {
8866 DeclarationName Name
= NewFD
->getDeclName();
8867 DeclContext
*NewDC
= NewFD
->getDeclContext();
8868 SmallVector
<unsigned, 1> MismatchedParams
;
8869 SmallVector
<std::pair
<FunctionDecl
*, unsigned>, 1> NearMatches
;
8870 TypoCorrection Correction
;
8871 bool IsDefinition
= ExtraArgs
.D
.isFunctionDefinition();
8873 IsLocalFriend
? diag::err_no_matching_local_friend
:
8874 NewFD
->getFriendObjectKind() ? diag::err_qualified_friend_no_match
:
8875 diag::err_member_decl_does_not_match
;
8876 LookupResult
Prev(SemaRef
, Name
, NewFD
->getLocation(),
8877 IsLocalFriend
? Sema::LookupLocalFriendName
8878 : Sema::LookupOrdinaryName
,
8879 Sema::ForVisibleRedeclaration
);
8881 NewFD
->setInvalidDecl();
8883 SemaRef
.LookupName(Prev
, S
);
8885 SemaRef
.LookupQualifiedName(Prev
, NewDC
);
8886 assert(!Prev
.isAmbiguous() &&
8887 "Cannot have an ambiguity in previous-declaration lookup");
8888 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
8889 DifferentNameValidatorCCC
CCC(SemaRef
.Context
, NewFD
,
8890 MD
? MD
->getParent() : nullptr);
8891 if (!Prev
.empty()) {
8892 for (LookupResult::iterator Func
= Prev
.begin(), FuncEnd
= Prev
.end();
8893 Func
!= FuncEnd
; ++Func
) {
8894 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*Func
);
8896 hasSimilarParameters(SemaRef
.Context
, FD
, NewFD
, MismatchedParams
)) {
8897 // Add 1 to the index so that 0 can mean the mismatch didn't
8898 // involve a parameter
8900 MismatchedParams
.empty() ? 0 : MismatchedParams
.front() + 1;
8901 NearMatches
.push_back(std::make_pair(FD
, ParamNum
));
8904 // If the qualified name lookup yielded nothing, try typo correction
8905 } else if ((Correction
= SemaRef
.CorrectTypo(
8906 Prev
.getLookupNameInfo(), Prev
.getLookupKind(), S
,
8907 &ExtraArgs
.D
.getCXXScopeSpec(), CCC
, Sema::CTK_ErrorRecovery
,
8908 IsLocalFriend
? nullptr : NewDC
))) {
8909 // Set up everything for the call to ActOnFunctionDeclarator
8910 ExtraArgs
.D
.SetIdentifier(Correction
.getCorrectionAsIdentifierInfo(),
8911 ExtraArgs
.D
.getIdentifierLoc());
8913 Previous
.setLookupName(Correction
.getCorrection());
8914 for (TypoCorrection::decl_iterator CDecl
= Correction
.begin(),
8915 CDeclEnd
= Correction
.end();
8916 CDecl
!= CDeclEnd
; ++CDecl
) {
8917 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*CDecl
);
8918 if (FD
&& !FD
->hasBody() &&
8919 hasSimilarParameters(SemaRef
.Context
, FD
, NewFD
, MismatchedParams
)) {
8920 Previous
.addDecl(FD
);
8923 bool wasRedeclaration
= ExtraArgs
.D
.isRedeclaration();
8926 // Retry building the function declaration with the new previous
8927 // declarations, and with errors suppressed.
8930 Sema::SFINAETrap
Trap(SemaRef
);
8932 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8933 // pieces need to verify the typo-corrected C++ declaration and hopefully
8934 // eliminate the need for the parameter pack ExtraArgs.
8935 Result
= SemaRef
.ActOnFunctionDeclarator(
8936 ExtraArgs
.S
, ExtraArgs
.D
,
8937 Correction
.getCorrectionDecl()->getDeclContext(),
8938 NewFD
->getTypeSourceInfo(), Previous
, ExtraArgs
.TemplateParamLists
,
8939 ExtraArgs
.AddToScope
);
8941 if (Trap
.hasErrorOccurred())
8946 // Determine which correction we picked.
8947 Decl
*Canonical
= Result
->getCanonicalDecl();
8948 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
8950 if ((*I
)->getCanonicalDecl() == Canonical
)
8951 Correction
.setCorrectionDecl(*I
);
8953 // Let Sema know about the correction.
8954 SemaRef
.MarkTypoCorrectedFunctionDefinition(Result
);
8955 SemaRef
.diagnoseTypo(
8957 SemaRef
.PDiag(IsLocalFriend
8958 ? diag::err_no_matching_local_friend_suggest
8959 : diag::err_member_decl_does_not_match_suggest
)
8960 << Name
<< NewDC
<< IsDefinition
);
8964 // Pretend the typo correction never occurred
8965 ExtraArgs
.D
.SetIdentifier(Name
.getAsIdentifierInfo(),
8966 ExtraArgs
.D
.getIdentifierLoc());
8967 ExtraArgs
.D
.setRedeclaration(wasRedeclaration
);
8969 Previous
.setLookupName(Name
);
8972 SemaRef
.Diag(NewFD
->getLocation(), DiagMsg
)
8973 << Name
<< NewDC
<< IsDefinition
<< NewFD
->getLocation();
8975 bool NewFDisConst
= false;
8976 if (CXXMethodDecl
*NewMD
= dyn_cast
<CXXMethodDecl
>(NewFD
))
8977 NewFDisConst
= NewMD
->isConst();
8979 for (SmallVectorImpl
<std::pair
<FunctionDecl
*, unsigned> >::iterator
8980 NearMatch
= NearMatches
.begin(), NearMatchEnd
= NearMatches
.end();
8981 NearMatch
!= NearMatchEnd
; ++NearMatch
) {
8982 FunctionDecl
*FD
= NearMatch
->first
;
8983 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
);
8984 bool FDisConst
= MD
&& MD
->isConst();
8985 bool IsMember
= MD
|| !IsLocalFriend
;
8987 // FIXME: These notes are poorly worded for the local friend case.
8988 if (unsigned Idx
= NearMatch
->second
) {
8989 ParmVarDecl
*FDParam
= FD
->getParamDecl(Idx
-1);
8990 SourceLocation Loc
= FDParam
->getTypeSpecStartLoc();
8991 if (Loc
.isInvalid()) Loc
= FD
->getLocation();
8992 SemaRef
.Diag(Loc
, IsMember
? diag::note_member_def_close_param_match
8993 : diag::note_local_decl_close_param_match
)
8994 << Idx
<< FDParam
->getType()
8995 << NewFD
->getParamDecl(Idx
- 1)->getType();
8996 } else if (FDisConst
!= NewFDisConst
) {
8997 SemaRef
.Diag(FD
->getLocation(), diag::note_member_def_close_const_match
)
8998 << NewFDisConst
<< FD
->getSourceRange().getEnd()
9000 ? FixItHint::CreateRemoval(ExtraArgs
.D
.getFunctionTypeInfo()
9001 .getConstQualifierLoc())
9002 : FixItHint::CreateInsertion(ExtraArgs
.D
.getFunctionTypeInfo()
9004 .getLocWithOffset(1),
9007 SemaRef
.Diag(FD
->getLocation(),
9008 IsMember
? diag::note_member_def_close_match
9009 : diag::note_local_decl_close_match
);
9014 static StorageClass
getFunctionStorageClass(Sema
&SemaRef
, Declarator
&D
) {
9015 switch (D
.getDeclSpec().getStorageClassSpec()) {
9016 default: llvm_unreachable("Unknown storage class!");
9017 case DeclSpec::SCS_auto
:
9018 case DeclSpec::SCS_register
:
9019 case DeclSpec::SCS_mutable
:
9020 SemaRef
.Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
9021 diag::err_typecheck_sclass_func
);
9022 D
.getMutableDeclSpec().ClearStorageClassSpecs();
9025 case DeclSpec::SCS_unspecified
: break;
9026 case DeclSpec::SCS_extern
:
9027 if (D
.getDeclSpec().isExternInLinkageSpec())
9030 case DeclSpec::SCS_static
: {
9031 if (SemaRef
.CurContext
->getRedeclContext()->isFunctionOrMethod()) {
9033 // The declaration of an identifier for a function that has
9034 // block scope shall have no explicit storage-class specifier
9035 // other than extern
9036 // See also (C++ [dcl.stc]p4).
9037 SemaRef
.Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
9038 diag::err_static_block_func
);
9043 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
9046 // No explicit storage class has already been returned
9050 static FunctionDecl
*CreateNewFunctionDecl(Sema
&SemaRef
, Declarator
&D
,
9051 DeclContext
*DC
, QualType
&R
,
9052 TypeSourceInfo
*TInfo
,
9054 bool &IsVirtualOkay
) {
9055 DeclarationNameInfo NameInfo
= SemaRef
.GetNameForDeclarator(D
);
9056 DeclarationName Name
= NameInfo
.getName();
9058 FunctionDecl
*NewFD
= nullptr;
9059 bool isInline
= D
.getDeclSpec().isInlineSpecified();
9061 if (!SemaRef
.getLangOpts().CPlusPlus
) {
9062 // Determine whether the function was written with a prototype. This is
9064 // - there is a prototype in the declarator, or
9065 // - the type R of the function is some kind of typedef or other non-
9066 // attributed reference to a type name (which eventually refers to a
9067 // function type). Note, we can't always look at the adjusted type to
9068 // check this case because attributes may cause a non-function
9069 // declarator to still have a function type. e.g.,
9070 // typedef void func(int a);
9071 // __attribute__((noreturn)) func other_func; // This has a prototype
9073 (D
.isFunctionDeclarator() && D
.getFunctionTypeInfo().hasPrototype
) ||
9074 (D
.getDeclSpec().isTypeRep() &&
9075 D
.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
9076 (!R
->getAsAdjusted
<FunctionType
>() && R
->isFunctionProtoType());
9078 (HasPrototype
|| !SemaRef
.getLangOpts().requiresStrictPrototypes()) &&
9079 "Strict prototypes are required");
9081 NewFD
= FunctionDecl::Create(
9082 SemaRef
.Context
, DC
, D
.getBeginLoc(), NameInfo
, R
, TInfo
, SC
,
9083 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
, HasPrototype
,
9084 ConstexprSpecKind::Unspecified
,
9085 /*TrailingRequiresClause=*/nullptr);
9086 if (D
.isInvalidType())
9087 NewFD
->setInvalidDecl();
9092 ExplicitSpecifier ExplicitSpecifier
= D
.getDeclSpec().getExplicitSpecifier();
9094 ConstexprSpecKind ConstexprKind
= D
.getDeclSpec().getConstexprSpecifier();
9095 if (ConstexprKind
== ConstexprSpecKind::Constinit
) {
9096 SemaRef
.Diag(D
.getDeclSpec().getConstexprSpecLoc(),
9097 diag::err_constexpr_wrong_decl_kind
)
9098 << static_cast<int>(ConstexprKind
);
9099 ConstexprKind
= ConstexprSpecKind::Unspecified
;
9100 D
.getMutableDeclSpec().ClearConstexprSpec();
9102 Expr
*TrailingRequiresClause
= D
.getTrailingRequiresClause();
9104 // Check that the return type is not an abstract class type.
9105 // For record types, this is done by the AbstractClassUsageDiagnoser once
9106 // the class has been completely parsed.
9107 if (!DC
->isRecord() &&
9108 SemaRef
.RequireNonAbstractType(
9109 D
.getIdentifierLoc(), R
->castAs
<FunctionType
>()->getReturnType(),
9110 diag::err_abstract_type_in_decl
, SemaRef
.AbstractReturnType
))
9113 if (Name
.getNameKind() == DeclarationName::CXXConstructorName
) {
9114 // This is a C++ constructor declaration.
9115 assert(DC
->isRecord() &&
9116 "Constructors can only be declared in a member context");
9118 R
= SemaRef
.CheckConstructorDeclarator(D
, R
, SC
);
9119 return CXXConstructorDecl::Create(
9120 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9121 TInfo
, ExplicitSpecifier
, SemaRef
.getCurFPFeatures().isFPConstrained(),
9122 isInline
, /*isImplicitlyDeclared=*/false, ConstexprKind
,
9123 InheritedConstructor(), TrailingRequiresClause
);
9125 } else if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
9126 // This is a C++ destructor declaration.
9127 if (DC
->isRecord()) {
9128 R
= SemaRef
.CheckDestructorDeclarator(D
, R
, SC
);
9129 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
9130 CXXDestructorDecl
*NewDD
= CXXDestructorDecl::Create(
9131 SemaRef
.Context
, Record
, D
.getBeginLoc(), NameInfo
, R
, TInfo
,
9132 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9133 /*isImplicitlyDeclared=*/false, ConstexprKind
,
9134 TrailingRequiresClause
);
9135 // User defined destructors start as not selected if the class definition is still
9137 if (Record
->isBeingDefined())
9138 NewDD
->setIneligibleOrNotSelected(true);
9140 // If the destructor needs an implicit exception specification, set it
9141 // now. FIXME: It'd be nice to be able to create the right type to start
9142 // with, but the type needs to reference the destructor declaration.
9143 if (SemaRef
.getLangOpts().CPlusPlus11
)
9144 SemaRef
.AdjustDestructorExceptionSpec(NewDD
);
9146 IsVirtualOkay
= true;
9150 SemaRef
.Diag(D
.getIdentifierLoc(), diag::err_destructor_not_member
);
9153 // Create a FunctionDecl to satisfy the function definition parsing
9155 return FunctionDecl::Create(
9156 SemaRef
.Context
, DC
, D
.getBeginLoc(), D
.getIdentifierLoc(), Name
, R
,
9157 TInfo
, SC
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9158 /*hasPrototype=*/true, ConstexprKind
, TrailingRequiresClause
);
9161 } else if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
9162 if (!DC
->isRecord()) {
9163 SemaRef
.Diag(D
.getIdentifierLoc(),
9164 diag::err_conv_function_not_member
);
9168 SemaRef
.CheckConversionDeclarator(D
, R
, SC
);
9169 if (D
.isInvalidType())
9172 IsVirtualOkay
= true;
9173 return CXXConversionDecl::Create(
9174 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9175 TInfo
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9176 ExplicitSpecifier
, ConstexprKind
, SourceLocation(),
9177 TrailingRequiresClause
);
9179 } else if (Name
.getNameKind() == DeclarationName::CXXDeductionGuideName
) {
9180 if (TrailingRequiresClause
)
9181 SemaRef
.Diag(TrailingRequiresClause
->getBeginLoc(),
9182 diag::err_trailing_requires_clause_on_deduction_guide
)
9183 << TrailingRequiresClause
->getSourceRange();
9184 SemaRef
.CheckDeductionGuideDeclarator(D
, R
, SC
);
9186 return CXXDeductionGuideDecl::Create(SemaRef
.Context
, DC
, D
.getBeginLoc(),
9187 ExplicitSpecifier
, NameInfo
, R
, TInfo
,
9189 } else if (DC
->isRecord()) {
9190 // If the name of the function is the same as the name of the record,
9191 // then this must be an invalid constructor that has a return type.
9192 // (The parser checks for a return type and makes the declarator a
9193 // constructor if it has no return type).
9194 if (Name
.getAsIdentifierInfo() &&
9195 Name
.getAsIdentifierInfo() == cast
<CXXRecordDecl
>(DC
)->getIdentifier()){
9196 SemaRef
.Diag(D
.getIdentifierLoc(), diag::err_constructor_return_type
)
9197 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
9198 << SourceRange(D
.getIdentifierLoc());
9202 // This is a C++ method declaration.
9203 CXXMethodDecl
*Ret
= CXXMethodDecl::Create(
9204 SemaRef
.Context
, cast
<CXXRecordDecl
>(DC
), D
.getBeginLoc(), NameInfo
, R
,
9205 TInfo
, SC
, SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9206 ConstexprKind
, SourceLocation(), TrailingRequiresClause
);
9207 IsVirtualOkay
= !Ret
->isStatic();
9211 SemaRef
.getLangOpts().CPlusPlus
&& D
.getDeclSpec().isFriendSpecified();
9212 if (!isFriend
&& SemaRef
.CurContext
->isRecord())
9215 // Determine whether the function was written with a
9216 // prototype. This true when:
9217 // - we're in C++ (where every function has a prototype),
9218 return FunctionDecl::Create(
9219 SemaRef
.Context
, DC
, D
.getBeginLoc(), NameInfo
, R
, TInfo
, SC
,
9220 SemaRef
.getCurFPFeatures().isFPConstrained(), isInline
,
9221 true /*HasPrototype*/, ConstexprKind
, TrailingRequiresClause
);
9225 enum OpenCLParamType
{
9229 InvalidAddrSpacePtrKernelParam
,
9234 static bool isOpenCLSizeDependentType(ASTContext
&C
, QualType Ty
) {
9235 // Size dependent types are just typedefs to normal integer types
9236 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9237 // integers other than by their names.
9238 StringRef SizeTypeNames
[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9240 // Remove typedefs one by one until we reach a typedef
9241 // for a size dependent type.
9242 QualType DesugaredTy
= Ty
;
9244 ArrayRef
<StringRef
> Names(SizeTypeNames
);
9245 auto Match
= llvm::find(Names
, DesugaredTy
.getUnqualifiedType().getAsString());
9246 if (Names
.end() != Match
)
9250 DesugaredTy
= Ty
.getSingleStepDesugaredType(C
);
9251 } while (DesugaredTy
!= Ty
);
9256 static OpenCLParamType
getOpenCLKernelParameterType(Sema
&S
, QualType PT
) {
9257 if (PT
->isDependentType())
9258 return InvalidKernelParam
;
9260 if (PT
->isPointerType() || PT
->isReferenceType()) {
9261 QualType PointeeType
= PT
->getPointeeType();
9262 if (PointeeType
.getAddressSpace() == LangAS::opencl_generic
||
9263 PointeeType
.getAddressSpace() == LangAS::opencl_private
||
9264 PointeeType
.getAddressSpace() == LangAS::Default
)
9265 return InvalidAddrSpacePtrKernelParam
;
9267 if (PointeeType
->isPointerType()) {
9268 // This is a pointer to pointer parameter.
9269 // Recursively check inner type.
9270 OpenCLParamType ParamKind
= getOpenCLKernelParameterType(S
, PointeeType
);
9271 if (ParamKind
== InvalidAddrSpacePtrKernelParam
||
9272 ParamKind
== InvalidKernelParam
)
9275 return PtrPtrKernelParam
;
9278 // C++ for OpenCL v1.0 s2.4:
9279 // Moreover the types used in parameters of the kernel functions must be:
9280 // Standard layout types for pointer parameters. The same applies to
9281 // reference if an implementation supports them in kernel parameters.
9282 if (S
.getLangOpts().OpenCLCPlusPlus
&&
9283 !S
.getOpenCLOptions().isAvailableOption(
9284 "__cl_clang_non_portable_kernel_param_types", S
.getLangOpts())) {
9285 auto CXXRec
= PointeeType
.getCanonicalType()->getAsCXXRecordDecl();
9286 bool IsStandardLayoutType
= true;
9288 // If template type is not ODR-used its definition is only available
9289 // in the template definition not its instantiation.
9290 // FIXME: This logic doesn't work for types that depend on template
9291 // parameter (PR58590).
9292 if (!CXXRec
->hasDefinition())
9293 CXXRec
= CXXRec
->getTemplateInstantiationPattern();
9294 if (!CXXRec
|| !CXXRec
->hasDefinition() || !CXXRec
->isStandardLayout())
9295 IsStandardLayoutType
= false;
9297 if (!PointeeType
->isAtomicType() && !PointeeType
->isVoidType() &&
9298 !IsStandardLayoutType
)
9299 return InvalidKernelParam
;
9302 return PtrKernelParam
;
9305 // OpenCL v1.2 s6.9.k:
9306 // Arguments to kernel functions in a program cannot be declared with the
9307 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9308 // uintptr_t or a struct and/or union that contain fields declared to be one
9309 // of these built-in scalar types.
9310 if (isOpenCLSizeDependentType(S
.getASTContext(), PT
))
9311 return InvalidKernelParam
;
9313 if (PT
->isImageType())
9314 return PtrKernelParam
;
9316 if (PT
->isBooleanType() || PT
->isEventT() || PT
->isReserveIDT())
9317 return InvalidKernelParam
;
9319 // OpenCL extension spec v1.2 s9.5:
9320 // This extension adds support for half scalar and vector types as built-in
9321 // types that can be used for arithmetic operations, conversions etc.
9322 if (!S
.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S
.getLangOpts()) &&
9324 return InvalidKernelParam
;
9326 // Look into an array argument to check if it has a forbidden type.
9327 if (PT
->isArrayType()) {
9328 const Type
*UnderlyingTy
= PT
->getPointeeOrArrayElementType();
9329 // Call ourself to check an underlying type of an array. Since the
9330 // getPointeeOrArrayElementType returns an innermost type which is not an
9331 // array, this recursive call only happens once.
9332 return getOpenCLKernelParameterType(S
, QualType(UnderlyingTy
, 0));
9335 // C++ for OpenCL v1.0 s2.4:
9336 // Moreover the types used in parameters of the kernel functions must be:
9337 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9338 // types) for parameters passed by value;
9339 if (S
.getLangOpts().OpenCLCPlusPlus
&&
9340 !S
.getOpenCLOptions().isAvailableOption(
9341 "__cl_clang_non_portable_kernel_param_types", S
.getLangOpts()) &&
9342 !PT
->isOpenCLSpecificType() && !PT
.isPODType(S
.Context
))
9343 return InvalidKernelParam
;
9345 if (PT
->isRecordType())
9346 return RecordKernelParam
;
9348 return ValidKernelParam
;
9351 static void checkIsValidOpenCLKernelParameter(
9355 llvm::SmallPtrSetImpl
<const Type
*> &ValidTypes
) {
9356 QualType PT
= Param
->getType();
9358 // Cache the valid types we encounter to avoid rechecking structs that are
9360 if (ValidTypes
.count(PT
.getTypePtr()))
9363 switch (getOpenCLKernelParameterType(S
, PT
)) {
9364 case PtrPtrKernelParam
:
9365 // OpenCL v3.0 s6.11.a:
9366 // A kernel function argument cannot be declared as a pointer to a pointer
9367 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9368 if (S
.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9369 S
.Diag(Param
->getLocation(), diag::err_opencl_ptrptr_kernel_param
);
9374 ValidTypes
.insert(PT
.getTypePtr());
9377 case InvalidAddrSpacePtrKernelParam
:
9378 // OpenCL v1.0 s6.5:
9379 // __kernel function arguments declared to be a pointer of a type can point
9380 // to one of the following address spaces only : __global, __local or
9382 S
.Diag(Param
->getLocation(), diag::err_kernel_arg_address_space
);
9386 // OpenCL v1.2 s6.9.k:
9387 // Arguments to kernel functions in a program cannot be declared with the
9388 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9389 // uintptr_t or a struct and/or union that contain fields declared to be
9390 // one of these built-in scalar types.
9392 case InvalidKernelParam
:
9393 // OpenCL v1.2 s6.8 n:
9394 // A kernel function argument cannot be declared
9396 // Do not diagnose half type since it is diagnosed as invalid argument
9397 // type for any function elsewhere.
9398 if (!PT
->isHalfType()) {
9399 S
.Diag(Param
->getLocation(), diag::err_bad_kernel_param_type
) << PT
;
9401 // Explain what typedefs are involved.
9402 const TypedefType
*Typedef
= nullptr;
9403 while ((Typedef
= PT
->getAs
<TypedefType
>())) {
9404 SourceLocation Loc
= Typedef
->getDecl()->getLocation();
9405 // SourceLocation may be invalid for a built-in type.
9407 S
.Diag(Loc
, diag::note_entity_declared_at
) << PT
;
9408 PT
= Typedef
->desugar();
9415 case PtrKernelParam
:
9416 case ValidKernelParam
:
9417 ValidTypes
.insert(PT
.getTypePtr());
9420 case RecordKernelParam
:
9424 // Track nested structs we will inspect
9425 SmallVector
<const Decl
*, 4> VisitStack
;
9427 // Track where we are in the nested structs. Items will migrate from
9428 // VisitStack to HistoryStack as we do the DFS for bad field.
9429 SmallVector
<const FieldDecl
*, 4> HistoryStack
;
9430 HistoryStack
.push_back(nullptr);
9432 // At this point we already handled everything except of a RecordType or
9433 // an ArrayType of a RecordType.
9434 assert((PT
->isArrayType() || PT
->isRecordType()) && "Unexpected type.");
9435 const RecordType
*RecTy
=
9436 PT
->getPointeeOrArrayElementType()->getAs
<RecordType
>();
9437 const RecordDecl
*OrigRecDecl
= RecTy
->getDecl();
9439 VisitStack
.push_back(RecTy
->getDecl());
9440 assert(VisitStack
.back() && "First decl null?");
9443 const Decl
*Next
= VisitStack
.pop_back_val();
9445 assert(!HistoryStack
.empty());
9446 // Found a marker, we have gone up a level
9447 if (const FieldDecl
*Hist
= HistoryStack
.pop_back_val())
9448 ValidTypes
.insert(Hist
->getType().getTypePtr());
9453 // Adds everything except the original parameter declaration (which is not a
9454 // field itself) to the history stack.
9455 const RecordDecl
*RD
;
9456 if (const FieldDecl
*Field
= dyn_cast
<FieldDecl
>(Next
)) {
9457 HistoryStack
.push_back(Field
);
9459 QualType FieldTy
= Field
->getType();
9460 // Other field types (known to be valid or invalid) are handled while we
9461 // walk around RecordDecl::fields().
9462 assert((FieldTy
->isArrayType() || FieldTy
->isRecordType()) &&
9463 "Unexpected type.");
9464 const Type
*FieldRecTy
= FieldTy
->getPointeeOrArrayElementType();
9466 RD
= FieldRecTy
->castAs
<RecordType
>()->getDecl();
9468 RD
= cast
<RecordDecl
>(Next
);
9471 // Add a null marker so we know when we've gone back up a level
9472 VisitStack
.push_back(nullptr);
9474 for (const auto *FD
: RD
->fields()) {
9475 QualType QT
= FD
->getType();
9477 if (ValidTypes
.count(QT
.getTypePtr()))
9480 OpenCLParamType ParamType
= getOpenCLKernelParameterType(S
, QT
);
9481 if (ParamType
== ValidKernelParam
)
9484 if (ParamType
== RecordKernelParam
) {
9485 VisitStack
.push_back(FD
);
9489 // OpenCL v1.2 s6.9.p:
9490 // Arguments to kernel functions that are declared to be a struct or union
9491 // do not allow OpenCL objects to be passed as elements of the struct or
9493 if (ParamType
== PtrKernelParam
|| ParamType
== PtrPtrKernelParam
||
9494 ParamType
== InvalidAddrSpacePtrKernelParam
) {
9495 S
.Diag(Param
->getLocation(),
9496 diag::err_record_with_pointers_kernel_param
)
9497 << PT
->isUnionType()
9500 S
.Diag(Param
->getLocation(), diag::err_bad_kernel_param_type
) << PT
;
9503 S
.Diag(OrigRecDecl
->getLocation(), diag::note_within_field_of_type
)
9504 << OrigRecDecl
->getDeclName();
9506 // We have an error, now let's go back up through history and show where
9507 // the offending field came from
9508 for (ArrayRef
<const FieldDecl
*>::const_iterator
9509 I
= HistoryStack
.begin() + 1,
9510 E
= HistoryStack
.end();
9512 const FieldDecl
*OuterField
= *I
;
9513 S
.Diag(OuterField
->getLocation(), diag::note_within_field_of_type
)
9514 << OuterField
->getType();
9517 S
.Diag(FD
->getLocation(), diag::note_illegal_field_declared_here
)
9518 << QT
->isPointerType()
9523 } while (!VisitStack
.empty());
9526 /// Find the DeclContext in which a tag is implicitly declared if we see an
9527 /// elaborated type specifier in the specified context, and lookup finds
9529 static DeclContext
*getTagInjectionContext(DeclContext
*DC
) {
9530 while (!DC
->isFileContext() && !DC
->isFunctionOrMethod())
9531 DC
= DC
->getParent();
9535 /// Find the Scope in which a tag is implicitly declared if we see an
9536 /// elaborated type specifier in the specified context, and lookup finds
9538 static Scope
*getTagInjectionScope(Scope
*S
, const LangOptions
&LangOpts
) {
9539 while (S
->isClassScope() ||
9540 (LangOpts
.CPlusPlus
&&
9541 S
->isFunctionPrototypeScope()) ||
9542 ((S
->getFlags() & Scope::DeclScope
) == 0) ||
9543 (S
->getEntity() && S
->getEntity()->isTransparentContext()))
9548 /// Determine whether a declaration matches a known function in namespace std.
9549 static bool isStdBuiltin(ASTContext
&Ctx
, FunctionDecl
*FD
,
9550 unsigned BuiltinID
) {
9551 switch (BuiltinID
) {
9552 case Builtin::BI__GetExceptionInfo
:
9553 // No type checking whatsoever.
9554 return Ctx
.getTargetInfo().getCXXABI().isMicrosoft();
9556 case Builtin::BIaddressof
:
9557 case Builtin::BI__addressof
:
9558 case Builtin::BIforward
:
9559 case Builtin::BIforward_like
:
9560 case Builtin::BImove
:
9561 case Builtin::BImove_if_noexcept
:
9562 case Builtin::BIas_const
: {
9563 // Ensure that we don't treat the algorithm
9564 // OutputIt std::move(InputIt, InputIt, OutputIt)
9565 // as the builtin std::move.
9566 const auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
9567 return FPT
->getNumParams() == 1 && !FPT
->isVariadic();
9576 Sema::ActOnFunctionDeclarator(Scope
*S
, Declarator
&D
, DeclContext
*DC
,
9577 TypeSourceInfo
*TInfo
, LookupResult
&Previous
,
9578 MultiTemplateParamsArg TemplateParamListsRef
,
9580 QualType R
= TInfo
->getType();
9582 assert(R
->isFunctionType());
9583 if (R
.getCanonicalType()->castAs
<FunctionType
>()->getCmseNSCallAttr())
9584 Diag(D
.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call
);
9586 SmallVector
<TemplateParameterList
*, 4> TemplateParamLists
;
9587 llvm::append_range(TemplateParamLists
, TemplateParamListsRef
);
9588 if (TemplateParameterList
*Invented
= D
.getInventedTemplateParameterList()) {
9589 if (!TemplateParamLists
.empty() &&
9590 Invented
->getDepth() == TemplateParamLists
.back()->getDepth())
9591 TemplateParamLists
.back() = Invented
;
9593 TemplateParamLists
.push_back(Invented
);
9596 // TODO: consider using NameInfo for diagnostic.
9597 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
9598 DeclarationName Name
= NameInfo
.getName();
9599 StorageClass SC
= getFunctionStorageClass(*this, D
);
9601 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
9602 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
9603 diag::err_invalid_thread
)
9604 << DeclSpec::getSpecifierName(TSCS
);
9606 if (D
.isFirstDeclarationOfMember())
9607 adjustMemberFunctionCC(R
, D
.isStaticMember(), D
.isCtorOrDtor(),
9608 D
.getIdentifierLoc());
9610 bool isFriend
= false;
9611 FunctionTemplateDecl
*FunctionTemplate
= nullptr;
9612 bool isMemberSpecialization
= false;
9613 bool isFunctionTemplateSpecialization
= false;
9615 bool isDependentClassScopeExplicitSpecialization
= false;
9616 bool HasExplicitTemplateArgs
= false;
9617 TemplateArgumentListInfo TemplateArgs
;
9619 bool isVirtualOkay
= false;
9621 DeclContext
*OriginalDC
= DC
;
9622 bool IsLocalExternDecl
= adjustContextForLocalExternDecl(DC
);
9624 FunctionDecl
*NewFD
= CreateNewFunctionDecl(*this, D
, DC
, R
, TInfo
, SC
,
9626 if (!NewFD
) return nullptr;
9628 if (OriginalLexicalContext
&& OriginalLexicalContext
->isObjCContainer())
9629 NewFD
->setTopLevelDeclInObjCContainer();
9631 // Set the lexical context. If this is a function-scope declaration, or has a
9632 // C++ scope specifier, or is the object of a friend declaration, the lexical
9633 // context will be different from the semantic context.
9634 NewFD
->setLexicalDeclContext(CurContext
);
9636 if (IsLocalExternDecl
)
9637 NewFD
->setLocalExternDecl();
9639 if (getLangOpts().CPlusPlus
) {
9640 // The rules for implicit inlines changed in C++20 for methods and friends
9641 // with an in-class definition (when such a definition is not attached to
9642 // the global module). User-specified 'inline' overrides this (set when
9643 // the function decl is created above).
9644 // FIXME: We need a better way to separate C++ standard and clang modules.
9645 bool ImplicitInlineCXX20
= !getLangOpts().CPlusPlusModules
||
9646 !NewFD
->getOwningModule() ||
9647 NewFD
->getOwningModule()->isGlobalModule() ||
9648 NewFD
->getOwningModule()->isHeaderLikeModule();
9649 bool isInline
= D
.getDeclSpec().isInlineSpecified();
9650 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
9651 bool hasExplicit
= D
.getDeclSpec().hasExplicitSpecifier();
9652 isFriend
= D
.getDeclSpec().isFriendSpecified();
9653 if (isFriend
&& !isInline
&& D
.isFunctionDefinition()) {
9654 // Pre-C++20 [class.friend]p5
9655 // A function can be defined in a friend declaration of a
9656 // class . . . . Such a function is implicitly inline.
9657 // Post C++20 [class.friend]p7
9658 // Such a function is implicitly an inline function if it is attached
9659 // to the global module.
9660 NewFD
->setImplicitlyInline(ImplicitInlineCXX20
);
9663 // If this is a method defined in an __interface, and is not a constructor
9664 // or an overloaded operator, then set the pure flag (isVirtual will already
9666 if (const CXXRecordDecl
*Parent
=
9667 dyn_cast
<CXXRecordDecl
>(NewFD
->getDeclContext())) {
9668 if (Parent
->isInterface() && cast
<CXXMethodDecl
>(NewFD
)->isUserProvided())
9669 NewFD
->setPure(true);
9671 // C++ [class.union]p2
9672 // A union can have member functions, but not virtual functions.
9673 if (isVirtual
&& Parent
->isUnion()) {
9674 Diag(D
.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union
);
9675 NewFD
->setInvalidDecl();
9677 if ((Parent
->isClass() || Parent
->isStruct()) &&
9678 Parent
->hasAttr
<SYCLSpecialClassAttr
>() &&
9679 NewFD
->getKind() == Decl::Kind::CXXMethod
&& NewFD
->getIdentifier() &&
9680 NewFD
->getName() == "__init" && D
.isFunctionDefinition()) {
9681 if (auto *Def
= Parent
->getDefinition())
9682 Def
->setInitMethod(true);
9686 SetNestedNameSpecifier(*this, NewFD
, D
);
9687 isMemberSpecialization
= false;
9688 isFunctionTemplateSpecialization
= false;
9689 if (D
.isInvalidType())
9690 NewFD
->setInvalidDecl();
9692 // Match up the template parameter lists with the scope specifier, then
9693 // determine whether we have a template or a template specialization.
9694 bool Invalid
= false;
9695 TemplateParameterList
*TemplateParams
=
9696 MatchTemplateParametersToScopeSpecifier(
9697 D
.getDeclSpec().getBeginLoc(), D
.getIdentifierLoc(),
9698 D
.getCXXScopeSpec(),
9699 D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9700 ? D
.getName().TemplateId
9702 TemplateParamLists
, isFriend
, isMemberSpecialization
,
9704 if (TemplateParams
) {
9705 // Check that we can declare a template here.
9706 if (CheckTemplateDeclScope(S
, TemplateParams
))
9707 NewFD
->setInvalidDecl();
9709 if (TemplateParams
->size() > 0) {
9710 // This is a function template
9712 // A destructor cannot be a template.
9713 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
9714 Diag(NewFD
->getLocation(), diag::err_destructor_template
);
9715 NewFD
->setInvalidDecl();
9718 // If we're adding a template to a dependent context, we may need to
9719 // rebuilding some of the types used within the template parameter list,
9720 // now that we know what the current instantiation is.
9721 if (DC
->isDependentContext()) {
9722 ContextRAII
SavedContext(*this, DC
);
9723 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams
))
9727 FunctionTemplate
= FunctionTemplateDecl::Create(Context
, DC
,
9728 NewFD
->getLocation(),
9729 Name
, TemplateParams
,
9731 FunctionTemplate
->setLexicalDeclContext(CurContext
);
9732 NewFD
->setDescribedFunctionTemplate(FunctionTemplate
);
9734 // For source fidelity, store the other template param lists.
9735 if (TemplateParamLists
.size() > 1) {
9736 NewFD
->setTemplateParameterListsInfo(Context
,
9737 ArrayRef
<TemplateParameterList
*>(TemplateParamLists
)
9741 // This is a function template specialization.
9742 isFunctionTemplateSpecialization
= true;
9743 // For source fidelity, store all the template param lists.
9744 if (TemplateParamLists
.size() > 0)
9745 NewFD
->setTemplateParameterListsInfo(Context
, TemplateParamLists
);
9747 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9749 // We want to remove the "template<>", found here.
9750 SourceRange RemoveRange
= TemplateParams
->getSourceRange();
9752 // If we remove the template<> and the name is not a
9753 // template-id, we're actually silently creating a problem:
9754 // the friend declaration will refer to an untemplated decl,
9755 // and clearly the user wants a template specialization. So
9756 // we need to insert '<>' after the name.
9757 SourceLocation InsertLoc
;
9758 if (D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
9759 InsertLoc
= D
.getName().getSourceRange().getEnd();
9760 InsertLoc
= getLocForEndOfToken(InsertLoc
);
9763 Diag(D
.getIdentifierLoc(), diag::err_template_spec_decl_friend
)
9764 << Name
<< RemoveRange
9765 << FixItHint::CreateRemoval(RemoveRange
)
9766 << FixItHint::CreateInsertion(InsertLoc
, "<>");
9771 // Check that we can declare a template here.
9772 if (!TemplateParamLists
.empty() && isMemberSpecialization
&&
9773 CheckTemplateDeclScope(S
, TemplateParamLists
.back()))
9774 NewFD
->setInvalidDecl();
9776 // All template param lists were matched against the scope specifier:
9777 // this is NOT (an explicit specialization of) a template.
9778 if (TemplateParamLists
.size() > 0)
9779 // For source fidelity, store all the template param lists.
9780 NewFD
->setTemplateParameterListsInfo(Context
, TemplateParamLists
);
9784 NewFD
->setInvalidDecl();
9785 if (FunctionTemplate
)
9786 FunctionTemplate
->setInvalidDecl();
9789 // C++ [dcl.fct.spec]p5:
9790 // The virtual specifier shall only be used in declarations of
9791 // nonstatic class member functions that appear within a
9792 // member-specification of a class declaration; see 10.3.
9794 if (isVirtual
&& !NewFD
->isInvalidDecl()) {
9795 if (!isVirtualOkay
) {
9796 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9797 diag::err_virtual_non_function
);
9798 } else if (!CurContext
->isRecord()) {
9799 // 'virtual' was specified outside of the class.
9800 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9801 diag::err_virtual_out_of_class
)
9802 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
9803 } else if (NewFD
->getDescribedFunctionTemplate()) {
9804 // C++ [temp.mem]p3:
9805 // A member function template shall not be virtual.
9806 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
9807 diag::err_virtual_member_function_template
)
9808 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
9810 // Okay: Add virtual to the method.
9811 NewFD
->setVirtualAsWritten(true);
9814 if (getLangOpts().CPlusPlus14
&&
9815 NewFD
->getReturnType()->isUndeducedType())
9816 Diag(D
.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual
);
9819 if (getLangOpts().CPlusPlus14
&&
9820 (NewFD
->isDependentContext() ||
9821 (isFriend
&& CurContext
->isDependentContext())) &&
9822 NewFD
->getReturnType()->isUndeducedType()) {
9823 // If the function template is referenced directly (for instance, as a
9824 // member of the current instantiation), pretend it has a dependent type.
9825 // This is not really justified by the standard, but is the only sane
9827 // FIXME: For a friend function, we have not marked the function as being
9828 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9829 const FunctionProtoType
*FPT
=
9830 NewFD
->getType()->castAs
<FunctionProtoType
>();
9831 QualType Result
= SubstAutoTypeDependent(FPT
->getReturnType());
9832 NewFD
->setType(Context
.getFunctionType(Result
, FPT
->getParamTypes(),
9833 FPT
->getExtProtoInfo()));
9836 // C++ [dcl.fct.spec]p3:
9837 // The inline specifier shall not appear on a block scope function
9839 if (isInline
&& !NewFD
->isInvalidDecl()) {
9840 if (CurContext
->isFunctionOrMethod()) {
9841 // 'inline' is not allowed on block scope function declaration.
9842 Diag(D
.getDeclSpec().getInlineSpecLoc(),
9843 diag::err_inline_declaration_block_scope
) << Name
9844 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
9848 // C++ [dcl.fct.spec]p6:
9849 // The explicit specifier shall be used only in the declaration of a
9850 // constructor or conversion function within its class definition;
9851 // see 12.3.1 and 12.3.2.
9852 if (hasExplicit
&& !NewFD
->isInvalidDecl() &&
9853 !isa
<CXXDeductionGuideDecl
>(NewFD
)) {
9854 if (!CurContext
->isRecord()) {
9855 // 'explicit' was specified outside of the class.
9856 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
9857 diag::err_explicit_out_of_class
)
9858 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecRange());
9859 } else if (!isa
<CXXConstructorDecl
>(NewFD
) &&
9860 !isa
<CXXConversionDecl
>(NewFD
)) {
9861 // 'explicit' was specified on a function that wasn't a constructor
9862 // or conversion function.
9863 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
9864 diag::err_explicit_non_ctor_or_conv_function
)
9865 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecRange());
9869 ConstexprSpecKind ConstexprKind
= D
.getDeclSpec().getConstexprSpecifier();
9870 if (ConstexprKind
!= ConstexprSpecKind::Unspecified
) {
9871 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9872 // are implicitly inline.
9873 NewFD
->setImplicitlyInline();
9875 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9876 // be either constructors or to return a literal type. Therefore,
9877 // destructors cannot be declared constexpr.
9878 if (isa
<CXXDestructorDecl
>(NewFD
) &&
9879 (!getLangOpts().CPlusPlus20
||
9880 ConstexprKind
== ConstexprSpecKind::Consteval
)) {
9881 Diag(D
.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor
)
9882 << static_cast<int>(ConstexprKind
);
9883 NewFD
->setConstexprKind(getLangOpts().CPlusPlus20
9884 ? ConstexprSpecKind::Unspecified
9885 : ConstexprSpecKind::Constexpr
);
9887 // C++20 [dcl.constexpr]p2: An allocation function, or a
9888 // deallocation function shall not be declared with the consteval
9890 if (ConstexprKind
== ConstexprSpecKind::Consteval
&&
9891 (NewFD
->getOverloadedOperator() == OO_New
||
9892 NewFD
->getOverloadedOperator() == OO_Array_New
||
9893 NewFD
->getOverloadedOperator() == OO_Delete
||
9894 NewFD
->getOverloadedOperator() == OO_Array_Delete
)) {
9895 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
9896 diag::err_invalid_consteval_decl_kind
)
9898 NewFD
->setConstexprKind(ConstexprSpecKind::Constexpr
);
9902 // If __module_private__ was specified, mark the function accordingly.
9903 if (D
.getDeclSpec().isModulePrivateSpecified()) {
9904 if (isFunctionTemplateSpecialization
) {
9905 SourceLocation ModulePrivateLoc
9906 = D
.getDeclSpec().getModulePrivateSpecLoc();
9907 Diag(ModulePrivateLoc
, diag::err_module_private_specialization
)
9909 << FixItHint::CreateRemoval(ModulePrivateLoc
);
9911 NewFD
->setModulePrivate();
9912 if (FunctionTemplate
)
9913 FunctionTemplate
->setModulePrivate();
9918 if (FunctionTemplate
) {
9919 FunctionTemplate
->setObjectOfFriendDecl();
9920 FunctionTemplate
->setAccess(AS_public
);
9922 NewFD
->setObjectOfFriendDecl();
9923 NewFD
->setAccess(AS_public
);
9926 // If a function is defined as defaulted or deleted, mark it as such now.
9927 // We'll do the relevant checks on defaulted / deleted functions later.
9928 switch (D
.getFunctionDefinitionKind()) {
9929 case FunctionDefinitionKind::Declaration
:
9930 case FunctionDefinitionKind::Definition
:
9933 case FunctionDefinitionKind::Defaulted
:
9934 NewFD
->setDefaulted();
9937 case FunctionDefinitionKind::Deleted
:
9938 NewFD
->setDeletedAsWritten();
9942 if (isa
<CXXMethodDecl
>(NewFD
) && DC
== CurContext
&&
9943 D
.isFunctionDefinition() && !isInline
) {
9944 // Pre C++20 [class.mfct]p2:
9945 // A member function may be defined (8.4) in its class definition, in
9946 // which case it is an inline member function (7.1.2)
9947 // Post C++20 [class.mfct]p1:
9948 // If a member function is attached to the global module and is defined
9949 // in its class definition, it is inline.
9950 NewFD
->setImplicitlyInline(ImplicitInlineCXX20
);
9953 if (SC
== SC_Static
&& isa
<CXXMethodDecl
>(NewFD
) &&
9954 !CurContext
->isRecord()) {
9955 // C++ [class.static]p1:
9956 // A data or function member of a class may be declared static
9957 // in a class definition, in which case it is a static member of
9960 // Complain about the 'static' specifier if it's on an out-of-line
9961 // member function definition.
9963 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9964 // member function template declaration and class member template
9965 // declaration (MSVC versions before 2015), warn about this.
9966 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
9967 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015
) &&
9968 cast
<CXXRecordDecl
>(DC
)->getDescribedClassTemplate()) ||
9969 (getLangOpts().MSVCCompat
&& NewFD
->getDescribedFunctionTemplate()))
9970 ? diag::ext_static_out_of_line
: diag::err_static_out_of_line
)
9971 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
9974 // C++11 [except.spec]p15:
9975 // A deallocation function with no exception-specification is treated
9976 // as if it were specified with noexcept(true).
9977 const FunctionProtoType
*FPT
= R
->getAs
<FunctionProtoType
>();
9978 if ((Name
.getCXXOverloadedOperator() == OO_Delete
||
9979 Name
.getCXXOverloadedOperator() == OO_Array_Delete
) &&
9980 getLangOpts().CPlusPlus11
&& FPT
&& !FPT
->hasExceptionSpec())
9981 NewFD
->setType(Context
.getFunctionType(
9982 FPT
->getReturnType(), FPT
->getParamTypes(),
9983 FPT
->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept
)));
9985 // C++20 [dcl.inline]/7
9986 // If an inline function or variable that is attached to a named module
9987 // is declared in a definition domain, it shall be defined in that
9989 // So, if the current declaration does not have a definition, we must
9990 // check at the end of the TU (or when the PMF starts) to see that we
9991 // have a definition at that point.
9992 if (isInline
&& !D
.isFunctionDefinition() && getLangOpts().CPlusPlus20
&&
9993 NewFD
->hasOwningModule() &&
9994 NewFD
->getOwningModule()->isModulePurview()) {
9995 PendingInlineFuncDecls
.insert(NewFD
);
9999 // Filter out previous declarations that don't match the scope.
10000 FilterLookupForScope(Previous
, OriginalDC
, S
, shouldConsiderLinkage(NewFD
),
10001 D
.getCXXScopeSpec().isNotEmpty() ||
10002 isMemberSpecialization
||
10003 isFunctionTemplateSpecialization
);
10005 // Handle GNU asm-label extension (encoded as an attribute).
10006 if (Expr
*E
= (Expr
*) D
.getAsmLabel()) {
10007 // The parser guarantees this is a string.
10008 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
10009 NewFD
->addAttr(AsmLabelAttr::Create(Context
, SE
->getString(),
10010 /*IsLiteralLabel=*/true,
10011 SE
->getStrTokenLoc(0)));
10012 } else if (!ExtnameUndeclaredIdentifiers
.empty()) {
10013 llvm::DenseMap
<IdentifierInfo
*,AsmLabelAttr
*>::iterator I
=
10014 ExtnameUndeclaredIdentifiers
.find(NewFD
->getIdentifier());
10015 if (I
!= ExtnameUndeclaredIdentifiers
.end()) {
10016 if (isDeclExternC(NewFD
)) {
10017 NewFD
->addAttr(I
->second
);
10018 ExtnameUndeclaredIdentifiers
.erase(I
);
10020 Diag(NewFD
->getLocation(), diag::warn_redefine_extname_not_applied
)
10021 << /*Variable*/0 << NewFD
;
10025 // Copy the parameter declarations from the declarator D to the function
10026 // declaration NewFD, if they are available. First scavenge them into Params.
10027 SmallVector
<ParmVarDecl
*, 16> Params
;
10029 if (D
.isFunctionDeclarator(FTIIdx
)) {
10030 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getTypeObject(FTIIdx
).Fun
;
10032 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10033 // function that takes no arguments, not a function that takes a
10034 // single void argument.
10035 // We let through "const void" here because Sema::GetTypeForDeclarator
10036 // already checks for that case.
10037 if (FTIHasNonVoidParameters(FTI
) && FTI
.Params
[0].Param
) {
10038 for (unsigned i
= 0, e
= FTI
.NumParams
; i
!= e
; ++i
) {
10039 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.Params
[i
].Param
);
10040 assert(Param
->getDeclContext() != NewFD
&& "Was set before ?");
10041 Param
->setDeclContext(NewFD
);
10042 Params
.push_back(Param
);
10044 if (Param
->isInvalidDecl())
10045 NewFD
->setInvalidDecl();
10049 if (!getLangOpts().CPlusPlus
) {
10050 // In C, find all the tag declarations from the prototype and move them
10051 // into the function DeclContext. Remove them from the surrounding tag
10052 // injection context of the function, which is typically but not always
10054 DeclContext
*PrototypeTagContext
=
10055 getTagInjectionContext(NewFD
->getLexicalDeclContext());
10056 for (NamedDecl
*NonParmDecl
: FTI
.getDeclsInPrototype()) {
10057 auto *TD
= dyn_cast
<TagDecl
>(NonParmDecl
);
10059 // We don't want to reparent enumerators. Look at their parent enum
10062 if (auto *ECD
= dyn_cast
<EnumConstantDecl
>(NonParmDecl
))
10063 TD
= cast
<EnumDecl
>(ECD
->getDeclContext());
10067 DeclContext
*TagDC
= TD
->getLexicalDeclContext();
10068 if (!TagDC
->containsDecl(TD
))
10070 TagDC
->removeDecl(TD
);
10071 TD
->setDeclContext(NewFD
);
10072 NewFD
->addDecl(TD
);
10074 // Preserve the lexical DeclContext if it is not the surrounding tag
10075 // injection context of the FD. In this example, the semantic context of
10076 // E will be f and the lexical context will be S, while both the
10077 // semantic and lexical contexts of S will be f:
10078 // void f(struct S { enum E { a } f; } s);
10079 if (TagDC
!= PrototypeTagContext
)
10080 TD
->setLexicalDeclContext(TagDC
);
10083 } else if (const FunctionProtoType
*FT
= R
->getAs
<FunctionProtoType
>()) {
10084 // When we're declaring a function with a typedef, typeof, etc as in the
10085 // following example, we'll need to synthesize (unnamed)
10086 // parameters for use in the declaration.
10089 // typedef void fn(int);
10093 // Synthesize a parameter for each argument type.
10094 for (const auto &AI
: FT
->param_types()) {
10095 ParmVarDecl
*Param
=
10096 BuildParmVarDeclForTypedef(NewFD
, D
.getIdentifierLoc(), AI
);
10097 Param
->setScopeInfo(0, Params
.size());
10098 Params
.push_back(Param
);
10101 assert(R
->isFunctionNoProtoType() && NewFD
->getNumParams() == 0 &&
10102 "Should not need args for typedef of non-prototype fn");
10105 // Finally, we know we have the right number of parameters, install them.
10106 NewFD
->setParams(Params
);
10108 if (D
.getDeclSpec().isNoreturnSpecified())
10109 NewFD
->addAttr(C11NoReturnAttr::Create(Context
,
10110 D
.getDeclSpec().getNoreturnSpecLoc(),
10111 AttributeCommonInfo::AS_Keyword
));
10113 // Functions returning a variably modified type violate C99 6.7.5.2p2
10114 // because all functions have linkage.
10115 if (!NewFD
->isInvalidDecl() &&
10116 NewFD
->getReturnType()->isVariablyModifiedType()) {
10117 Diag(NewFD
->getLocation(), diag::err_vm_func_decl
);
10118 NewFD
->setInvalidDecl();
10121 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10122 if (PragmaClangTextSection
.Valid
&& D
.isFunctionDefinition() &&
10123 !NewFD
->hasAttr
<SectionAttr
>())
10124 NewFD
->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10125 Context
, PragmaClangTextSection
.SectionName
,
10126 PragmaClangTextSection
.PragmaLocation
, AttributeCommonInfo::AS_Pragma
));
10128 // Apply an implicit SectionAttr if #pragma code_seg is active.
10129 if (CodeSegStack
.CurrentValue
&& D
.isFunctionDefinition() &&
10130 !NewFD
->hasAttr
<SectionAttr
>()) {
10131 NewFD
->addAttr(SectionAttr::CreateImplicit(
10132 Context
, CodeSegStack
.CurrentValue
->getString(),
10133 CodeSegStack
.CurrentPragmaLocation
, AttributeCommonInfo::AS_Pragma
,
10134 SectionAttr::Declspec_allocate
));
10135 if (UnifySection(CodeSegStack
.CurrentValue
->getString(),
10136 ASTContext::PSF_Implicit
| ASTContext::PSF_Execute
|
10137 ASTContext::PSF_Read
,
10139 NewFD
->dropAttr
<SectionAttr
>();
10142 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10144 if (StrictGuardStackCheckStack
.CurrentValue
&& D
.isFunctionDefinition() &&
10145 !NewFD
->hasAttr
<StrictGuardStackCheckAttr
>())
10146 NewFD
->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10147 Context
, PragmaClangTextSection
.PragmaLocation
,
10148 AttributeCommonInfo::AS_Pragma
));
10150 // Apply an implicit CodeSegAttr from class declspec or
10151 // apply an implicit SectionAttr from #pragma code_seg if active.
10152 if (!NewFD
->hasAttr
<CodeSegAttr
>()) {
10153 if (Attr
*SAttr
= getImplicitCodeSegOrSectionAttrForFunction(NewFD
,
10154 D
.isFunctionDefinition())) {
10155 NewFD
->addAttr(SAttr
);
10159 // Handle attributes.
10160 ProcessDeclAttributes(S
, NewFD
, D
);
10161 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
10162 if (NewTVA
&& !NewTVA
->isDefaultVersion() &&
10163 !Context
.getTargetInfo().hasFeature("fmv")) {
10164 // Don't add to scope fmv functions declarations if fmv disabled
10165 AddToScope
= false;
10169 if (getLangOpts().OpenCL
) {
10170 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10171 // type declaration will generate a compilation error.
10172 LangAS AddressSpace
= NewFD
->getReturnType().getAddressSpace();
10173 if (AddressSpace
!= LangAS::Default
) {
10174 Diag(NewFD
->getLocation(), diag::err_return_value_with_address_space
);
10175 NewFD
->setInvalidDecl();
10179 if (getLangOpts().HLSL
) {
10180 auto &TargetInfo
= getASTContext().getTargetInfo();
10181 // Skip operator overload which not identifier.
10182 // Also make sure NewFD is in translation-unit scope.
10183 if (!NewFD
->isInvalidDecl() && Name
.isIdentifier() &&
10184 NewFD
->getName() == TargetInfo
.getTargetOpts().HLSLEntry
&&
10185 S
->getDepth() == 0) {
10186 CheckHLSLEntryPoint(NewFD
);
10187 if (!NewFD
->isInvalidDecl()) {
10188 auto Env
= TargetInfo
.getTriple().getEnvironment();
10189 AttributeCommonInfo
AL(NewFD
->getBeginLoc());
10190 HLSLShaderAttr::ShaderType ShaderType
=
10191 static_cast<HLSLShaderAttr::ShaderType
>(
10192 hlsl::getStageFromEnvironment(Env
));
10193 // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10195 if (HLSLShaderAttr
*Attr
= mergeHLSLShaderAttr(NewFD
, AL
, ShaderType
))
10196 NewFD
->addAttr(Attr
);
10199 // HLSL does not support specifying an address space on a function return
10201 LangAS AddressSpace
= NewFD
->getReturnType().getAddressSpace();
10202 if (AddressSpace
!= LangAS::Default
) {
10203 Diag(NewFD
->getLocation(), diag::err_return_value_with_address_space
);
10204 NewFD
->setInvalidDecl();
10208 if (!getLangOpts().CPlusPlus
) {
10209 // Perform semantic checking on the function declaration.
10210 if (!NewFD
->isInvalidDecl() && NewFD
->isMain())
10211 CheckMain(NewFD
, D
.getDeclSpec());
10213 if (!NewFD
->isInvalidDecl() && NewFD
->isMSVCRTEntryPoint())
10214 CheckMSVCRTEntryPoint(NewFD
);
10216 if (!NewFD
->isInvalidDecl())
10217 D
.setRedeclaration(CheckFunctionDeclaration(S
, NewFD
, Previous
,
10218 isMemberSpecialization
,
10219 D
.isFunctionDefinition()));
10220 else if (!Previous
.empty())
10221 // Recover gracefully from an invalid redeclaration.
10222 D
.setRedeclaration(true);
10223 assert((NewFD
->isInvalidDecl() || !D
.isRedeclaration() ||
10224 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
10225 "previous declaration set still overloaded");
10227 // Diagnose no-prototype function declarations with calling conventions that
10228 // don't support variadic calls. Only do this in C and do it after merging
10229 // possibly prototyped redeclarations.
10230 const FunctionType
*FT
= NewFD
->getType()->castAs
<FunctionType
>();
10231 if (isa
<FunctionNoProtoType
>(FT
) && !D
.isFunctionDefinition()) {
10232 CallingConv CC
= FT
->getExtInfo().getCC();
10233 if (!supportsVariadicCall(CC
)) {
10234 // Windows system headers sometimes accidentally use stdcall without
10235 // (void) parameters, so we relax this to a warning.
10237 CC
== CC_X86StdCall
? diag::warn_cconv_knr
: diag::err_cconv_knr
;
10238 Diag(NewFD
->getLocation(), DiagID
)
10239 << FunctionType::getNameForCallConv(CC
);
10243 if (NewFD
->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10244 NewFD
->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10245 checkNonTrivialCUnion(NewFD
->getReturnType(),
10246 NewFD
->getReturnTypeSourceRange().getBegin(),
10247 NTCUC_FunctionReturn
, NTCUK_Destruct
|NTCUK_Copy
);
10249 // C++11 [replacement.functions]p3:
10250 // The program's definitions shall not be specified as inline.
10252 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10254 // Suppress the diagnostic if the function is __attribute__((used)), since
10255 // that forces an external definition to be emitted.
10256 if (D
.getDeclSpec().isInlineSpecified() &&
10257 NewFD
->isReplaceableGlobalAllocationFunction() &&
10258 !NewFD
->hasAttr
<UsedAttr
>())
10259 Diag(D
.getDeclSpec().getInlineSpecLoc(),
10260 diag::ext_operator_new_delete_declared_inline
)
10261 << NewFD
->getDeclName();
10263 // If the declarator is a template-id, translate the parser's template
10264 // argument list into our AST format.
10265 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
10266 TemplateIdAnnotation
*TemplateId
= D
.getName().TemplateId
;
10267 TemplateArgs
.setLAngleLoc(TemplateId
->LAngleLoc
);
10268 TemplateArgs
.setRAngleLoc(TemplateId
->RAngleLoc
);
10269 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
->getTemplateArgs(),
10270 TemplateId
->NumArgs
);
10271 translateTemplateArguments(TemplateArgsPtr
,
10274 HasExplicitTemplateArgs
= true;
10276 if (NewFD
->isInvalidDecl()) {
10277 HasExplicitTemplateArgs
= false;
10278 } else if (FunctionTemplate
) {
10279 // Function template with explicit template arguments.
10280 Diag(D
.getIdentifierLoc(), diag::err_function_template_partial_spec
)
10281 << SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
);
10283 HasExplicitTemplateArgs
= false;
10285 assert((isFunctionTemplateSpecialization
||
10286 D
.getDeclSpec().isFriendSpecified()) &&
10287 "should have a 'template<>' for this decl");
10288 // "friend void foo<>(int);" is an implicit specialization decl.
10289 isFunctionTemplateSpecialization
= true;
10291 } else if (isFriend
&& isFunctionTemplateSpecialization
) {
10292 // This combination is only possible in a recovery case; the user
10293 // wrote something like:
10294 // template <> friend void foo(int);
10295 // which we're recovering from as if the user had written:
10296 // friend void foo<>(int);
10297 // Go ahead and fake up a template id.
10298 HasExplicitTemplateArgs
= true;
10299 TemplateArgs
.setLAngleLoc(D
.getIdentifierLoc());
10300 TemplateArgs
.setRAngleLoc(D
.getIdentifierLoc());
10303 // We do not add HD attributes to specializations here because
10304 // they may have different constexpr-ness compared to their
10305 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10306 // may end up with different effective targets. Instead, a
10307 // specialization inherits its target attributes from its template
10308 // in the CheckFunctionTemplateSpecialization() call below.
10309 if (getLangOpts().CUDA
&& !isFunctionTemplateSpecialization
)
10310 maybeAddCUDAHostDeviceAttrs(NewFD
, Previous
);
10312 // If it's a friend (and only if it's a friend), it's possible
10313 // that either the specialized function type or the specialized
10314 // template is dependent, and therefore matching will fail. In
10315 // this case, don't check the specialization yet.
10316 if (isFunctionTemplateSpecialization
&& isFriend
&&
10317 (NewFD
->getType()->isDependentType() || DC
->isDependentContext() ||
10318 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10319 TemplateArgs
.arguments()))) {
10320 assert(HasExplicitTemplateArgs
&&
10321 "friend function specialization without template args");
10322 if (CheckDependentFunctionTemplateSpecialization(NewFD
, TemplateArgs
,
10324 NewFD
->setInvalidDecl();
10325 } else if (isFunctionTemplateSpecialization
) {
10326 if (CurContext
->isDependentContext() && CurContext
->isRecord()
10328 isDependentClassScopeExplicitSpecialization
= true;
10329 } else if (!NewFD
->isInvalidDecl() &&
10330 CheckFunctionTemplateSpecialization(
10331 NewFD
, (HasExplicitTemplateArgs
? &TemplateArgs
: nullptr),
10333 NewFD
->setInvalidDecl();
10335 // C++ [dcl.stc]p1:
10336 // A storage-class-specifier shall not be specified in an explicit
10337 // specialization (14.7.3)
10338 FunctionTemplateSpecializationInfo
*Info
=
10339 NewFD
->getTemplateSpecializationInfo();
10340 if (Info
&& SC
!= SC_None
) {
10341 if (SC
!= Info
->getTemplate()->getTemplatedDecl()->getStorageClass())
10342 Diag(NewFD
->getLocation(),
10343 diag::err_explicit_specialization_inconsistent_storage_class
)
10345 << FixItHint::CreateRemoval(
10346 D
.getDeclSpec().getStorageClassSpecLoc());
10349 Diag(NewFD
->getLocation(),
10350 diag::ext_explicit_specialization_storage_class
)
10351 << FixItHint::CreateRemoval(
10352 D
.getDeclSpec().getStorageClassSpecLoc());
10354 } else if (isMemberSpecialization
&& isa
<CXXMethodDecl
>(NewFD
)) {
10355 if (CheckMemberSpecialization(NewFD
, Previous
))
10356 NewFD
->setInvalidDecl();
10359 // Perform semantic checking on the function declaration.
10360 if (!isDependentClassScopeExplicitSpecialization
) {
10361 if (!NewFD
->isInvalidDecl() && NewFD
->isMain())
10362 CheckMain(NewFD
, D
.getDeclSpec());
10364 if (!NewFD
->isInvalidDecl() && NewFD
->isMSVCRTEntryPoint())
10365 CheckMSVCRTEntryPoint(NewFD
);
10367 if (!NewFD
->isInvalidDecl())
10368 D
.setRedeclaration(CheckFunctionDeclaration(S
, NewFD
, Previous
,
10369 isMemberSpecialization
,
10370 D
.isFunctionDefinition()));
10371 else if (!Previous
.empty())
10372 // Recover gracefully from an invalid redeclaration.
10373 D
.setRedeclaration(true);
10376 assert((NewFD
->isInvalidDecl() || NewFD
->isMultiVersion() ||
10377 !D
.isRedeclaration() ||
10378 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
10379 "previous declaration set still overloaded");
10381 NamedDecl
*PrincipalDecl
= (FunctionTemplate
10382 ? cast
<NamedDecl
>(FunctionTemplate
)
10385 if (isFriend
&& NewFD
->getPreviousDecl()) {
10386 AccessSpecifier Access
= AS_public
;
10387 if (!NewFD
->isInvalidDecl())
10388 Access
= NewFD
->getPreviousDecl()->getAccess();
10390 NewFD
->setAccess(Access
);
10391 if (FunctionTemplate
) FunctionTemplate
->setAccess(Access
);
10394 if (NewFD
->isOverloadedOperator() && !DC
->isRecord() &&
10395 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
10396 PrincipalDecl
->setNonMemberOperator();
10398 // If we have a function template, check the template parameter
10399 // list. This will check and merge default template arguments.
10400 if (FunctionTemplate
) {
10401 FunctionTemplateDecl
*PrevTemplate
=
10402 FunctionTemplate
->getPreviousDecl();
10403 CheckTemplateParameterList(FunctionTemplate
->getTemplateParameters(),
10404 PrevTemplate
? PrevTemplate
->getTemplateParameters()
10406 D
.getDeclSpec().isFriendSpecified()
10407 ? (D
.isFunctionDefinition()
10408 ? TPC_FriendFunctionTemplateDefinition
10409 : TPC_FriendFunctionTemplate
)
10410 : (D
.getCXXScopeSpec().isSet() &&
10411 DC
&& DC
->isRecord() &&
10412 DC
->isDependentContext())
10413 ? TPC_ClassTemplateMember
10414 : TPC_FunctionTemplate
);
10417 if (NewFD
->isInvalidDecl()) {
10418 // Ignore all the rest of this.
10419 } else if (!D
.isRedeclaration()) {
10420 struct ActOnFDArgs ExtraArgs
= { S
, D
, TemplateParamLists
,
10422 // Fake up an access specifier if it's supposed to be a class member.
10423 if (isa
<CXXRecordDecl
>(NewFD
->getDeclContext()))
10424 NewFD
->setAccess(AS_public
);
10426 // Qualified decls generally require a previous declaration.
10427 if (D
.getCXXScopeSpec().isSet()) {
10428 // ...with the major exception of templated-scope or
10429 // dependent-scope friend declarations.
10431 // TODO: we currently also suppress this check in dependent
10432 // contexts because (1) the parameter depth will be off when
10433 // matching friend templates and (2) we might actually be
10434 // selecting a friend based on a dependent factor. But there
10435 // are situations where these conditions don't apply and we
10436 // can actually do this check immediately.
10438 // Unless the scope is dependent, it's always an error if qualified
10439 // redeclaration lookup found nothing at all. Diagnose that now;
10440 // nothing will diagnose that error later.
10442 (D
.getCXXScopeSpec().getScopeRep()->isDependent() ||
10443 (!Previous
.empty() && CurContext
->isDependentContext()))) {
10445 } else if (NewFD
->isCPUDispatchMultiVersion() ||
10446 NewFD
->isCPUSpecificMultiVersion()) {
10447 // ignore this, we allow the redeclaration behavior here to create new
10448 // versions of the function.
10450 // The user tried to provide an out-of-line definition for a
10451 // function that is a member of a class or namespace, but there
10452 // was no such member function declared (C++ [class.mfct]p2,
10453 // C++ [namespace.memdef]p2). For example:
10459 // void X::f() { } // ill-formed
10461 // Complain about this problem, and attempt to suggest close
10462 // matches (e.g., those that differ only in cv-qualifiers and
10463 // whether the parameter types are references).
10465 if (NamedDecl
*Result
= DiagnoseInvalidRedeclaration(
10466 *this, Previous
, NewFD
, ExtraArgs
, false, nullptr)) {
10467 AddToScope
= ExtraArgs
.AddToScope
;
10472 // Unqualified local friend declarations are required to resolve
10474 } else if (isFriend
&& cast
<CXXRecordDecl
>(CurContext
)->isLocalClass()) {
10475 if (NamedDecl
*Result
= DiagnoseInvalidRedeclaration(
10476 *this, Previous
, NewFD
, ExtraArgs
, true, S
)) {
10477 AddToScope
= ExtraArgs
.AddToScope
;
10481 } else if (!D
.isFunctionDefinition() &&
10482 isa
<CXXMethodDecl
>(NewFD
) && NewFD
->isOutOfLine() &&
10483 !isFriend
&& !isFunctionTemplateSpecialization
&&
10484 !isMemberSpecialization
) {
10485 // An out-of-line member function declaration must also be a
10486 // definition (C++ [class.mfct]p2).
10487 // Note that this is not the case for explicit specializations of
10488 // function templates or member functions of class templates, per
10489 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10490 // extension for compatibility with old SWIG code which likes to
10492 Diag(NewFD
->getLocation(), diag::ext_out_of_line_declaration
)
10493 << D
.getCXXScopeSpec().getRange();
10497 // If this is the first declaration of a library builtin function, add
10498 // attributes as appropriate.
10499 if (!D
.isRedeclaration()) {
10500 if (IdentifierInfo
*II
= Previous
.getLookupName().getAsIdentifierInfo()) {
10501 if (unsigned BuiltinID
= II
->getBuiltinID()) {
10502 bool InStdNamespace
= Context
.BuiltinInfo
.isInStdNamespace(BuiltinID
);
10503 if (!InStdNamespace
&&
10504 NewFD
->getDeclContext()->getRedeclContext()->isFileContext()) {
10505 if (NewFD
->getLanguageLinkage() == CLanguageLinkage
) {
10506 // Validate the type matches unless this builtin is specified as
10507 // matching regardless of its declared type.
10508 if (Context
.BuiltinInfo
.allowTypeMismatch(BuiltinID
)) {
10509 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10511 ASTContext::GetBuiltinTypeError Error
;
10512 LookupNecessaryTypesForBuiltin(S
, BuiltinID
);
10513 QualType BuiltinType
= Context
.GetBuiltinType(BuiltinID
, Error
);
10515 if (!Error
&& !BuiltinType
.isNull() &&
10516 Context
.hasSameFunctionTypeIgnoringExceptionSpec(
10517 NewFD
->getType(), BuiltinType
))
10518 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10521 } else if (InStdNamespace
&& NewFD
->isInStdNamespace() &&
10522 isStdBuiltin(Context
, NewFD
, BuiltinID
)) {
10523 NewFD
->addAttr(BuiltinAttr::CreateImplicit(Context
, BuiltinID
));
10529 ProcessPragmaWeak(S
, NewFD
);
10530 checkAttributesAfterMerging(*this, *NewFD
);
10532 AddKnownFunctionAttributes(NewFD
);
10534 if (NewFD
->hasAttr
<OverloadableAttr
>() &&
10535 !NewFD
->getType()->getAs
<FunctionProtoType
>()) {
10536 Diag(NewFD
->getLocation(),
10537 diag::err_attribute_overloadable_no_prototype
)
10539 NewFD
->dropAttr
<OverloadableAttr
>();
10542 // If there's a #pragma GCC visibility in scope, and this isn't a class
10543 // member, set the visibility of this function.
10544 if (!DC
->isRecord() && NewFD
->isExternallyVisible())
10545 AddPushedVisibilityAttribute(NewFD
);
10547 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10548 // marking the function.
10549 AddCFAuditedAttribute(NewFD
);
10551 // If this is a function definition, check if we have to apply any
10552 // attributes (i.e. optnone and no_builtin) due to a pragma.
10553 if (D
.isFunctionDefinition()) {
10554 AddRangeBasedOptnone(NewFD
);
10555 AddImplicitMSFunctionNoBuiltinAttr(NewFD
);
10556 AddSectionMSAllocText(NewFD
);
10557 ModifyFnAttributesMSPragmaOptimize(NewFD
);
10560 // If this is the first declaration of an extern C variable, update
10561 // the map of such variables.
10562 if (NewFD
->isFirstDecl() && !NewFD
->isInvalidDecl() &&
10563 isIncompleteDeclExternC(*this, NewFD
))
10564 RegisterLocallyScopedExternCDecl(NewFD
, S
);
10566 // Set this FunctionDecl's range up to the right paren.
10567 NewFD
->setRangeEnd(D
.getSourceRange().getEnd());
10569 if (D
.isRedeclaration() && !Previous
.empty()) {
10570 NamedDecl
*Prev
= Previous
.getRepresentativeDecl();
10571 checkDLLAttributeRedeclaration(*this, Prev
, NewFD
,
10572 isMemberSpecialization
||
10573 isFunctionTemplateSpecialization
,
10574 D
.isFunctionDefinition());
10577 if (getLangOpts().CUDA
) {
10578 IdentifierInfo
*II
= NewFD
->getIdentifier();
10579 if (II
&& II
->isStr(getCudaConfigureFuncName()) &&
10580 !NewFD
->isInvalidDecl() &&
10581 NewFD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10582 if (!R
->castAs
<FunctionType
>()->getReturnType()->isScalarType())
10583 Diag(NewFD
->getLocation(), diag::err_config_scalar_return
)
10584 << getCudaConfigureFuncName();
10585 Context
.setcudaConfigureCallDecl(NewFD
);
10588 // Variadic functions, other than a *declaration* of printf, are not allowed
10589 // in device-side CUDA code, unless someone passed
10590 // -fcuda-allow-variadic-functions.
10591 if (!getLangOpts().CUDAAllowVariadicFunctions
&& NewFD
->isVariadic() &&
10592 (NewFD
->hasAttr
<CUDADeviceAttr
>() ||
10593 NewFD
->hasAttr
<CUDAGlobalAttr
>()) &&
10594 !(II
&& II
->isStr("printf") && NewFD
->isExternC() &&
10595 !D
.isFunctionDefinition())) {
10596 Diag(NewFD
->getLocation(), diag::err_variadic_device_fn
);
10600 MarkUnusedFileScopedDecl(NewFD
);
10604 if (getLangOpts().OpenCL
&& NewFD
->hasAttr
<OpenCLKernelAttr
>()) {
10605 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10606 if (SC
== SC_Static
) {
10607 Diag(D
.getIdentifierLoc(), diag::err_static_kernel
);
10608 D
.setInvalidType();
10611 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10612 if (!NewFD
->getReturnType()->isVoidType()) {
10613 SourceRange RTRange
= NewFD
->getReturnTypeSourceRange();
10614 Diag(D
.getIdentifierLoc(), diag::err_expected_kernel_void_return_type
)
10615 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "void")
10617 D
.setInvalidType();
10620 llvm::SmallPtrSet
<const Type
*, 16> ValidTypes
;
10621 for (auto *Param
: NewFD
->parameters())
10622 checkIsValidOpenCLKernelParameter(*this, D
, Param
, ValidTypes
);
10624 if (getLangOpts().OpenCLCPlusPlus
) {
10625 if (DC
->isRecord()) {
10626 Diag(D
.getIdentifierLoc(), diag::err_method_kernel
);
10627 D
.setInvalidType();
10629 if (FunctionTemplate
) {
10630 Diag(D
.getIdentifierLoc(), diag::err_template_kernel
);
10631 D
.setInvalidType();
10636 if (getLangOpts().CPlusPlus
) {
10637 // Precalculate whether this is a friend function template with a constraint
10638 // that depends on an enclosing template, per [temp.friend]p9.
10639 if (isFriend
&& FunctionTemplate
&&
10640 FriendConstraintsDependOnEnclosingTemplate(NewFD
))
10641 NewFD
->setFriendConstraintRefersToEnclosingTemplate(true);
10643 if (FunctionTemplate
) {
10644 if (NewFD
->isInvalidDecl())
10645 FunctionTemplate
->setInvalidDecl();
10646 return FunctionTemplate
;
10649 if (isMemberSpecialization
&& !NewFD
->isInvalidDecl())
10650 CompleteMemberSpecialization(NewFD
, Previous
);
10653 for (const ParmVarDecl
*Param
: NewFD
->parameters()) {
10654 QualType PT
= Param
->getType();
10656 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10658 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10659 if(const PipeType
*PipeTy
= PT
->getAs
<PipeType
>()) {
10660 QualType ElemTy
= PipeTy
->getElementType();
10661 if (ElemTy
->isReferenceType() || ElemTy
->isPointerType()) {
10662 Diag(Param
->getTypeSpecStartLoc(), diag::err_reference_pipe_type
);
10663 D
.setInvalidType();
10669 // Here we have an function template explicit specialization at class scope.
10670 // The actual specialization will be postponed to template instatiation
10671 // time via the ClassScopeFunctionSpecializationDecl node.
10672 if (isDependentClassScopeExplicitSpecialization
) {
10673 ClassScopeFunctionSpecializationDecl
*NewSpec
=
10674 ClassScopeFunctionSpecializationDecl::Create(
10675 Context
, CurContext
, NewFD
->getLocation(),
10676 cast
<CXXMethodDecl
>(NewFD
),
10677 HasExplicitTemplateArgs
, TemplateArgs
);
10678 CurContext
->addDecl(NewSpec
);
10679 AddToScope
= false;
10682 // Diagnose availability attributes. Availability cannot be used on functions
10683 // that are run during load/unload.
10684 if (const auto *attr
= NewFD
->getAttr
<AvailabilityAttr
>()) {
10685 if (NewFD
->hasAttr
<ConstructorAttr
>()) {
10686 Diag(attr
->getLocation(), diag::warn_availability_on_static_initializer
)
10688 NewFD
->dropAttr
<AvailabilityAttr
>();
10690 if (NewFD
->hasAttr
<DestructorAttr
>()) {
10691 Diag(attr
->getLocation(), diag::warn_availability_on_static_initializer
)
10693 NewFD
->dropAttr
<AvailabilityAttr
>();
10697 // Diagnose no_builtin attribute on function declaration that are not a
10699 // FIXME: We should really be doing this in
10700 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10701 // the FunctionDecl and at this point of the code
10702 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10703 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10704 if (const auto *NBA
= NewFD
->getAttr
<NoBuiltinAttr
>())
10705 switch (D
.getFunctionDefinitionKind()) {
10706 case FunctionDefinitionKind::Defaulted
:
10707 case FunctionDefinitionKind::Deleted
:
10708 Diag(NBA
->getLocation(),
10709 diag::err_attribute_no_builtin_on_defaulted_deleted_function
)
10710 << NBA
->getSpelling();
10712 case FunctionDefinitionKind::Declaration
:
10713 Diag(NBA
->getLocation(), diag::err_attribute_no_builtin_on_non_definition
)
10714 << NBA
->getSpelling();
10716 case FunctionDefinitionKind::Definition
:
10723 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10724 /// when __declspec(code_seg) "is applied to a class, all member functions of
10725 /// the class and nested classes -- this includes compiler-generated special
10726 /// member functions -- are put in the specified segment."
10727 /// The actual behavior is a little more complicated. The Microsoft compiler
10728 /// won't check outer classes if there is an active value from #pragma code_seg.
10729 /// The CodeSeg is always applied from the direct parent but only from outer
10730 /// classes when the #pragma code_seg stack is empty. See:
10731 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10732 /// available since MS has removed the page.
10733 static Attr
*getImplicitCodeSegAttrFromClass(Sema
&S
, const FunctionDecl
*FD
) {
10734 const auto *Method
= dyn_cast
<CXXMethodDecl
>(FD
);
10737 const CXXRecordDecl
*Parent
= Method
->getParent();
10738 if (const auto *SAttr
= Parent
->getAttr
<CodeSegAttr
>()) {
10739 Attr
*NewAttr
= SAttr
->clone(S
.getASTContext());
10740 NewAttr
->setImplicit(true);
10744 // The Microsoft compiler won't check outer classes for the CodeSeg
10745 // when the #pragma code_seg stack is active.
10746 if (S
.CodeSegStack
.CurrentValue
)
10749 while ((Parent
= dyn_cast
<CXXRecordDecl
>(Parent
->getParent()))) {
10750 if (const auto *SAttr
= Parent
->getAttr
<CodeSegAttr
>()) {
10751 Attr
*NewAttr
= SAttr
->clone(S
.getASTContext());
10752 NewAttr
->setImplicit(true);
10759 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10760 /// containing class. Otherwise it will return implicit SectionAttr if the
10761 /// function is a definition and there is an active value on CodeSegStack
10762 /// (from the current #pragma code-seg value).
10764 /// \param FD Function being declared.
10765 /// \param IsDefinition Whether it is a definition or just a declaration.
10766 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10767 /// nullptr if no attribute should be added.
10768 Attr
*Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl
*FD
,
10769 bool IsDefinition
) {
10770 if (Attr
*A
= getImplicitCodeSegAttrFromClass(*this, FD
))
10772 if (!FD
->hasAttr
<SectionAttr
>() && IsDefinition
&&
10773 CodeSegStack
.CurrentValue
)
10774 return SectionAttr::CreateImplicit(
10775 getASTContext(), CodeSegStack
.CurrentValue
->getString(),
10776 CodeSegStack
.CurrentPragmaLocation
, AttributeCommonInfo::AS_Pragma
,
10777 SectionAttr::Declspec_allocate
);
10781 /// Determines if we can perform a correct type check for \p D as a
10782 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10783 /// best-effort check.
10785 /// \param NewD The new declaration.
10786 /// \param OldD The old declaration.
10787 /// \param NewT The portion of the type of the new declaration to check.
10788 /// \param OldT The portion of the type of the old declaration to check.
10789 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl
*NewD
, ValueDecl
*OldD
,
10790 QualType NewT
, QualType OldT
) {
10791 if (!NewD
->getLexicalDeclContext()->isDependentContext())
10794 // For dependently-typed local extern declarations and friends, we can't
10795 // perform a correct type check in general until instantiation:
10798 // template<typename T> void g() { T f(); }
10800 // (valid if g() is only instantiated with T = int).
10801 if (NewT
->isDependentType() &&
10802 (NewD
->isLocalExternDecl() || NewD
->getFriendObjectKind()))
10805 // Similarly, if the previous declaration was a dependent local extern
10806 // declaration, we don't really know its type yet.
10807 if (OldT
->isDependentType() && OldD
->isLocalExternDecl())
10813 /// Checks if the new declaration declared in dependent context must be
10814 /// put in the same redeclaration chain as the specified declaration.
10816 /// \param D Declaration that is checked.
10817 /// \param PrevDecl Previous declaration found with proper lookup method for the
10818 /// same declaration name.
10819 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10822 bool Sema::shouldLinkDependentDeclWithPrevious(Decl
*D
, Decl
*PrevDecl
) {
10823 if (!D
->getLexicalDeclContext()->isDependentContext())
10826 // Don't chain dependent friend function definitions until instantiation, to
10827 // permit cases like
10830 // template<typename T> class C1 { friend void func() {} };
10831 // template<typename T> class C2 { friend void func() {} };
10833 // ... which is valid if only one of C1 and C2 is ever instantiated.
10835 // FIXME: This need only apply to function definitions. For now, we proxy
10836 // this by checking for a file-scope function. We do not want this to apply
10837 // to friend declarations nominating member functions, because that gets in
10838 // the way of access checks.
10839 if (D
->getFriendObjectKind() && D
->getDeclContext()->isFileContext())
10842 auto *VD
= dyn_cast
<ValueDecl
>(D
);
10843 auto *PrevVD
= dyn_cast
<ValueDecl
>(PrevDecl
);
10844 return !VD
|| !PrevVD
||
10845 canFullyTypeCheckRedeclaration(VD
, PrevVD
, VD
->getType(),
10846 PrevVD
->getType());
10849 /// Check the target or target_version attribute of the function for
10850 /// MultiVersion validity.
10852 /// Returns true if there was an error, false otherwise.
10853 static bool CheckMultiVersionValue(Sema
&S
, const FunctionDecl
*FD
) {
10854 const auto *TA
= FD
->getAttr
<TargetAttr
>();
10855 const auto *TVA
= FD
->getAttr
<TargetVersionAttr
>();
10858 "MultiVersion candidate requires a target or target_version attribute");
10859 const TargetInfo
&TargetInfo
= S
.Context
.getTargetInfo();
10860 enum ErrType
{ Feature
= 0, Architecture
= 1 };
10863 ParsedTargetAttr ParseInfo
=
10864 S
.getASTContext().getTargetInfo().parseTargetAttr(TA
->getFeaturesStr());
10865 if (!ParseInfo
.CPU
.empty() && !TargetInfo
.validateCpuIs(ParseInfo
.CPU
)) {
10866 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10867 << Architecture
<< ParseInfo
.CPU
;
10870 for (const auto &Feat
: ParseInfo
.Features
) {
10871 auto BareFeat
= StringRef
{Feat
}.substr(1);
10872 if (Feat
[0] == '-') {
10873 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10874 << Feature
<< ("no-" + BareFeat
).str();
10878 if (!TargetInfo
.validateCpuSupports(BareFeat
) ||
10879 !TargetInfo
.isValidFeatureName(BareFeat
)) {
10880 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10881 << Feature
<< BareFeat
;
10888 llvm::SmallVector
<StringRef
, 8> Feats
;
10889 TVA
->getFeatures(Feats
);
10890 for (const auto &Feat
: Feats
) {
10891 if (!TargetInfo
.validateCpuSupports(Feat
)) {
10892 S
.Diag(FD
->getLocation(), diag::err_bad_multiversion_option
)
10893 << Feature
<< Feat
;
10901 // Provide a white-list of attributes that are allowed to be combined with
10902 // multiversion functions.
10903 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind
,
10904 MultiVersionKind MVKind
) {
10905 // Note: this list/diagnosis must match the list in
10906 // checkMultiversionAttributesAllSame.
10911 return MVKind
== MultiVersionKind::Target
;
10912 case attr::NonNull
:
10913 case attr::NoThrow
:
10918 static bool checkNonMultiVersionCompatAttributes(Sema
&S
,
10919 const FunctionDecl
*FD
,
10920 const FunctionDecl
*CausedFD
,
10921 MultiVersionKind MVKind
) {
10922 const auto Diagnose
= [FD
, CausedFD
, MVKind
](Sema
&S
, const Attr
*A
) {
10923 S
.Diag(FD
->getLocation(), diag::err_multiversion_disallowed_other_attr
)
10924 << static_cast<unsigned>(MVKind
) << A
;
10926 S
.Diag(CausedFD
->getLocation(), diag::note_multiversioning_caused_here
);
10930 for (const Attr
*A
: FD
->attrs()) {
10931 switch (A
->getKind()) {
10932 case attr::CPUDispatch
:
10933 case attr::CPUSpecific
:
10934 if (MVKind
!= MultiVersionKind::CPUDispatch
&&
10935 MVKind
!= MultiVersionKind::CPUSpecific
)
10936 return Diagnose(S
, A
);
10939 if (MVKind
!= MultiVersionKind::Target
)
10940 return Diagnose(S
, A
);
10942 case attr::TargetVersion
:
10943 if (MVKind
!= MultiVersionKind::TargetVersion
)
10944 return Diagnose(S
, A
);
10946 case attr::TargetClones
:
10947 if (MVKind
!= MultiVersionKind::TargetClones
)
10948 return Diagnose(S
, A
);
10951 if (!AttrCompatibleWithMultiVersion(A
->getKind(), MVKind
))
10952 return Diagnose(S
, A
);
10959 bool Sema::areMultiversionVariantFunctionsCompatible(
10960 const FunctionDecl
*OldFD
, const FunctionDecl
*NewFD
,
10961 const PartialDiagnostic
&NoProtoDiagID
,
10962 const PartialDiagnosticAt
&NoteCausedDiagIDAt
,
10963 const PartialDiagnosticAt
&NoSupportDiagIDAt
,
10964 const PartialDiagnosticAt
&DiffDiagIDAt
, bool TemplatesSupported
,
10965 bool ConstexprSupported
, bool CLinkageMayDiffer
) {
10966 enum DoesntSupport
{
10973 DefaultedFuncs
= 6,
10974 ConstexprFuncs
= 7,
10975 ConstevalFuncs
= 8,
10984 LanguageLinkage
= 5,
10987 if (NoProtoDiagID
.getDiagID() != 0 && OldFD
&&
10988 !OldFD
->getType()->getAs
<FunctionProtoType
>()) {
10989 Diag(OldFD
->getLocation(), NoProtoDiagID
);
10990 Diag(NoteCausedDiagIDAt
.first
, NoteCausedDiagIDAt
.second
);
10994 if (NoProtoDiagID
.getDiagID() != 0 &&
10995 !NewFD
->getType()->getAs
<FunctionProtoType
>())
10996 return Diag(NewFD
->getLocation(), NoProtoDiagID
);
10998 if (!TemplatesSupported
&&
10999 NewFD
->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate
)
11000 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11003 if (const auto *NewCXXFD
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
11004 if (NewCXXFD
->isVirtual())
11005 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11008 if (isa
<CXXConstructorDecl
>(NewCXXFD
))
11009 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11012 if (isa
<CXXDestructorDecl
>(NewCXXFD
))
11013 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11017 if (NewFD
->isDeleted())
11018 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11021 if (NewFD
->isDefaulted())
11022 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11025 if (!ConstexprSupported
&& NewFD
->isConstexpr())
11026 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11027 << (NewFD
->isConsteval() ? ConstevalFuncs
: ConstexprFuncs
);
11029 QualType NewQType
= Context
.getCanonicalType(NewFD
->getType());
11030 const auto *NewType
= cast
<FunctionType
>(NewQType
);
11031 QualType NewReturnType
= NewType
->getReturnType();
11033 if (NewReturnType
->isUndeducedType())
11034 return Diag(NoSupportDiagIDAt
.first
, NoSupportDiagIDAt
.second
)
11037 // Ensure the return type is identical.
11039 QualType OldQType
= Context
.getCanonicalType(OldFD
->getType());
11040 const auto *OldType
= cast
<FunctionType
>(OldQType
);
11041 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
11042 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
11044 if (OldTypeInfo
.getCC() != NewTypeInfo
.getCC())
11045 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << CallingConv
;
11047 QualType OldReturnType
= OldType
->getReturnType();
11049 if (OldReturnType
!= NewReturnType
)
11050 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << ReturnType
;
11052 if (OldFD
->getConstexprKind() != NewFD
->getConstexprKind())
11053 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << ConstexprSpec
;
11055 if (OldFD
->isInlineSpecified() != NewFD
->isInlineSpecified())
11056 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << InlineSpec
;
11058 if (OldFD
->getFormalLinkage() != NewFD
->getFormalLinkage())
11059 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << Linkage
;
11061 if (!CLinkageMayDiffer
&& OldFD
->isExternC() != NewFD
->isExternC())
11062 return Diag(DiffDiagIDAt
.first
, DiffDiagIDAt
.second
) << LanguageLinkage
;
11064 if (CheckEquivalentExceptionSpec(
11065 OldFD
->getType()->getAs
<FunctionProtoType
>(), OldFD
->getLocation(),
11066 NewFD
->getType()->getAs
<FunctionProtoType
>(), NewFD
->getLocation()))
11072 static bool CheckMultiVersionAdditionalRules(Sema
&S
, const FunctionDecl
*OldFD
,
11073 const FunctionDecl
*NewFD
,
11075 MultiVersionKind MVKind
) {
11076 if (!S
.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11077 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_not_supported
);
11079 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11083 bool IsCPUSpecificCPUDispatchMVKind
=
11084 MVKind
== MultiVersionKind::CPUDispatch
||
11085 MVKind
== MultiVersionKind::CPUSpecific
;
11087 if (CausesMV
&& OldFD
&&
11088 checkNonMultiVersionCompatAttributes(S
, OldFD
, NewFD
, MVKind
))
11091 if (checkNonMultiVersionCompatAttributes(S
, NewFD
, nullptr, MVKind
))
11094 // Only allow transition to MultiVersion if it hasn't been used.
11095 if (OldFD
&& CausesMV
&& OldFD
->isUsed(false))
11096 return S
.Diag(NewFD
->getLocation(), diag::err_multiversion_after_used
);
11098 return S
.areMultiversionVariantFunctionsCompatible(
11099 OldFD
, NewFD
, S
.PDiag(diag::err_multiversion_noproto
),
11100 PartialDiagnosticAt(NewFD
->getLocation(),
11101 S
.PDiag(diag::note_multiversioning_caused_here
)),
11102 PartialDiagnosticAt(NewFD
->getLocation(),
11103 S
.PDiag(diag::err_multiversion_doesnt_support
)
11104 << static_cast<unsigned>(MVKind
)),
11105 PartialDiagnosticAt(NewFD
->getLocation(),
11106 S
.PDiag(diag::err_multiversion_diff
)),
11107 /*TemplatesSupported=*/false,
11108 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind
,
11109 /*CLinkageMayDiffer=*/false);
11112 /// Check the validity of a multiversion function declaration that is the
11113 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11115 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11117 /// Returns true if there was an error, false otherwise.
11118 static bool CheckMultiVersionFirstFunction(Sema
&S
, FunctionDecl
*FD
) {
11119 MultiVersionKind MVKind
= FD
->getMultiVersionKind();
11120 assert(MVKind
!= MultiVersionKind::None
&&
11121 "Function lacks multiversion attribute");
11122 const auto *TA
= FD
->getAttr
<TargetAttr
>();
11123 const auto *TVA
= FD
->getAttr
<TargetVersionAttr
>();
11124 // Target and target_version only causes MV if it is default, otherwise this
11125 // is a normal function.
11126 if ((TA
&& !TA
->isDefaultVersion()) || (TVA
&& !TVA
->isDefaultVersion()))
11129 if ((TA
|| TVA
) && CheckMultiVersionValue(S
, FD
)) {
11130 FD
->setInvalidDecl();
11134 if (CheckMultiVersionAdditionalRules(S
, nullptr, FD
, true, MVKind
)) {
11135 FD
->setInvalidDecl();
11139 FD
->setIsMultiVersion();
11143 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl
*FD
) {
11144 for (const Decl
*D
= FD
->getPreviousDecl(); D
; D
= D
->getPreviousDecl()) {
11145 if (D
->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None
)
11152 static bool CheckTargetCausesMultiVersioning(Sema
&S
, FunctionDecl
*OldFD
,
11153 FunctionDecl
*NewFD
,
11154 bool &Redeclaration
,
11155 NamedDecl
*&OldDecl
,
11156 LookupResult
&Previous
) {
11157 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11158 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11159 const auto *OldTA
= OldFD
->getAttr
<TargetAttr
>();
11160 const auto *OldTVA
= OldFD
->getAttr
<TargetVersionAttr
>();
11161 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11162 // to change, this is a simple redeclaration.
11163 if ((NewTA
&& !NewTA
->isDefaultVersion() &&
11164 (!OldTA
|| OldTA
->getFeaturesStr() == NewTA
->getFeaturesStr())) ||
11165 (NewTVA
&& !NewTVA
->isDefaultVersion() &&
11166 (!OldTVA
|| OldTVA
->getName() == NewTVA
->getName())))
11169 // Otherwise, this decl causes MultiVersioning.
11170 if (CheckMultiVersionAdditionalRules(S
, OldFD
, NewFD
, true,
11171 NewTVA
? MultiVersionKind::TargetVersion
11172 : MultiVersionKind::Target
)) {
11173 NewFD
->setInvalidDecl();
11177 if (CheckMultiVersionValue(S
, NewFD
)) {
11178 NewFD
->setInvalidDecl();
11182 // If this is 'default', permit the forward declaration.
11183 if (!OldFD
->isMultiVersion() &&
11184 ((NewTA
&& NewTA
->isDefaultVersion() && !OldTA
) ||
11185 (NewTVA
&& NewTVA
->isDefaultVersion() && !OldTVA
))) {
11186 Redeclaration
= true;
11188 OldFD
->setIsMultiVersion();
11189 NewFD
->setIsMultiVersion();
11193 if (CheckMultiVersionValue(S
, OldFD
)) {
11194 S
.Diag(NewFD
->getLocation(), diag::note_multiversioning_caused_here
);
11195 NewFD
->setInvalidDecl();
11200 ParsedTargetAttr OldParsed
=
11201 S
.getASTContext().getTargetInfo().parseTargetAttr(
11202 OldTA
->getFeaturesStr());
11203 llvm::sort(OldParsed
.Features
);
11204 ParsedTargetAttr NewParsed
=
11205 S
.getASTContext().getTargetInfo().parseTargetAttr(
11206 NewTA
->getFeaturesStr());
11207 // Sort order doesn't matter, it just needs to be consistent.
11208 llvm::sort(NewParsed
.Features
);
11209 if (OldParsed
== NewParsed
) {
11210 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11211 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11212 NewFD
->setInvalidDecl();
11218 llvm::SmallVector
<StringRef
, 8> Feats
;
11219 OldTVA
->getFeatures(Feats
);
11221 llvm::SmallVector
<StringRef
, 8> NewFeats
;
11222 NewTVA
->getFeatures(NewFeats
);
11223 llvm::sort(NewFeats
);
11225 if (Feats
== NewFeats
) {
11226 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11227 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11228 NewFD
->setInvalidDecl();
11233 for (const auto *FD
: OldFD
->redecls()) {
11234 const auto *CurTA
= FD
->getAttr
<TargetAttr
>();
11235 const auto *CurTVA
= FD
->getAttr
<TargetVersionAttr
>();
11236 // We allow forward declarations before ANY multiversioning attributes, but
11237 // nothing after the fact.
11238 if (PreviousDeclsHaveMultiVersionAttribute(FD
) &&
11239 ((NewTA
&& (!CurTA
|| CurTA
->isInherited())) ||
11240 (NewTVA
&& (!CurTVA
|| CurTVA
->isInherited())))) {
11241 S
.Diag(FD
->getLocation(), diag::err_multiversion_required_in_redecl
)
11242 << (NewTA
? 0 : 2);
11243 S
.Diag(NewFD
->getLocation(), diag::note_multiversioning_caused_here
);
11244 NewFD
->setInvalidDecl();
11249 OldFD
->setIsMultiVersion();
11250 NewFD
->setIsMultiVersion();
11251 Redeclaration
= false;
11257 static bool MultiVersionTypesCompatible(MultiVersionKind Old
,
11258 MultiVersionKind New
) {
11259 if (Old
== New
|| Old
== MultiVersionKind::None
||
11260 New
== MultiVersionKind::None
)
11263 return (Old
== MultiVersionKind::CPUDispatch
&&
11264 New
== MultiVersionKind::CPUSpecific
) ||
11265 (Old
== MultiVersionKind::CPUSpecific
&&
11266 New
== MultiVersionKind::CPUDispatch
);
11269 /// Check the validity of a new function declaration being added to an existing
11270 /// multiversioned declaration collection.
11271 static bool CheckMultiVersionAdditionalDecl(
11272 Sema
&S
, FunctionDecl
*OldFD
, FunctionDecl
*NewFD
,
11273 MultiVersionKind NewMVKind
, const CPUDispatchAttr
*NewCPUDisp
,
11274 const CPUSpecificAttr
*NewCPUSpec
, const TargetClonesAttr
*NewClones
,
11275 bool &Redeclaration
, NamedDecl
*&OldDecl
, LookupResult
&Previous
) {
11276 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11277 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11278 MultiVersionKind OldMVKind
= OldFD
->getMultiVersionKind();
11279 // Disallow mixing of multiversioning types.
11280 if (!MultiVersionTypesCompatible(OldMVKind
, NewMVKind
)) {
11281 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_types_mixed
);
11282 S
.Diag(OldFD
->getLocation(), diag::note_previous_declaration
);
11283 NewFD
->setInvalidDecl();
11287 ParsedTargetAttr NewParsed
;
11289 NewParsed
= S
.getASTContext().getTargetInfo().parseTargetAttr(
11290 NewTA
->getFeaturesStr());
11291 llvm::sort(NewParsed
.Features
);
11293 llvm::SmallVector
<StringRef
, 8> NewFeats
;
11295 NewTVA
->getFeatures(NewFeats
);
11296 llvm::sort(NewFeats
);
11299 bool UseMemberUsingDeclRules
=
11300 S
.CurContext
->isRecord() && !NewFD
->getFriendObjectKind();
11302 bool MayNeedOverloadableChecks
=
11303 AllowOverloadingOfFunction(Previous
, S
.Context
, NewFD
);
11305 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11306 // of a previous member of the MultiVersion set.
11307 for (NamedDecl
*ND
: Previous
) {
11308 FunctionDecl
*CurFD
= ND
->getAsFunction();
11309 if (!CurFD
|| CurFD
->isInvalidDecl())
11311 if (MayNeedOverloadableChecks
&&
11312 S
.IsOverload(NewFD
, CurFD
, UseMemberUsingDeclRules
))
11315 if (NewMVKind
== MultiVersionKind::None
&&
11316 OldMVKind
== MultiVersionKind::TargetVersion
) {
11317 NewFD
->addAttr(TargetVersionAttr::CreateImplicit(
11318 S
.Context
, "default", NewFD
->getSourceRange(),
11319 AttributeCommonInfo::AS_GNU
));
11320 NewFD
->setIsMultiVersion();
11321 NewMVKind
= MultiVersionKind::TargetVersion
;
11323 NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11324 NewTVA
->getFeatures(NewFeats
);
11325 llvm::sort(NewFeats
);
11329 switch (NewMVKind
) {
11330 case MultiVersionKind::None
:
11331 assert(OldMVKind
== MultiVersionKind::TargetClones
&&
11332 "Only target_clones can be omitted in subsequent declarations");
11334 case MultiVersionKind::Target
: {
11335 const auto *CurTA
= CurFD
->getAttr
<TargetAttr
>();
11336 if (CurTA
->getFeaturesStr() == NewTA
->getFeaturesStr()) {
11337 NewFD
->setIsMultiVersion();
11338 Redeclaration
= true;
11343 ParsedTargetAttr CurParsed
=
11344 S
.getASTContext().getTargetInfo().parseTargetAttr(
11345 CurTA
->getFeaturesStr());
11346 llvm::sort(CurParsed
.Features
);
11347 if (CurParsed
== NewParsed
) {
11348 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11349 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11350 NewFD
->setInvalidDecl();
11355 case MultiVersionKind::TargetVersion
: {
11356 const auto *CurTVA
= CurFD
->getAttr
<TargetVersionAttr
>();
11357 if (CurTVA
->getName() == NewTVA
->getName()) {
11358 NewFD
->setIsMultiVersion();
11359 Redeclaration
= true;
11363 llvm::SmallVector
<StringRef
, 8> CurFeats
;
11365 CurTVA
->getFeatures(CurFeats
);
11366 llvm::sort(CurFeats
);
11368 if (CurFeats
== NewFeats
) {
11369 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_duplicate
);
11370 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11371 NewFD
->setInvalidDecl();
11376 case MultiVersionKind::TargetClones
: {
11377 const auto *CurClones
= CurFD
->getAttr
<TargetClonesAttr
>();
11378 Redeclaration
= true;
11380 NewFD
->setIsMultiVersion();
11382 if (CurClones
&& NewClones
&&
11383 (CurClones
->featuresStrs_size() != NewClones
->featuresStrs_size() ||
11384 !std::equal(CurClones
->featuresStrs_begin(),
11385 CurClones
->featuresStrs_end(),
11386 NewClones
->featuresStrs_begin()))) {
11387 S
.Diag(NewFD
->getLocation(), diag::err_target_clone_doesnt_match
);
11388 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11389 NewFD
->setInvalidDecl();
11395 case MultiVersionKind::CPUSpecific
:
11396 case MultiVersionKind::CPUDispatch
: {
11397 const auto *CurCPUSpec
= CurFD
->getAttr
<CPUSpecificAttr
>();
11398 const auto *CurCPUDisp
= CurFD
->getAttr
<CPUDispatchAttr
>();
11399 // Handle CPUDispatch/CPUSpecific versions.
11400 // Only 1 CPUDispatch function is allowed, this will make it go through
11401 // the redeclaration errors.
11402 if (NewMVKind
== MultiVersionKind::CPUDispatch
&&
11403 CurFD
->hasAttr
<CPUDispatchAttr
>()) {
11404 if (CurCPUDisp
->cpus_size() == NewCPUDisp
->cpus_size() &&
11406 CurCPUDisp
->cpus_begin(), CurCPUDisp
->cpus_end(),
11407 NewCPUDisp
->cpus_begin(),
11408 [](const IdentifierInfo
*Cur
, const IdentifierInfo
*New
) {
11409 return Cur
->getName() == New
->getName();
11411 NewFD
->setIsMultiVersion();
11412 Redeclaration
= true;
11417 // If the declarations don't match, this is an error condition.
11418 S
.Diag(NewFD
->getLocation(), diag::err_cpu_dispatch_mismatch
);
11419 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11420 NewFD
->setInvalidDecl();
11423 if (NewMVKind
== MultiVersionKind::CPUSpecific
&& CurCPUSpec
) {
11424 if (CurCPUSpec
->cpus_size() == NewCPUSpec
->cpus_size() &&
11426 CurCPUSpec
->cpus_begin(), CurCPUSpec
->cpus_end(),
11427 NewCPUSpec
->cpus_begin(),
11428 [](const IdentifierInfo
*Cur
, const IdentifierInfo
*New
) {
11429 return Cur
->getName() == New
->getName();
11431 NewFD
->setIsMultiVersion();
11432 Redeclaration
= true;
11437 // Only 1 version of CPUSpecific is allowed for each CPU.
11438 for (const IdentifierInfo
*CurII
: CurCPUSpec
->cpus()) {
11439 for (const IdentifierInfo
*NewII
: NewCPUSpec
->cpus()) {
11440 if (CurII
== NewII
) {
11441 S
.Diag(NewFD
->getLocation(), diag::err_cpu_specific_multiple_defs
)
11443 S
.Diag(CurFD
->getLocation(), diag::note_previous_declaration
);
11444 NewFD
->setInvalidDecl();
11455 // Else, this is simply a non-redecl case. Checking the 'value' is only
11456 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11457 // handled in the attribute adding step.
11458 if ((NewMVKind
== MultiVersionKind::TargetVersion
||
11459 NewMVKind
== MultiVersionKind::Target
) &&
11460 CheckMultiVersionValue(S
, NewFD
)) {
11461 NewFD
->setInvalidDecl();
11465 if (CheckMultiVersionAdditionalRules(S
, OldFD
, NewFD
,
11466 !OldFD
->isMultiVersion(), NewMVKind
)) {
11467 NewFD
->setInvalidDecl();
11471 // Permit forward declarations in the case where these two are compatible.
11472 if (!OldFD
->isMultiVersion()) {
11473 OldFD
->setIsMultiVersion();
11474 NewFD
->setIsMultiVersion();
11475 Redeclaration
= true;
11480 NewFD
->setIsMultiVersion();
11481 Redeclaration
= false;
11487 /// Check the validity of a mulitversion function declaration.
11488 /// Also sets the multiversion'ness' of the function itself.
11490 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11492 /// Returns true if there was an error, false otherwise.
11493 static bool CheckMultiVersionFunction(Sema
&S
, FunctionDecl
*NewFD
,
11494 bool &Redeclaration
, NamedDecl
*&OldDecl
,
11495 LookupResult
&Previous
) {
11496 const auto *NewTA
= NewFD
->getAttr
<TargetAttr
>();
11497 const auto *NewTVA
= NewFD
->getAttr
<TargetVersionAttr
>();
11498 const auto *NewCPUDisp
= NewFD
->getAttr
<CPUDispatchAttr
>();
11499 const auto *NewCPUSpec
= NewFD
->getAttr
<CPUSpecificAttr
>();
11500 const auto *NewClones
= NewFD
->getAttr
<TargetClonesAttr
>();
11501 MultiVersionKind MVKind
= NewFD
->getMultiVersionKind();
11503 // Main isn't allowed to become a multiversion function, however it IS
11504 // permitted to have 'main' be marked with the 'target' optimization hint,
11505 // for 'target_version' only default is allowed.
11506 if (NewFD
->isMain()) {
11507 if (MVKind
!= MultiVersionKind::None
&&
11508 !(MVKind
== MultiVersionKind::Target
&& !NewTA
->isDefaultVersion()) &&
11509 !(MVKind
== MultiVersionKind::TargetVersion
&&
11510 NewTVA
->isDefaultVersion())) {
11511 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_not_allowed_on_main
);
11512 NewFD
->setInvalidDecl();
11518 if (!OldDecl
|| !OldDecl
->getAsFunction() ||
11519 OldDecl
->getDeclContext()->getRedeclContext() !=
11520 NewFD
->getDeclContext()->getRedeclContext()) {
11521 // If there's no previous declaration, AND this isn't attempting to cause
11522 // multiversioning, this isn't an error condition.
11523 if (MVKind
== MultiVersionKind::None
)
11525 return CheckMultiVersionFirstFunction(S
, NewFD
);
11528 FunctionDecl
*OldFD
= OldDecl
->getAsFunction();
11530 if (!OldFD
->isMultiVersion() && MVKind
== MultiVersionKind::None
) {
11531 // No target_version attributes mean default
11533 const auto *OldTVA
= OldFD
->getAttr
<TargetVersionAttr
>();
11535 NewFD
->addAttr(TargetVersionAttr::CreateImplicit(
11536 S
.Context
, "default", NewFD
->getSourceRange(),
11537 AttributeCommonInfo::AS_GNU
));
11538 NewFD
->setIsMultiVersion();
11539 OldFD
->setIsMultiVersion();
11541 Redeclaration
= true;
11548 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11549 // for target_clones and target_version.
11550 if (OldFD
->isMultiVersion() && MVKind
== MultiVersionKind::None
&&
11551 OldFD
->getMultiVersionKind() != MultiVersionKind::TargetClones
&&
11552 OldFD
->getMultiVersionKind() != MultiVersionKind::TargetVersion
) {
11553 S
.Diag(NewFD
->getLocation(), diag::err_multiversion_required_in_redecl
)
11554 << (OldFD
->getMultiVersionKind() != MultiVersionKind::Target
);
11555 NewFD
->setInvalidDecl();
11559 if (!OldFD
->isMultiVersion()) {
11561 case MultiVersionKind::Target
:
11562 case MultiVersionKind::TargetVersion
:
11563 return CheckTargetCausesMultiVersioning(S
, OldFD
, NewFD
, Redeclaration
,
11564 OldDecl
, Previous
);
11565 case MultiVersionKind::TargetClones
:
11566 if (OldFD
->isUsed(false)) {
11567 NewFD
->setInvalidDecl();
11568 return S
.Diag(NewFD
->getLocation(), diag::err_multiversion_after_used
);
11570 OldFD
->setIsMultiVersion();
11573 case MultiVersionKind::CPUDispatch
:
11574 case MultiVersionKind::CPUSpecific
:
11575 case MultiVersionKind::None
:
11580 // At this point, we have a multiversion function decl (in OldFD) AND an
11581 // appropriate attribute in the current function decl. Resolve that these are
11582 // still compatible with previous declarations.
11583 return CheckMultiVersionAdditionalDecl(S
, OldFD
, NewFD
, MVKind
, NewCPUDisp
,
11584 NewCPUSpec
, NewClones
, Redeclaration
,
11585 OldDecl
, Previous
);
11588 /// Perform semantic checking of a new function declaration.
11590 /// Performs semantic analysis of the new function declaration
11591 /// NewFD. This routine performs all semantic checking that does not
11592 /// require the actual declarator involved in the declaration, and is
11593 /// used both for the declaration of functions as they are parsed
11594 /// (called via ActOnDeclarator) and for the declaration of functions
11595 /// that have been instantiated via C++ template instantiation (called
11596 /// via InstantiateDecl).
11598 /// \param IsMemberSpecialization whether this new function declaration is
11599 /// a member specialization (that replaces any definition provided by the
11600 /// previous declaration).
11602 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11604 /// \returns true if the function declaration is a redeclaration.
11605 bool Sema::CheckFunctionDeclaration(Scope
*S
, FunctionDecl
*NewFD
,
11606 LookupResult
&Previous
,
11607 bool IsMemberSpecialization
,
11609 assert(!NewFD
->getReturnType()->isVariablyModifiedType() &&
11610 "Variably modified return types are not handled here");
11612 // Determine whether the type of this function should be merged with
11613 // a previous visible declaration. This never happens for functions in C++,
11614 // and always happens in C if the previous declaration was visible.
11615 bool MergeTypeWithPrevious
= !getLangOpts().CPlusPlus
&&
11616 !Previous
.isShadowed();
11618 bool Redeclaration
= false;
11619 NamedDecl
*OldDecl
= nullptr;
11620 bool MayNeedOverloadableChecks
= false;
11622 // Merge or overload the declaration with an existing declaration of
11623 // the same name, if appropriate.
11624 if (!Previous
.empty()) {
11625 // Determine whether NewFD is an overload of PrevDecl or
11626 // a declaration that requires merging. If it's an overload,
11627 // there's no more work to do here; we'll just add the new
11628 // function to the scope.
11629 if (!AllowOverloadingOfFunction(Previous
, Context
, NewFD
)) {
11630 NamedDecl
*Candidate
= Previous
.getRepresentativeDecl();
11631 if (shouldLinkPossiblyHiddenDecl(Candidate
, NewFD
)) {
11632 Redeclaration
= true;
11633 OldDecl
= Candidate
;
11636 MayNeedOverloadableChecks
= true;
11637 switch (CheckOverload(S
, NewFD
, Previous
, OldDecl
,
11638 /*NewIsUsingDecl*/ false)) {
11640 Redeclaration
= true;
11643 case Ovl_NonFunction
:
11644 Redeclaration
= true;
11648 Redeclaration
= false;
11654 // Check for a previous extern "C" declaration with this name.
11655 if (!Redeclaration
&&
11656 checkForConflictWithNonVisibleExternC(*this, NewFD
, Previous
)) {
11657 if (!Previous
.empty()) {
11658 // This is an extern "C" declaration with the same name as a previous
11659 // declaration, and thus redeclares that entity...
11660 Redeclaration
= true;
11661 OldDecl
= Previous
.getFoundDecl();
11662 MergeTypeWithPrevious
= false;
11664 // ... except in the presence of __attribute__((overloadable)).
11665 if (OldDecl
->hasAttr
<OverloadableAttr
>() ||
11666 NewFD
->hasAttr
<OverloadableAttr
>()) {
11667 if (IsOverload(NewFD
, cast
<FunctionDecl
>(OldDecl
), false)) {
11668 MayNeedOverloadableChecks
= true;
11669 Redeclaration
= false;
11676 if (CheckMultiVersionFunction(*this, NewFD
, Redeclaration
, OldDecl
, Previous
))
11677 return Redeclaration
;
11679 // PPC MMA non-pointer types are not allowed as function return types.
11680 if (Context
.getTargetInfo().getTriple().isPPC64() &&
11681 CheckPPCMMAType(NewFD
->getReturnType(), NewFD
->getLocation())) {
11682 NewFD
->setInvalidDecl();
11685 // C++11 [dcl.constexpr]p8:
11686 // A constexpr specifier for a non-static member function that is not
11687 // a constructor declares that member function to be const.
11689 // This needs to be delayed until we know whether this is an out-of-line
11690 // definition of a static member function.
11692 // This rule is not present in C++1y, so we produce a backwards
11693 // compatibility warning whenever it happens in C++11.
11694 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewFD
);
11695 if (!getLangOpts().CPlusPlus14
&& MD
&& MD
->isConstexpr() &&
11696 !MD
->isStatic() && !isa
<CXXConstructorDecl
>(MD
) &&
11697 !isa
<CXXDestructorDecl
>(MD
) && !MD
->getMethodQualifiers().hasConst()) {
11698 CXXMethodDecl
*OldMD
= nullptr;
11700 OldMD
= dyn_cast_or_null
<CXXMethodDecl
>(OldDecl
->getAsFunction());
11701 if (!OldMD
|| !OldMD
->isStatic()) {
11702 const FunctionProtoType
*FPT
=
11703 MD
->getType()->castAs
<FunctionProtoType
>();
11704 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
11705 EPI
.TypeQuals
.addConst();
11706 MD
->setType(Context
.getFunctionType(FPT
->getReturnType(),
11707 FPT
->getParamTypes(), EPI
));
11709 // Warn that we did this, if we're not performing template instantiation.
11710 // In that case, we'll have warned already when the template was defined.
11711 if (!inTemplateInstantiation()) {
11712 SourceLocation AddConstLoc
;
11713 if (FunctionTypeLoc FTL
= MD
->getTypeSourceInfo()->getTypeLoc()
11714 .IgnoreParens().getAs
<FunctionTypeLoc
>())
11715 AddConstLoc
= getLocForEndOfToken(FTL
.getRParenLoc());
11717 Diag(MD
->getLocation(), diag::warn_cxx14_compat_constexpr_not_const
)
11718 << FixItHint::CreateInsertion(AddConstLoc
, " const");
11723 if (Redeclaration
) {
11724 // NewFD and OldDecl represent declarations that need to be
11726 if (MergeFunctionDecl(NewFD
, OldDecl
, S
, MergeTypeWithPrevious
,
11728 NewFD
->setInvalidDecl();
11729 return Redeclaration
;
11733 Previous
.addDecl(OldDecl
);
11735 if (FunctionTemplateDecl
*OldTemplateDecl
=
11736 dyn_cast
<FunctionTemplateDecl
>(OldDecl
)) {
11737 auto *OldFD
= OldTemplateDecl
->getTemplatedDecl();
11738 FunctionTemplateDecl
*NewTemplateDecl
11739 = NewFD
->getDescribedFunctionTemplate();
11740 assert(NewTemplateDecl
&& "Template/non-template mismatch");
11742 // The call to MergeFunctionDecl above may have created some state in
11743 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11744 // can add it as a redeclaration.
11745 NewTemplateDecl
->mergePrevDecl(OldTemplateDecl
);
11747 NewFD
->setPreviousDeclaration(OldFD
);
11748 if (NewFD
->isCXXClassMember()) {
11749 NewFD
->setAccess(OldTemplateDecl
->getAccess());
11750 NewTemplateDecl
->setAccess(OldTemplateDecl
->getAccess());
11753 // If this is an explicit specialization of a member that is a function
11754 // template, mark it as a member specialization.
11755 if (IsMemberSpecialization
&&
11756 NewTemplateDecl
->getInstantiatedFromMemberTemplate()) {
11757 NewTemplateDecl
->setMemberSpecialization();
11758 assert(OldTemplateDecl
->isMemberSpecialization());
11759 // Explicit specializations of a member template do not inherit deleted
11760 // status from the parent member template that they are specializing.
11761 if (OldFD
->isDeleted()) {
11762 // FIXME: This assert will not hold in the presence of modules.
11763 assert(OldFD
->getCanonicalDecl() == OldFD
);
11764 // FIXME: We need an update record for this AST mutation.
11765 OldFD
->setDeletedAsWritten(false);
11770 if (shouldLinkDependentDeclWithPrevious(NewFD
, OldDecl
)) {
11771 auto *OldFD
= cast
<FunctionDecl
>(OldDecl
);
11772 // This needs to happen first so that 'inline' propagates.
11773 NewFD
->setPreviousDeclaration(OldFD
);
11774 if (NewFD
->isCXXClassMember())
11775 NewFD
->setAccess(OldFD
->getAccess());
11778 } else if (!getLangOpts().CPlusPlus
&& MayNeedOverloadableChecks
&&
11779 !NewFD
->getAttr
<OverloadableAttr
>()) {
11780 assert((Previous
.empty() ||
11781 llvm::any_of(Previous
,
11782 [](const NamedDecl
*ND
) {
11783 return ND
->hasAttr
<OverloadableAttr
>();
11785 "Non-redecls shouldn't happen without overloadable present");
11787 auto OtherUnmarkedIter
= llvm::find_if(Previous
, [](const NamedDecl
*ND
) {
11788 const auto *FD
= dyn_cast
<FunctionDecl
>(ND
);
11789 return FD
&& !FD
->hasAttr
<OverloadableAttr
>();
11792 if (OtherUnmarkedIter
!= Previous
.end()) {
11793 Diag(NewFD
->getLocation(),
11794 diag::err_attribute_overloadable_multiple_unmarked_overloads
);
11795 Diag((*OtherUnmarkedIter
)->getLocation(),
11796 diag::note_attribute_overloadable_prev_overload
)
11799 NewFD
->addAttr(OverloadableAttr::CreateImplicit(Context
));
11803 if (LangOpts
.OpenMP
)
11804 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD
);
11806 // Semantic checking for this function declaration (in isolation).
11808 if (getLangOpts().CPlusPlus
) {
11809 // C++-specific checks.
11810 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(NewFD
)) {
11811 CheckConstructor(Constructor
);
11812 } else if (CXXDestructorDecl
*Destructor
=
11813 dyn_cast
<CXXDestructorDecl
>(NewFD
)) {
11814 // We check here for invalid destructor names.
11815 // If we have a friend destructor declaration that is dependent, we can't
11816 // diagnose right away because cases like this are still valid:
11817 // template <class T> struct A { friend T::X::~Y(); };
11818 // struct B { struct Y { ~Y(); }; using X = Y; };
11819 // template struct A<B>;
11820 if (NewFD
->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None
||
11821 !Destructor
->getThisType()->isDependentType()) {
11822 CXXRecordDecl
*Record
= Destructor
->getParent();
11823 QualType ClassType
= Context
.getTypeDeclType(Record
);
11825 DeclarationName Name
= Context
.DeclarationNames
.getCXXDestructorName(
11826 Context
.getCanonicalType(ClassType
));
11827 if (NewFD
->getDeclName() != Name
) {
11828 Diag(NewFD
->getLocation(), diag::err_destructor_name
);
11829 NewFD
->setInvalidDecl();
11830 return Redeclaration
;
11833 } else if (auto *Guide
= dyn_cast
<CXXDeductionGuideDecl
>(NewFD
)) {
11834 if (auto *TD
= Guide
->getDescribedFunctionTemplate())
11835 CheckDeductionGuideTemplate(TD
);
11837 // A deduction guide is not on the list of entities that can be
11838 // explicitly specialized.
11839 if (Guide
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
11840 Diag(Guide
->getBeginLoc(), diag::err_deduction_guide_specialized
)
11841 << /*explicit specialization*/ 1;
11844 // Find any virtual functions that this function overrides.
11845 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
11846 if (!Method
->isFunctionTemplateSpecialization() &&
11847 !Method
->getDescribedFunctionTemplate() &&
11848 Method
->isCanonicalDecl()) {
11849 AddOverriddenMethods(Method
->getParent(), Method
);
11851 if (Method
->isVirtual() && NewFD
->getTrailingRequiresClause())
11852 // C++2a [class.virtual]p6
11853 // A virtual method shall not have a requires-clause.
11854 Diag(NewFD
->getTrailingRequiresClause()->getBeginLoc(),
11855 diag::err_constrained_virtual_method
);
11857 if (Method
->isStatic())
11858 checkThisInStaticMemberFunctionType(Method
);
11861 // C++20: dcl.decl.general p4:
11862 // The optional requires-clause ([temp.pre]) in an init-declarator or
11863 // member-declarator shall be present only if the declarator declares a
11864 // templated function ([dcl.fct]).
11865 if (Expr
*TRC
= NewFD
->getTrailingRequiresClause()) {
11866 if (!NewFD
->isTemplated() && !NewFD
->isTemplateInstantiation())
11867 Diag(TRC
->getBeginLoc(), diag::err_constrained_non_templated_function
);
11870 if (CXXConversionDecl
*Conversion
= dyn_cast
<CXXConversionDecl
>(NewFD
))
11871 ActOnConversionDeclarator(Conversion
);
11873 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11874 if (NewFD
->isOverloadedOperator() &&
11875 CheckOverloadedOperatorDeclaration(NewFD
)) {
11876 NewFD
->setInvalidDecl();
11877 return Redeclaration
;
11880 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11881 if (NewFD
->getLiteralIdentifier() &&
11882 CheckLiteralOperatorDeclaration(NewFD
)) {
11883 NewFD
->setInvalidDecl();
11884 return Redeclaration
;
11887 // In C++, check default arguments now that we have merged decls. Unless
11888 // the lexical context is the class, because in this case this is done
11889 // during delayed parsing anyway.
11890 if (!CurContext
->isRecord())
11891 CheckCXXDefaultArguments(NewFD
);
11893 // If this function is declared as being extern "C", then check to see if
11894 // the function returns a UDT (class, struct, or union type) that is not C
11895 // compatible, and if it does, warn the user.
11896 // But, issue any diagnostic on the first declaration only.
11897 if (Previous
.empty() && NewFD
->isExternC()) {
11898 QualType R
= NewFD
->getReturnType();
11899 if (R
->isIncompleteType() && !R
->isVoidType())
11900 Diag(NewFD
->getLocation(), diag::warn_return_value_udt_incomplete
)
11902 else if (!R
.isPODType(Context
) && !R
->isVoidType() &&
11903 !R
->isObjCObjectPointerType())
11904 Diag(NewFD
->getLocation(), diag::warn_return_value_udt
) << NewFD
<< R
;
11907 // C++1z [dcl.fct]p6:
11908 // [...] whether the function has a non-throwing exception-specification
11909 // [is] part of the function type
11911 // This results in an ABI break between C++14 and C++17 for functions whose
11912 // declared type includes an exception-specification in a parameter or
11913 // return type. (Exception specifications on the function itself are OK in
11914 // most cases, and exception specifications are not permitted in most other
11915 // contexts where they could make it into a mangling.)
11916 if (!getLangOpts().CPlusPlus17
&& !NewFD
->getPrimaryTemplate()) {
11917 auto HasNoexcept
= [&](QualType T
) -> bool {
11918 // Strip off declarator chunks that could be between us and a function
11919 // type. We don't need to look far, exception specifications are very
11920 // restricted prior to C++17.
11921 if (auto *RT
= T
->getAs
<ReferenceType
>())
11922 T
= RT
->getPointeeType();
11923 else if (T
->isAnyPointerType())
11924 T
= T
->getPointeeType();
11925 else if (auto *MPT
= T
->getAs
<MemberPointerType
>())
11926 T
= MPT
->getPointeeType();
11927 if (auto *FPT
= T
->getAs
<FunctionProtoType
>())
11928 if (FPT
->isNothrow())
11933 auto *FPT
= NewFD
->getType()->castAs
<FunctionProtoType
>();
11934 bool AnyNoexcept
= HasNoexcept(FPT
->getReturnType());
11935 for (QualType T
: FPT
->param_types())
11936 AnyNoexcept
|= HasNoexcept(T
);
11938 Diag(NewFD
->getLocation(),
11939 diag::warn_cxx17_compat_exception_spec_in_signature
)
11943 if (!Redeclaration
&& LangOpts
.CUDA
)
11944 checkCUDATargetOverload(NewFD
, Previous
);
11946 return Redeclaration
;
11949 void Sema::CheckMain(FunctionDecl
* FD
, const DeclSpec
& DS
) {
11950 // C++11 [basic.start.main]p3:
11951 // A program that [...] declares main to be inline, static or
11952 // constexpr is ill-formed.
11953 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11954 // appear in a declaration of main.
11955 // static main is not an error under C99, but we should warn about it.
11956 // We accept _Noreturn main as an extension.
11957 if (FD
->getStorageClass() == SC_Static
)
11958 Diag(DS
.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11959 ? diag::err_static_main
: diag::warn_static_main
)
11960 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
11961 if (FD
->isInlineSpecified())
11962 Diag(DS
.getInlineSpecLoc(), diag::err_inline_main
)
11963 << FixItHint::CreateRemoval(DS
.getInlineSpecLoc());
11964 if (DS
.isNoreturnSpecified()) {
11965 SourceLocation NoreturnLoc
= DS
.getNoreturnSpecLoc();
11966 SourceRange
NoreturnRange(NoreturnLoc
, getLocForEndOfToken(NoreturnLoc
));
11967 Diag(NoreturnLoc
, diag::ext_noreturn_main
);
11968 Diag(NoreturnLoc
, diag::note_main_remove_noreturn
)
11969 << FixItHint::CreateRemoval(NoreturnRange
);
11971 if (FD
->isConstexpr()) {
11972 Diag(DS
.getConstexprSpecLoc(), diag::err_constexpr_main
)
11973 << FD
->isConsteval()
11974 << FixItHint::CreateRemoval(DS
.getConstexprSpecLoc());
11975 FD
->setConstexprKind(ConstexprSpecKind::Unspecified
);
11978 if (getLangOpts().OpenCL
) {
11979 Diag(FD
->getLocation(), diag::err_opencl_no_main
)
11980 << FD
->hasAttr
<OpenCLKernelAttr
>();
11981 FD
->setInvalidDecl();
11985 // Functions named main in hlsl are default entries, but don't have specific
11986 // signatures they are required to conform to.
11987 if (getLangOpts().HLSL
)
11990 QualType T
= FD
->getType();
11991 assert(T
->isFunctionType() && "function decl is not of function type");
11992 const FunctionType
* FT
= T
->castAs
<FunctionType
>();
11994 // Set default calling convention for main()
11995 if (FT
->getCallConv() != CC_C
) {
11996 FT
= Context
.adjustFunctionType(FT
, FT
->getExtInfo().withCallingConv(CC_C
));
11997 FD
->setType(QualType(FT
, 0));
11998 T
= Context
.getCanonicalType(FD
->getType());
12001 if (getLangOpts().GNUMode
&& !getLangOpts().CPlusPlus
) {
12002 // In C with GNU extensions we allow main() to have non-integer return
12003 // type, but we should warn about the extension, and we disable the
12004 // implicit-return-zero rule.
12006 // GCC in C mode accepts qualified 'int'.
12007 if (Context
.hasSameUnqualifiedType(FT
->getReturnType(), Context
.IntTy
))
12008 FD
->setHasImplicitReturnZero(true);
12010 Diag(FD
->getTypeSpecStartLoc(), diag::ext_main_returns_nonint
);
12011 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
12012 if (RTRange
.isValid())
12013 Diag(RTRange
.getBegin(), diag::note_main_change_return_type
)
12014 << FixItHint::CreateReplacement(RTRange
, "int");
12017 // In C and C++, main magically returns 0 if you fall off the end;
12018 // set the flag which tells us that.
12019 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12021 // All the standards say that main() should return 'int'.
12022 if (Context
.hasSameType(FT
->getReturnType(), Context
.IntTy
))
12023 FD
->setHasImplicitReturnZero(true);
12025 // Otherwise, this is just a flat-out error.
12026 SourceRange RTRange
= FD
->getReturnTypeSourceRange();
12027 Diag(FD
->getTypeSpecStartLoc(), diag::err_main_returns_nonint
)
12028 << (RTRange
.isValid() ? FixItHint::CreateReplacement(RTRange
, "int")
12030 FD
->setInvalidDecl(true);
12034 // Treat protoless main() as nullary.
12035 if (isa
<FunctionNoProtoType
>(FT
)) return;
12037 const FunctionProtoType
* FTP
= cast
<const FunctionProtoType
>(FT
);
12038 unsigned nparams
= FTP
->getNumParams();
12039 assert(FD
->getNumParams() == nparams
);
12041 bool HasExtraParameters
= (nparams
> 3);
12043 if (FTP
->isVariadic()) {
12044 Diag(FD
->getLocation(), diag::ext_variadic_main
);
12045 // FIXME: if we had information about the location of the ellipsis, we
12046 // could add a FixIt hint to remove it as a parameter.
12049 // Darwin passes an undocumented fourth argument of type char**. If
12050 // other platforms start sprouting these, the logic below will start
12052 if (nparams
== 4 && Context
.getTargetInfo().getTriple().isOSDarwin())
12053 HasExtraParameters
= false;
12055 if (HasExtraParameters
) {
12056 Diag(FD
->getLocation(), diag::err_main_surplus_args
) << nparams
;
12057 FD
->setInvalidDecl(true);
12061 // FIXME: a lot of the following diagnostics would be improved
12062 // if we had some location information about types.
12065 Context
.getPointerType(Context
.getPointerType(Context
.CharTy
));
12066 QualType Expected
[] = { Context
.IntTy
, CharPP
, CharPP
, CharPP
};
12068 for (unsigned i
= 0; i
< nparams
; ++i
) {
12069 QualType AT
= FTP
->getParamType(i
);
12071 bool mismatch
= true;
12073 if (Context
.hasSameUnqualifiedType(AT
, Expected
[i
]))
12075 else if (Expected
[i
] == CharPP
) {
12076 // As an extension, the following forms are okay:
12078 // char const * const *
12081 QualifierCollector qs
;
12082 const PointerType
* PT
;
12083 if ((PT
= qs
.strip(AT
)->getAs
<PointerType
>()) &&
12084 (PT
= qs
.strip(PT
->getPointeeType())->getAs
<PointerType
>()) &&
12085 Context
.hasSameType(QualType(qs
.strip(PT
->getPointeeType()), 0),
12088 mismatch
= !qs
.empty();
12093 Diag(FD
->getLocation(), diag::err_main_arg_wrong
) << i
<< Expected
[i
];
12094 // TODO: suggest replacing given type with expected type
12095 FD
->setInvalidDecl(true);
12099 if (nparams
== 1 && !FD
->isInvalidDecl()) {
12100 Diag(FD
->getLocation(), diag::warn_main_one_arg
);
12103 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
12104 Diag(FD
->getLocation(), diag::err_mainlike_template_decl
) << FD
;
12105 FD
->setInvalidDecl();
12109 static bool isDefaultStdCall(FunctionDecl
*FD
, Sema
&S
) {
12111 // Default calling convention for main and wmain is __cdecl
12112 if (FD
->getName() == "main" || FD
->getName() == "wmain")
12115 // Default calling convention for MinGW is __cdecl
12116 const llvm::Triple
&T
= S
.Context
.getTargetInfo().getTriple();
12117 if (T
.isWindowsGNUEnvironment())
12120 // Default calling convention for WinMain, wWinMain and DllMain
12121 // is __stdcall on 32 bit Windows
12122 if (T
.isOSWindows() && T
.getArch() == llvm::Triple::x86
)
12128 void Sema::CheckMSVCRTEntryPoint(FunctionDecl
*FD
) {
12129 QualType T
= FD
->getType();
12130 assert(T
->isFunctionType() && "function decl is not of function type");
12131 const FunctionType
*FT
= T
->castAs
<FunctionType
>();
12133 // Set an implicit return of 'zero' if the function can return some integral,
12134 // enumeration, pointer or nullptr type.
12135 if (FT
->getReturnType()->isIntegralOrEnumerationType() ||
12136 FT
->getReturnType()->isAnyPointerType() ||
12137 FT
->getReturnType()->isNullPtrType())
12138 // DllMain is exempt because a return value of zero means it failed.
12139 if (FD
->getName() != "DllMain")
12140 FD
->setHasImplicitReturnZero(true);
12142 // Explicity specified calling conventions are applied to MSVC entry points
12143 if (!hasExplicitCallingConv(T
)) {
12144 if (isDefaultStdCall(FD
, *this)) {
12145 if (FT
->getCallConv() != CC_X86StdCall
) {
12146 FT
= Context
.adjustFunctionType(
12147 FT
, FT
->getExtInfo().withCallingConv(CC_X86StdCall
));
12148 FD
->setType(QualType(FT
, 0));
12150 } else if (FT
->getCallConv() != CC_C
) {
12151 FT
= Context
.adjustFunctionType(FT
,
12152 FT
->getExtInfo().withCallingConv(CC_C
));
12153 FD
->setType(QualType(FT
, 0));
12157 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
12158 Diag(FD
->getLocation(), diag::err_mainlike_template_decl
) << FD
;
12159 FD
->setInvalidDecl();
12163 void Sema::CheckHLSLEntryPoint(FunctionDecl
*FD
) {
12164 auto &TargetInfo
= getASTContext().getTargetInfo();
12165 auto const Triple
= TargetInfo
.getTriple();
12166 switch (Triple
.getEnvironment()) {
12168 // FIXME: check all shader profiles.
12170 case llvm::Triple::EnvironmentType::Compute
:
12171 if (!FD
->hasAttr
<HLSLNumThreadsAttr
>()) {
12172 Diag(FD
->getLocation(), diag::err_hlsl_missing_numthreads
)
12173 << Triple
.getEnvironmentName();
12174 FD
->setInvalidDecl();
12179 for (const auto *Param
: FD
->parameters()) {
12180 if (!Param
->hasAttr
<HLSLAnnotationAttr
>()) {
12181 // FIXME: Handle struct parameters where annotations are on struct fields.
12182 // See: https://github.com/llvm/llvm-project/issues/57875
12183 Diag(FD
->getLocation(), diag::err_hlsl_missing_semantic_annotation
);
12184 Diag(Param
->getLocation(), diag::note_previous_decl
) << Param
;
12185 FD
->setInvalidDecl();
12188 // FIXME: Verify return type semantic annotation.
12191 bool Sema::CheckForConstantInitializer(Expr
*Init
, QualType DclT
) {
12192 // FIXME: Need strict checking. In C89, we need to check for
12193 // any assignment, increment, decrement, function-calls, or
12194 // commas outside of a sizeof. In C99, it's the same list,
12195 // except that the aforementioned are allowed in unevaluated
12196 // expressions. Everything else falls under the
12197 // "may accept other forms of constant expressions" exception.
12199 // Regular C++ code will not end up here (exceptions: language extensions,
12200 // OpenCL C++ etc), so the constant expression rules there don't matter.
12201 if (Init
->isValueDependent()) {
12202 assert(Init
->containsErrors() &&
12203 "Dependent code should only occur in error-recovery path.");
12206 const Expr
*Culprit
;
12207 if (Init
->isConstantInitializer(Context
, false, &Culprit
))
12209 Diag(Culprit
->getExprLoc(), diag::err_init_element_not_constant
)
12210 << Culprit
->getSourceRange();
12215 // Visits an initialization expression to see if OrigDecl is evaluated in
12216 // its own initialization and throws a warning if it does.
12217 class SelfReferenceChecker
12218 : public EvaluatedExprVisitor
<SelfReferenceChecker
> {
12223 bool isReferenceType
;
12226 llvm::SmallVector
<unsigned, 4> InitFieldIndex
;
12229 typedef EvaluatedExprVisitor
<SelfReferenceChecker
> Inherited
;
12231 SelfReferenceChecker(Sema
&S
, Decl
*OrigDecl
) : Inherited(S
.Context
),
12232 S(S
), OrigDecl(OrigDecl
) {
12234 isRecordType
= false;
12235 isReferenceType
= false;
12236 isInitList
= false;
12237 if (ValueDecl
*VD
= dyn_cast
<ValueDecl
>(OrigDecl
)) {
12238 isPODType
= VD
->getType().isPODType(S
.Context
);
12239 isRecordType
= VD
->getType()->isRecordType();
12240 isReferenceType
= VD
->getType()->isReferenceType();
12244 // For most expressions, just call the visitor. For initializer lists,
12245 // track the index of the field being initialized since fields are
12246 // initialized in order allowing use of previously initialized fields.
12247 void CheckExpr(Expr
*E
) {
12248 InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(E
);
12254 // Track and increment the index here.
12256 InitFieldIndex
.push_back(0);
12257 for (auto *Child
: InitList
->children()) {
12258 CheckExpr(cast
<Expr
>(Child
));
12259 ++InitFieldIndex
.back();
12261 InitFieldIndex
.pop_back();
12264 // Returns true if MemberExpr is checked and no further checking is needed.
12265 // Returns false if additional checking is required.
12266 bool CheckInitListMemberExpr(MemberExpr
*E
, bool CheckReference
) {
12267 llvm::SmallVector
<FieldDecl
*, 4> Fields
;
12269 bool ReferenceField
= false;
12271 // Get the field members used.
12272 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12273 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl());
12276 Fields
.push_back(FD
);
12277 if (FD
->getType()->isReferenceType())
12278 ReferenceField
= true;
12279 Base
= ME
->getBase()->IgnoreParenImpCasts();
12282 // Keep checking only if the base Decl is the same.
12283 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
);
12284 if (!DRE
|| DRE
->getDecl() != OrigDecl
)
12287 // A reference field can be bound to an unininitialized field.
12288 if (CheckReference
&& !ReferenceField
)
12291 // Convert FieldDecls to their index number.
12292 llvm::SmallVector
<unsigned, 4> UsedFieldIndex
;
12293 for (const FieldDecl
*I
: llvm::reverse(Fields
))
12294 UsedFieldIndex
.push_back(I
->getFieldIndex());
12296 // See if a warning is needed by checking the first difference in index
12297 // numbers. If field being used has index less than the field being
12298 // initialized, then the use is safe.
12299 for (auto UsedIter
= UsedFieldIndex
.begin(),
12300 UsedEnd
= UsedFieldIndex
.end(),
12301 OrigIter
= InitFieldIndex
.begin(),
12302 OrigEnd
= InitFieldIndex
.end();
12303 UsedIter
!= UsedEnd
&& OrigIter
!= OrigEnd
; ++UsedIter
, ++OrigIter
) {
12304 if (*UsedIter
< *OrigIter
)
12306 if (*UsedIter
> *OrigIter
)
12310 // TODO: Add a different warning which will print the field names.
12311 HandleDeclRefExpr(DRE
);
12315 // For most expressions, the cast is directly above the DeclRefExpr.
12316 // For conditional operators, the cast can be outside the conditional
12317 // operator if both expressions are DeclRefExpr's.
12318 void HandleValue(Expr
*E
) {
12319 E
= E
->IgnoreParens();
12320 if (DeclRefExpr
* DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
12321 HandleDeclRefExpr(DRE
);
12325 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
12326 Visit(CO
->getCond());
12327 HandleValue(CO
->getTrueExpr());
12328 HandleValue(CO
->getFalseExpr());
12332 if (BinaryConditionalOperator
*BCO
=
12333 dyn_cast
<BinaryConditionalOperator
>(E
)) {
12334 Visit(BCO
->getCond());
12335 HandleValue(BCO
->getFalseExpr());
12339 if (OpaqueValueExpr
*OVE
= dyn_cast
<OpaqueValueExpr
>(E
)) {
12340 HandleValue(OVE
->getSourceExpr());
12344 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
12345 if (BO
->getOpcode() == BO_Comma
) {
12346 Visit(BO
->getLHS());
12347 HandleValue(BO
->getRHS());
12352 if (isa
<MemberExpr
>(E
)) {
12354 if (CheckInitListMemberExpr(cast
<MemberExpr
>(E
),
12355 false /*CheckReference*/))
12359 Expr
*Base
= E
->IgnoreParenImpCasts();
12360 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12361 // Check for static member variables and don't warn on them.
12362 if (!isa
<FieldDecl
>(ME
->getMemberDecl()))
12364 Base
= ME
->getBase()->IgnoreParenImpCasts();
12366 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
))
12367 HandleDeclRefExpr(DRE
);
12374 // Reference types not handled in HandleValue are handled here since all
12375 // uses of references are bad, not just r-value uses.
12376 void VisitDeclRefExpr(DeclRefExpr
*E
) {
12377 if (isReferenceType
)
12378 HandleDeclRefExpr(E
);
12381 void VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
12382 if (E
->getCastKind() == CK_LValueToRValue
) {
12383 HandleValue(E
->getSubExpr());
12387 Inherited::VisitImplicitCastExpr(E
);
12390 void VisitMemberExpr(MemberExpr
*E
) {
12392 if (CheckInitListMemberExpr(E
, true /*CheckReference*/))
12396 // Don't warn on arrays since they can be treated as pointers.
12397 if (E
->getType()->canDecayToPointerType()) return;
12399 // Warn when a non-static method call is followed by non-static member
12400 // field accesses, which is followed by a DeclRefExpr.
12401 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl());
12402 bool Warn
= (MD
&& !MD
->isStatic());
12403 Expr
*Base
= E
->getBase()->IgnoreParenImpCasts();
12404 while (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Base
)) {
12405 if (!isa
<FieldDecl
>(ME
->getMemberDecl()))
12407 Base
= ME
->getBase()->IgnoreParenImpCasts();
12410 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Base
)) {
12412 HandleDeclRefExpr(DRE
);
12416 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12417 // Visit that expression.
12421 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
12422 Expr
*Callee
= E
->getCallee();
12424 if (isa
<UnresolvedLookupExpr
>(Callee
))
12425 return Inherited::VisitCXXOperatorCallExpr(E
);
12428 for (auto Arg
: E
->arguments())
12429 HandleValue(Arg
->IgnoreParenImpCasts());
12432 void VisitUnaryOperator(UnaryOperator
*E
) {
12433 // For POD record types, addresses of its own members are well-defined.
12434 if (E
->getOpcode() == UO_AddrOf
&& isRecordType
&&
12435 isa
<MemberExpr
>(E
->getSubExpr()->IgnoreParens())) {
12437 HandleValue(E
->getSubExpr());
12441 if (E
->isIncrementDecrementOp()) {
12442 HandleValue(E
->getSubExpr());
12446 Inherited::VisitUnaryOperator(E
);
12449 void VisitObjCMessageExpr(ObjCMessageExpr
*E
) {}
12451 void VisitCXXConstructExpr(CXXConstructExpr
*E
) {
12452 if (E
->getConstructor()->isCopyConstructor()) {
12453 Expr
*ArgExpr
= E
->getArg(0);
12454 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(ArgExpr
))
12455 if (ILE
->getNumInits() == 1)
12456 ArgExpr
= ILE
->getInit(0);
12457 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(ArgExpr
))
12458 if (ICE
->getCastKind() == CK_NoOp
)
12459 ArgExpr
= ICE
->getSubExpr();
12460 HandleValue(ArgExpr
);
12463 Inherited::VisitCXXConstructExpr(E
);
12466 void VisitCallExpr(CallExpr
*E
) {
12467 // Treat std::move as a use.
12468 if (E
->isCallToStdMove()) {
12469 HandleValue(E
->getArg(0));
12473 Inherited::VisitCallExpr(E
);
12476 void VisitBinaryOperator(BinaryOperator
*E
) {
12477 if (E
->isCompoundAssignmentOp()) {
12478 HandleValue(E
->getLHS());
12479 Visit(E
->getRHS());
12483 Inherited::VisitBinaryOperator(E
);
12486 // A custom visitor for BinaryConditionalOperator is needed because the
12487 // regular visitor would check the condition and true expression separately
12488 // but both point to the same place giving duplicate diagnostics.
12489 void VisitBinaryConditionalOperator(BinaryConditionalOperator
*E
) {
12490 Visit(E
->getCond());
12491 Visit(E
->getFalseExpr());
12494 void HandleDeclRefExpr(DeclRefExpr
*DRE
) {
12495 Decl
* ReferenceDecl
= DRE
->getDecl();
12496 if (OrigDecl
!= ReferenceDecl
) return;
12498 if (isReferenceType
) {
12499 diag
= diag::warn_uninit_self_reference_in_reference_init
;
12500 } else if (cast
<VarDecl
>(OrigDecl
)->isStaticLocal()) {
12501 diag
= diag::warn_static_self_reference_in_init
;
12502 } else if (isa
<TranslationUnitDecl
>(OrigDecl
->getDeclContext()) ||
12503 isa
<NamespaceDecl
>(OrigDecl
->getDeclContext()) ||
12504 DRE
->getDecl()->getType()->isRecordType()) {
12505 diag
= diag::warn_uninit_self_reference_in_init
;
12507 // Local variables will be handled by the CFG analysis.
12511 S
.DiagRuntimeBehavior(DRE
->getBeginLoc(), DRE
,
12513 << DRE
->getDecl() << OrigDecl
->getLocation()
12514 << DRE
->getSourceRange());
12518 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12519 static void CheckSelfReference(Sema
&S
, Decl
* OrigDecl
, Expr
*E
,
12521 // Parameters arguments are occassionially constructed with itself,
12522 // for instance, in recursive functions. Skip them.
12523 if (isa
<ParmVarDecl
>(OrigDecl
))
12526 E
= E
->IgnoreParens();
12528 // Skip checking T a = a where T is not a record or reference type.
12529 // Doing so is a way to silence uninitialized warnings.
12530 if (!DirectInit
&& !cast
<VarDecl
>(OrigDecl
)->getType()->isRecordType())
12531 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
12532 if (ICE
->getCastKind() == CK_LValueToRValue
)
12533 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ICE
->getSubExpr()))
12534 if (DRE
->getDecl() == OrigDecl
)
12537 SelfReferenceChecker(S
, OrigDecl
).CheckExpr(E
);
12539 } // end anonymous namespace
12542 // Simple wrapper to add the name of a variable or (if no variable is
12543 // available) a DeclarationName into a diagnostic.
12544 struct VarDeclOrName
{
12546 DeclarationName Name
;
12548 friend const Sema::SemaDiagnosticBuilder
&
12549 operator<<(const Sema::SemaDiagnosticBuilder
&Diag
, VarDeclOrName VN
) {
12550 return VN
.VDecl
? Diag
<< VN
.VDecl
: Diag
<< VN
.Name
;
12553 } // end anonymous namespace
12555 QualType
Sema::deduceVarTypeFromInitializer(VarDecl
*VDecl
,
12556 DeclarationName Name
, QualType Type
,
12557 TypeSourceInfo
*TSI
,
12558 SourceRange Range
, bool DirectInit
,
12560 bool IsInitCapture
= !VDecl
;
12561 assert((!VDecl
|| !VDecl
->isInitCapture()) &&
12562 "init captures are expected to be deduced prior to initialization");
12564 VarDeclOrName VN
{VDecl
, Name
};
12566 DeducedType
*Deduced
= Type
->getContainedDeducedType();
12567 assert(Deduced
&& "deduceVarTypeFromInitializer for non-deduced type");
12569 // C++11 [dcl.spec.auto]p3
12571 assert(VDecl
&& "no init for init capture deduction?");
12573 // Except for class argument deduction, and then for an initializing
12574 // declaration only, i.e. no static at class scope or extern.
12575 if (!isa
<DeducedTemplateSpecializationType
>(Deduced
) ||
12576 VDecl
->hasExternalStorage() ||
12577 VDecl
->isStaticDataMember()) {
12578 Diag(VDecl
->getLocation(), diag::err_auto_var_requires_init
)
12579 << VDecl
->getDeclName() << Type
;
12584 ArrayRef
<Expr
*> DeduceInits
;
12586 DeduceInits
= Init
;
12589 if (auto *PL
= dyn_cast_or_null
<ParenListExpr
>(Init
))
12590 DeduceInits
= PL
->exprs();
12593 if (isa
<DeducedTemplateSpecializationType
>(Deduced
)) {
12594 assert(VDecl
&& "non-auto type for init capture deduction?");
12595 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
12596 InitializationKind Kind
= InitializationKind::CreateForInit(
12597 VDecl
->getLocation(), DirectInit
, Init
);
12598 // FIXME: Initialization should not be taking a mutable list of inits.
12599 SmallVector
<Expr
*, 8> InitsCopy(DeduceInits
.begin(), DeduceInits
.end());
12600 return DeduceTemplateSpecializationFromInitializer(TSI
, Entity
, Kind
,
12605 if (auto *IL
= dyn_cast
<InitListExpr
>(Init
))
12606 DeduceInits
= IL
->inits();
12609 // Deduction only works if we have exactly one source expression.
12610 if (DeduceInits
.empty()) {
12611 // It isn't possible to write this directly, but it is possible to
12612 // end up in this situation with "auto x(some_pack...);"
12613 Diag(Init
->getBeginLoc(), IsInitCapture
12614 ? diag::err_init_capture_no_expression
12615 : diag::err_auto_var_init_no_expression
)
12616 << VN
<< Type
<< Range
;
12620 if (DeduceInits
.size() > 1) {
12621 Diag(DeduceInits
[1]->getBeginLoc(),
12622 IsInitCapture
? diag::err_init_capture_multiple_expressions
12623 : diag::err_auto_var_init_multiple_expressions
)
12624 << VN
<< Type
<< Range
;
12628 Expr
*DeduceInit
= DeduceInits
[0];
12629 if (DirectInit
&& isa
<InitListExpr
>(DeduceInit
)) {
12630 Diag(Init
->getBeginLoc(), IsInitCapture
12631 ? diag::err_init_capture_paren_braces
12632 : diag::err_auto_var_init_paren_braces
)
12633 << isa
<InitListExpr
>(Init
) << VN
<< Type
<< Range
;
12637 // Expressions default to 'id' when we're in a debugger.
12638 bool DefaultedAnyToId
= false;
12639 if (getLangOpts().DebuggerCastResultToId
&&
12640 Init
->getType() == Context
.UnknownAnyTy
&& !IsInitCapture
) {
12641 ExprResult Result
= forceUnknownAnyToType(Init
, Context
.getObjCIdType());
12642 if (Result
.isInvalid()) {
12645 Init
= Result
.get();
12646 DefaultedAnyToId
= true;
12649 // C++ [dcl.decomp]p1:
12650 // If the assignment-expression [...] has array type A and no ref-qualifier
12651 // is present, e has type cv A
12652 if (VDecl
&& isa
<DecompositionDecl
>(VDecl
) &&
12653 Context
.hasSameUnqualifiedType(Type
, Context
.getAutoDeductType()) &&
12654 DeduceInit
->getType()->isConstantArrayType())
12655 return Context
.getQualifiedType(DeduceInit
->getType(),
12656 Type
.getQualifiers());
12658 QualType DeducedType
;
12659 TemplateDeductionInfo
Info(DeduceInit
->getExprLoc());
12660 TemplateDeductionResult Result
=
12661 DeduceAutoType(TSI
->getTypeLoc(), DeduceInit
, DeducedType
, Info
);
12662 if (Result
!= TDK_Success
&& Result
!= TDK_AlreadyDiagnosed
) {
12663 if (!IsInitCapture
)
12664 DiagnoseAutoDeductionFailure(VDecl
, DeduceInit
);
12665 else if (isa
<InitListExpr
>(Init
))
12666 Diag(Range
.getBegin(),
12667 diag::err_init_capture_deduction_failure_from_init_list
)
12669 << (DeduceInit
->getType().isNull() ? TSI
->getType()
12670 : DeduceInit
->getType())
12671 << DeduceInit
->getSourceRange();
12673 Diag(Range
.getBegin(), diag::err_init_capture_deduction_failure
)
12674 << VN
<< TSI
->getType()
12675 << (DeduceInit
->getType().isNull() ? TSI
->getType()
12676 : DeduceInit
->getType())
12677 << DeduceInit
->getSourceRange();
12680 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12681 // 'id' instead of a specific object type prevents most of our usual
12683 // We only want to warn outside of template instantiations, though:
12684 // inside a template, the 'id' could have come from a parameter.
12685 if (!inTemplateInstantiation() && !DefaultedAnyToId
&& !IsInitCapture
&&
12686 !DeducedType
.isNull() && DeducedType
->isObjCIdType()) {
12687 SourceLocation Loc
= TSI
->getTypeLoc().getBeginLoc();
12688 Diag(Loc
, diag::warn_auto_var_is_id
) << VN
<< Range
;
12691 return DeducedType
;
12694 bool Sema::DeduceVariableDeclarationType(VarDecl
*VDecl
, bool DirectInit
,
12696 assert(!Init
|| !Init
->containsErrors());
12697 QualType DeducedType
= deduceVarTypeFromInitializer(
12698 VDecl
, VDecl
->getDeclName(), VDecl
->getType(), VDecl
->getTypeSourceInfo(),
12699 VDecl
->getSourceRange(), DirectInit
, Init
);
12700 if (DeducedType
.isNull()) {
12701 VDecl
->setInvalidDecl();
12705 VDecl
->setType(DeducedType
);
12706 assert(VDecl
->isLinkageValid());
12708 // In ARC, infer lifetime.
12709 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(VDecl
))
12710 VDecl
->setInvalidDecl();
12712 if (getLangOpts().OpenCL
)
12713 deduceOpenCLAddressSpace(VDecl
);
12715 // If this is a redeclaration, check that the type we just deduced matches
12716 // the previously declared type.
12717 if (VarDecl
*Old
= VDecl
->getPreviousDecl()) {
12718 // We never need to merge the type, because we cannot form an incomplete
12719 // array of auto, nor deduce such a type.
12720 MergeVarDeclTypes(VDecl
, Old
, /*MergeTypeWithPrevious*/ false);
12723 // Check the deduced type is valid for a variable declaration.
12724 CheckVariableDeclarationType(VDecl
);
12725 return VDecl
->isInvalidDecl();
12728 void Sema::checkNonTrivialCUnionInInitializer(const Expr
*Init
,
12729 SourceLocation Loc
) {
12730 if (auto *EWC
= dyn_cast
<ExprWithCleanups
>(Init
))
12731 Init
= EWC
->getSubExpr();
12733 if (auto *CE
= dyn_cast
<ConstantExpr
>(Init
))
12734 Init
= CE
->getSubExpr();
12736 QualType InitType
= Init
->getType();
12737 assert((InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12738 InitType
.hasNonTrivialToPrimitiveCopyCUnion()) &&
12739 "shouldn't be called if type doesn't have a non-trivial C struct");
12740 if (auto *ILE
= dyn_cast
<InitListExpr
>(Init
)) {
12741 for (auto *I
: ILE
->inits()) {
12742 if (!I
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12743 !I
->getType().hasNonTrivialToPrimitiveCopyCUnion())
12745 SourceLocation SL
= I
->getExprLoc();
12746 checkNonTrivialCUnionInInitializer(I
, SL
.isValid() ? SL
: Loc
);
12751 if (isa
<ImplicitValueInitExpr
>(Init
)) {
12752 if (InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12753 checkNonTrivialCUnion(InitType
, Loc
, NTCUC_DefaultInitializedObject
,
12756 // Assume all other explicit initializers involving copying some existing
12758 // TODO: ignore any explicit initializers where we can guarantee
12760 if (InitType
.hasNonTrivialToPrimitiveCopyCUnion())
12761 checkNonTrivialCUnion(InitType
, Loc
, NTCUC_CopyInit
, NTCUK_Copy
);
12767 bool shouldIgnoreForRecordTriviality(const FieldDecl
*FD
) {
12768 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12769 // in the source code or implicitly by the compiler if it is in a union
12770 // defined in a system header and has non-trivial ObjC ownership
12771 // qualifications. We don't want those fields to participate in determining
12772 // whether the containing union is non-trivial.
12773 return FD
->hasAttr
<UnavailableAttr
>();
12776 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12777 : DefaultInitializedTypeVisitor
<DiagNonTrivalCUnionDefaultInitializeVisitor
,
12780 DefaultInitializedTypeVisitor
<DiagNonTrivalCUnionDefaultInitializeVisitor
,
12783 DiagNonTrivalCUnionDefaultInitializeVisitor(
12784 QualType OrigTy
, SourceLocation OrigLoc
,
12785 Sema::NonTrivialCUnionContext UseContext
, Sema
&S
)
12786 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
12788 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK
, QualType QT
,
12789 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12790 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
12791 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
12792 InNonTrivialUnion
);
12793 return Super::visitWithKind(PDIK
, QT
, FD
, InNonTrivialUnion
);
12796 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
12797 bool InNonTrivialUnion
) {
12798 if (InNonTrivialUnion
)
12799 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12800 << 1 << 0 << QT
<< FD
->getName();
12803 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12804 if (InNonTrivialUnion
)
12805 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12806 << 1 << 0 << QT
<< FD
->getName();
12809 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12810 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
12811 if (RD
->isUnion()) {
12812 if (OrigLoc
.isValid()) {
12813 bool IsUnion
= false;
12814 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
12815 IsUnion
= OrigRD
->isUnion();
12816 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
12817 << 0 << OrigTy
<< IsUnion
<< UseContext
;
12818 // Reset OrigLoc so that this diagnostic is emitted only once.
12819 OrigLoc
= SourceLocation();
12821 InNonTrivialUnion
= true;
12824 if (InNonTrivialUnion
)
12825 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
12826 << 0 << 0 << QT
.getUnqualifiedType() << "";
12828 for (const FieldDecl
*FD
: RD
->fields())
12829 if (!shouldIgnoreForRecordTriviality(FD
))
12830 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
12833 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12835 // The non-trivial C union type or the struct/union type that contains a
12836 // non-trivial C union.
12838 SourceLocation OrigLoc
;
12839 Sema::NonTrivialCUnionContext UseContext
;
12843 struct DiagNonTrivalCUnionDestructedTypeVisitor
12844 : DestructedTypeVisitor
<DiagNonTrivalCUnionDestructedTypeVisitor
, void> {
12846 DestructedTypeVisitor
<DiagNonTrivalCUnionDestructedTypeVisitor
, void>;
12848 DiagNonTrivalCUnionDestructedTypeVisitor(
12849 QualType OrigTy
, SourceLocation OrigLoc
,
12850 Sema::NonTrivialCUnionContext UseContext
, Sema
&S
)
12851 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
12853 void visitWithKind(QualType::DestructionKind DK
, QualType QT
,
12854 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12855 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
12856 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
12857 InNonTrivialUnion
);
12858 return Super::visitWithKind(DK
, QT
, FD
, InNonTrivialUnion
);
12861 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
12862 bool InNonTrivialUnion
) {
12863 if (InNonTrivialUnion
)
12864 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12865 << 1 << 1 << QT
<< FD
->getName();
12868 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12869 if (InNonTrivialUnion
)
12870 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12871 << 1 << 1 << QT
<< FD
->getName();
12874 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12875 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
12876 if (RD
->isUnion()) {
12877 if (OrigLoc
.isValid()) {
12878 bool IsUnion
= false;
12879 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
12880 IsUnion
= OrigRD
->isUnion();
12881 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
12882 << 1 << OrigTy
<< IsUnion
<< UseContext
;
12883 // Reset OrigLoc so that this diagnostic is emitted only once.
12884 OrigLoc
= SourceLocation();
12886 InNonTrivialUnion
= true;
12889 if (InNonTrivialUnion
)
12890 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
12891 << 0 << 1 << QT
.getUnqualifiedType() << "";
12893 for (const FieldDecl
*FD
: RD
->fields())
12894 if (!shouldIgnoreForRecordTriviality(FD
))
12895 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
12898 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12899 void visitCXXDestructor(QualType QT
, const FieldDecl
*FD
,
12900 bool InNonTrivialUnion
) {}
12902 // The non-trivial C union type or the struct/union type that contains a
12903 // non-trivial C union.
12905 SourceLocation OrigLoc
;
12906 Sema::NonTrivialCUnionContext UseContext
;
12910 struct DiagNonTrivalCUnionCopyVisitor
12911 : CopiedTypeVisitor
<DiagNonTrivalCUnionCopyVisitor
, false, void> {
12912 using Super
= CopiedTypeVisitor
<DiagNonTrivalCUnionCopyVisitor
, false, void>;
12914 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy
, SourceLocation OrigLoc
,
12915 Sema::NonTrivialCUnionContext UseContext
,
12917 : OrigTy(OrigTy
), OrigLoc(OrigLoc
), UseContext(UseContext
), S(S
) {}
12919 void visitWithKind(QualType::PrimitiveCopyKind PCK
, QualType QT
,
12920 const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12921 if (const auto *AT
= S
.Context
.getAsArrayType(QT
))
12922 return this->asDerived().visit(S
.Context
.getBaseElementType(AT
), FD
,
12923 InNonTrivialUnion
);
12924 return Super::visitWithKind(PCK
, QT
, FD
, InNonTrivialUnion
);
12927 void visitARCStrong(QualType QT
, const FieldDecl
*FD
,
12928 bool InNonTrivialUnion
) {
12929 if (InNonTrivialUnion
)
12930 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12931 << 1 << 2 << QT
<< FD
->getName();
12934 void visitARCWeak(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12935 if (InNonTrivialUnion
)
12936 S
.Diag(FD
->getLocation(), diag::note_non_trivial_c_union
)
12937 << 1 << 2 << QT
<< FD
->getName();
12940 void visitStruct(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {
12941 const RecordDecl
*RD
= QT
->castAs
<RecordType
>()->getDecl();
12942 if (RD
->isUnion()) {
12943 if (OrigLoc
.isValid()) {
12944 bool IsUnion
= false;
12945 if (auto *OrigRD
= OrigTy
->getAsRecordDecl())
12946 IsUnion
= OrigRD
->isUnion();
12947 S
.Diag(OrigLoc
, diag::err_non_trivial_c_union_in_invalid_context
)
12948 << 2 << OrigTy
<< IsUnion
<< UseContext
;
12949 // Reset OrigLoc so that this diagnostic is emitted only once.
12950 OrigLoc
= SourceLocation();
12952 InNonTrivialUnion
= true;
12955 if (InNonTrivialUnion
)
12956 S
.Diag(RD
->getLocation(), diag::note_non_trivial_c_union
)
12957 << 0 << 2 << QT
.getUnqualifiedType() << "";
12959 for (const FieldDecl
*FD
: RD
->fields())
12960 if (!shouldIgnoreForRecordTriviality(FD
))
12961 asDerived().visit(FD
->getType(), FD
, InNonTrivialUnion
);
12964 void preVisit(QualType::PrimitiveCopyKind PCK
, QualType QT
,
12965 const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12966 void visitTrivial(QualType QT
, const FieldDecl
*FD
, bool InNonTrivialUnion
) {}
12967 void visitVolatileTrivial(QualType QT
, const FieldDecl
*FD
,
12968 bool InNonTrivialUnion
) {}
12970 // The non-trivial C union type or the struct/union type that contains a
12971 // non-trivial C union.
12973 SourceLocation OrigLoc
;
12974 Sema::NonTrivialCUnionContext UseContext
;
12980 void Sema::checkNonTrivialCUnion(QualType QT
, SourceLocation Loc
,
12981 NonTrivialCUnionContext UseContext
,
12982 unsigned NonTrivialKind
) {
12983 assert((QT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12984 QT
.hasNonTrivialToPrimitiveDestructCUnion() ||
12985 QT
.hasNonTrivialToPrimitiveCopyCUnion()) &&
12986 "shouldn't be called if type doesn't have a non-trivial C union");
12988 if ((NonTrivialKind
& NTCUK_Init
) &&
12989 QT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12990 DiagNonTrivalCUnionDefaultInitializeVisitor(QT
, Loc
, UseContext
, *this)
12991 .visit(QT
, nullptr, false);
12992 if ((NonTrivialKind
& NTCUK_Destruct
) &&
12993 QT
.hasNonTrivialToPrimitiveDestructCUnion())
12994 DiagNonTrivalCUnionDestructedTypeVisitor(QT
, Loc
, UseContext
, *this)
12995 .visit(QT
, nullptr, false);
12996 if ((NonTrivialKind
& NTCUK_Copy
) && QT
.hasNonTrivialToPrimitiveCopyCUnion())
12997 DiagNonTrivalCUnionCopyVisitor(QT
, Loc
, UseContext
, *this)
12998 .visit(QT
, nullptr, false);
13001 /// AddInitializerToDecl - Adds the initializer Init to the
13002 /// declaration dcl. If DirectInit is true, this is C++ direct
13003 /// initialization rather than copy initialization.
13004 void Sema::AddInitializerToDecl(Decl
*RealDecl
, Expr
*Init
, bool DirectInit
) {
13005 // If there is no declaration, there was an error parsing it. Just ignore
13006 // the initializer.
13007 if (!RealDecl
|| RealDecl
->isInvalidDecl()) {
13008 CorrectDelayedTyposInExpr(Init
, dyn_cast_or_null
<VarDecl
>(RealDecl
));
13012 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(RealDecl
)) {
13013 // Pure-specifiers are handled in ActOnPureSpecifier.
13014 Diag(Method
->getLocation(), diag::err_member_function_initialization
)
13015 << Method
->getDeclName() << Init
->getSourceRange();
13016 Method
->setInvalidDecl();
13020 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
13022 assert(!isa
<FieldDecl
>(RealDecl
) && "field init shouldn't get here");
13023 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
13024 RealDecl
->setInvalidDecl();
13028 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13029 if (VDecl
->getType()->isUndeducedType()) {
13030 // Attempt typo correction early so that the type of the init expression can
13031 // be deduced based on the chosen correction if the original init contains a
13033 ExprResult Res
= CorrectDelayedTyposInExpr(Init
, VDecl
);
13034 if (!Res
.isUsable()) {
13035 // There are unresolved typos in Init, just drop them.
13036 // FIXME: improve the recovery strategy to preserve the Init.
13037 RealDecl
->setInvalidDecl();
13040 if (Res
.get()->containsErrors()) {
13041 // Invalidate the decl as we don't know the type for recovery-expr yet.
13042 RealDecl
->setInvalidDecl();
13043 VDecl
->setInit(Res
.get());
13048 if (DeduceVariableDeclarationType(VDecl
, DirectInit
, Init
))
13052 // dllimport cannot be used on variable definitions.
13053 if (VDecl
->hasAttr
<DLLImportAttr
>() && !VDecl
->isStaticDataMember()) {
13054 Diag(VDecl
->getLocation(), diag::err_attribute_dllimport_data_definition
);
13055 VDecl
->setInvalidDecl();
13059 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13060 // the identifier has external or internal linkage, the declaration shall
13061 // have no initializer for the identifier.
13062 // C++14 [dcl.init]p5 is the same restriction for C++.
13063 if (VDecl
->isLocalVarDecl() && VDecl
->hasExternalStorage()) {
13064 Diag(VDecl
->getLocation(), diag::err_block_extern_cant_init
);
13065 VDecl
->setInvalidDecl();
13069 if (!VDecl
->getType()->isDependentType()) {
13070 // A definition must end up with a complete type, which means it must be
13071 // complete with the restriction that an array type might be completed by
13072 // the initializer; note that later code assumes this restriction.
13073 QualType BaseDeclType
= VDecl
->getType();
13074 if (const ArrayType
*Array
= Context
.getAsIncompleteArrayType(BaseDeclType
))
13075 BaseDeclType
= Array
->getElementType();
13076 if (RequireCompleteType(VDecl
->getLocation(), BaseDeclType
,
13077 diag::err_typecheck_decl_incomplete_type
)) {
13078 RealDecl
->setInvalidDecl();
13082 // The variable can not have an abstract class type.
13083 if (RequireNonAbstractType(VDecl
->getLocation(), VDecl
->getType(),
13084 diag::err_abstract_type_in_decl
,
13085 AbstractVariableType
))
13086 VDecl
->setInvalidDecl();
13089 // C++ [module.import/6] external definitions are not permitted in header
13091 if (getLangOpts().CPlusPlusModules
&& currentModuleIsHeaderUnit() &&
13092 !VDecl
->isInvalidDecl() && VDecl
->isThisDeclarationADefinition() &&
13093 VDecl
->getFormalLinkage() == Linkage::ExternalLinkage
&&
13094 !VDecl
->isInline() && !VDecl
->isTemplated() &&
13095 !isa
<VarTemplateSpecializationDecl
>(VDecl
)) {
13096 Diag(VDecl
->getLocation(), diag::err_extern_def_in_header_unit
);
13097 VDecl
->setInvalidDecl();
13100 // If adding the initializer will turn this declaration into a definition,
13101 // and we already have a definition for this variable, diagnose or otherwise
13102 // handle the situation.
13103 if (VarDecl
*Def
= VDecl
->getDefinition())
13104 if (Def
!= VDecl
&&
13105 (!VDecl
->isStaticDataMember() || VDecl
->isOutOfLine()) &&
13106 !VDecl
->isThisDeclarationADemotedDefinition() &&
13107 checkVarDeclRedefinition(Def
, VDecl
))
13110 if (getLangOpts().CPlusPlus
) {
13111 // C++ [class.static.data]p4
13112 // If a static data member is of const integral or const
13113 // enumeration type, its declaration in the class definition can
13114 // specify a constant-initializer which shall be an integral
13115 // constant expression (5.19). In that case, the member can appear
13116 // in integral constant expressions. The member shall still be
13117 // defined in a namespace scope if it is used in the program and the
13118 // namespace scope definition shall not contain an initializer.
13120 // We already performed a redefinition check above, but for static
13121 // data members we also need to check whether there was an in-class
13122 // declaration with an initializer.
13123 if (VDecl
->isStaticDataMember() && VDecl
->getCanonicalDecl()->hasInit()) {
13124 Diag(Init
->getExprLoc(), diag::err_static_data_member_reinitialization
)
13125 << VDecl
->getDeclName();
13126 Diag(VDecl
->getCanonicalDecl()->getInit()->getExprLoc(),
13127 diag::note_previous_initializer
)
13132 if (VDecl
->hasLocalStorage())
13133 setFunctionHasBranchProtectedScope();
13135 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
)) {
13136 VDecl
->setInvalidDecl();
13141 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13142 // a kernel function cannot be initialized."
13143 if (VDecl
->getType().getAddressSpace() == LangAS::opencl_local
) {
13144 Diag(VDecl
->getLocation(), diag::err_local_cant_init
);
13145 VDecl
->setInvalidDecl();
13149 // The LoaderUninitialized attribute acts as a definition (of undef).
13150 if (VDecl
->hasAttr
<LoaderUninitializedAttr
>()) {
13151 Diag(VDecl
->getLocation(), diag::err_loader_uninitialized_cant_init
);
13152 VDecl
->setInvalidDecl();
13156 // Get the decls type and save a reference for later, since
13157 // CheckInitializerTypes may change it.
13158 QualType DclT
= VDecl
->getType(), SavT
= DclT
;
13160 // Expressions default to 'id' when we're in a debugger
13161 // and we are assigning it to a variable of Objective-C pointer type.
13162 if (getLangOpts().DebuggerCastResultToId
&& DclT
->isObjCObjectPointerType() &&
13163 Init
->getType() == Context
.UnknownAnyTy
) {
13164 ExprResult Result
= forceUnknownAnyToType(Init
, Context
.getObjCIdType());
13165 if (Result
.isInvalid()) {
13166 VDecl
->setInvalidDecl();
13169 Init
= Result
.get();
13172 // Perform the initialization.
13173 ParenListExpr
*CXXDirectInit
= dyn_cast
<ParenListExpr
>(Init
);
13174 bool IsParenListInit
= false;
13175 if (!VDecl
->isInvalidDecl()) {
13176 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
13177 InitializationKind Kind
= InitializationKind::CreateForInit(
13178 VDecl
->getLocation(), DirectInit
, Init
);
13180 MultiExprArg Args
= Init
;
13182 Args
= MultiExprArg(CXXDirectInit
->getExprs(),
13183 CXXDirectInit
->getNumExprs());
13185 // Try to correct any TypoExprs in the initialization arguments.
13186 for (size_t Idx
= 0; Idx
< Args
.size(); ++Idx
) {
13187 ExprResult Res
= CorrectDelayedTyposInExpr(
13188 Args
[Idx
], VDecl
, /*RecoverUncorrectedTypos=*/true,
13189 [this, Entity
, Kind
](Expr
*E
) {
13190 InitializationSequence
Init(*this, Entity
, Kind
, MultiExprArg(E
));
13191 return Init
.Failed() ? ExprError() : E
;
13193 if (Res
.isInvalid()) {
13194 VDecl
->setInvalidDecl();
13195 } else if (Res
.get() != Args
[Idx
]) {
13196 Args
[Idx
] = Res
.get();
13199 if (VDecl
->isInvalidDecl())
13202 InitializationSequence
InitSeq(*this, Entity
, Kind
, Args
,
13203 /*TopLevelOfInitList=*/false,
13204 /*TreatUnavailableAsInvalid=*/false);
13205 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Args
, &DclT
);
13206 if (Result
.isInvalid()) {
13207 // If the provided initializer fails to initialize the var decl,
13208 // we attach a recovery expr for better recovery.
13209 auto RecoveryExpr
=
13210 CreateRecoveryExpr(Init
->getBeginLoc(), Init
->getEndLoc(), Args
);
13211 if (RecoveryExpr
.get())
13212 VDecl
->setInit(RecoveryExpr
.get());
13216 Init
= Result
.getAs
<Expr
>();
13217 IsParenListInit
= !InitSeq
.steps().empty() &&
13218 InitSeq
.step_begin()->Kind
==
13219 InitializationSequence::SK_ParenthesizedListInit
;
13222 // Check for self-references within variable initializers.
13223 // Variables declared within a function/method body (except for references)
13224 // are handled by a dataflow analysis.
13225 // This is undefined behavior in C++, but valid in C.
13226 if (getLangOpts().CPlusPlus
)
13227 if (!VDecl
->hasLocalStorage() || VDecl
->getType()->isRecordType() ||
13228 VDecl
->getType()->isReferenceType())
13229 CheckSelfReference(*this, RealDecl
, Init
, DirectInit
);
13231 // If the type changed, it means we had an incomplete type that was
13232 // completed by the initializer. For example:
13233 // int ary[] = { 1, 3, 5 };
13234 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13235 if (!VDecl
->isInvalidDecl() && (DclT
!= SavT
))
13236 VDecl
->setType(DclT
);
13238 if (!VDecl
->isInvalidDecl()) {
13239 checkUnsafeAssigns(VDecl
->getLocation(), VDecl
->getType(), Init
);
13241 if (VDecl
->hasAttr
<BlocksAttr
>())
13242 checkRetainCycles(VDecl
, Init
);
13244 // It is safe to assign a weak reference into a strong variable.
13245 // Although this code can still have problems:
13246 // id x = self.weakProp;
13247 // id y = self.weakProp;
13248 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13249 // paths through the function. This should be revisited if
13250 // -Wrepeated-use-of-weak is made flow-sensitive.
13251 if (FunctionScopeInfo
*FSI
= getCurFunction())
13252 if ((VDecl
->getType().getObjCLifetime() == Qualifiers::OCL_Strong
||
13253 VDecl
->getType().isNonWeakInMRRWithObjCWeak(Context
)) &&
13254 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
,
13255 Init
->getBeginLoc()))
13256 FSI
->markSafeWeakUse(Init
);
13259 // The initialization is usually a full-expression.
13261 // FIXME: If this is a braced initialization of an aggregate, it is not
13262 // an expression, and each individual field initializer is a separate
13263 // full-expression. For instance, in:
13265 // struct Temp { ~Temp(); };
13266 // struct S { S(Temp); };
13267 // struct T { S a, b; } t = { Temp(), Temp() }
13269 // we should destroy the first Temp before constructing the second.
13270 ExprResult Result
=
13271 ActOnFinishFullExpr(Init
, VDecl
->getLocation(),
13272 /*DiscardedValue*/ false, VDecl
->isConstexpr());
13273 if (Result
.isInvalid()) {
13274 VDecl
->setInvalidDecl();
13277 Init
= Result
.get();
13279 // Attach the initializer to the decl.
13280 VDecl
->setInit(Init
);
13282 if (VDecl
->isLocalVarDecl()) {
13283 // Don't check the initializer if the declaration is malformed.
13284 if (VDecl
->isInvalidDecl()) {
13287 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13288 // This is true even in C++ for OpenCL.
13289 } else if (VDecl
->getType().getAddressSpace() == LangAS::opencl_constant
) {
13290 CheckForConstantInitializer(Init
, DclT
);
13292 // Otherwise, C++ does not restrict the initializer.
13293 } else if (getLangOpts().CPlusPlus
) {
13296 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13297 // static storage duration shall be constant expressions or string literals.
13298 } else if (VDecl
->getStorageClass() == SC_Static
) {
13299 CheckForConstantInitializer(Init
, DclT
);
13301 // C89 is stricter than C99 for aggregate initializers.
13302 // C89 6.5.7p3: All the expressions [...] in an initializer list
13303 // for an object that has aggregate or union type shall be
13304 // constant expressions.
13305 } else if (!getLangOpts().C99
&& VDecl
->getType()->isAggregateType() &&
13306 isa
<InitListExpr
>(Init
)) {
13307 const Expr
*Culprit
;
13308 if (!Init
->isConstantInitializer(Context
, false, &Culprit
)) {
13309 Diag(Culprit
->getExprLoc(),
13310 diag::ext_aggregate_init_not_constant
)
13311 << Culprit
->getSourceRange();
13315 if (auto *E
= dyn_cast
<ExprWithCleanups
>(Init
))
13316 if (auto *BE
= dyn_cast
<BlockExpr
>(E
->getSubExpr()->IgnoreParens()))
13317 if (VDecl
->hasLocalStorage())
13318 BE
->getBlockDecl()->setCanAvoidCopyToHeap();
13319 } else if (VDecl
->isStaticDataMember() && !VDecl
->isInline() &&
13320 VDecl
->getLexicalDeclContext()->isRecord()) {
13321 // This is an in-class initialization for a static data member, e.g.,
13324 // static const int value = 17;
13327 // C++ [class.mem]p4:
13328 // A member-declarator can contain a constant-initializer only
13329 // if it declares a static member (9.4) of const integral or
13330 // const enumeration type, see 9.4.2.
13332 // C++11 [class.static.data]p3:
13333 // If a non-volatile non-inline const static data member is of integral
13334 // or enumeration type, its declaration in the class definition can
13335 // specify a brace-or-equal-initializer in which every initializer-clause
13336 // that is an assignment-expression is a constant expression. A static
13337 // data member of literal type can be declared in the class definition
13338 // with the constexpr specifier; if so, its declaration shall specify a
13339 // brace-or-equal-initializer in which every initializer-clause that is
13340 // an assignment-expression is a constant expression.
13342 // Do nothing on dependent types.
13343 if (DclT
->isDependentType()) {
13345 // Allow any 'static constexpr' members, whether or not they are of literal
13346 // type. We separately check that every constexpr variable is of literal
13348 } else if (VDecl
->isConstexpr()) {
13350 // Require constness.
13351 } else if (!DclT
.isConstQualified()) {
13352 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_non_const
)
13353 << Init
->getSourceRange();
13354 VDecl
->setInvalidDecl();
13356 // We allow integer constant expressions in all cases.
13357 } else if (DclT
->isIntegralOrEnumerationType()) {
13358 // Check whether the expression is a constant expression.
13359 SourceLocation Loc
;
13360 if (getLangOpts().CPlusPlus11
&& DclT
.isVolatileQualified())
13361 // In C++11, a non-constexpr const static data member with an
13362 // in-class initializer cannot be volatile.
13363 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_volatile
);
13364 else if (Init
->isValueDependent())
13365 ; // Nothing to check.
13366 else if (Init
->isIntegerConstantExpr(Context
, &Loc
))
13367 ; // Ok, it's an ICE!
13368 else if (Init
->getType()->isScopedEnumeralType() &&
13369 Init
->isCXX11ConstantExpr(Context
))
13370 ; // Ok, it is a scoped-enum constant expression.
13371 else if (Init
->isEvaluatable(Context
)) {
13372 // If we can constant fold the initializer through heroics, accept it,
13373 // but report this as a use of an extension for -pedantic.
13374 Diag(Loc
, diag::ext_in_class_initializer_non_constant
)
13375 << Init
->getSourceRange();
13377 // Otherwise, this is some crazy unknown case. Report the issue at the
13378 // location provided by the isIntegerConstantExpr failed check.
13379 Diag(Loc
, diag::err_in_class_initializer_non_constant
)
13380 << Init
->getSourceRange();
13381 VDecl
->setInvalidDecl();
13384 // We allow foldable floating-point constants as an extension.
13385 } else if (DclT
->isFloatingType()) { // also permits complex, which is ok
13386 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13387 // it anyway and provide a fixit to add the 'constexpr'.
13388 if (getLangOpts().CPlusPlus11
) {
13389 Diag(VDecl
->getLocation(),
13390 diag::ext_in_class_initializer_float_type_cxx11
)
13391 << DclT
<< Init
->getSourceRange();
13392 Diag(VDecl
->getBeginLoc(),
13393 diag::note_in_class_initializer_float_type_cxx11
)
13394 << FixItHint::CreateInsertion(VDecl
->getBeginLoc(), "constexpr ");
13396 Diag(VDecl
->getLocation(), diag::ext_in_class_initializer_float_type
)
13397 << DclT
<< Init
->getSourceRange();
13399 if (!Init
->isValueDependent() && !Init
->isEvaluatable(Context
)) {
13400 Diag(Init
->getExprLoc(), diag::err_in_class_initializer_non_constant
)
13401 << Init
->getSourceRange();
13402 VDecl
->setInvalidDecl();
13406 // Suggest adding 'constexpr' in C++11 for literal types.
13407 } else if (getLangOpts().CPlusPlus11
&& DclT
->isLiteralType(Context
)) {
13408 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_literal_type
)
13409 << DclT
<< Init
->getSourceRange()
13410 << FixItHint::CreateInsertion(VDecl
->getBeginLoc(), "constexpr ");
13411 VDecl
->setConstexpr(true);
13414 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_bad_type
)
13415 << DclT
<< Init
->getSourceRange();
13416 VDecl
->setInvalidDecl();
13418 } else if (VDecl
->isFileVarDecl()) {
13419 // In C, extern is typically used to avoid tentative definitions when
13420 // declaring variables in headers, but adding an intializer makes it a
13421 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13422 // In C++, extern is often used to give implictly static const variables
13423 // external linkage, so don't warn in that case. If selectany is present,
13424 // this might be header code intended for C and C++ inclusion, so apply the
13426 if (VDecl
->getStorageClass() == SC_Extern
&&
13427 ((!getLangOpts().CPlusPlus
&& !VDecl
->hasAttr
<SelectAnyAttr
>()) ||
13428 !Context
.getBaseElementType(VDecl
->getType()).isConstQualified()) &&
13429 !(getLangOpts().CPlusPlus
&& VDecl
->isExternC()) &&
13430 !isTemplateInstantiation(VDecl
->getTemplateSpecializationKind()))
13431 Diag(VDecl
->getLocation(), diag::warn_extern_init
);
13433 // In Microsoft C++ mode, a const variable defined in namespace scope has
13434 // external linkage by default if the variable is declared with
13435 // __declspec(dllexport).
13436 if (Context
.getTargetInfo().getCXXABI().isMicrosoft() &&
13437 getLangOpts().CPlusPlus
&& VDecl
->getType().isConstQualified() &&
13438 VDecl
->hasAttr
<DLLExportAttr
>() && VDecl
->getDefinition())
13439 VDecl
->setStorageClass(SC_Extern
);
13441 // C99 6.7.8p4. All file scoped initializers need to be constant.
13442 if (!getLangOpts().CPlusPlus
&& !VDecl
->isInvalidDecl())
13443 CheckForConstantInitializer(Init
, DclT
);
13446 QualType InitType
= Init
->getType();
13447 if (!InitType
.isNull() &&
13448 (InitType
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13449 InitType
.hasNonTrivialToPrimitiveCopyCUnion()))
13450 checkNonTrivialCUnionInInitializer(Init
, Init
->getExprLoc());
13452 // We will represent direct-initialization similarly to copy-initialization:
13453 // int x(1); -as-> int x = 1;
13454 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13456 // Clients that want to distinguish between the two forms, can check for
13457 // direct initializer using VarDecl::getInitStyle().
13458 // A major benefit is that clients that don't particularly care about which
13459 // exactly form was it (like the CodeGen) can handle both cases without
13460 // special case code.
13463 // The form of initialization (using parentheses or '=') is generally
13464 // insignificant, but does matter when the entity being initialized has a
13466 if (CXXDirectInit
) {
13467 assert(DirectInit
&& "Call-style initializer must be direct init.");
13468 VDecl
->setInitStyle(IsParenListInit
? VarDecl::ParenListInit
13469 : VarDecl::CallInit
);
13470 } else if (DirectInit
) {
13471 // This must be list-initialization. No other way is direct-initialization.
13472 VDecl
->setInitStyle(VarDecl::ListInit
);
13475 if (LangOpts
.OpenMP
&&
13476 (LangOpts
.OpenMPIsDevice
|| !LangOpts
.OMPTargetTriples
.empty()) &&
13477 VDecl
->isFileVarDecl())
13478 DeclsToCheckForDeferredDiags
.insert(VDecl
);
13479 CheckCompleteVariableDeclaration(VDecl
);
13482 /// ActOnInitializerError - Given that there was an error parsing an
13483 /// initializer for the given declaration, try to at least re-establish
13484 /// invariants such as whether a variable's type is either dependent or
13486 void Sema::ActOnInitializerError(Decl
*D
) {
13487 // Our main concern here is re-establishing invariants like "a
13488 // variable's type is either dependent or complete".
13489 if (!D
|| D
->isInvalidDecl()) return;
13491 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
13494 // Bindings are not usable if we can't make sense of the initializer.
13495 if (auto *DD
= dyn_cast
<DecompositionDecl
>(D
))
13496 for (auto *BD
: DD
->bindings())
13497 BD
->setInvalidDecl();
13499 // Auto types are meaningless if we can't make sense of the initializer.
13500 if (VD
->getType()->isUndeducedType()) {
13501 D
->setInvalidDecl();
13505 QualType Ty
= VD
->getType();
13506 if (Ty
->isDependentType()) return;
13508 // Require a complete type.
13509 if (RequireCompleteType(VD
->getLocation(),
13510 Context
.getBaseElementType(Ty
),
13511 diag::err_typecheck_decl_incomplete_type
)) {
13512 VD
->setInvalidDecl();
13516 // Require a non-abstract type.
13517 if (RequireNonAbstractType(VD
->getLocation(), Ty
,
13518 diag::err_abstract_type_in_decl
,
13519 AbstractVariableType
)) {
13520 VD
->setInvalidDecl();
13524 // Don't bother complaining about constructors or destructors,
13528 void Sema::ActOnUninitializedDecl(Decl
*RealDecl
) {
13529 // If there is no declaration, there was an error parsing it. Just ignore it.
13533 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(RealDecl
)) {
13534 QualType Type
= Var
->getType();
13536 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13537 if (isa
<DecompositionDecl
>(RealDecl
)) {
13538 Diag(Var
->getLocation(), diag::err_decomp_decl_requires_init
) << Var
;
13539 Var
->setInvalidDecl();
13543 if (Type
->isUndeducedType() &&
13544 DeduceVariableDeclarationType(Var
, false, nullptr))
13547 // C++11 [class.static.data]p3: A static data member can be declared with
13548 // the constexpr specifier; if so, its declaration shall specify
13549 // a brace-or-equal-initializer.
13550 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13551 // the definition of a variable [...] or the declaration of a static data
13553 if (Var
->isConstexpr() && !Var
->isThisDeclarationADefinition() &&
13554 !Var
->isThisDeclarationADemotedDefinition()) {
13555 if (Var
->isStaticDataMember()) {
13556 // C++1z removes the relevant rule; the in-class declaration is always
13557 // a definition there.
13558 if (!getLangOpts().CPlusPlus17
&&
13559 !Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
13560 Diag(Var
->getLocation(),
13561 diag::err_constexpr_static_mem_var_requires_init
)
13563 Var
->setInvalidDecl();
13567 Diag(Var
->getLocation(), diag::err_invalid_constexpr_var_decl
);
13568 Var
->setInvalidDecl();
13573 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13575 if (!Var
->isInvalidDecl() &&
13576 Var
->getType().getAddressSpace() == LangAS::opencl_constant
&&
13577 Var
->getStorageClass() != SC_Extern
&& !Var
->getInit()) {
13578 bool HasConstExprDefaultConstructor
= false;
13579 if (CXXRecordDecl
*RD
= Var
->getType()->getAsCXXRecordDecl()) {
13580 for (auto *Ctor
: RD
->ctors()) {
13581 if (Ctor
->isConstexpr() && Ctor
->getNumParams() == 0 &&
13582 Ctor
->getMethodQualifiers().getAddressSpace() ==
13583 LangAS::opencl_constant
) {
13584 HasConstExprDefaultConstructor
= true;
13588 if (!HasConstExprDefaultConstructor
) {
13589 Diag(Var
->getLocation(), diag::err_opencl_constant_no_init
);
13590 Var
->setInvalidDecl();
13595 if (!Var
->isInvalidDecl() && RealDecl
->hasAttr
<LoaderUninitializedAttr
>()) {
13596 if (Var
->getStorageClass() == SC_Extern
) {
13597 Diag(Var
->getLocation(), diag::err_loader_uninitialized_extern_decl
)
13599 Var
->setInvalidDecl();
13602 if (RequireCompleteType(Var
->getLocation(), Var
->getType(),
13603 diag::err_typecheck_decl_incomplete_type
)) {
13604 Var
->setInvalidDecl();
13607 if (CXXRecordDecl
*RD
= Var
->getType()->getAsCXXRecordDecl()) {
13608 if (!RD
->hasTrivialDefaultConstructor()) {
13609 Diag(Var
->getLocation(), diag::err_loader_uninitialized_trivial_ctor
);
13610 Var
->setInvalidDecl();
13614 // The declaration is unitialized, no need for further checks.
13618 VarDecl::DefinitionKind DefKind
= Var
->isThisDeclarationADefinition();
13619 if (!Var
->isInvalidDecl() && DefKind
!= VarDecl::DeclarationOnly
&&
13620 Var
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13621 checkNonTrivialCUnion(Var
->getType(), Var
->getLocation(),
13622 NTCUC_DefaultInitializedObject
, NTCUK_Init
);
13626 case VarDecl::Definition
:
13627 if (!Var
->isStaticDataMember() || !Var
->getAnyInitializer())
13630 // We have an out-of-line definition of a static data member
13631 // that has an in-class initializer, so we type-check this like
13636 case VarDecl::DeclarationOnly
:
13637 // It's only a declaration.
13639 // Block scope. C99 6.7p7: If an identifier for an object is
13640 // declared with no linkage (C99 6.2.2p6), the type for the
13641 // object shall be complete.
13642 if (!Type
->isDependentType() && Var
->isLocalVarDecl() &&
13643 !Var
->hasLinkage() && !Var
->isInvalidDecl() &&
13644 RequireCompleteType(Var
->getLocation(), Type
,
13645 diag::err_typecheck_decl_incomplete_type
))
13646 Var
->setInvalidDecl();
13648 // Make sure that the type is not abstract.
13649 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
13650 RequireNonAbstractType(Var
->getLocation(), Type
,
13651 diag::err_abstract_type_in_decl
,
13652 AbstractVariableType
))
13653 Var
->setInvalidDecl();
13654 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
13655 Var
->getStorageClass() == SC_PrivateExtern
) {
13656 Diag(Var
->getLocation(), diag::warn_private_extern
);
13657 Diag(Var
->getLocation(), diag::note_private_extern
);
13660 if (Context
.getTargetInfo().allowDebugInfoForExternalRef() &&
13661 !Var
->isInvalidDecl() && !getLangOpts().CPlusPlus
)
13662 ExternalDeclarations
.push_back(Var
);
13666 case VarDecl::TentativeDefinition
:
13667 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13668 // object that has file scope without an initializer, and without a
13669 // storage-class specifier or with the storage-class specifier "static",
13670 // constitutes a tentative definition. Note: A tentative definition with
13671 // external linkage is valid (C99 6.2.2p5).
13672 if (!Var
->isInvalidDecl()) {
13673 if (const IncompleteArrayType
*ArrayT
13674 = Context
.getAsIncompleteArrayType(Type
)) {
13675 if (RequireCompleteSizedType(
13676 Var
->getLocation(), ArrayT
->getElementType(),
13677 diag::err_array_incomplete_or_sizeless_type
))
13678 Var
->setInvalidDecl();
13679 } else if (Var
->getStorageClass() == SC_Static
) {
13680 // C99 6.9.2p3: If the declaration of an identifier for an object is
13681 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13682 // declared type shall not be an incomplete type.
13683 // NOTE: code such as the following
13684 // static struct s;
13685 // struct s { int a; };
13686 // is accepted by gcc. Hence here we issue a warning instead of
13687 // an error and we do not invalidate the static declaration.
13688 // NOTE: to avoid multiple warnings, only check the first declaration.
13689 if (Var
->isFirstDecl())
13690 RequireCompleteType(Var
->getLocation(), Type
,
13691 diag::ext_typecheck_decl_incomplete_type
);
13695 // Record the tentative definition; we're done.
13696 if (!Var
->isInvalidDecl())
13697 TentativeDefinitions
.push_back(Var
);
13701 // Provide a specific diagnostic for uninitialized variable
13702 // definitions with incomplete array type.
13703 if (Type
->isIncompleteArrayType()) {
13704 if (Var
->isConstexpr())
13705 Diag(Var
->getLocation(), diag::err_constexpr_var_requires_const_init
)
13708 Diag(Var
->getLocation(),
13709 diag::err_typecheck_incomplete_array_needs_initializer
);
13710 Var
->setInvalidDecl();
13714 // Provide a specific diagnostic for uninitialized variable
13715 // definitions with reference type.
13716 if (Type
->isReferenceType()) {
13717 Diag(Var
->getLocation(), diag::err_reference_var_requires_init
)
13718 << Var
<< SourceRange(Var
->getLocation(), Var
->getLocation());
13722 // Do not attempt to type-check the default initializer for a
13723 // variable with dependent type.
13724 if (Type
->isDependentType())
13727 if (Var
->isInvalidDecl())
13730 if (!Var
->hasAttr
<AliasAttr
>()) {
13731 if (RequireCompleteType(Var
->getLocation(),
13732 Context
.getBaseElementType(Type
),
13733 diag::err_typecheck_decl_incomplete_type
)) {
13734 Var
->setInvalidDecl();
13741 // The variable can not have an abstract class type.
13742 if (RequireNonAbstractType(Var
->getLocation(), Type
,
13743 diag::err_abstract_type_in_decl
,
13744 AbstractVariableType
)) {
13745 Var
->setInvalidDecl();
13749 // Check for jumps past the implicit initializer. C++0x
13750 // clarifies that this applies to a "variable with automatic
13751 // storage duration", not a "local variable".
13752 // C++11 [stmt.dcl]p3
13753 // A program that jumps from a point where a variable with automatic
13754 // storage duration is not in scope to a point where it is in scope is
13755 // ill-formed unless the variable has scalar type, class type with a
13756 // trivial default constructor and a trivial destructor, a cv-qualified
13757 // version of one of these types, or an array of one of the preceding
13758 // types and is declared without an initializer.
13759 if (getLangOpts().CPlusPlus
&& Var
->hasLocalStorage()) {
13760 if (const RecordType
*Record
13761 = Context
.getBaseElementType(Type
)->getAs
<RecordType
>()) {
13762 CXXRecordDecl
*CXXRecord
= cast
<CXXRecordDecl
>(Record
->getDecl());
13763 // Mark the function (if we're in one) for further checking even if the
13764 // looser rules of C++11 do not require such checks, so that we can
13765 // diagnose incompatibilities with C++98.
13766 if (!CXXRecord
->isPOD())
13767 setFunctionHasBranchProtectedScope();
13770 // In OpenCL, we can't initialize objects in the __local address space,
13771 // even implicitly, so don't synthesize an implicit initializer.
13772 if (getLangOpts().OpenCL
&&
13773 Var
->getType().getAddressSpace() == LangAS::opencl_local
)
13775 // C++03 [dcl.init]p9:
13776 // If no initializer is specified for an object, and the
13777 // object is of (possibly cv-qualified) non-POD class type (or
13778 // array thereof), the object shall be default-initialized; if
13779 // the object is of const-qualified type, the underlying class
13780 // type shall have a user-declared default
13781 // constructor. Otherwise, if no initializer is specified for
13782 // a non- static object, the object and its subobjects, if
13783 // any, have an indeterminate initial value); if the object
13784 // or any of its subobjects are of const-qualified type, the
13785 // program is ill-formed.
13786 // C++0x [dcl.init]p11:
13787 // If no initializer is specified for an object, the object is
13788 // default-initialized; [...].
13789 InitializedEntity Entity
= InitializedEntity::InitializeVariable(Var
);
13790 InitializationKind Kind
13791 = InitializationKind::CreateDefault(Var
->getLocation());
13793 InitializationSequence
InitSeq(*this, Entity
, Kind
, std::nullopt
);
13794 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
, std::nullopt
);
13797 Var
->setInit(MaybeCreateExprWithCleanups(Init
.get()));
13798 // This is important for template substitution.
13799 Var
->setInitStyle(VarDecl::CallInit
);
13800 } else if (Init
.isInvalid()) {
13801 // If default-init fails, attach a recovery-expr initializer to track
13802 // that initialization was attempted and failed.
13803 auto RecoveryExpr
=
13804 CreateRecoveryExpr(Var
->getLocation(), Var
->getLocation(), {});
13805 if (RecoveryExpr
.get())
13806 Var
->setInit(RecoveryExpr
.get());
13809 CheckCompleteVariableDeclaration(Var
);
13813 void Sema::ActOnCXXForRangeDecl(Decl
*D
) {
13814 // If there is no declaration, there was an error parsing it. Ignore it.
13818 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
13820 Diag(D
->getLocation(), diag::err_for_range_decl_must_be_var
);
13821 D
->setInvalidDecl();
13825 VD
->setCXXForRangeDecl(true);
13827 // for-range-declaration cannot be given a storage class specifier.
13829 switch (VD
->getStorageClass()) {
13838 case SC_PrivateExtern
:
13849 // for-range-declaration cannot be given a storage class specifier con't.
13850 switch (VD
->getTSCSpec()) {
13851 case TSCS_thread_local
:
13854 case TSCS___thread
:
13855 case TSCS__Thread_local
:
13856 case TSCS_unspecified
:
13861 Diag(VD
->getOuterLocStart(), diag::err_for_range_storage_class
)
13863 D
->setInvalidDecl();
13867 StmtResult
Sema::ActOnCXXForRangeIdentifier(Scope
*S
, SourceLocation IdentLoc
,
13868 IdentifierInfo
*Ident
,
13869 ParsedAttributes
&Attrs
) {
13870 // C++1y [stmt.iter]p1:
13871 // A range-based for statement of the form
13872 // for ( for-range-identifier : for-range-initializer ) statement
13873 // is equivalent to
13874 // for ( auto&& for-range-identifier : for-range-initializer ) statement
13875 DeclSpec
DS(Attrs
.getPool().getFactory());
13877 const char *PrevSpec
;
13879 DS
.SetTypeSpecType(DeclSpec::TST_auto
, IdentLoc
, PrevSpec
, DiagID
,
13880 getPrintingPolicy());
13882 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::ForInit
);
13883 D
.SetIdentifier(Ident
, IdentLoc
);
13884 D
.takeAttributes(Attrs
);
13886 D
.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc
, /*lvalue*/ false),
13888 Decl
*Var
= ActOnDeclarator(S
, D
);
13889 cast
<VarDecl
>(Var
)->setCXXForRangeDecl(true);
13890 FinalizeDeclaration(Var
);
13891 return ActOnDeclStmt(FinalizeDeclaratorGroup(S
, DS
, Var
), IdentLoc
,
13892 Attrs
.Range
.getEnd().isValid() ? Attrs
.Range
.getEnd()
13896 void Sema::CheckCompleteVariableDeclaration(VarDecl
*var
) {
13897 if (var
->isInvalidDecl()) return;
13899 MaybeAddCUDAConstantAttr(var
);
13901 if (getLangOpts().OpenCL
) {
13902 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13904 if (var
->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13906 Diag(var
->getLocation(), diag::err_opencl_invalid_block_declaration
)
13908 var
->setInvalidDecl();
13913 // In Objective-C, don't allow jumps past the implicit initialization of a
13914 // local retaining variable.
13915 if (getLangOpts().ObjC
&&
13916 var
->hasLocalStorage()) {
13917 switch (var
->getType().getObjCLifetime()) {
13918 case Qualifiers::OCL_None
:
13919 case Qualifiers::OCL_ExplicitNone
:
13920 case Qualifiers::OCL_Autoreleasing
:
13923 case Qualifiers::OCL_Weak
:
13924 case Qualifiers::OCL_Strong
:
13925 setFunctionHasBranchProtectedScope();
13930 if (var
->hasLocalStorage() &&
13931 var
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
13932 setFunctionHasBranchProtectedScope();
13934 // Warn about externally-visible variables being defined without a
13935 // prior declaration. We only want to do this for global
13936 // declarations, but we also specifically need to avoid doing it for
13937 // class members because the linkage of an anonymous class can
13938 // change if it's later given a typedef name.
13939 if (var
->isThisDeclarationADefinition() &&
13940 var
->getDeclContext()->getRedeclContext()->isFileContext() &&
13941 var
->isExternallyVisible() && var
->hasLinkage() &&
13942 !var
->isInline() && !var
->getDescribedVarTemplate() &&
13943 !isa
<VarTemplatePartialSpecializationDecl
>(var
) &&
13944 !isTemplateInstantiation(var
->getTemplateSpecializationKind()) &&
13945 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations
,
13946 var
->getLocation())) {
13947 // Find a previous declaration that's not a definition.
13948 VarDecl
*prev
= var
->getPreviousDecl();
13949 while (prev
&& prev
->isThisDeclarationADefinition())
13950 prev
= prev
->getPreviousDecl();
13953 Diag(var
->getLocation(), diag::warn_missing_variable_declarations
) << var
;
13954 Diag(var
->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage
)
13955 << /* variable */ 0;
13959 // Cache the result of checking for constant initialization.
13960 std::optional
<bool> CacheHasConstInit
;
13961 const Expr
*CacheCulprit
= nullptr;
13962 auto checkConstInit
= [&]() mutable {
13963 if (!CacheHasConstInit
)
13964 CacheHasConstInit
= var
->getInit()->isConstantInitializer(
13965 Context
, var
->getType()->isReferenceType(), &CacheCulprit
);
13966 return *CacheHasConstInit
;
13969 if (var
->getTLSKind() == VarDecl::TLS_Static
) {
13970 if (var
->getType().isDestructedType()) {
13971 // GNU C++98 edits for __thread, [basic.start.term]p3:
13972 // The type of an object with thread storage duration shall not
13973 // have a non-trivial destructor.
13974 Diag(var
->getLocation(), diag::err_thread_nontrivial_dtor
);
13975 if (getLangOpts().CPlusPlus11
)
13976 Diag(var
->getLocation(), diag::note_use_thread_local
);
13977 } else if (getLangOpts().CPlusPlus
&& var
->hasInit()) {
13978 if (!checkConstInit()) {
13979 // GNU C++98 edits for __thread, [basic.start.init]p4:
13980 // An object of thread storage duration shall not require dynamic
13982 // FIXME: Need strict checking here.
13983 Diag(CacheCulprit
->getExprLoc(), diag::err_thread_dynamic_init
)
13984 << CacheCulprit
->getSourceRange();
13985 if (getLangOpts().CPlusPlus11
)
13986 Diag(var
->getLocation(), diag::note_use_thread_local
);
13992 if (!var
->getType()->isStructureType() && var
->hasInit() &&
13993 isa
<InitListExpr
>(var
->getInit())) {
13994 const auto *ILE
= cast
<InitListExpr
>(var
->getInit());
13995 unsigned NumInits
= ILE
->getNumInits();
13997 for (unsigned I
= 0; I
< NumInits
; ++I
) {
13998 const auto *Init
= ILE
->getInit(I
);
14001 const auto *SL
= dyn_cast
<StringLiteral
>(Init
->IgnoreImpCasts());
14005 unsigned NumConcat
= SL
->getNumConcatenated();
14006 // Diagnose missing comma in string array initialization.
14007 // Do not warn when all the elements in the initializer are concatenated
14008 // together. Do not warn for macros too.
14009 if (NumConcat
== 2 && !SL
->getBeginLoc().isMacroID()) {
14010 bool OnlyOneMissingComma
= true;
14011 for (unsigned J
= I
+ 1; J
< NumInits
; ++J
) {
14012 const auto *Init
= ILE
->getInit(J
);
14015 const auto *SLJ
= dyn_cast
<StringLiteral
>(Init
->IgnoreImpCasts());
14016 if (!SLJ
|| SLJ
->getNumConcatenated() > 1) {
14017 OnlyOneMissingComma
= false;
14022 if (OnlyOneMissingComma
) {
14023 SmallVector
<FixItHint
, 1> Hints
;
14024 for (unsigned i
= 0; i
< NumConcat
- 1; ++i
)
14025 Hints
.push_back(FixItHint::CreateInsertion(
14026 PP
.getLocForEndOfToken(SL
->getStrTokenLoc(i
)), ","));
14028 Diag(SL
->getStrTokenLoc(1),
14029 diag::warn_concatenated_literal_array_init
)
14031 Diag(SL
->getBeginLoc(),
14032 diag::note_concatenated_string_literal_silence
);
14034 // In any case, stop now.
14041 QualType type
= var
->getType();
14043 if (var
->hasAttr
<BlocksAttr
>())
14044 getCurFunction()->addByrefBlockVar(var
);
14046 Expr
*Init
= var
->getInit();
14047 bool GlobalStorage
= var
->hasGlobalStorage();
14048 bool IsGlobal
= GlobalStorage
&& !var
->isStaticLocal();
14049 QualType baseType
= Context
.getBaseElementType(type
);
14050 bool HasConstInit
= true;
14052 // Check whether the initializer is sufficiently constant.
14053 if (getLangOpts().CPlusPlus
&& !type
->isDependentType() && Init
&&
14054 !Init
->isValueDependent() &&
14055 (GlobalStorage
|| var
->isConstexpr() ||
14056 var
->mightBeUsableInConstantExpressions(Context
))) {
14057 // If this variable might have a constant initializer or might be usable in
14058 // constant expressions, check whether or not it actually is now. We can't
14059 // do this lazily, because the result might depend on things that change
14060 // later, such as which constexpr functions happen to be defined.
14061 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
14062 if (!getLangOpts().CPlusPlus11
) {
14063 // Prior to C++11, in contexts where a constant initializer is required,
14064 // the set of valid constant initializers is described by syntactic rules
14065 // in [expr.const]p2-6.
14066 // FIXME: Stricter checking for these rules would be useful for constinit /
14067 // -Wglobal-constructors.
14068 HasConstInit
= checkConstInit();
14070 // Compute and cache the constant value, and remember that we have a
14071 // constant initializer.
14072 if (HasConstInit
) {
14073 (void)var
->checkForConstantInitialization(Notes
);
14075 } else if (CacheCulprit
) {
14076 Notes
.emplace_back(CacheCulprit
->getExprLoc(),
14077 PDiag(diag::note_invalid_subexpr_in_const_expr
));
14078 Notes
.back().second
<< CacheCulprit
->getSourceRange();
14081 // Evaluate the initializer to see if it's a constant initializer.
14082 HasConstInit
= var
->checkForConstantInitialization(Notes
);
14085 if (HasConstInit
) {
14086 // FIXME: Consider replacing the initializer with a ConstantExpr.
14087 } else if (var
->isConstexpr()) {
14088 SourceLocation DiagLoc
= var
->getLocation();
14089 // If the note doesn't add any useful information other than a source
14090 // location, fold it into the primary diagnostic.
14091 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
14092 diag::note_invalid_subexpr_in_const_expr
) {
14093 DiagLoc
= Notes
[0].first
;
14096 Diag(DiagLoc
, diag::err_constexpr_var_requires_const_init
)
14097 << var
<< Init
->getSourceRange();
14098 for (unsigned I
= 0, N
= Notes
.size(); I
!= N
; ++I
)
14099 Diag(Notes
[I
].first
, Notes
[I
].second
);
14100 } else if (GlobalStorage
&& var
->hasAttr
<ConstInitAttr
>()) {
14101 auto *Attr
= var
->getAttr
<ConstInitAttr
>();
14102 Diag(var
->getLocation(), diag::err_require_constant_init_failed
)
14103 << Init
->getSourceRange();
14104 Diag(Attr
->getLocation(), diag::note_declared_required_constant_init_here
)
14105 << Attr
->getRange() << Attr
->isConstinit();
14106 for (auto &it
: Notes
)
14107 Diag(it
.first
, it
.second
);
14108 } else if (IsGlobal
&&
14109 !getDiagnostics().isIgnored(diag::warn_global_constructor
,
14110 var
->getLocation())) {
14111 // Warn about globals which don't have a constant initializer. Don't
14112 // warn about globals with a non-trivial destructor because we already
14113 // warned about them.
14114 CXXRecordDecl
*RD
= baseType
->getAsCXXRecordDecl();
14115 if (!(RD
&& !RD
->hasTrivialDestructor())) {
14116 // checkConstInit() here permits trivial default initialization even in
14117 // C++11 onwards, where such an initializer is not a constant initializer
14118 // but nonetheless doesn't require a global constructor.
14119 if (!checkConstInit())
14120 Diag(var
->getLocation(), diag::warn_global_constructor
)
14121 << Init
->getSourceRange();
14126 // Apply section attributes and pragmas to global variables.
14127 if (GlobalStorage
&& var
->isThisDeclarationADefinition() &&
14128 !inTemplateInstantiation()) {
14129 PragmaStack
<StringLiteral
*> *Stack
= nullptr;
14130 int SectionFlags
= ASTContext::PSF_Read
;
14131 if (var
->getType().isConstQualified()) {
14133 Stack
= &ConstSegStack
;
14135 Stack
= &BSSSegStack
;
14136 SectionFlags
|= ASTContext::PSF_Write
;
14138 } else if (var
->hasInit() && HasConstInit
) {
14139 Stack
= &DataSegStack
;
14140 SectionFlags
|= ASTContext::PSF_Write
;
14142 Stack
= &BSSSegStack
;
14143 SectionFlags
|= ASTContext::PSF_Write
;
14145 if (const SectionAttr
*SA
= var
->getAttr
<SectionAttr
>()) {
14146 if (SA
->getSyntax() == AttributeCommonInfo::AS_Declspec
)
14147 SectionFlags
|= ASTContext::PSF_Implicit
;
14148 UnifySection(SA
->getName(), SectionFlags
, var
);
14149 } else if (Stack
->CurrentValue
) {
14150 SectionFlags
|= ASTContext::PSF_Implicit
;
14151 auto SectionName
= Stack
->CurrentValue
->getString();
14152 var
->addAttr(SectionAttr::CreateImplicit(
14153 Context
, SectionName
, Stack
->CurrentPragmaLocation
,
14154 AttributeCommonInfo::AS_Pragma
, SectionAttr::Declspec_allocate
));
14155 if (UnifySection(SectionName
, SectionFlags
, var
))
14156 var
->dropAttr
<SectionAttr
>();
14159 // Apply the init_seg attribute if this has an initializer. If the
14160 // initializer turns out to not be dynamic, we'll end up ignoring this
14162 if (CurInitSeg
&& var
->getInit())
14163 var
->addAttr(InitSegAttr::CreateImplicit(Context
, CurInitSeg
->getString(),
14165 AttributeCommonInfo::AS_Pragma
));
14168 // All the following checks are C++ only.
14169 if (!getLangOpts().CPlusPlus
) {
14170 // If this variable must be emitted, add it as an initializer for the
14172 if (Context
.DeclMustBeEmitted(var
) && !ModuleScopes
.empty())
14173 Context
.addModuleInitializer(ModuleScopes
.back().Module
, var
);
14177 // Require the destructor.
14178 if (!type
->isDependentType())
14179 if (const RecordType
*recordType
= baseType
->getAs
<RecordType
>())
14180 FinalizeVarWithDestructor(var
, recordType
);
14182 // If this variable must be emitted, add it as an initializer for the current
14184 if (Context
.DeclMustBeEmitted(var
) && !ModuleScopes
.empty())
14185 Context
.addModuleInitializer(ModuleScopes
.back().Module
, var
);
14187 // Build the bindings if this is a structured binding declaration.
14188 if (auto *DD
= dyn_cast
<DecompositionDecl
>(var
))
14189 CheckCompleteDecompositionDeclaration(DD
);
14192 /// Check if VD needs to be dllexport/dllimport due to being in a
14193 /// dllexport/import function.
14194 void Sema::CheckStaticLocalForDllExport(VarDecl
*VD
) {
14195 assert(VD
->isStaticLocal());
14197 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(VD
->getParentFunctionOrMethod());
14199 // Find outermost function when VD is in lambda function.
14200 while (FD
&& !getDLLAttr(FD
) &&
14201 !FD
->hasAttr
<DLLExportStaticLocalAttr
>() &&
14202 !FD
->hasAttr
<DLLImportStaticLocalAttr
>()) {
14203 FD
= dyn_cast_or_null
<FunctionDecl
>(FD
->getParentFunctionOrMethod());
14209 // Static locals inherit dll attributes from their function.
14210 if (Attr
*A
= getDLLAttr(FD
)) {
14211 auto *NewAttr
= cast
<InheritableAttr
>(A
->clone(getASTContext()));
14212 NewAttr
->setInherited(true);
14213 VD
->addAttr(NewAttr
);
14214 } else if (Attr
*A
= FD
->getAttr
<DLLExportStaticLocalAttr
>()) {
14215 auto *NewAttr
= DLLExportAttr::CreateImplicit(getASTContext(), *A
);
14216 NewAttr
->setInherited(true);
14217 VD
->addAttr(NewAttr
);
14219 // Export this function to enforce exporting this static variable even
14220 // if it is not used in this compilation unit.
14221 if (!FD
->hasAttr
<DLLExportAttr
>())
14222 FD
->addAttr(NewAttr
);
14224 } else if (Attr
*A
= FD
->getAttr
<DLLImportStaticLocalAttr
>()) {
14225 auto *NewAttr
= DLLImportAttr::CreateImplicit(getASTContext(), *A
);
14226 NewAttr
->setInherited(true);
14227 VD
->addAttr(NewAttr
);
14231 void Sema::CheckThreadLocalForLargeAlignment(VarDecl
*VD
) {
14232 assert(VD
->getTLSKind());
14234 // Perform TLS alignment check here after attributes attached to the variable
14235 // which may affect the alignment have been processed. Only perform the check
14236 // if the target has a maximum TLS alignment (zero means no constraints).
14237 if (unsigned MaxAlign
= Context
.getTargetInfo().getMaxTLSAlign()) {
14238 // Protect the check so that it's not performed on dependent types and
14239 // dependent alignments (we can't determine the alignment in that case).
14240 if (!VD
->hasDependentAlignment()) {
14241 CharUnits MaxAlignChars
= Context
.toCharUnitsFromBits(MaxAlign
);
14242 if (Context
.getDeclAlign(VD
) > MaxAlignChars
) {
14243 Diag(VD
->getLocation(), diag::err_tls_var_aligned_over_maximum
)
14244 << (unsigned)Context
.getDeclAlign(VD
).getQuantity() << VD
14245 << (unsigned)MaxAlignChars
.getQuantity();
14251 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14252 /// any semantic actions necessary after any initializer has been attached.
14253 void Sema::FinalizeDeclaration(Decl
*ThisDecl
) {
14254 // Note that we are no longer parsing the initializer for this declaration.
14255 ParsingInitForAutoVars
.erase(ThisDecl
);
14257 VarDecl
*VD
= dyn_cast_or_null
<VarDecl
>(ThisDecl
);
14261 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14262 if (VD
->hasGlobalStorage() && VD
->isThisDeclarationADefinition() &&
14263 !inTemplateInstantiation() && !VD
->hasAttr
<SectionAttr
>()) {
14264 if (PragmaClangBSSSection
.Valid
)
14265 VD
->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14266 Context
, PragmaClangBSSSection
.SectionName
,
14267 PragmaClangBSSSection
.PragmaLocation
,
14268 AttributeCommonInfo::AS_Pragma
));
14269 if (PragmaClangDataSection
.Valid
)
14270 VD
->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14271 Context
, PragmaClangDataSection
.SectionName
,
14272 PragmaClangDataSection
.PragmaLocation
,
14273 AttributeCommonInfo::AS_Pragma
));
14274 if (PragmaClangRodataSection
.Valid
)
14275 VD
->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14276 Context
, PragmaClangRodataSection
.SectionName
,
14277 PragmaClangRodataSection
.PragmaLocation
,
14278 AttributeCommonInfo::AS_Pragma
));
14279 if (PragmaClangRelroSection
.Valid
)
14280 VD
->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14281 Context
, PragmaClangRelroSection
.SectionName
,
14282 PragmaClangRelroSection
.PragmaLocation
,
14283 AttributeCommonInfo::AS_Pragma
));
14286 if (auto *DD
= dyn_cast
<DecompositionDecl
>(ThisDecl
)) {
14287 for (auto *BD
: DD
->bindings()) {
14288 FinalizeDeclaration(BD
);
14292 checkAttributesAfterMerging(*this, *VD
);
14294 if (VD
->isStaticLocal())
14295 CheckStaticLocalForDllExport(VD
);
14297 if (VD
->getTLSKind())
14298 CheckThreadLocalForLargeAlignment(VD
);
14300 // Perform check for initializers of device-side global variables.
14301 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14302 // 7.5). We must also apply the same checks to all __shared__
14303 // variables whether they are local or not. CUDA also allows
14304 // constant initializers for __constant__ and __device__ variables.
14305 if (getLangOpts().CUDA
)
14306 checkAllowedCUDAInitializer(VD
);
14308 // Grab the dllimport or dllexport attribute off of the VarDecl.
14309 const InheritableAttr
*DLLAttr
= getDLLAttr(VD
);
14311 // Imported static data members cannot be defined out-of-line.
14312 if (const auto *IA
= dyn_cast_or_null
<DLLImportAttr
>(DLLAttr
)) {
14313 if (VD
->isStaticDataMember() && VD
->isOutOfLine() &&
14314 VD
->isThisDeclarationADefinition()) {
14315 // We allow definitions of dllimport class template static data members
14317 CXXRecordDecl
*Context
=
14318 cast
<CXXRecordDecl
>(VD
->getFirstDecl()->getDeclContext());
14319 bool IsClassTemplateMember
=
14320 isa
<ClassTemplatePartialSpecializationDecl
>(Context
) ||
14321 Context
->getDescribedClassTemplate();
14323 Diag(VD
->getLocation(),
14324 IsClassTemplateMember
14325 ? diag::warn_attribute_dllimport_static_field_definition
14326 : diag::err_attribute_dllimport_static_field_definition
);
14327 Diag(IA
->getLocation(), diag::note_attribute
);
14328 if (!IsClassTemplateMember
)
14329 VD
->setInvalidDecl();
14333 // dllimport/dllexport variables cannot be thread local, their TLS index
14334 // isn't exported with the variable.
14335 if (DLLAttr
&& VD
->getTLSKind()) {
14336 auto *F
= dyn_cast_or_null
<FunctionDecl
>(VD
->getParentFunctionOrMethod());
14337 if (F
&& getDLLAttr(F
)) {
14338 assert(VD
->isStaticLocal());
14339 // But if this is a static local in a dlimport/dllexport function, the
14340 // function will never be inlined, which means the var would never be
14341 // imported, so having it marked import/export is safe.
14343 Diag(VD
->getLocation(), diag::err_attribute_dll_thread_local
) << VD
14345 VD
->setInvalidDecl();
14349 if (UsedAttr
*Attr
= VD
->getAttr
<UsedAttr
>()) {
14350 if (!Attr
->isInherited() && !VD
->isThisDeclarationADefinition()) {
14351 Diag(Attr
->getLocation(), diag::warn_attribute_ignored_on_non_definition
)
14353 VD
->dropAttr
<UsedAttr
>();
14356 if (RetainAttr
*Attr
= VD
->getAttr
<RetainAttr
>()) {
14357 if (!Attr
->isInherited() && !VD
->isThisDeclarationADefinition()) {
14358 Diag(Attr
->getLocation(), diag::warn_attribute_ignored_on_non_definition
)
14360 VD
->dropAttr
<RetainAttr
>();
14364 const DeclContext
*DC
= VD
->getDeclContext();
14365 // If there's a #pragma GCC visibility in scope, and this isn't a class
14366 // member, set the visibility of this variable.
14367 if (DC
->getRedeclContext()->isFileContext() && VD
->isExternallyVisible())
14368 AddPushedVisibilityAttribute(VD
);
14370 // FIXME: Warn on unused var template partial specializations.
14371 if (VD
->isFileVarDecl() && !isa
<VarTemplatePartialSpecializationDecl
>(VD
))
14372 MarkUnusedFileScopedDecl(VD
);
14374 // Now we have parsed the initializer and can update the table of magic
14376 if (!VD
->hasAttr
<TypeTagForDatatypeAttr
>() ||
14377 !VD
->getType()->isIntegralOrEnumerationType())
14380 for (const auto *I
: ThisDecl
->specific_attrs
<TypeTagForDatatypeAttr
>()) {
14381 const Expr
*MagicValueExpr
= VD
->getInit();
14382 if (!MagicValueExpr
) {
14385 std::optional
<llvm::APSInt
> MagicValueInt
;
14386 if (!(MagicValueInt
= MagicValueExpr
->getIntegerConstantExpr(Context
))) {
14387 Diag(I
->getRange().getBegin(),
14388 diag::err_type_tag_for_datatype_not_ice
)
14389 << LangOpts
.CPlusPlus
<< MagicValueExpr
->getSourceRange();
14392 if (MagicValueInt
->getActiveBits() > 64) {
14393 Diag(I
->getRange().getBegin(),
14394 diag::err_type_tag_for_datatype_too_large
)
14395 << LangOpts
.CPlusPlus
<< MagicValueExpr
->getSourceRange();
14398 uint64_t MagicValue
= MagicValueInt
->getZExtValue();
14399 RegisterTypeTagForDatatype(I
->getArgumentKind(),
14401 I
->getMatchingCType(),
14402 I
->getLayoutCompatible(),
14403 I
->getMustBeNull());
14407 static bool hasDeducedAuto(DeclaratorDecl
*DD
) {
14408 auto *VD
= dyn_cast
<VarDecl
>(DD
);
14409 return VD
&& !VD
->getType()->hasAutoForTrailingReturnType();
14412 Sema::DeclGroupPtrTy
Sema::FinalizeDeclaratorGroup(Scope
*S
, const DeclSpec
&DS
,
14413 ArrayRef
<Decl
*> Group
) {
14414 SmallVector
<Decl
*, 8> Decls
;
14416 if (DS
.isTypeSpecOwned())
14417 Decls
.push_back(DS
.getRepAsDecl());
14419 DeclaratorDecl
*FirstDeclaratorInGroup
= nullptr;
14420 DecompositionDecl
*FirstDecompDeclaratorInGroup
= nullptr;
14421 bool DiagnosedMultipleDecomps
= false;
14422 DeclaratorDecl
*FirstNonDeducedAutoInGroup
= nullptr;
14423 bool DiagnosedNonDeducedAuto
= false;
14425 for (unsigned i
= 0, e
= Group
.size(); i
!= e
; ++i
) {
14426 if (Decl
*D
= Group
[i
]) {
14427 // For declarators, there are some additional syntactic-ish checks we need
14429 if (auto *DD
= dyn_cast
<DeclaratorDecl
>(D
)) {
14430 if (!FirstDeclaratorInGroup
)
14431 FirstDeclaratorInGroup
= DD
;
14432 if (!FirstDecompDeclaratorInGroup
)
14433 FirstDecompDeclaratorInGroup
= dyn_cast
<DecompositionDecl
>(D
);
14434 if (!FirstNonDeducedAutoInGroup
&& DS
.hasAutoTypeSpec() &&
14435 !hasDeducedAuto(DD
))
14436 FirstNonDeducedAutoInGroup
= DD
;
14438 if (FirstDeclaratorInGroup
!= DD
) {
14439 // A decomposition declaration cannot be combined with any other
14440 // declaration in the same group.
14441 if (FirstDecompDeclaratorInGroup
&& !DiagnosedMultipleDecomps
) {
14442 Diag(FirstDecompDeclaratorInGroup
->getLocation(),
14443 diag::err_decomp_decl_not_alone
)
14444 << FirstDeclaratorInGroup
->getSourceRange()
14445 << DD
->getSourceRange();
14446 DiagnosedMultipleDecomps
= true;
14449 // A declarator that uses 'auto' in any way other than to declare a
14450 // variable with a deduced type cannot be combined with any other
14451 // declarator in the same group.
14452 if (FirstNonDeducedAutoInGroup
&& !DiagnosedNonDeducedAuto
) {
14453 Diag(FirstNonDeducedAutoInGroup
->getLocation(),
14454 diag::err_auto_non_deduced_not_alone
)
14455 << FirstNonDeducedAutoInGroup
->getType()
14456 ->hasAutoForTrailingReturnType()
14457 << FirstDeclaratorInGroup
->getSourceRange()
14458 << DD
->getSourceRange();
14459 DiagnosedNonDeducedAuto
= true;
14464 Decls
.push_back(D
);
14468 if (DeclSpec::isDeclRep(DS
.getTypeSpecType())) {
14469 if (TagDecl
*Tag
= dyn_cast_or_null
<TagDecl
>(DS
.getRepAsDecl())) {
14470 handleTagNumbering(Tag
, S
);
14471 if (FirstDeclaratorInGroup
&& !Tag
->hasNameForLinkage() &&
14472 getLangOpts().CPlusPlus
)
14473 Context
.addDeclaratorForUnnamedTagDecl(Tag
, FirstDeclaratorInGroup
);
14477 return BuildDeclaratorGroup(Decls
);
14480 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14481 /// group, performing any necessary semantic checking.
14482 Sema::DeclGroupPtrTy
14483 Sema::BuildDeclaratorGroup(MutableArrayRef
<Decl
*> Group
) {
14484 // C++14 [dcl.spec.auto]p7: (DR1347)
14485 // If the type that replaces the placeholder type is not the same in each
14486 // deduction, the program is ill-formed.
14487 if (Group
.size() > 1) {
14489 VarDecl
*DeducedDecl
= nullptr;
14490 for (unsigned i
= 0, e
= Group
.size(); i
!= e
; ++i
) {
14491 VarDecl
*D
= dyn_cast
<VarDecl
>(Group
[i
]);
14492 if (!D
|| D
->isInvalidDecl())
14494 DeducedType
*DT
= D
->getType()->getContainedDeducedType();
14495 if (!DT
|| DT
->getDeducedType().isNull())
14497 if (Deduced
.isNull()) {
14498 Deduced
= DT
->getDeducedType();
14500 } else if (!Context
.hasSameType(DT
->getDeducedType(), Deduced
)) {
14501 auto *AT
= dyn_cast
<AutoType
>(DT
);
14502 auto Dia
= Diag(D
->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14503 diag::err_auto_different_deductions
)
14504 << (AT
? (unsigned)AT
->getKeyword() : 3) << Deduced
14505 << DeducedDecl
->getDeclName() << DT
->getDeducedType()
14506 << D
->getDeclName();
14507 if (DeducedDecl
->hasInit())
14508 Dia
<< DeducedDecl
->getInit()->getSourceRange();
14510 Dia
<< D
->getInit()->getSourceRange();
14511 D
->setInvalidDecl();
14517 ActOnDocumentableDecls(Group
);
14519 return DeclGroupPtrTy::make(
14520 DeclGroupRef::Create(Context
, Group
.data(), Group
.size()));
14523 void Sema::ActOnDocumentableDecl(Decl
*D
) {
14524 ActOnDocumentableDecls(D
);
14527 void Sema::ActOnDocumentableDecls(ArrayRef
<Decl
*> Group
) {
14528 // Don't parse the comment if Doxygen diagnostics are ignored.
14529 if (Group
.empty() || !Group
[0])
14532 if (Diags
.isIgnored(diag::warn_doc_param_not_found
,
14533 Group
[0]->getLocation()) &&
14534 Diags
.isIgnored(diag::warn_unknown_comment_command_name
,
14535 Group
[0]->getLocation()))
14538 if (Group
.size() >= 2) {
14539 // This is a decl group. Normally it will contain only declarations
14540 // produced from declarator list. But in case we have any definitions or
14541 // additional declaration references:
14542 // 'typedef struct S {} S;'
14543 // 'typedef struct S *S;'
14545 // FinalizeDeclaratorGroup adds these as separate declarations.
14546 Decl
*MaybeTagDecl
= Group
[0];
14547 if (MaybeTagDecl
&& isa
<TagDecl
>(MaybeTagDecl
)) {
14548 Group
= Group
.slice(1);
14552 // FIMXE: We assume every Decl in the group is in the same file.
14553 // This is false when preprocessor constructs the group from decls in
14554 // different files (e. g. macros or #include).
14555 Context
.attachCommentsToJustParsedDecls(Group
, &getPreprocessor());
14558 /// Common checks for a parameter-declaration that should apply to both function
14559 /// parameters and non-type template parameters.
14560 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope
*S
, Declarator
&D
) {
14561 // Check that there are no default arguments inside the type of this
14563 if (getLangOpts().CPlusPlus
)
14564 CheckExtraCXXDefaultArguments(D
);
14566 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14567 if (D
.getCXXScopeSpec().isSet()) {
14568 Diag(D
.getIdentifierLoc(), diag::err_qualified_param_declarator
)
14569 << D
.getCXXScopeSpec().getRange();
14572 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14573 // simple identifier except [...irrelevant cases...].
14574 switch (D
.getName().getKind()) {
14575 case UnqualifiedIdKind::IK_Identifier
:
14578 case UnqualifiedIdKind::IK_OperatorFunctionId
:
14579 case UnqualifiedIdKind::IK_ConversionFunctionId
:
14580 case UnqualifiedIdKind::IK_LiteralOperatorId
:
14581 case UnqualifiedIdKind::IK_ConstructorName
:
14582 case UnqualifiedIdKind::IK_DestructorName
:
14583 case UnqualifiedIdKind::IK_ImplicitSelfParam
:
14584 case UnqualifiedIdKind::IK_DeductionGuideName
:
14585 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name
)
14586 << GetNameForDeclarator(D
).getName();
14589 case UnqualifiedIdKind::IK_TemplateId
:
14590 case UnqualifiedIdKind::IK_ConstructorTemplateId
:
14591 // GetNameForDeclarator would not produce a useful name in this case.
14592 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name_template_id
);
14597 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14598 /// to introduce parameters into function prototype scope.
14599 Decl
*Sema::ActOnParamDeclarator(Scope
*S
, Declarator
&D
) {
14600 const DeclSpec
&DS
= D
.getDeclSpec();
14602 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14604 // C++03 [dcl.stc]p2 also permits 'auto'.
14605 StorageClass SC
= SC_None
;
14606 if (DS
.getStorageClassSpec() == DeclSpec::SCS_register
) {
14608 // In C++11, the 'register' storage class specifier is deprecated.
14609 // In C++17, it is not allowed, but we tolerate it as an extension.
14610 if (getLangOpts().CPlusPlus11
) {
14611 Diag(DS
.getStorageClassSpecLoc(),
14612 getLangOpts().CPlusPlus17
? diag::ext_register_storage_class
14613 : diag::warn_deprecated_register
)
14614 << FixItHint::CreateRemoval(DS
.getStorageClassSpecLoc());
14616 } else if (getLangOpts().CPlusPlus
&&
14617 DS
.getStorageClassSpec() == DeclSpec::SCS_auto
) {
14619 } else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
) {
14620 Diag(DS
.getStorageClassSpecLoc(),
14621 diag::err_invalid_storage_class_in_func_decl
);
14622 D
.getMutableDeclSpec().ClearStorageClassSpecs();
14625 if (DeclSpec::TSCS TSCS
= DS
.getThreadStorageClassSpec())
14626 Diag(DS
.getThreadStorageClassSpecLoc(), diag::err_invalid_thread
)
14627 << DeclSpec::getSpecifierName(TSCS
);
14628 if (DS
.isInlineSpecified())
14629 Diag(DS
.getInlineSpecLoc(), diag::err_inline_non_function
)
14630 << getLangOpts().CPlusPlus17
;
14631 if (DS
.hasConstexprSpecifier())
14632 Diag(DS
.getConstexprSpecLoc(), diag::err_invalid_constexpr
)
14633 << 0 << static_cast<int>(D
.getDeclSpec().getConstexprSpecifier());
14635 DiagnoseFunctionSpecifiers(DS
);
14637 CheckFunctionOrTemplateParamDeclarator(S
, D
);
14639 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
14640 QualType parmDeclType
= TInfo
->getType();
14642 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14643 IdentifierInfo
*II
= D
.getIdentifier();
14645 LookupResult
R(*this, II
, D
.getIdentifierLoc(), LookupOrdinaryName
,
14646 ForVisibleRedeclaration
);
14648 if (R
.isSingleResult()) {
14649 NamedDecl
*PrevDecl
= R
.getFoundDecl();
14650 if (PrevDecl
->isTemplateParameter()) {
14651 // Maybe we will complain about the shadowed template parameter.
14652 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
14653 // Just pretend that we didn't see the previous declaration.
14654 PrevDecl
= nullptr;
14655 } else if (S
->isDeclScope(PrevDecl
)) {
14656 Diag(D
.getIdentifierLoc(), diag::err_param_redefinition
) << II
;
14657 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
14659 // Recover by removing the name
14661 D
.SetIdentifier(nullptr, D
.getIdentifierLoc());
14662 D
.setInvalidType(true);
14667 // Temporarily put parameter variables in the translation unit, not
14668 // the enclosing context. This prevents them from accidentally
14669 // looking like class members in C++.
14671 CheckParameter(Context
.getTranslationUnitDecl(), D
.getBeginLoc(),
14672 D
.getIdentifierLoc(), II
, parmDeclType
, TInfo
, SC
);
14674 if (D
.isInvalidType())
14675 New
->setInvalidDecl();
14677 assert(S
->isFunctionPrototypeScope());
14678 assert(S
->getFunctionPrototypeDepth() >= 1);
14679 New
->setScopeInfo(S
->getFunctionPrototypeDepth() - 1,
14680 S
->getNextFunctionPrototypeIndex());
14682 // Add the parameter declaration into this scope.
14685 IdResolver
.AddDecl(New
);
14687 ProcessDeclAttributes(S
, New
, D
);
14689 if (D
.getDeclSpec().isModulePrivateSpecified())
14690 Diag(New
->getLocation(), diag::err_module_private_local
)
14691 << 1 << New
<< SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
14692 << FixItHint::CreateRemoval(D
.getDeclSpec().getModulePrivateSpecLoc());
14694 if (New
->hasAttr
<BlocksAttr
>()) {
14695 Diag(New
->getLocation(), diag::err_block_on_nonlocal
);
14698 if (getLangOpts().OpenCL
)
14699 deduceOpenCLAddressSpace(New
);
14704 /// Synthesizes a variable for a parameter arising from a
14706 ParmVarDecl
*Sema::BuildParmVarDeclForTypedef(DeclContext
*DC
,
14707 SourceLocation Loc
,
14709 /* FIXME: setting StartLoc == Loc.
14710 Would it be worth to modify callers so as to provide proper source
14711 location for the unnamed parameters, embedding the parameter's type? */
14712 ParmVarDecl
*Param
= ParmVarDecl::Create(Context
, DC
, Loc
, Loc
, nullptr,
14713 T
, Context
.getTrivialTypeSourceInfo(T
, Loc
),
14715 Param
->setImplicit();
14719 void Sema::DiagnoseUnusedParameters(ArrayRef
<ParmVarDecl
*> Parameters
) {
14720 // Don't diagnose unused-parameter errors in template instantiations; we
14721 // will already have done so in the template itself.
14722 if (inTemplateInstantiation())
14725 for (const ParmVarDecl
*Parameter
: Parameters
) {
14726 if (!Parameter
->isReferenced() && Parameter
->getDeclName() &&
14727 !Parameter
->hasAttr
<UnusedAttr
>()) {
14728 Diag(Parameter
->getLocation(), diag::warn_unused_parameter
)
14729 << Parameter
->getDeclName();
14734 void Sema::DiagnoseSizeOfParametersAndReturnValue(
14735 ArrayRef
<ParmVarDecl
*> Parameters
, QualType ReturnTy
, NamedDecl
*D
) {
14736 if (LangOpts
.NumLargeByValueCopy
== 0) // No check.
14739 // Warn if the return value is pass-by-value and larger than the specified
14741 if (!ReturnTy
->isDependentType() && ReturnTy
.isPODType(Context
)) {
14742 unsigned Size
= Context
.getTypeSizeInChars(ReturnTy
).getQuantity();
14743 if (Size
> LangOpts
.NumLargeByValueCopy
)
14744 Diag(D
->getLocation(), diag::warn_return_value_size
) << D
<< Size
;
14747 // Warn if any parameter is pass-by-value and larger than the specified
14749 for (const ParmVarDecl
*Parameter
: Parameters
) {
14750 QualType T
= Parameter
->getType();
14751 if (T
->isDependentType() || !T
.isPODType(Context
))
14753 unsigned Size
= Context
.getTypeSizeInChars(T
).getQuantity();
14754 if (Size
> LangOpts
.NumLargeByValueCopy
)
14755 Diag(Parameter
->getLocation(), diag::warn_parameter_size
)
14756 << Parameter
<< Size
;
14760 ParmVarDecl
*Sema::CheckParameter(DeclContext
*DC
, SourceLocation StartLoc
,
14761 SourceLocation NameLoc
, IdentifierInfo
*Name
,
14762 QualType T
, TypeSourceInfo
*TSInfo
,
14764 // In ARC, infer a lifetime qualifier for appropriate parameter types.
14765 if (getLangOpts().ObjCAutoRefCount
&&
14766 T
.getObjCLifetime() == Qualifiers::OCL_None
&&
14767 T
->isObjCLifetimeType()) {
14769 Qualifiers::ObjCLifetime lifetime
;
14771 // Special cases for arrays:
14772 // - if it's const, use __unsafe_unretained
14773 // - otherwise, it's an error
14774 if (T
->isArrayType()) {
14775 if (!T
.isConstQualified()) {
14776 if (DelayedDiagnostics
.shouldDelayDiagnostics())
14777 DelayedDiagnostics
.add(
14778 sema::DelayedDiagnostic::makeForbiddenType(
14779 NameLoc
, diag::err_arc_array_param_no_ownership
, T
, false));
14781 Diag(NameLoc
, diag::err_arc_array_param_no_ownership
)
14782 << TSInfo
->getTypeLoc().getSourceRange();
14784 lifetime
= Qualifiers::OCL_ExplicitNone
;
14786 lifetime
= T
->getObjCARCImplicitLifetime();
14788 T
= Context
.getLifetimeQualifiedType(T
, lifetime
);
14791 ParmVarDecl
*New
= ParmVarDecl::Create(Context
, DC
, StartLoc
, NameLoc
, Name
,
14792 Context
.getAdjustedParameterType(T
),
14793 TSInfo
, SC
, nullptr);
14795 // Make a note if we created a new pack in the scope of a lambda, so that
14796 // we know that references to that pack must also be expanded within the
14798 if (New
->isParameterPack())
14799 if (auto *LSI
= getEnclosingLambda())
14800 LSI
->LocalPacks
.push_back(New
);
14802 if (New
->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
14803 New
->getType().hasNonTrivialToPrimitiveCopyCUnion())
14804 checkNonTrivialCUnion(New
->getType(), New
->getLocation(),
14805 NTCUC_FunctionParam
, NTCUK_Destruct
|NTCUK_Copy
);
14807 // Parameters can not be abstract class types.
14808 // For record types, this is done by the AbstractClassUsageDiagnoser once
14809 // the class has been completely parsed.
14810 if (!CurContext
->isRecord() &&
14811 RequireNonAbstractType(NameLoc
, T
, diag::err_abstract_type_in_decl
,
14812 AbstractParamType
))
14813 New
->setInvalidDecl();
14815 // Parameter declarators cannot be interface types. All ObjC objects are
14816 // passed by reference.
14817 if (T
->isObjCObjectType()) {
14818 SourceLocation TypeEndLoc
=
14819 getLocForEndOfToken(TSInfo
->getTypeLoc().getEndLoc());
14821 diag::err_object_cannot_be_passed_returned_by_value
) << 1 << T
14822 << FixItHint::CreateInsertion(TypeEndLoc
, "*");
14823 T
= Context
.getObjCObjectPointerType(T
);
14827 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14828 // duration shall not be qualified by an address-space qualifier."
14829 // Since all parameters have automatic store duration, they can not have
14830 // an address space.
14831 if (T
.getAddressSpace() != LangAS::Default
&&
14832 // OpenCL allows function arguments declared to be an array of a type
14833 // to be qualified with an address space.
14834 !(getLangOpts().OpenCL
&&
14835 (T
->isArrayType() || T
.getAddressSpace() == LangAS::opencl_private
))) {
14836 Diag(NameLoc
, diag::err_arg_with_address_space
);
14837 New
->setInvalidDecl();
14840 // PPC MMA non-pointer types are not allowed as function argument types.
14841 if (Context
.getTargetInfo().getTriple().isPPC64() &&
14842 CheckPPCMMAType(New
->getOriginalType(), New
->getLocation())) {
14843 New
->setInvalidDecl();
14849 void Sema::ActOnFinishKNRParamDeclarations(Scope
*S
, Declarator
&D
,
14850 SourceLocation LocAfterDecls
) {
14851 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
14853 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14854 // in the declaration list shall have at least one declarator, those
14855 // declarators shall only declare identifiers from the identifier list, and
14856 // every identifier in the identifier list shall be declared.
14858 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14859 // identifiers it names shall be declared in the declaration list."
14861 // This is why we only diagnose in C99 and later. Note, the other conditions
14862 // listed are checked elsewhere.
14863 if (!FTI
.hasPrototype
) {
14864 for (int i
= FTI
.NumParams
; i
!= 0; /* decrement in loop */) {
14866 if (FTI
.Params
[i
].Param
== nullptr) {
14867 if (getLangOpts().C99
) {
14868 SmallString
<256> Code
;
14869 llvm::raw_svector_ostream(Code
)
14870 << " int " << FTI
.Params
[i
].Ident
->getName() << ";\n";
14871 Diag(FTI
.Params
[i
].IdentLoc
, diag::ext_param_not_declared
)
14872 << FTI
.Params
[i
].Ident
14873 << FixItHint::CreateInsertion(LocAfterDecls
, Code
);
14876 // Implicitly declare the argument as type 'int' for lack of a better
14878 AttributeFactory attrs
;
14879 DeclSpec
DS(attrs
);
14880 const char* PrevSpec
; // unused
14881 unsigned DiagID
; // unused
14882 DS
.SetTypeSpecType(DeclSpec::TST_int
, FTI
.Params
[i
].IdentLoc
, PrevSpec
,
14883 DiagID
, Context
.getPrintingPolicy());
14884 // Use the identifier location for the type source range.
14885 DS
.SetRangeStart(FTI
.Params
[i
].IdentLoc
);
14886 DS
.SetRangeEnd(FTI
.Params
[i
].IdentLoc
);
14887 Declarator
ParamD(DS
, ParsedAttributesView::none(),
14888 DeclaratorContext::KNRTypeList
);
14889 ParamD
.SetIdentifier(FTI
.Params
[i
].Ident
, FTI
.Params
[i
].IdentLoc
);
14890 FTI
.Params
[i
].Param
= ActOnParamDeclarator(S
, ParamD
);
14897 Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Declarator
&D
,
14898 MultiTemplateParamsArg TemplateParameterLists
,
14899 SkipBodyInfo
*SkipBody
, FnBodyKind BodyKind
) {
14900 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14901 assert(D
.isFunctionDeclarator() && "Not a function declarator!");
14902 Scope
*ParentScope
= FnBodyScope
->getParent();
14904 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14905 // we define a non-templated function definition, we will create a declaration
14906 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14907 // The base function declaration will have the equivalent of an `omp declare
14908 // variant` annotation which specifies the mangled definition as a
14909 // specialization function under the OpenMP context defined as part of the
14910 // `omp begin declare variant`.
14911 SmallVector
<FunctionDecl
*, 4> Bases
;
14912 if (LangOpts
.OpenMP
&& isInOpenMPDeclareVariantScope())
14913 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14914 ParentScope
, D
, TemplateParameterLists
, Bases
);
14916 D
.setFunctionDefinitionKind(FunctionDefinitionKind::Definition
);
14917 Decl
*DP
= HandleDeclarator(ParentScope
, D
, TemplateParameterLists
);
14918 Decl
*Dcl
= ActOnStartOfFunctionDef(FnBodyScope
, DP
, SkipBody
, BodyKind
);
14920 if (!Bases
.empty())
14921 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl
, Bases
);
14926 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl
*D
) {
14927 Consumer
.HandleInlineFunctionDefinition(D
);
14930 static bool FindPossiblePrototype(const FunctionDecl
*FD
,
14931 const FunctionDecl
*&PossiblePrototype
) {
14932 for (const FunctionDecl
*Prev
= FD
->getPreviousDecl(); Prev
;
14933 Prev
= Prev
->getPreviousDecl()) {
14934 // Ignore any declarations that occur in function or method
14935 // scope, because they aren't visible from the header.
14936 if (Prev
->getLexicalDeclContext()->isFunctionOrMethod())
14939 PossiblePrototype
= Prev
;
14940 return Prev
->getType()->isFunctionProtoType();
14946 ShouldWarnAboutMissingPrototype(const FunctionDecl
*FD
,
14947 const FunctionDecl
*&PossiblePrototype
) {
14948 // Don't warn about invalid declarations.
14949 if (FD
->isInvalidDecl())
14952 // Or declarations that aren't global.
14953 if (!FD
->isGlobal())
14956 // Don't warn about C++ member functions.
14957 if (isa
<CXXMethodDecl
>(FD
))
14960 // Don't warn about 'main'.
14961 if (isa
<TranslationUnitDecl
>(FD
->getDeclContext()->getRedeclContext()))
14962 if (IdentifierInfo
*II
= FD
->getIdentifier())
14963 if (II
->isStr("main") || II
->isStr("efi_main"))
14966 // Don't warn about inline functions.
14967 if (FD
->isInlined())
14970 // Don't warn about function templates.
14971 if (FD
->getDescribedFunctionTemplate())
14974 // Don't warn about function template specializations.
14975 if (FD
->isFunctionTemplateSpecialization())
14978 // Don't warn for OpenCL kernels.
14979 if (FD
->hasAttr
<OpenCLKernelAttr
>())
14982 // Don't warn on explicitly deleted functions.
14983 if (FD
->isDeleted())
14986 // Don't warn on implicitly local functions (such as having local-typed
14988 if (!FD
->isExternallyVisible())
14991 // If we were able to find a potential prototype, don't warn.
14992 if (FindPossiblePrototype(FD
, PossiblePrototype
))
14999 Sema::CheckForFunctionRedefinition(FunctionDecl
*FD
,
15000 const FunctionDecl
*EffectiveDefinition
,
15001 SkipBodyInfo
*SkipBody
) {
15002 const FunctionDecl
*Definition
= EffectiveDefinition
;
15004 !FD
->isDefined(Definition
, /*CheckForPendingFriendDefinition*/ true))
15007 if (Definition
->getFriendObjectKind() != Decl::FOK_None
) {
15008 if (FunctionDecl
*OrigDef
= Definition
->getInstantiatedFromMemberFunction()) {
15009 if (FunctionDecl
*OrigFD
= FD
->getInstantiatedFromMemberFunction()) {
15010 // A merged copy of the same function, instantiated as a member of
15011 // the same class, is OK.
15012 if (declaresSameEntity(OrigFD
, OrigDef
) &&
15013 declaresSameEntity(cast
<Decl
>(Definition
->getLexicalDeclContext()),
15014 cast
<Decl
>(FD
->getLexicalDeclContext())))
15020 if (canRedefineFunction(Definition
, getLangOpts()))
15023 // Don't emit an error when this is redefinition of a typo-corrected
15025 if (TypoCorrectedFunctionDefinitions
.count(Definition
))
15028 // If we don't have a visible definition of the function, and it's inline or
15029 // a template, skip the new definition.
15030 if (SkipBody
&& !hasVisibleDefinition(Definition
) &&
15031 (Definition
->getFormalLinkage() == InternalLinkage
||
15032 Definition
->isInlined() ||
15033 Definition
->getDescribedFunctionTemplate() ||
15034 Definition
->getNumTemplateParameterLists())) {
15035 SkipBody
->ShouldSkip
= true;
15036 SkipBody
->Previous
= const_cast<FunctionDecl
*>(Definition
);
15037 if (auto *TD
= Definition
->getDescribedFunctionTemplate())
15038 makeMergedDefinitionVisible(TD
);
15039 makeMergedDefinitionVisible(const_cast<FunctionDecl
*>(Definition
));
15043 if (getLangOpts().GNUMode
&& Definition
->isInlineSpecified() &&
15044 Definition
->getStorageClass() == SC_Extern
)
15045 Diag(FD
->getLocation(), diag::err_redefinition_extern_inline
)
15046 << FD
<< getLangOpts().CPlusPlus
;
15048 Diag(FD
->getLocation(), diag::err_redefinition
) << FD
;
15050 Diag(Definition
->getLocation(), diag::note_previous_definition
);
15051 FD
->setInvalidDecl();
15054 static void RebuildLambdaScopeInfo(CXXMethodDecl
*CallOperator
,
15056 CXXRecordDecl
*const LambdaClass
= CallOperator
->getParent();
15058 LambdaScopeInfo
*LSI
= S
.PushLambdaScope();
15059 LSI
->CallOperator
= CallOperator
;
15060 LSI
->Lambda
= LambdaClass
;
15061 LSI
->ReturnType
= CallOperator
->getReturnType();
15062 const LambdaCaptureDefault LCD
= LambdaClass
->getLambdaCaptureDefault();
15064 if (LCD
== LCD_None
)
15065 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_None
;
15066 else if (LCD
== LCD_ByCopy
)
15067 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_LambdaByval
;
15068 else if (LCD
== LCD_ByRef
)
15069 LSI
->ImpCaptureStyle
= CapturingScopeInfo::ImpCap_LambdaByref
;
15070 DeclarationNameInfo DNI
= CallOperator
->getNameInfo();
15072 LSI
->IntroducerRange
= DNI
.getCXXOperatorNameRange();
15073 LSI
->Mutable
= !CallOperator
->isConst();
15075 // Add the captures to the LSI so they can be noted as already
15076 // captured within tryCaptureVar.
15077 auto I
= LambdaClass
->field_begin();
15078 for (const auto &C
: LambdaClass
->captures()) {
15079 if (C
.capturesVariable()) {
15080 ValueDecl
*VD
= C
.getCapturedVar();
15081 if (VD
->isInitCapture())
15082 S
.CurrentInstantiationScope
->InstantiatedLocal(VD
, VD
);
15083 const bool ByRef
= C
.getCaptureKind() == LCK_ByRef
;
15084 LSI
->addCapture(VD
, /*IsBlock*/false, ByRef
,
15085 /*RefersToEnclosingVariableOrCapture*/true, C
.getLocation(),
15086 /*EllipsisLoc*/C
.isPackExpansion()
15087 ? C
.getEllipsisLoc() : SourceLocation(),
15088 I
->getType(), /*Invalid*/false);
15090 } else if (C
.capturesThis()) {
15091 LSI
->addThisCapture(/*Nested*/ false, C
.getLocation(), I
->getType(),
15092 C
.getCaptureKind() == LCK_StarThis
);
15094 LSI
->addVLATypeCapture(C
.getLocation(), I
->getCapturedVLAType(),
15101 Decl
*Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Decl
*D
,
15102 SkipBodyInfo
*SkipBody
,
15103 FnBodyKind BodyKind
) {
15105 // Parsing the function declaration failed in some way. Push on a fake scope
15106 // anyway so we can try to parse the function body.
15107 PushFunctionScope();
15108 PushExpressionEvaluationContext(ExprEvalContexts
.back().Context
);
15112 FunctionDecl
*FD
= nullptr;
15114 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
))
15115 FD
= FunTmpl
->getTemplatedDecl();
15117 FD
= cast
<FunctionDecl
>(D
);
15119 // Do not push if it is a lambda because one is already pushed when building
15120 // the lambda in ActOnStartOfLambdaDefinition().
15121 if (!isLambdaCallOperator(FD
))
15122 // [expr.const]/p14.1
15123 // An expression or conversion is in an immediate function context if it is
15124 // potentially evaluated and either: its innermost enclosing non-block scope
15125 // is a function parameter scope of an immediate function.
15126 PushExpressionEvaluationContext(
15127 FD
->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15128 : ExprEvalContexts
.back().Context
);
15130 // Check for defining attributes before the check for redefinition.
15131 if (const auto *Attr
= FD
->getAttr
<AliasAttr
>()) {
15132 Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << FD
<< 0;
15133 FD
->dropAttr
<AliasAttr
>();
15134 FD
->setInvalidDecl();
15136 if (const auto *Attr
= FD
->getAttr
<IFuncAttr
>()) {
15137 Diag(Attr
->getLocation(), diag::err_alias_is_definition
) << FD
<< 1;
15138 FD
->dropAttr
<IFuncAttr
>();
15139 FD
->setInvalidDecl();
15141 if (const auto *Attr
= FD
->getAttr
<TargetVersionAttr
>()) {
15142 if (!Context
.getTargetInfo().hasFeature("fmv") &&
15143 !Attr
->isDefaultVersion()) {
15144 // If function multi versioning disabled skip parsing function body
15145 // defined with non-default target_version attribute
15147 SkipBody
->ShouldSkip
= true;
15152 if (auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
)) {
15153 if (Ctor
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
&&
15154 Ctor
->isDefaultConstructor() &&
15155 Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
15156 // If this is an MS ABI dllexport default constructor, instantiate any
15157 // default arguments.
15158 InstantiateDefaultCtorDefaultArgs(Ctor
);
15162 // See if this is a redefinition. If 'will have body' (or similar) is already
15163 // set, then these checks were already performed when it was set.
15164 if (!FD
->willHaveBody() && !FD
->isLateTemplateParsed() &&
15165 !FD
->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15166 CheckForFunctionRedefinition(FD
, nullptr, SkipBody
);
15168 // If we're skipping the body, we're done. Don't enter the scope.
15169 if (SkipBody
&& SkipBody
->ShouldSkip
)
15173 // Mark this function as "will have a body eventually". This lets users to
15174 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15176 FD
->setWillHaveBody();
15178 // If we are instantiating a generic lambda call operator, push
15179 // a LambdaScopeInfo onto the function stack. But use the information
15180 // that's already been calculated (ActOnLambdaExpr) to prime the current
15181 // LambdaScopeInfo.
15182 // When the template operator is being specialized, the LambdaScopeInfo,
15183 // has to be properly restored so that tryCaptureVariable doesn't try
15184 // and capture any new variables. In addition when calculating potential
15185 // captures during transformation of nested lambdas, it is necessary to
15186 // have the LSI properly restored.
15187 if (isGenericLambdaCallOperatorSpecialization(FD
)) {
15188 assert(inTemplateInstantiation() &&
15189 "There should be an active template instantiation on the stack "
15190 "when instantiating a generic lambda!");
15191 RebuildLambdaScopeInfo(cast
<CXXMethodDecl
>(D
), *this);
15193 // Enter a new function scope
15194 PushFunctionScope();
15197 // Builtin functions cannot be defined.
15198 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
15199 if (!Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
) &&
15200 !Context
.BuiltinInfo
.isPredefinedRuntimeFunction(BuiltinID
)) {
15201 Diag(FD
->getLocation(), diag::err_builtin_definition
) << FD
;
15202 FD
->setInvalidDecl();
15206 // The return type of a function definition must be complete (C99 6.9.1p3),
15207 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
15208 QualType ResultType
= FD
->getReturnType();
15209 if (!ResultType
->isDependentType() && !ResultType
->isVoidType() &&
15210 !FD
->isInvalidDecl() && BodyKind
!= FnBodyKind::Delete
&&
15211 RequireCompleteType(FD
->getLocation(), ResultType
,
15212 diag::err_func_def_incomplete_result
))
15213 FD
->setInvalidDecl();
15216 PushDeclContext(FnBodyScope
, FD
);
15218 // Check the validity of our function parameters
15219 if (BodyKind
!= FnBodyKind::Delete
)
15220 CheckParmsForFunctionDef(FD
->parameters(),
15221 /*CheckParameterNames=*/true);
15223 // Add non-parameter declarations already in the function to the current
15226 for (Decl
*NPD
: FD
->decls()) {
15227 auto *NonParmDecl
= dyn_cast
<NamedDecl
>(NPD
);
15230 assert(!isa
<ParmVarDecl
>(NonParmDecl
) &&
15231 "parameters should not be in newly created FD yet");
15233 // If the decl has a name, make it accessible in the current scope.
15234 if (NonParmDecl
->getDeclName())
15235 PushOnScopeChains(NonParmDecl
, FnBodyScope
, /*AddToContext=*/false);
15237 // Similarly, dive into enums and fish their constants out, making them
15238 // accessible in this scope.
15239 if (auto *ED
= dyn_cast
<EnumDecl
>(NonParmDecl
)) {
15240 for (auto *EI
: ED
->enumerators())
15241 PushOnScopeChains(EI
, FnBodyScope
, /*AddToContext=*/false);
15246 // Introduce our parameters into the function scope
15247 for (auto *Param
: FD
->parameters()) {
15248 Param
->setOwningFunction(FD
);
15250 // If this has an identifier, add it to the scope stack.
15251 if (Param
->getIdentifier() && FnBodyScope
) {
15252 CheckShadow(FnBodyScope
, Param
);
15254 PushOnScopeChains(Param
, FnBodyScope
);
15258 // C++ [module.import/6] external definitions are not permitted in header
15259 // units. Deleted and Defaulted functions are implicitly inline (but the
15260 // inline state is not set at this point, so check the BodyKind explicitly).
15261 // FIXME: Consider an alternate location for the test where the inlined()
15262 // state is complete.
15263 if (getLangOpts().CPlusPlusModules
&& currentModuleIsHeaderUnit() &&
15264 !FD
->isInvalidDecl() && !FD
->isInlined() &&
15265 BodyKind
!= FnBodyKind::Delete
&& BodyKind
!= FnBodyKind::Default
&&
15266 FD
->getFormalLinkage() == Linkage::ExternalLinkage
&&
15267 !FD
->isTemplated() && !FD
->isTemplateInstantiation()) {
15268 assert(FD
->isThisDeclarationADefinition());
15269 Diag(FD
->getLocation(), diag::err_extern_def_in_header_unit
);
15270 FD
->setInvalidDecl();
15273 // Ensure that the function's exception specification is instantiated.
15274 if (const FunctionProtoType
*FPT
= FD
->getType()->getAs
<FunctionProtoType
>())
15275 ResolveExceptionSpec(D
->getLocation(), FPT
);
15277 // dllimport cannot be applied to non-inline function definitions.
15278 if (FD
->hasAttr
<DLLImportAttr
>() && !FD
->isInlined() &&
15279 !FD
->isTemplateInstantiation()) {
15280 assert(!FD
->hasAttr
<DLLExportAttr
>());
15281 Diag(FD
->getLocation(), diag::err_attribute_dllimport_function_definition
);
15282 FD
->setInvalidDecl();
15285 // We want to attach documentation to original Decl (which might be
15286 // a function template).
15287 ActOnDocumentableDecl(D
);
15288 if (getCurLexicalContext()->isObjCContainer() &&
15289 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl
&&
15290 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation
)
15291 Diag(FD
->getLocation(), diag::warn_function_def_in_objc_container
);
15296 /// Given the set of return statements within a function body,
15297 /// compute the variables that are subject to the named return value
15300 /// Each of the variables that is subject to the named return value
15301 /// optimization will be marked as NRVO variables in the AST, and any
15302 /// return statement that has a marked NRVO variable as its NRVO candidate can
15303 /// use the named return value optimization.
15305 /// This function applies a very simplistic algorithm for NRVO: if every return
15306 /// statement in the scope of a variable has the same NRVO candidate, that
15307 /// candidate is an NRVO variable.
15308 void Sema::computeNRVO(Stmt
*Body
, FunctionScopeInfo
*Scope
) {
15309 ReturnStmt
**Returns
= Scope
->Returns
.data();
15311 for (unsigned I
= 0, E
= Scope
->Returns
.size(); I
!= E
; ++I
) {
15312 if (const VarDecl
*NRVOCandidate
= Returns
[I
]->getNRVOCandidate()) {
15313 if (!NRVOCandidate
->isNRVOVariable())
15314 Returns
[I
]->setNRVOCandidate(nullptr);
15319 bool Sema::canDelayFunctionBody(const Declarator
&D
) {
15320 // We can't delay parsing the body of a constexpr function template (yet).
15321 if (D
.getDeclSpec().hasConstexprSpecifier())
15324 // We can't delay parsing the body of a function template with a deduced
15325 // return type (yet).
15326 if (D
.getDeclSpec().hasAutoTypeSpec()) {
15327 // If the placeholder introduces a non-deduced trailing return type,
15328 // we can still delay parsing it.
15329 if (D
.getNumTypeObjects()) {
15330 const auto &Outer
= D
.getTypeObject(D
.getNumTypeObjects() - 1);
15331 if (Outer
.Kind
== DeclaratorChunk::Function
&&
15332 Outer
.Fun
.hasTrailingReturnType()) {
15333 QualType Ty
= GetTypeFromParser(Outer
.Fun
.getTrailingReturnType());
15334 return Ty
.isNull() || !Ty
->isUndeducedType();
15343 bool Sema::canSkipFunctionBody(Decl
*D
) {
15344 // We cannot skip the body of a function (or function template) which is
15345 // constexpr, since we may need to evaluate its body in order to parse the
15346 // rest of the file.
15347 // We cannot skip the body of a function with an undeduced return type,
15348 // because any callers of that function need to know the type.
15349 if (const FunctionDecl
*FD
= D
->getAsFunction()) {
15350 if (FD
->isConstexpr())
15352 // We can't simply call Type::isUndeducedType here, because inside template
15353 // auto can be deduced to a dependent type, which is not considered
15355 if (FD
->getReturnType()->getContainedDeducedType())
15358 return Consumer
.shouldSkipFunctionBody(D
);
15361 Decl
*Sema::ActOnSkippedFunctionBody(Decl
*Decl
) {
15364 if (FunctionDecl
*FD
= Decl
->getAsFunction())
15365 FD
->setHasSkippedBody();
15366 else if (ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(Decl
))
15367 MD
->setHasSkippedBody();
15371 Decl
*Sema::ActOnFinishFunctionBody(Decl
*D
, Stmt
*BodyArg
) {
15372 return ActOnFinishFunctionBody(D
, BodyArg
, false);
15375 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15377 class ExitFunctionBodyRAII
{
15379 ExitFunctionBodyRAII(Sema
&S
, bool IsLambda
) : S(S
), IsLambda(IsLambda
) {}
15380 ~ExitFunctionBodyRAII() {
15382 S
.PopExpressionEvaluationContext();
15387 bool IsLambda
= false;
15390 static void diagnoseImplicitlyRetainedSelf(Sema
&S
) {
15391 llvm::DenseMap
<const BlockDecl
*, bool> EscapeInfo
;
15393 auto IsOrNestedInEscapingBlock
= [&](const BlockDecl
*BD
) {
15394 if (EscapeInfo
.count(BD
))
15395 return EscapeInfo
[BD
];
15398 const BlockDecl
*CurBD
= BD
;
15401 R
= !CurBD
->doesNotEscape();
15404 CurBD
= CurBD
->getParent()->getInnermostBlockDecl();
15407 return EscapeInfo
[BD
] = R
;
15410 // If the location where 'self' is implicitly retained is inside a escaping
15411 // block, emit a diagnostic.
15412 for (const std::pair
<SourceLocation
, const BlockDecl
*> &P
:
15413 S
.ImplicitlyRetainedSelfLocs
)
15414 if (IsOrNestedInEscapingBlock(P
.second
))
15415 S
.Diag(P
.first
, diag::warn_implicitly_retains_self
)
15416 << FixItHint::CreateInsertion(P
.first
, "self->");
15419 Decl
*Sema::ActOnFinishFunctionBody(Decl
*dcl
, Stmt
*Body
,
15420 bool IsInstantiation
) {
15421 FunctionScopeInfo
*FSI
= getCurFunction();
15422 FunctionDecl
*FD
= dcl
? dcl
->getAsFunction() : nullptr;
15424 if (FSI
->UsesFPIntrin
&& FD
&& !FD
->hasAttr
<StrictFPAttr
>())
15425 FD
->addAttr(StrictFPAttr::CreateImplicit(Context
));
15427 sema::AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
15428 sema::AnalysisBasedWarnings::Policy
*ActivePolicy
= nullptr;
15430 if (getLangOpts().Coroutines
&& FSI
->isCoroutine())
15431 CheckCompletedCoroutineBody(FD
, Body
);
15434 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15435 // one is already popped when finishing the lambda in BuildLambdaExpr().
15436 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15437 ExitFunctionBodyRAII
ExitRAII(*this, isLambdaCallOperator(FD
));
15441 FD
->setWillHaveBody(false);
15443 if (getLangOpts().CPlusPlus14
) {
15444 if (!FD
->isInvalidDecl() && Body
&& !FD
->isDependentContext() &&
15445 FD
->getReturnType()->isUndeducedType()) {
15446 // For a function with a deduced result type to return void,
15447 // the result type as written must be 'auto' or 'decltype(auto)',
15448 // possibly cv-qualified or constrained, but not ref-qualified.
15449 if (!FD
->getReturnType()->getAs
<AutoType
>()) {
15450 Diag(dcl
->getLocation(), diag::err_auto_fn_no_return_but_not_auto
)
15451 << FD
->getReturnType();
15452 FD
->setInvalidDecl();
15454 // Falling off the end of the function is the same as 'return;'.
15455 Expr
*Dummy
= nullptr;
15456 if (DeduceFunctionTypeFromReturnExpr(
15457 FD
, dcl
->getLocation(), Dummy
,
15458 FD
->getReturnType()->getAs
<AutoType
>()))
15459 FD
->setInvalidDecl();
15462 } else if (getLangOpts().CPlusPlus11
&& isLambdaCallOperator(FD
)) {
15463 // In C++11, we don't use 'auto' deduction rules for lambda call
15464 // operators because we don't support return type deduction.
15465 auto *LSI
= getCurLambda();
15466 if (LSI
->HasImplicitReturnType
) {
15467 deduceClosureReturnType(*LSI
);
15469 // C++11 [expr.prim.lambda]p4:
15470 // [...] if there are no return statements in the compound-statement
15471 // [the deduced type is] the type void
15473 LSI
->ReturnType
.isNull() ? Context
.VoidTy
: LSI
->ReturnType
;
15475 // Update the return type to the deduced type.
15476 const auto *Proto
= FD
->getType()->castAs
<FunctionProtoType
>();
15477 FD
->setType(Context
.getFunctionType(RetType
, Proto
->getParamTypes(),
15478 Proto
->getExtProtoInfo()));
15482 // If the function implicitly returns zero (like 'main') or is naked,
15483 // don't complain about missing return statements.
15484 if (FD
->hasImplicitReturnZero() || FD
->hasAttr
<NakedAttr
>())
15485 WP
.disableCheckFallThrough();
15487 // MSVC permits the use of pure specifier (=0) on function definition,
15488 // defined at class scope, warn about this non-standard construct.
15489 if (getLangOpts().MicrosoftExt
&& FD
->isPure() && !FD
->isOutOfLine())
15490 Diag(FD
->getLocation(), diag::ext_pure_function_definition
);
15492 if (!FD
->isInvalidDecl()) {
15493 // Don't diagnose unused parameters of defaulted, deleted or naked
15495 if (!FD
->isDeleted() && !FD
->isDefaulted() && !FD
->hasSkippedBody() &&
15496 !FD
->hasAttr
<NakedAttr
>())
15497 DiagnoseUnusedParameters(FD
->parameters());
15498 DiagnoseSizeOfParametersAndReturnValue(FD
->parameters(),
15499 FD
->getReturnType(), FD
);
15501 // If this is a structor, we need a vtable.
15502 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(FD
))
15503 MarkVTableUsed(FD
->getLocation(), Constructor
->getParent());
15504 else if (CXXDestructorDecl
*Destructor
=
15505 dyn_cast
<CXXDestructorDecl
>(FD
))
15506 MarkVTableUsed(FD
->getLocation(), Destructor
->getParent());
15508 // Try to apply the named return value optimization. We have to check
15509 // if we can do this here because lambdas keep return statements around
15510 // to deduce an implicit return type.
15511 if (FD
->getReturnType()->isRecordType() &&
15512 (!getLangOpts().CPlusPlus
|| !FD
->isDependentContext()))
15513 computeNRVO(Body
, FSI
);
15516 // GNU warning -Wmissing-prototypes:
15517 // Warn if a global function is defined without a previous
15518 // prototype declaration. This warning is issued even if the
15519 // definition itself provides a prototype. The aim is to detect
15520 // global functions that fail to be declared in header files.
15521 const FunctionDecl
*PossiblePrototype
= nullptr;
15522 if (ShouldWarnAboutMissingPrototype(FD
, PossiblePrototype
)) {
15523 Diag(FD
->getLocation(), diag::warn_missing_prototype
) << FD
;
15525 if (PossiblePrototype
) {
15526 // We found a declaration that is not a prototype,
15527 // but that could be a zero-parameter prototype
15528 if (TypeSourceInfo
*TI
= PossiblePrototype
->getTypeSourceInfo()) {
15529 TypeLoc TL
= TI
->getTypeLoc();
15530 if (FunctionNoProtoTypeLoc FTL
= TL
.getAs
<FunctionNoProtoTypeLoc
>())
15531 Diag(PossiblePrototype
->getLocation(),
15532 diag::note_declaration_not_a_prototype
)
15533 << (FD
->getNumParams() != 0)
15534 << (FD
->getNumParams() == 0 ? FixItHint::CreateInsertion(
15535 FTL
.getRParenLoc(), "void")
15539 // Returns true if the token beginning at this Loc is `const`.
15540 auto isLocAtConst
= [&](SourceLocation Loc
, const SourceManager
&SM
,
15541 const LangOptions
&LangOpts
) {
15542 std::pair
<FileID
, unsigned> LocInfo
= SM
.getDecomposedLoc(Loc
);
15543 if (LocInfo
.first
.isInvalid())
15546 bool Invalid
= false;
15547 StringRef Buffer
= SM
.getBufferData(LocInfo
.first
, &Invalid
);
15551 if (LocInfo
.second
> Buffer
.size())
15554 const char *LexStart
= Buffer
.data() + LocInfo
.second
;
15555 StringRef
StartTok(LexStart
, Buffer
.size() - LocInfo
.second
);
15557 return StartTok
.consume_front("const") &&
15558 (StartTok
.empty() || isWhitespace(StartTok
[0]) ||
15559 StartTok
.startswith("/*") || StartTok
.startswith("//"));
15562 auto findBeginLoc
= [&]() {
15563 // If the return type has `const` qualifier, we want to insert
15564 // `static` before `const` (and not before the typename).
15565 if ((FD
->getReturnType()->isAnyPointerType() &&
15566 FD
->getReturnType()->getPointeeType().isConstQualified()) ||
15567 FD
->getReturnType().isConstQualified()) {
15568 // But only do this if we can determine where the `const` is.
15570 if (isLocAtConst(FD
->getBeginLoc(), getSourceManager(),
15573 return FD
->getBeginLoc();
15575 return FD
->getTypeSpecStartLoc();
15577 Diag(FD
->getTypeSpecStartLoc(),
15578 diag::note_static_for_internal_linkage
)
15579 << /* function */ 1
15580 << (FD
->getStorageClass() == SC_None
15581 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15586 // We might not have found a prototype because we didn't wish to warn on
15587 // the lack of a missing prototype. Try again without the checks for
15588 // whether we want to warn on the missing prototype.
15589 if (!PossiblePrototype
)
15590 (void)FindPossiblePrototype(FD
, PossiblePrototype
);
15592 // If the function being defined does not have a prototype, then we may
15593 // need to diagnose it as changing behavior in C2x because we now know
15594 // whether the function accepts arguments or not. This only handles the
15595 // case where the definition has no prototype but does have parameters
15596 // and either there is no previous potential prototype, or the previous
15597 // potential prototype also has no actual prototype. This handles cases
15599 // void f(); void f(a) int a; {}
15600 // void g(a) int a; {}
15601 // See MergeFunctionDecl() for other cases of the behavior change
15602 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15603 // type without a prototype.
15604 if (!FD
->hasWrittenPrototype() && FD
->getNumParams() != 0 &&
15605 (!PossiblePrototype
|| (!PossiblePrototype
->hasWrittenPrototype() &&
15606 !PossiblePrototype
->isImplicit()))) {
15607 // The function definition has parameters, so this will change behavior
15608 // in C2x. If there is a possible prototype, it comes before the
15609 // function definition.
15610 // FIXME: The declaration may have already been diagnosed as being
15611 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15612 // there's no way to test for the "changes behavior" condition in
15613 // SemaType.cpp when forming the declaration's function type. So, we do
15614 // this awkward dance instead.
15616 // If we have a possible prototype and it declares a function with a
15617 // prototype, we don't want to diagnose it; if we have a possible
15618 // prototype and it has no prototype, it may have already been
15619 // diagnosed in SemaType.cpp as deprecated depending on whether
15620 // -Wstrict-prototypes is enabled. If we already warned about it being
15621 // deprecated, add a note that it also changes behavior. If we didn't
15622 // warn about it being deprecated (because the diagnostic is not
15623 // enabled), warn now that it is deprecated and changes behavior.
15625 // This K&R C function definition definitely changes behavior in C2x,
15627 Diag(FD
->getLocation(), diag::warn_non_prototype_changes_behavior
)
15628 << /*definition*/ 1 << /* not supported in C2x */ 0;
15630 // If we have a possible prototype for the function which is a user-
15631 // visible declaration, we already tested that it has no prototype.
15632 // This will change behavior in C2x. This gets a warning rather than a
15633 // note because it's the same behavior-changing problem as with the
15635 if (PossiblePrototype
)
15636 Diag(PossiblePrototype
->getLocation(),
15637 diag::warn_non_prototype_changes_behavior
)
15638 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15639 << /*definition*/ 1;
15642 // Warn on CPUDispatch with an actual body.
15643 if (FD
->isMultiVersion() && FD
->hasAttr
<CPUDispatchAttr
>() && Body
)
15644 if (const auto *CmpndBody
= dyn_cast
<CompoundStmt
>(Body
))
15645 if (!CmpndBody
->body_empty())
15646 Diag(CmpndBody
->body_front()->getBeginLoc(),
15647 diag::warn_dispatch_body_ignored
);
15649 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
15650 const CXXMethodDecl
*KeyFunction
;
15651 if (MD
->isOutOfLine() && (MD
= MD
->getCanonicalDecl()) &&
15653 (KeyFunction
= Context
.getCurrentKeyFunction(MD
->getParent())) &&
15654 MD
== KeyFunction
->getCanonicalDecl()) {
15655 // Update the key-function state if necessary for this ABI.
15656 if (FD
->isInlined() &&
15657 !Context
.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
15658 Context
.setNonKeyFunction(MD
);
15660 // If the newly-chosen key function is already defined, then we
15661 // need to mark the vtable as used retroactively.
15662 KeyFunction
= Context
.getCurrentKeyFunction(MD
->getParent());
15663 const FunctionDecl
*Definition
;
15664 if (KeyFunction
&& KeyFunction
->isDefined(Definition
))
15665 MarkVTableUsed(Definition
->getLocation(), MD
->getParent(), true);
15667 // We just defined they key function; mark the vtable as used.
15668 MarkVTableUsed(FD
->getLocation(), MD
->getParent(), true);
15674 (FD
== getCurFunctionDecl() || getCurLambda()->CallOperator
== FD
) &&
15675 "Function parsing confused");
15676 } else if (ObjCMethodDecl
*MD
= dyn_cast_or_null
<ObjCMethodDecl
>(dcl
)) {
15677 assert(MD
== getCurMethodDecl() && "Method parsing confused");
15679 if (!MD
->isInvalidDecl()) {
15680 DiagnoseSizeOfParametersAndReturnValue(MD
->parameters(),
15681 MD
->getReturnType(), MD
);
15684 computeNRVO(Body
, FSI
);
15686 if (FSI
->ObjCShouldCallSuper
) {
15687 Diag(MD
->getEndLoc(), diag::warn_objc_missing_super_call
)
15688 << MD
->getSelector().getAsString();
15689 FSI
->ObjCShouldCallSuper
= false;
15691 if (FSI
->ObjCWarnForNoDesignatedInitChain
) {
15692 const ObjCMethodDecl
*InitMethod
= nullptr;
15693 bool isDesignated
=
15694 MD
->isDesignatedInitializerForTheInterface(&InitMethod
);
15695 assert(isDesignated
&& InitMethod
);
15696 (void)isDesignated
;
15698 auto superIsNSObject
= [&](const ObjCMethodDecl
*MD
) {
15699 auto IFace
= MD
->getClassInterface();
15702 auto SuperD
= IFace
->getSuperClass();
15705 return SuperD
->getIdentifier() ==
15706 NSAPIObj
->getNSClassId(NSAPI::ClassId_NSObject
);
15708 // Don't issue this warning for unavailable inits or direct subclasses
15710 if (!MD
->isUnavailable() && !superIsNSObject(MD
)) {
15711 Diag(MD
->getLocation(),
15712 diag::warn_objc_designated_init_missing_super_call
);
15713 Diag(InitMethod
->getLocation(),
15714 diag::note_objc_designated_init_marked_here
);
15716 FSI
->ObjCWarnForNoDesignatedInitChain
= false;
15718 if (FSI
->ObjCWarnForNoInitDelegation
) {
15719 // Don't issue this warning for unavaialable inits.
15720 if (!MD
->isUnavailable())
15721 Diag(MD
->getLocation(),
15722 diag::warn_objc_secondary_init_missing_init_call
);
15723 FSI
->ObjCWarnForNoInitDelegation
= false;
15726 diagnoseImplicitlyRetainedSelf(*this);
15728 // Parsing the function declaration failed in some way. Pop the fake scope
15730 PopFunctionScopeInfo(ActivePolicy
, dcl
);
15734 if (Body
&& FSI
->HasPotentialAvailabilityViolations
)
15735 DiagnoseUnguardedAvailabilityViolations(dcl
);
15737 assert(!FSI
->ObjCShouldCallSuper
&&
15738 "This should only be set for ObjC methods, which should have been "
15739 "handled in the block above.");
15741 // Verify and clean out per-function state.
15742 if (Body
&& (!FD
|| !FD
->isDefaulted())) {
15743 // C++ constructors that have function-try-blocks can't have return
15744 // statements in the handlers of that block. (C++ [except.handle]p14)
15746 if (FD
&& isa
<CXXConstructorDecl
>(FD
) && isa
<CXXTryStmt
>(Body
))
15747 DiagnoseReturnInConstructorExceptionHandler(cast
<CXXTryStmt
>(Body
));
15749 // Verify that gotos and switch cases don't jump into scopes illegally.
15750 if (FSI
->NeedsScopeChecking() && !PP
.isCodeCompletionEnabled())
15751 DiagnoseInvalidJumps(Body
);
15753 if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(dcl
)) {
15754 if (!Destructor
->getParent()->isDependentType())
15755 CheckDestructor(Destructor
);
15757 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
15758 Destructor
->getParent());
15761 // If any errors have occurred, clear out any temporaries that may have
15762 // been leftover. This ensures that these temporaries won't be picked up
15763 // for deletion in some later function.
15764 if (hasUncompilableErrorOccurred() ||
15765 getDiagnostics().getSuppressAllDiagnostics()) {
15766 DiscardCleanupsInEvaluationContext();
15768 if (!hasUncompilableErrorOccurred() && !isa
<FunctionTemplateDecl
>(dcl
)) {
15769 // Since the body is valid, issue any analysis-based warnings that are
15771 ActivePolicy
= &WP
;
15774 if (!IsInstantiation
&& FD
&& FD
->isConstexpr() && !FD
->isInvalidDecl() &&
15775 !CheckConstexprFunctionDefinition(FD
, CheckConstexprKind::Diagnose
))
15776 FD
->setInvalidDecl();
15778 if (FD
&& FD
->hasAttr
<NakedAttr
>()) {
15779 for (const Stmt
*S
: Body
->children()) {
15780 // Allow local register variables without initializer as they don't
15781 // require prologue.
15782 bool RegisterVariables
= false;
15783 if (auto *DS
= dyn_cast
<DeclStmt
>(S
)) {
15784 for (const auto *Decl
: DS
->decls()) {
15785 if (const auto *Var
= dyn_cast
<VarDecl
>(Decl
)) {
15786 RegisterVariables
=
15787 Var
->hasAttr
<AsmLabelAttr
>() && !Var
->hasInit();
15788 if (!RegisterVariables
)
15793 if (RegisterVariables
)
15795 if (!isa
<AsmStmt
>(S
) && !isa
<NullStmt
>(S
)) {
15796 Diag(S
->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function
);
15797 Diag(FD
->getAttr
<NakedAttr
>()->getLocation(), diag::note_attribute
);
15798 FD
->setInvalidDecl();
15804 assert(ExprCleanupObjects
.size() ==
15805 ExprEvalContexts
.back().NumCleanupObjects
&&
15806 "Leftover temporaries in function");
15807 assert(!Cleanup
.exprNeedsCleanups() &&
15808 "Unaccounted cleanups in function");
15809 assert(MaybeODRUseExprs
.empty() &&
15810 "Leftover expressions for odr-use checking");
15812 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15813 // the declaration context below. Otherwise, we're unable to transform
15814 // 'this' expressions when transforming immediate context functions.
15816 if (!IsInstantiation
)
15819 PopFunctionScopeInfo(ActivePolicy
, dcl
);
15820 // If any errors have occurred, clear out any temporaries that may have
15821 // been leftover. This ensures that these temporaries won't be picked up for
15822 // deletion in some later function.
15823 if (hasUncompilableErrorOccurred()) {
15824 DiscardCleanupsInEvaluationContext();
15827 if (FD
&& ((LangOpts
.OpenMP
&& (LangOpts
.OpenMPIsDevice
||
15828 !LangOpts
.OMPTargetTriples
.empty())) ||
15829 LangOpts
.CUDA
|| LangOpts
.SYCLIsDevice
)) {
15830 auto ES
= getEmissionStatus(FD
);
15831 if (ES
== Sema::FunctionEmissionStatus::Emitted
||
15832 ES
== Sema::FunctionEmissionStatus::Unknown
)
15833 DeclsToCheckForDeferredDiags
.insert(FD
);
15836 if (FD
&& !FD
->isDeleted())
15837 checkTypeSupport(FD
->getType(), FD
->getLocation(), FD
);
15842 /// When we finish delayed parsing of an attribute, we must attach it to the
15844 void Sema::ActOnFinishDelayedAttribute(Scope
*S
, Decl
*D
,
15845 ParsedAttributes
&Attrs
) {
15846 // Always attach attributes to the underlying decl.
15847 if (TemplateDecl
*TD
= dyn_cast
<TemplateDecl
>(D
))
15848 D
= TD
->getTemplatedDecl();
15849 ProcessDeclAttributeList(S
, D
, Attrs
);
15851 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(D
))
15852 if (Method
->isStatic())
15853 checkThisInStaticMemberFunctionAttributes(Method
);
15856 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15857 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15858 NamedDecl
*Sema::ImplicitlyDefineFunction(SourceLocation Loc
,
15859 IdentifierInfo
&II
, Scope
*S
) {
15860 // It is not valid to implicitly define a function in C2x.
15861 assert(LangOpts
.implicitFunctionsAllowed() &&
15862 "Implicit function declarations aren't allowed in this language mode");
15864 // Find the scope in which the identifier is injected and the corresponding
15866 // FIXME: C89 does not say what happens if there is no enclosing block scope.
15867 // In that case, we inject the declaration into the translation unit scope
15869 Scope
*BlockScope
= S
;
15870 while (!BlockScope
->isCompoundStmtScope() && BlockScope
->getParent())
15871 BlockScope
= BlockScope
->getParent();
15873 Scope
*ContextScope
= BlockScope
;
15874 while (!ContextScope
->getEntity())
15875 ContextScope
= ContextScope
->getParent();
15876 ContextRAII
SavedContext(*this, ContextScope
->getEntity());
15878 // Before we produce a declaration for an implicitly defined
15879 // function, see whether there was a locally-scoped declaration of
15880 // this name as a function or variable. If so, use that
15881 // (non-visible) declaration, and complain about it.
15882 NamedDecl
*ExternCPrev
= findLocallyScopedExternCDecl(&II
);
15884 // We still need to inject the function into the enclosing block scope so
15885 // that later (non-call) uses can see it.
15886 PushOnScopeChains(ExternCPrev
, BlockScope
, /*AddToContext*/false);
15888 // C89 footnote 38:
15889 // If in fact it is not defined as having type "function returning int",
15890 // the behavior is undefined.
15891 if (!isa
<FunctionDecl
>(ExternCPrev
) ||
15892 !Context
.typesAreCompatible(
15893 cast
<FunctionDecl
>(ExternCPrev
)->getType(),
15894 Context
.getFunctionNoProtoType(Context
.IntTy
))) {
15895 Diag(Loc
, diag::ext_use_out_of_scope_declaration
)
15896 << ExternCPrev
<< !getLangOpts().C99
;
15897 Diag(ExternCPrev
->getLocation(), diag::note_previous_declaration
);
15898 return ExternCPrev
;
15902 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
15904 if (II
.getName().startswith("__builtin_"))
15905 diag_id
= diag::warn_builtin_unknown
;
15906 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15907 else if (getLangOpts().C99
)
15908 diag_id
= diag::ext_implicit_function_decl_c99
;
15910 diag_id
= diag::warn_implicit_function_decl
;
15912 TypoCorrection Corrected
;
15913 // Because typo correction is expensive, only do it if the implicit
15914 // function declaration is going to be treated as an error.
15916 // Perform the correction before issuing the main diagnostic, as some
15917 // consumers use typo-correction callbacks to enhance the main diagnostic.
15918 if (S
&& !ExternCPrev
&&
15919 (Diags
.getDiagnosticLevel(diag_id
, Loc
) >= DiagnosticsEngine::Error
)) {
15920 DeclFilterCCC
<FunctionDecl
> CCC
{};
15921 Corrected
= CorrectTypo(DeclarationNameInfo(&II
, Loc
), LookupOrdinaryName
,
15922 S
, nullptr, CCC
, CTK_NonError
);
15925 Diag(Loc
, diag_id
) << &II
;
15927 // If the correction is going to suggest an implicitly defined function,
15928 // skip the correction as not being a particularly good idea.
15929 bool Diagnose
= true;
15930 if (const auto *D
= Corrected
.getCorrectionDecl())
15931 Diagnose
= !D
->isImplicit();
15933 diagnoseTypo(Corrected
, PDiag(diag::note_function_suggestion
),
15934 /*ErrorRecovery*/ false);
15937 // If we found a prior declaration of this function, don't bother building
15938 // another one. We've already pushed that one into scope, so there's nothing
15941 return ExternCPrev
;
15943 // Set a Declarator for the implicit definition: int foo();
15945 AttributeFactory attrFactory
;
15946 DeclSpec
DS(attrFactory
);
15948 bool Error
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, Dummy
, DiagID
,
15949 Context
.getPrintingPolicy());
15950 (void)Error
; // Silence warning.
15951 assert(!Error
&& "Error setting up implicit decl!");
15952 SourceLocation NoLoc
;
15953 Declarator
D(DS
, ParsedAttributesView::none(), DeclaratorContext::Block
);
15954 D
.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15955 /*IsAmbiguous=*/false,
15956 /*LParenLoc=*/NoLoc
,
15957 /*Params=*/nullptr,
15959 /*EllipsisLoc=*/NoLoc
,
15960 /*RParenLoc=*/NoLoc
,
15961 /*RefQualifierIsLvalueRef=*/true,
15962 /*RefQualifierLoc=*/NoLoc
,
15963 /*MutableLoc=*/NoLoc
, EST_None
,
15964 /*ESpecRange=*/SourceRange(),
15965 /*Exceptions=*/nullptr,
15966 /*ExceptionRanges=*/nullptr,
15967 /*NumExceptions=*/0,
15968 /*NoexceptExpr=*/nullptr,
15969 /*ExceptionSpecTokens=*/nullptr,
15970 /*DeclsInPrototype=*/std::nullopt
,
15972 std::move(DS
.getAttributes()), SourceLocation());
15973 D
.SetIdentifier(&II
, Loc
);
15975 // Insert this function into the enclosing block scope.
15976 FunctionDecl
*FD
= cast
<FunctionDecl
>(ActOnDeclarator(BlockScope
, D
));
15979 AddKnownFunctionAttributes(FD
);
15984 /// If this function is a C++ replaceable global allocation function
15985 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15986 /// adds any function attributes that we know a priori based on the standard.
15988 /// We need to check for duplicate attributes both here and where user-written
15989 /// attributes are applied to declarations.
15990 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15991 FunctionDecl
*FD
) {
15992 if (FD
->isInvalidDecl())
15995 if (FD
->getDeclName().getCXXOverloadedOperator() != OO_New
&&
15996 FD
->getDeclName().getCXXOverloadedOperator() != OO_Array_New
)
15999 std::optional
<unsigned> AlignmentParam
;
16000 bool IsNothrow
= false;
16001 if (!FD
->isReplaceableGlobalAllocationFunction(&AlignmentParam
, &IsNothrow
))
16004 // C++2a [basic.stc.dynamic.allocation]p4:
16005 // An allocation function that has a non-throwing exception specification
16006 // indicates failure by returning a null pointer value. Any other allocation
16007 // function never returns a null pointer value and indicates failure only by
16008 // throwing an exception [...]
16009 if (!IsNothrow
&& !FD
->hasAttr
<ReturnsNonNullAttr
>())
16010 FD
->addAttr(ReturnsNonNullAttr::CreateImplicit(Context
, FD
->getLocation()));
16012 // C++2a [basic.stc.dynamic.allocation]p2:
16013 // An allocation function attempts to allocate the requested amount of
16014 // storage. [...] If the request succeeds, the value returned by a
16015 // replaceable allocation function is a [...] pointer value p0 different
16016 // from any previously returned value p1 [...]
16018 // However, this particular information is being added in codegen,
16019 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16021 // C++2a [basic.stc.dynamic.allocation]p2:
16022 // An allocation function attempts to allocate the requested amount of
16023 // storage. If it is successful, it returns the address of the start of a
16024 // block of storage whose length in bytes is at least as large as the
16026 if (!FD
->hasAttr
<AllocSizeAttr
>()) {
16027 FD
->addAttr(AllocSizeAttr::CreateImplicit(
16028 Context
, /*ElemSizeParam=*/ParamIdx(1, FD
),
16029 /*NumElemsParam=*/ParamIdx(), FD
->getLocation()));
16032 // C++2a [basic.stc.dynamic.allocation]p3:
16033 // For an allocation function [...], the pointer returned on a successful
16034 // call shall represent the address of storage that is aligned as follows:
16035 // (3.1) If the allocation function takes an argument of type
16036 // std​::​align_Âval_Ât, the storage will have the alignment
16037 // specified by the value of this argument.
16038 if (AlignmentParam
&& !FD
->hasAttr
<AllocAlignAttr
>()) {
16039 FD
->addAttr(AllocAlignAttr::CreateImplicit(
16040 Context
, ParamIdx(*AlignmentParam
, FD
), FD
->getLocation()));
16044 // C++2a [basic.stc.dynamic.allocation]p3:
16045 // For an allocation function [...], the pointer returned on a successful
16046 // call shall represent the address of storage that is aligned as follows:
16047 // (3.2) Otherwise, if the allocation function is named operator new[],
16048 // the storage is aligned for any object that does not have
16049 // new-extended alignment ([basic.align]) and is no larger than the
16051 // (3.3) Otherwise, the storage is aligned for any object that does not
16052 // have new-extended alignment and is of the requested size.
16055 /// Adds any function attributes that we know a priori based on
16056 /// the declaration of this function.
16058 /// These attributes can apply both to implicitly-declared builtins
16059 /// (like __builtin___printf_chk) or to library-declared functions
16060 /// like NSLog or printf.
16062 /// We need to check for duplicate attributes both here and where user-written
16063 /// attributes are applied to declarations.
16064 void Sema::AddKnownFunctionAttributes(FunctionDecl
*FD
) {
16065 if (FD
->isInvalidDecl())
16068 // If this is a built-in function, map its builtin attributes to
16069 // actual attributes.
16070 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
16071 // Handle printf-formatting attributes.
16072 unsigned FormatIdx
;
16074 if (Context
.BuiltinInfo
.isPrintfLike(BuiltinID
, FormatIdx
, HasVAListArg
)) {
16075 if (!FD
->hasAttr
<FormatAttr
>()) {
16076 const char *fmt
= "printf";
16077 unsigned int NumParams
= FD
->getNumParams();
16078 if (FormatIdx
< NumParams
&& // NumParams may be 0 (e.g. vfprintf)
16079 FD
->getParamDecl(FormatIdx
)->getType()->isObjCObjectPointerType())
16081 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
16082 &Context
.Idents
.get(fmt
),
16084 HasVAListArg
? 0 : FormatIdx
+2,
16085 FD
->getLocation()));
16088 if (Context
.BuiltinInfo
.isScanfLike(BuiltinID
, FormatIdx
,
16090 if (!FD
->hasAttr
<FormatAttr
>())
16091 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
16092 &Context
.Idents
.get("scanf"),
16094 HasVAListArg
? 0 : FormatIdx
+2,
16095 FD
->getLocation()));
16098 // Handle automatically recognized callbacks.
16099 SmallVector
<int, 4> Encoding
;
16100 if (!FD
->hasAttr
<CallbackAttr
>() &&
16101 Context
.BuiltinInfo
.performsCallback(BuiltinID
, Encoding
))
16102 FD
->addAttr(CallbackAttr::CreateImplicit(
16103 Context
, Encoding
.data(), Encoding
.size(), FD
->getLocation()));
16105 // Mark const if we don't care about errno and/or floating point exceptions
16106 // that are the only thing preventing the function from being const. This
16107 // allows IRgen to use LLVM intrinsics for such functions.
16108 bool NoExceptions
=
16109 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore
;
16110 bool ConstWithoutErrnoAndExceptions
=
16111 Context
.BuiltinInfo
.isConstWithoutErrnoAndExceptions(BuiltinID
);
16112 bool ConstWithoutExceptions
=
16113 Context
.BuiltinInfo
.isConstWithoutExceptions(BuiltinID
);
16114 if (!FD
->hasAttr
<ConstAttr
>() &&
16115 (ConstWithoutErrnoAndExceptions
|| ConstWithoutExceptions
) &&
16116 (!ConstWithoutErrnoAndExceptions
||
16117 (!getLangOpts().MathErrno
&& NoExceptions
)) &&
16118 (!ConstWithoutExceptions
|| NoExceptions
))
16119 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
16121 // We make "fma" on GNU or Windows const because we know it does not set
16122 // errno in those environments even though it could set errno based on the
16124 const llvm::Triple
&Trip
= Context
.getTargetInfo().getTriple();
16125 if ((Trip
.isGNUEnvironment() || Trip
.isOSMSVCRT()) &&
16126 !FD
->hasAttr
<ConstAttr
>()) {
16127 switch (BuiltinID
) {
16128 case Builtin::BI__builtin_fma
:
16129 case Builtin::BI__builtin_fmaf
:
16130 case Builtin::BI__builtin_fmal
:
16131 case Builtin::BIfma
:
16132 case Builtin::BIfmaf
:
16133 case Builtin::BIfmal
:
16134 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
16141 if (Context
.BuiltinInfo
.isReturnsTwice(BuiltinID
) &&
16142 !FD
->hasAttr
<ReturnsTwiceAttr
>())
16143 FD
->addAttr(ReturnsTwiceAttr::CreateImplicit(Context
,
16144 FD
->getLocation()));
16145 if (Context
.BuiltinInfo
.isNoThrow(BuiltinID
) && !FD
->hasAttr
<NoThrowAttr
>())
16146 FD
->addAttr(NoThrowAttr::CreateImplicit(Context
, FD
->getLocation()));
16147 if (Context
.BuiltinInfo
.isPure(BuiltinID
) && !FD
->hasAttr
<PureAttr
>())
16148 FD
->addAttr(PureAttr::CreateImplicit(Context
, FD
->getLocation()));
16149 if (Context
.BuiltinInfo
.isConst(BuiltinID
) && !FD
->hasAttr
<ConstAttr
>())
16150 FD
->addAttr(ConstAttr::CreateImplicit(Context
, FD
->getLocation()));
16151 if (getLangOpts().CUDA
&& Context
.BuiltinInfo
.isTSBuiltin(BuiltinID
) &&
16152 !FD
->hasAttr
<CUDADeviceAttr
>() && !FD
->hasAttr
<CUDAHostAttr
>()) {
16153 // Add the appropriate attribute, depending on the CUDA compilation mode
16154 // and which target the builtin belongs to. For example, during host
16155 // compilation, aux builtins are __device__, while the rest are __host__.
16156 if (getLangOpts().CUDAIsDevice
!=
16157 Context
.BuiltinInfo
.isAuxBuiltinID(BuiltinID
))
16158 FD
->addAttr(CUDADeviceAttr::CreateImplicit(Context
, FD
->getLocation()));
16160 FD
->addAttr(CUDAHostAttr::CreateImplicit(Context
, FD
->getLocation()));
16163 // Add known guaranteed alignment for allocation functions.
16164 switch (BuiltinID
) {
16165 case Builtin::BImemalign
:
16166 case Builtin::BIaligned_alloc
:
16167 if (!FD
->hasAttr
<AllocAlignAttr
>())
16168 FD
->addAttr(AllocAlignAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
16169 FD
->getLocation()));
16175 // Add allocsize attribute for allocation functions.
16176 switch (BuiltinID
) {
16177 case Builtin::BIcalloc
:
16178 FD
->addAttr(AllocSizeAttr::CreateImplicit(
16179 Context
, ParamIdx(1, FD
), ParamIdx(2, FD
), FD
->getLocation()));
16181 case Builtin::BImemalign
:
16182 case Builtin::BIaligned_alloc
:
16183 case Builtin::BIrealloc
:
16184 FD
->addAttr(AllocSizeAttr::CreateImplicit(Context
, ParamIdx(2, FD
),
16185 ParamIdx(), FD
->getLocation()));
16187 case Builtin::BImalloc
:
16188 FD
->addAttr(AllocSizeAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
16189 ParamIdx(), FD
->getLocation()));
16195 // Add lifetime attribute to std::move, std::fowrard et al.
16196 switch (BuiltinID
) {
16197 case Builtin::BIaddressof
:
16198 case Builtin::BI__addressof
:
16199 case Builtin::BI__builtin_addressof
:
16200 case Builtin::BIas_const
:
16201 case Builtin::BIforward
:
16202 case Builtin::BIforward_like
:
16203 case Builtin::BImove
:
16204 case Builtin::BImove_if_noexcept
:
16205 if (ParmVarDecl
*P
= FD
->getParamDecl(0u);
16206 !P
->hasAttr
<LifetimeBoundAttr
>())
16208 LifetimeBoundAttr::CreateImplicit(Context
, FD
->getLocation()));
16215 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD
);
16217 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16218 // throw, add an implicit nothrow attribute to any extern "C" function we come
16220 if (getLangOpts().CXXExceptions
&& getLangOpts().ExternCNoUnwind
&&
16221 FD
->isExternC() && !FD
->hasAttr
<NoThrowAttr
>()) {
16222 const auto *FPT
= FD
->getType()->getAs
<FunctionProtoType
>();
16223 if (!FPT
|| FPT
->getExceptionSpecType() == EST_None
)
16224 FD
->addAttr(NoThrowAttr::CreateImplicit(Context
, FD
->getLocation()));
16227 IdentifierInfo
*Name
= FD
->getIdentifier();
16230 if ((!getLangOpts().CPlusPlus
&&
16231 FD
->getDeclContext()->isTranslationUnit()) ||
16232 (isa
<LinkageSpecDecl
>(FD
->getDeclContext()) &&
16233 cast
<LinkageSpecDecl
>(FD
->getDeclContext())->getLanguage() ==
16234 LinkageSpecDecl::lang_c
)) {
16235 // Okay: this could be a libc/libm/Objective-C function we know
16240 if (Name
->isStr("asprintf") || Name
->isStr("vasprintf")) {
16241 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16242 // target-specific builtins, perhaps?
16243 if (!FD
->hasAttr
<FormatAttr
>())
16244 FD
->addAttr(FormatAttr::CreateImplicit(Context
,
16245 &Context
.Idents
.get("printf"), 2,
16246 Name
->isStr("vasprintf") ? 0 : 3,
16247 FD
->getLocation()));
16250 if (Name
->isStr("__CFStringMakeConstantString")) {
16251 // We already have a __builtin___CFStringMakeConstantString,
16252 // but builds that use -fno-constant-cfstrings don't go through that.
16253 if (!FD
->hasAttr
<FormatArgAttr
>())
16254 FD
->addAttr(FormatArgAttr::CreateImplicit(Context
, ParamIdx(1, FD
),
16255 FD
->getLocation()));
16259 TypedefDecl
*Sema::ParseTypedefDecl(Scope
*S
, Declarator
&D
, QualType T
,
16260 TypeSourceInfo
*TInfo
) {
16261 assert(D
.getIdentifier() && "Wrong callback for declspec without declarator");
16262 assert(!T
.isNull() && "GetTypeForDeclarator() returned null type");
16265 assert(D
.isInvalidType() && "no declarator info for valid type");
16266 TInfo
= Context
.getTrivialTypeSourceInfo(T
);
16269 // Scope manipulation handled by caller.
16270 TypedefDecl
*NewTD
=
16271 TypedefDecl::Create(Context
, CurContext
, D
.getBeginLoc(),
16272 D
.getIdentifierLoc(), D
.getIdentifier(), TInfo
);
16274 // Bail out immediately if we have an invalid declaration.
16275 if (D
.isInvalidType()) {
16276 NewTD
->setInvalidDecl();
16280 if (D
.getDeclSpec().isModulePrivateSpecified()) {
16281 if (CurContext
->isFunctionOrMethod())
16282 Diag(NewTD
->getLocation(), diag::err_module_private_local
)
16284 << SourceRange(D
.getDeclSpec().getModulePrivateSpecLoc())
16285 << FixItHint::CreateRemoval(
16286 D
.getDeclSpec().getModulePrivateSpecLoc());
16288 NewTD
->setModulePrivate();
16291 // C++ [dcl.typedef]p8:
16292 // If the typedef declaration defines an unnamed class (or
16293 // enum), the first typedef-name declared by the declaration
16294 // to be that class type (or enum type) is used to denote the
16295 // class type (or enum type) for linkage purposes only.
16296 // We need to check whether the type was declared in the declaration.
16297 switch (D
.getDeclSpec().getTypeSpecType()) {
16300 case TST_interface
:
16303 TagDecl
*tagFromDeclSpec
= cast
<TagDecl
>(D
.getDeclSpec().getRepAsDecl());
16304 setTagNameForLinkagePurposes(tagFromDeclSpec
, NewTD
);
16315 /// Check that this is a valid underlying type for an enum declaration.
16316 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo
*TI
) {
16317 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
16318 QualType T
= TI
->getType();
16320 if (T
->isDependentType())
16323 // This doesn't use 'isIntegralType' despite the error message mentioning
16324 // integral type because isIntegralType would also allow enum types in C.
16325 if (const BuiltinType
*BT
= T
->getAs
<BuiltinType
>())
16326 if (BT
->isInteger())
16329 if (T
->isBitIntType())
16332 return Diag(UnderlyingLoc
, diag::err_enum_invalid_underlying
) << T
;
16335 /// Check whether this is a valid redeclaration of a previous enumeration.
16336 /// \return true if the redeclaration was invalid.
16337 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc
, bool IsScoped
,
16338 QualType EnumUnderlyingTy
, bool IsFixed
,
16339 const EnumDecl
*Prev
) {
16340 if (IsScoped
!= Prev
->isScoped()) {
16341 Diag(EnumLoc
, diag::err_enum_redeclare_scoped_mismatch
)
16342 << Prev
->isScoped();
16343 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
16347 if (IsFixed
&& Prev
->isFixed()) {
16348 if (!EnumUnderlyingTy
->isDependentType() &&
16349 !Prev
->getIntegerType()->isDependentType() &&
16350 !Context
.hasSameUnqualifiedType(EnumUnderlyingTy
,
16351 Prev
->getIntegerType())) {
16352 // TODO: Highlight the underlying type of the redeclaration.
16353 Diag(EnumLoc
, diag::err_enum_redeclare_type_mismatch
)
16354 << EnumUnderlyingTy
<< Prev
->getIntegerType();
16355 Diag(Prev
->getLocation(), diag::note_previous_declaration
)
16356 << Prev
->getIntegerTypeRange();
16359 } else if (IsFixed
!= Prev
->isFixed()) {
16360 Diag(EnumLoc
, diag::err_enum_redeclare_fixed_mismatch
)
16361 << Prev
->isFixed();
16362 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
16369 /// Get diagnostic %select index for tag kind for
16370 /// redeclaration diagnostic message.
16371 /// WARNING: Indexes apply to particular diagnostics only!
16373 /// \returns diagnostic %select index.
16374 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag
) {
16376 case TTK_Struct
: return 0;
16377 case TTK_Interface
: return 1;
16378 case TTK_Class
: return 2;
16379 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16383 /// Determine if tag kind is a class-key compatible with
16384 /// class for redeclaration (class, struct, or __interface).
16386 /// \returns true iff the tag kind is compatible.
16387 static bool isClassCompatTagKind(TagTypeKind Tag
)
16389 return Tag
== TTK_Struct
|| Tag
== TTK_Class
|| Tag
== TTK_Interface
;
16392 Sema::NonTagKind
Sema::getNonTagTypeDeclKind(const Decl
*PrevDecl
,
16394 if (isa
<TypedefDecl
>(PrevDecl
))
16395 return NTK_Typedef
;
16396 else if (isa
<TypeAliasDecl
>(PrevDecl
))
16397 return NTK_TypeAlias
;
16398 else if (isa
<ClassTemplateDecl
>(PrevDecl
))
16399 return NTK_Template
;
16400 else if (isa
<TypeAliasTemplateDecl
>(PrevDecl
))
16401 return NTK_TypeAliasTemplate
;
16402 else if (isa
<TemplateTemplateParmDecl
>(PrevDecl
))
16403 return NTK_TemplateTemplateArgument
;
16406 case TTK_Interface
:
16408 return getLangOpts().CPlusPlus
? NTK_NonClass
: NTK_NonStruct
;
16410 return NTK_NonUnion
;
16412 return NTK_NonEnum
;
16414 llvm_unreachable("invalid TTK");
16417 /// Determine whether a tag with a given kind is acceptable
16418 /// as a redeclaration of the given tag declaration.
16420 /// \returns true if the new tag kind is acceptable, false otherwise.
16421 bool Sema::isAcceptableTagRedeclaration(const TagDecl
*Previous
,
16422 TagTypeKind NewTag
, bool isDefinition
,
16423 SourceLocation NewTagLoc
,
16424 const IdentifierInfo
*Name
) {
16425 // C++ [dcl.type.elab]p3:
16426 // The class-key or enum keyword present in the
16427 // elaborated-type-specifier shall agree in kind with the
16428 // declaration to which the name in the elaborated-type-specifier
16429 // refers. This rule also applies to the form of
16430 // elaborated-type-specifier that declares a class-name or
16431 // friend class since it can be construed as referring to the
16432 // definition of the class. Thus, in any
16433 // elaborated-type-specifier, the enum keyword shall be used to
16434 // refer to an enumeration (7.2), the union class-key shall be
16435 // used to refer to a union (clause 9), and either the class or
16436 // struct class-key shall be used to refer to a class (clause 9)
16437 // declared using the class or struct class-key.
16438 TagTypeKind OldTag
= Previous
->getTagKind();
16439 if (OldTag
!= NewTag
&&
16440 !(isClassCompatTagKind(OldTag
) && isClassCompatTagKind(NewTag
)))
16443 // Tags are compatible, but we might still want to warn on mismatched tags.
16444 // Non-class tags can't be mismatched at this point.
16445 if (!isClassCompatTagKind(NewTag
))
16448 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16449 // by our warning analysis. We don't want to warn about mismatches with (eg)
16450 // declarations in system headers that are designed to be specialized, but if
16451 // a user asks us to warn, we should warn if their code contains mismatched
16453 auto IsIgnoredLoc
= [&](SourceLocation Loc
) {
16454 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch
,
16457 if (IsIgnoredLoc(NewTagLoc
))
16460 auto IsIgnored
= [&](const TagDecl
*Tag
) {
16461 return IsIgnoredLoc(Tag
->getLocation());
16463 while (IsIgnored(Previous
)) {
16464 Previous
= Previous
->getPreviousDecl();
16467 OldTag
= Previous
->getTagKind();
16470 bool isTemplate
= false;
16471 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Previous
))
16472 isTemplate
= Record
->getDescribedClassTemplate();
16474 if (inTemplateInstantiation()) {
16475 if (OldTag
!= NewTag
) {
16476 // In a template instantiation, do not offer fix-its for tag mismatches
16477 // since they usually mess up the template instead of fixing the problem.
16478 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
16479 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16480 << getRedeclDiagFromTagKind(OldTag
);
16481 // FIXME: Note previous location?
16486 if (isDefinition
) {
16487 // On definitions, check all previous tags and issue a fix-it for each
16488 // one that doesn't match the current tag.
16489 if (Previous
->getDefinition()) {
16490 // Don't suggest fix-its for redefinitions.
16494 bool previousMismatch
= false;
16495 for (const TagDecl
*I
: Previous
->redecls()) {
16496 if (I
->getTagKind() != NewTag
) {
16497 // Ignore previous declarations for which the warning was disabled.
16501 if (!previousMismatch
) {
16502 previousMismatch
= true;
16503 Diag(NewTagLoc
, diag::warn_struct_class_previous_tag_mismatch
)
16504 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16505 << getRedeclDiagFromTagKind(I
->getTagKind());
16507 Diag(I
->getInnerLocStart(), diag::note_struct_class_suggestion
)
16508 << getRedeclDiagFromTagKind(NewTag
)
16509 << FixItHint::CreateReplacement(I
->getInnerLocStart(),
16510 TypeWithKeyword::getTagTypeKindName(NewTag
));
16516 // Identify the prevailing tag kind: this is the kind of the definition (if
16517 // there is a non-ignored definition), or otherwise the kind of the prior
16518 // (non-ignored) declaration.
16519 const TagDecl
*PrevDef
= Previous
->getDefinition();
16520 if (PrevDef
&& IsIgnored(PrevDef
))
16522 const TagDecl
*Redecl
= PrevDef
? PrevDef
: Previous
;
16523 if (Redecl
->getTagKind() != NewTag
) {
16524 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
16525 << getRedeclDiagFromTagKind(NewTag
) << isTemplate
<< Name
16526 << getRedeclDiagFromTagKind(OldTag
);
16527 Diag(Redecl
->getLocation(), diag::note_previous_use
);
16529 // If there is a previous definition, suggest a fix-it.
16531 Diag(NewTagLoc
, diag::note_struct_class_suggestion
)
16532 << getRedeclDiagFromTagKind(Redecl
->getTagKind())
16533 << FixItHint::CreateReplacement(SourceRange(NewTagLoc
),
16534 TypeWithKeyword::getTagTypeKindName(Redecl
->getTagKind()));
16541 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16542 /// from an outer enclosing namespace or file scope inside a friend declaration.
16543 /// This should provide the commented out code in the following snippet:
16547 /// struct Y { friend struct /*N::*/ X; };
16550 static FixItHint
createFriendTagNNSFixIt(Sema
&SemaRef
, NamedDecl
*ND
, Scope
*S
,
16551 SourceLocation NameLoc
) {
16552 // While the decl is in a namespace, do repeated lookup of that name and see
16553 // if we get the same namespace back. If we do not, continue until
16554 // translation unit scope, at which point we have a fully qualified NNS.
16555 SmallVector
<IdentifierInfo
*, 4> Namespaces
;
16556 DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
16557 for (; !DC
->isTranslationUnit(); DC
= DC
->getParent()) {
16558 // This tag should be declared in a namespace, which can only be enclosed by
16559 // other namespaces. Bail if there's an anonymous namespace in the chain.
16560 NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(DC
);
16561 if (!Namespace
|| Namespace
->isAnonymousNamespace())
16562 return FixItHint();
16563 IdentifierInfo
*II
= Namespace
->getIdentifier();
16564 Namespaces
.push_back(II
);
16565 NamedDecl
*Lookup
= SemaRef
.LookupSingleName(
16566 S
, II
, NameLoc
, Sema::LookupNestedNameSpecifierName
);
16567 if (Lookup
== Namespace
)
16571 // Once we have all the namespaces, reverse them to go outermost first, and
16573 SmallString
<64> Insertion
;
16574 llvm::raw_svector_ostream
OS(Insertion
);
16575 if (DC
->isTranslationUnit())
16577 std::reverse(Namespaces
.begin(), Namespaces
.end());
16578 for (auto *II
: Namespaces
)
16579 OS
<< II
->getName() << "::";
16580 return FixItHint::CreateInsertion(NameLoc
, Insertion
);
16583 /// Determine whether a tag originally declared in context \p OldDC can
16584 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16585 /// found a declaration in \p OldDC as a previous decl, perhaps through a
16586 /// using-declaration).
16587 static bool isAcceptableTagRedeclContext(Sema
&S
, DeclContext
*OldDC
,
16588 DeclContext
*NewDC
) {
16589 OldDC
= OldDC
->getRedeclContext();
16590 NewDC
= NewDC
->getRedeclContext();
16592 if (OldDC
->Equals(NewDC
))
16595 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16596 // encloses the other).
16597 if (S
.getLangOpts().MSVCCompat
&&
16598 (OldDC
->Encloses(NewDC
) || NewDC
->Encloses(OldDC
)))
16604 /// This is invoked when we see 'struct foo' or 'struct {'. In the
16605 /// former case, Name will be non-null. In the later case, Name will be null.
16606 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16607 /// reference/declaration/definition of a tag.
16609 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
16610 /// trailing-type-specifier) other than one in an alias-declaration.
16612 /// \param SkipBody If non-null, will be set to indicate if the caller should
16613 /// skip the definition of this tag and treat it as if it were a declaration.
16615 Sema::ActOnTag(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
, SourceLocation KWLoc
,
16616 CXXScopeSpec
&SS
, IdentifierInfo
*Name
, SourceLocation NameLoc
,
16617 const ParsedAttributesView
&Attrs
, AccessSpecifier AS
,
16618 SourceLocation ModulePrivateLoc
,
16619 MultiTemplateParamsArg TemplateParameterLists
, bool &OwnedDecl
,
16620 bool &IsDependent
, SourceLocation ScopedEnumKWLoc
,
16621 bool ScopedEnumUsesClassTag
, TypeResult UnderlyingType
,
16622 bool IsTypeSpecifier
, bool IsTemplateParamOrArg
,
16623 OffsetOfKind OOK
, SkipBodyInfo
*SkipBody
) {
16624 // If this is not a definition, it must have a name.
16625 IdentifierInfo
*OrigName
= Name
;
16626 assert((Name
!= nullptr || TUK
== TUK_Definition
) &&
16627 "Nameless record must be a definition!");
16628 assert(TemplateParameterLists
.size() == 0 || TUK
!= TUK_Reference
);
16631 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
16632 bool ScopedEnum
= ScopedEnumKWLoc
.isValid();
16634 // FIXME: Check member specializations more carefully.
16635 bool isMemberSpecialization
= false;
16636 bool Invalid
= false;
16638 // We only need to do this matching if we have template parameters
16639 // or a scope specifier, which also conveniently avoids this work
16640 // for non-C++ cases.
16641 if (TemplateParameterLists
.size() > 0 ||
16642 (SS
.isNotEmpty() && TUK
!= TUK_Reference
)) {
16643 if (TemplateParameterList
*TemplateParams
=
16644 MatchTemplateParametersToScopeSpecifier(
16645 KWLoc
, NameLoc
, SS
, nullptr, TemplateParameterLists
,
16646 TUK
== TUK_Friend
, isMemberSpecialization
, Invalid
)) {
16647 if (Kind
== TTK_Enum
) {
16648 Diag(KWLoc
, diag::err_enum_template
);
16652 if (TemplateParams
->size() > 0) {
16653 // This is a declaration or definition of a class template (which may
16654 // be a member of another template).
16660 DeclResult Result
= CheckClassTemplate(
16661 S
, TagSpec
, TUK
, KWLoc
, SS
, Name
, NameLoc
, Attrs
, TemplateParams
,
16662 AS
, ModulePrivateLoc
,
16663 /*FriendLoc*/ SourceLocation(), TemplateParameterLists
.size() - 1,
16664 TemplateParameterLists
.data(), SkipBody
);
16665 return Result
.get();
16667 // The "template<>" header is extraneous.
16668 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
16669 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
16670 isMemberSpecialization
= true;
16674 if (!TemplateParameterLists
.empty() && isMemberSpecialization
&&
16675 CheckTemplateDeclScope(S
, TemplateParameterLists
.back()))
16679 // Figure out the underlying type if this a enum declaration. We need to do
16680 // this early, because it's needed to detect if this is an incompatible
16682 llvm::PointerUnion
<const Type
*, TypeSourceInfo
*> EnumUnderlying
;
16683 bool IsFixed
= !UnderlyingType
.isUnset() || ScopedEnum
;
16685 if (Kind
== TTK_Enum
) {
16686 if (UnderlyingType
.isInvalid() || (!UnderlyingType
.get() && ScopedEnum
)) {
16687 // No underlying type explicitly specified, or we failed to parse the
16688 // type, default to int.
16689 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16690 } else if (UnderlyingType
.get()) {
16691 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16692 // integral type; any cv-qualification is ignored.
16693 TypeSourceInfo
*TI
= nullptr;
16694 GetTypeFromParser(UnderlyingType
.get(), &TI
);
16695 EnumUnderlying
= TI
;
16697 if (CheckEnumUnderlyingType(TI
))
16698 // Recover by falling back to int.
16699 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16701 if (DiagnoseUnexpandedParameterPack(TI
->getTypeLoc().getBeginLoc(), TI
,
16702 UPPC_FixedUnderlyingType
))
16703 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16705 } else if (Context
.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16706 // For MSVC ABI compatibility, unfixed enums must use an underlying type
16707 // of 'int'. However, if this is an unfixed forward declaration, don't set
16708 // the underlying type unless the user enables -fms-compatibility. This
16709 // makes unfixed forward declared enums incomplete and is more conforming.
16710 if (TUK
== TUK_Definition
|| getLangOpts().MSVCCompat
)
16711 EnumUnderlying
= Context
.IntTy
.getTypePtr();
16715 DeclContext
*SearchDC
= CurContext
;
16716 DeclContext
*DC
= CurContext
;
16717 bool isStdBadAlloc
= false;
16718 bool isStdAlignValT
= false;
16720 RedeclarationKind Redecl
= forRedeclarationInCurContext();
16721 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
)
16722 Redecl
= NotForRedeclaration
;
16724 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16725 /// implemented asks for structural equivalence checking, the returned decl
16726 /// here is passed back to the parser, allowing the tag body to be parsed.
16727 auto createTagFromNewDecl
= [&]() -> TagDecl
* {
16728 assert(!getLangOpts().CPlusPlus
&& "not meant for C++ usage");
16729 // If there is an identifier, use the location of the identifier as the
16730 // location of the decl, otherwise use the location of the struct/union
16732 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
16733 TagDecl
*New
= nullptr;
16735 if (Kind
== TTK_Enum
) {
16736 New
= EnumDecl::Create(Context
, SearchDC
, KWLoc
, Loc
, Name
, nullptr,
16737 ScopedEnum
, ScopedEnumUsesClassTag
, IsFixed
);
16738 // If this is an undefined enum, bail.
16739 if (TUK
!= TUK_Definition
&& !Invalid
)
16741 if (EnumUnderlying
) {
16742 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
16743 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
16744 ED
->setIntegerTypeSourceInfo(TI
);
16746 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
16747 QualType EnumTy
= ED
->getIntegerType();
16748 ED
->setPromotionType(Context
.isPromotableIntegerType(EnumTy
)
16749 ? Context
.getPromotedIntegerType(EnumTy
)
16752 } else { // struct/union
16753 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
16757 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
16758 // Add alignment attributes if necessary; these attributes are checked
16759 // when the ASTContext lays out the structure.
16761 // It is important for implementing the correct semantics that this
16762 // happen here (in ActOnTag). The #pragma pack stack is
16763 // maintained as a result of parser callbacks which can occur at
16764 // many points during the parsing of a struct declaration (because
16765 // the #pragma tokens are effectively skipped over during the
16766 // parsing of the struct).
16767 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
16768 AddAlignmentAttributesForRecord(RD
);
16769 AddMsStructLayoutForRecord(RD
);
16772 New
->setLexicalDeclContext(CurContext
);
16776 LookupResult
Previous(*this, Name
, NameLoc
, LookupTagName
, Redecl
);
16777 if (Name
&& SS
.isNotEmpty()) {
16778 // We have a nested-name tag ('struct foo::bar').
16780 // Check for invalid 'foo::'.
16781 if (SS
.isInvalid()) {
16783 goto CreateNewDecl
;
16786 // If this is a friend or a reference to a class in a dependent
16787 // context, don't try to make a decl for it.
16788 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
16789 DC
= computeDeclContext(SS
, false);
16791 IsDependent
= true;
16795 DC
= computeDeclContext(SS
, true);
16797 Diag(SS
.getRange().getBegin(), diag::err_dependent_nested_name_spec
)
16803 if (RequireCompleteDeclContext(SS
, DC
))
16807 // Look-up name inside 'foo::'.
16808 LookupQualifiedName(Previous
, DC
);
16810 if (Previous
.isAmbiguous())
16813 if (Previous
.empty()) {
16814 // Name lookup did not find anything. However, if the
16815 // nested-name-specifier refers to the current instantiation,
16816 // and that current instantiation has any dependent base
16817 // classes, we might find something at instantiation time: treat
16818 // this as a dependent elaborated-type-specifier.
16819 // But this only makes any sense for reference-like lookups.
16820 if (Previous
.wasNotFoundInCurrentInstantiation() &&
16821 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)) {
16822 IsDependent
= true;
16826 // A tag 'foo::bar' must already exist.
16827 Diag(NameLoc
, diag::err_not_tag_in_scope
)
16828 << Kind
<< Name
<< DC
<< SS
.getRange();
16831 goto CreateNewDecl
;
16834 // C++14 [class.mem]p14:
16835 // If T is the name of a class, then each of the following shall have a
16836 // name different from T:
16837 // -- every member of class T that is itself a type
16838 if (TUK
!= TUK_Reference
&& TUK
!= TUK_Friend
&&
16839 DiagnoseClassNameShadow(SearchDC
, DeclarationNameInfo(Name
, NameLoc
)))
16842 // If this is a named struct, check to see if there was a previous forward
16843 // declaration or definition.
16844 // FIXME: We're looking into outer scopes here, even when we
16845 // shouldn't be. Doing so can result in ambiguities that we
16846 // shouldn't be diagnosing.
16847 LookupName(Previous
, S
);
16849 // When declaring or defining a tag, ignore ambiguities introduced
16850 // by types using'ed into this scope.
16851 if (Previous
.isAmbiguous() &&
16852 (TUK
== TUK_Definition
|| TUK
== TUK_Declaration
)) {
16853 LookupResult::Filter F
= Previous
.makeFilter();
16854 while (F
.hasNext()) {
16855 NamedDecl
*ND
= F
.next();
16856 if (!ND
->getDeclContext()->getRedeclContext()->Equals(
16857 SearchDC
->getRedeclContext()))
16863 // C++11 [namespace.memdef]p3:
16864 // If the name in a friend declaration is neither qualified nor
16865 // a template-id and the declaration is a function or an
16866 // elaborated-type-specifier, the lookup to determine whether
16867 // the entity has been previously declared shall not consider
16868 // any scopes outside the innermost enclosing namespace.
16870 // MSVC doesn't implement the above rule for types, so a friend tag
16871 // declaration may be a redeclaration of a type declared in an enclosing
16872 // scope. They do implement this rule for friend functions.
16874 // Does it matter that this should be by scope instead of by
16875 // semantic context?
16876 if (!Previous
.empty() && TUK
== TUK_Friend
) {
16877 DeclContext
*EnclosingNS
= SearchDC
->getEnclosingNamespaceContext();
16878 LookupResult::Filter F
= Previous
.makeFilter();
16879 bool FriendSawTagOutsideEnclosingNamespace
= false;
16880 while (F
.hasNext()) {
16881 NamedDecl
*ND
= F
.next();
16882 DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
16883 if (DC
->isFileContext() &&
16884 !EnclosingNS
->Encloses(ND
->getDeclContext())) {
16885 if (getLangOpts().MSVCCompat
)
16886 FriendSawTagOutsideEnclosingNamespace
= true;
16893 // Diagnose this MSVC extension in the easy case where lookup would have
16894 // unambiguously found something outside the enclosing namespace.
16895 if (Previous
.isSingleResult() && FriendSawTagOutsideEnclosingNamespace
) {
16896 NamedDecl
*ND
= Previous
.getFoundDecl();
16897 Diag(NameLoc
, diag::ext_friend_tag_redecl_outside_namespace
)
16898 << createFriendTagNNSFixIt(*this, ND
, S
, NameLoc
);
16902 // Note: there used to be some attempt at recovery here.
16903 if (Previous
.isAmbiguous())
16906 if (!getLangOpts().CPlusPlus
&& TUK
!= TUK_Reference
) {
16907 // FIXME: This makes sure that we ignore the contexts associated
16908 // with C structs, unions, and enums when looking for a matching
16909 // tag declaration or definition. See the similar lookup tweak
16910 // in Sema::LookupName; is there a better way to deal with this?
16911 while (isa
<RecordDecl
, EnumDecl
, ObjCContainerDecl
>(SearchDC
))
16912 SearchDC
= SearchDC
->getParent();
16913 } else if (getLangOpts().CPlusPlus
) {
16914 // Inside ObjCContainer want to keep it as a lexical decl context but go
16915 // past it (most often to TranslationUnit) to find the semantic decl
16917 while (isa
<ObjCContainerDecl
>(SearchDC
))
16918 SearchDC
= SearchDC
->getParent();
16920 } else if (getLangOpts().CPlusPlus
) {
16921 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
16922 // TagDecl the same way as we skip it for named TagDecl.
16923 while (isa
<ObjCContainerDecl
>(SearchDC
))
16924 SearchDC
= SearchDC
->getParent();
16927 if (Previous
.isSingleResult() &&
16928 Previous
.getFoundDecl()->isTemplateParameter()) {
16929 // Maybe we will complain about the shadowed template parameter.
16930 DiagnoseTemplateParameterShadow(NameLoc
, Previous
.getFoundDecl());
16931 // Just pretend that we didn't see the previous declaration.
16935 if (getLangOpts().CPlusPlus
&& Name
&& DC
&& StdNamespace
&&
16936 DC
->Equals(getStdNamespace())) {
16937 if (Name
->isStr("bad_alloc")) {
16938 // This is a declaration of or a reference to "std::bad_alloc".
16939 isStdBadAlloc
= true;
16941 // If std::bad_alloc has been implicitly declared (but made invisible to
16942 // name lookup), fill in this implicit declaration as the previous
16943 // declaration, so that the declarations get chained appropriately.
16944 if (Previous
.empty() && StdBadAlloc
)
16945 Previous
.addDecl(getStdBadAlloc());
16946 } else if (Name
->isStr("align_val_t")) {
16947 isStdAlignValT
= true;
16948 if (Previous
.empty() && StdAlignValT
)
16949 Previous
.addDecl(getStdAlignValT());
16953 // If we didn't find a previous declaration, and this is a reference
16954 // (or friend reference), move to the correct scope. In C++, we
16955 // also need to do a redeclaration lookup there, just in case
16956 // there's a shadow friend decl.
16957 if (Name
&& Previous
.empty() &&
16958 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
|| IsTemplateParamOrArg
)) {
16959 if (Invalid
) goto CreateNewDecl
;
16960 assert(SS
.isEmpty());
16962 if (TUK
== TUK_Reference
|| IsTemplateParamOrArg
) {
16963 // C++ [basic.scope.pdecl]p5:
16964 // -- for an elaborated-type-specifier of the form
16966 // class-key identifier
16968 // if the elaborated-type-specifier is used in the
16969 // decl-specifier-seq or parameter-declaration-clause of a
16970 // function defined in namespace scope, the identifier is
16971 // declared as a class-name in the namespace that contains
16972 // the declaration; otherwise, except as a friend
16973 // declaration, the identifier is declared in the smallest
16974 // non-class, non-function-prototype scope that contains the
16977 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16978 // C structs and unions.
16980 // It is an error in C++ to declare (rather than define) an enum
16981 // type, including via an elaborated type specifier. We'll
16982 // diagnose that later; for now, declare the enum in the same
16983 // scope as we would have picked for any other tag type.
16985 // GNU C also supports this behavior as part of its incomplete
16986 // enum types extension, while GNU C++ does not.
16988 // Find the context where we'll be declaring the tag.
16989 // FIXME: We would like to maintain the current DeclContext as the
16990 // lexical context,
16991 SearchDC
= getTagInjectionContext(SearchDC
);
16993 // Find the scope where we'll be declaring the tag.
16994 S
= getTagInjectionScope(S
, getLangOpts());
16996 assert(TUK
== TUK_Friend
);
16997 // C++ [namespace.memdef]p3:
16998 // If a friend declaration in a non-local class first declares a
16999 // class or function, the friend class or function is a member of
17000 // the innermost enclosing namespace.
17001 SearchDC
= SearchDC
->getEnclosingNamespaceContext();
17004 // In C++, we need to do a redeclaration lookup to properly
17005 // diagnose some problems.
17006 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17007 // hidden declaration so that we don't get ambiguity errors when using a
17008 // type declared by an elaborated-type-specifier. In C that is not correct
17009 // and we should instead merge compatible types found by lookup.
17010 if (getLangOpts().CPlusPlus
) {
17011 // FIXME: This can perform qualified lookups into function contexts,
17012 // which are meaningless.
17013 Previous
.setRedeclarationKind(forRedeclarationInCurContext());
17014 LookupQualifiedName(Previous
, SearchDC
);
17016 Previous
.setRedeclarationKind(forRedeclarationInCurContext());
17017 LookupName(Previous
, S
);
17021 // If we have a known previous declaration to use, then use it.
17022 if (Previous
.empty() && SkipBody
&& SkipBody
->Previous
)
17023 Previous
.addDecl(SkipBody
->Previous
);
17025 if (!Previous
.empty()) {
17026 NamedDecl
*PrevDecl
= Previous
.getFoundDecl();
17027 NamedDecl
*DirectPrevDecl
= Previous
.getRepresentativeDecl();
17029 // It's okay to have a tag decl in the same scope as a typedef
17030 // which hides a tag decl in the same scope. Finding this
17031 // with a redeclaration lookup can only actually happen in C++.
17033 // This is also okay for elaborated-type-specifiers, which is
17034 // technically forbidden by the current standard but which is
17035 // okay according to the likely resolution of an open issue;
17036 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17037 if (getLangOpts().CPlusPlus
) {
17038 if (TypedefNameDecl
*TD
= dyn_cast
<TypedefNameDecl
>(PrevDecl
)) {
17039 if (const TagType
*TT
= TD
->getUnderlyingType()->getAs
<TagType
>()) {
17040 TagDecl
*Tag
= TT
->getDecl();
17041 if (Tag
->getDeclName() == Name
&&
17042 Tag
->getDeclContext()->getRedeclContext()
17043 ->Equals(TD
->getDeclContext()->getRedeclContext())) {
17046 Previous
.addDecl(Tag
);
17047 Previous
.resolveKind();
17053 // If this is a redeclaration of a using shadow declaration, it must
17054 // declare a tag in the same context. In MSVC mode, we allow a
17055 // redefinition if either context is within the other.
17056 if (auto *Shadow
= dyn_cast
<UsingShadowDecl
>(DirectPrevDecl
)) {
17057 auto *OldTag
= dyn_cast
<TagDecl
>(PrevDecl
);
17058 if (SS
.isEmpty() && TUK
!= TUK_Reference
&& TUK
!= TUK_Friend
&&
17059 isDeclInScope(Shadow
, SearchDC
, S
, isMemberSpecialization
) &&
17060 !(OldTag
&& isAcceptableTagRedeclContext(
17061 *this, OldTag
->getDeclContext(), SearchDC
))) {
17062 Diag(KWLoc
, diag::err_using_decl_conflict_reverse
);
17063 Diag(Shadow
->getTargetDecl()->getLocation(),
17064 diag::note_using_decl_target
);
17065 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
)
17067 // Recover by ignoring the old declaration.
17069 goto CreateNewDecl
;
17073 if (TagDecl
*PrevTagDecl
= dyn_cast
<TagDecl
>(PrevDecl
)) {
17074 // If this is a use of a previous tag, or if the tag is already declared
17075 // in the same scope (so that the definition/declaration completes or
17076 // rementions the tag), reuse the decl.
17077 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
||
17078 isDeclInScope(DirectPrevDecl
, SearchDC
, S
,
17079 SS
.isNotEmpty() || isMemberSpecialization
)) {
17080 // Make sure that this wasn't declared as an enum and now used as a
17081 // struct or something similar.
17082 if (!isAcceptableTagRedeclaration(PrevTagDecl
, Kind
,
17083 TUK
== TUK_Definition
, KWLoc
,
17085 bool SafeToContinue
17086 = (PrevTagDecl
->getTagKind() != TTK_Enum
&&
17088 if (SafeToContinue
)
17089 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
17091 << FixItHint::CreateReplacement(SourceRange(KWLoc
),
17092 PrevTagDecl
->getKindName());
17094 Diag(KWLoc
, diag::err_use_with_wrong_tag
) << Name
;
17095 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
17097 if (SafeToContinue
)
17098 Kind
= PrevTagDecl
->getTagKind();
17100 // Recover by making this an anonymous redefinition.
17107 if (Kind
== TTK_Enum
&& PrevTagDecl
->getTagKind() == TTK_Enum
) {
17108 const EnumDecl
*PrevEnum
= cast
<EnumDecl
>(PrevTagDecl
);
17109 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)
17110 return PrevTagDecl
;
17112 QualType EnumUnderlyingTy
;
17113 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
17114 EnumUnderlyingTy
= TI
->getType().getUnqualifiedType();
17115 else if (const Type
*T
= EnumUnderlying
.dyn_cast
<const Type
*>())
17116 EnumUnderlyingTy
= QualType(T
, 0);
17118 // All conflicts with previous declarations are recovered by
17119 // returning the previous declaration, unless this is a definition,
17120 // in which case we want the caller to bail out.
17121 if (CheckEnumRedeclaration(NameLoc
.isValid() ? NameLoc
: KWLoc
,
17122 ScopedEnum
, EnumUnderlyingTy
,
17123 IsFixed
, PrevEnum
))
17124 return TUK
== TUK_Declaration
? PrevTagDecl
: nullptr;
17127 // C++11 [class.mem]p1:
17128 // A member shall not be declared twice in the member-specification,
17129 // except that a nested class or member class template can be declared
17130 // and then later defined.
17131 if (TUK
== TUK_Declaration
&& PrevDecl
->isCXXClassMember() &&
17132 S
->isDeclScope(PrevDecl
)) {
17133 Diag(NameLoc
, diag::ext_member_redeclared
);
17134 Diag(PrevTagDecl
->getLocation(), diag::note_previous_declaration
);
17138 // If this is a use, just return the declaration we found, unless
17139 // we have attributes.
17140 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
17141 if (!Attrs
.empty()) {
17142 // FIXME: Diagnose these attributes. For now, we create a new
17143 // declaration to hold them.
17144 } else if (TUK
== TUK_Reference
&&
17145 (PrevTagDecl
->getFriendObjectKind() ==
17146 Decl::FOK_Undeclared
||
17147 PrevDecl
->getOwningModule() != getCurrentModule()) &&
17149 // This declaration is a reference to an existing entity, but
17150 // has different visibility from that entity: it either makes
17151 // a friend visible or it makes a type visible in a new module.
17152 // In either case, create a new declaration. We only do this if
17153 // the declaration would have meant the same thing if no prior
17154 // declaration were found, that is, if it was found in the same
17155 // scope where we would have injected a declaration.
17156 if (!getTagInjectionContext(CurContext
)->getRedeclContext()
17157 ->Equals(PrevDecl
->getDeclContext()->getRedeclContext()))
17158 return PrevTagDecl
;
17159 // This is in the injected scope, create a new declaration in
17161 S
= getTagInjectionScope(S
, getLangOpts());
17163 return PrevTagDecl
;
17167 // Diagnose attempts to redefine a tag.
17168 if (TUK
== TUK_Definition
) {
17169 if (NamedDecl
*Def
= PrevTagDecl
->getDefinition()) {
17170 // If we're defining a specialization and the previous definition
17171 // is from an implicit instantiation, don't emit an error
17172 // here; we'll catch this in the general case below.
17173 bool IsExplicitSpecializationAfterInstantiation
= false;
17174 if (isMemberSpecialization
) {
17175 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Def
))
17176 IsExplicitSpecializationAfterInstantiation
=
17177 RD
->getTemplateSpecializationKind() !=
17178 TSK_ExplicitSpecialization
;
17179 else if (EnumDecl
*ED
= dyn_cast
<EnumDecl
>(Def
))
17180 IsExplicitSpecializationAfterInstantiation
=
17181 ED
->getTemplateSpecializationKind() !=
17182 TSK_ExplicitSpecialization
;
17185 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17186 // not keep more that one definition around (merge them). However,
17187 // ensure the decl passes the structural compatibility check in
17188 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17189 NamedDecl
*Hidden
= nullptr;
17190 if (SkipBody
&& !hasVisibleDefinition(Def
, &Hidden
)) {
17191 // There is a definition of this tag, but it is not visible. We
17192 // explicitly make use of C++'s one definition rule here, and
17193 // assume that this definition is identical to the hidden one
17194 // we already have. Make the existing definition visible and
17195 // use it in place of this one.
17196 if (!getLangOpts().CPlusPlus
) {
17197 // Postpone making the old definition visible until after we
17198 // complete parsing the new one and do the structural
17200 SkipBody
->CheckSameAsPrevious
= true;
17201 SkipBody
->New
= createTagFromNewDecl();
17202 SkipBody
->Previous
= Def
;
17205 SkipBody
->ShouldSkip
= true;
17206 SkipBody
->Previous
= Def
;
17207 makeMergedDefinitionVisible(Hidden
);
17208 // Carry on and handle it like a normal definition. We'll
17209 // skip starting the definitiion later.
17211 } else if (!IsExplicitSpecializationAfterInstantiation
) {
17212 // A redeclaration in function prototype scope in C isn't
17213 // visible elsewhere, so merely issue a warning.
17214 if (!getLangOpts().CPlusPlus
&& S
->containedInPrototypeScope())
17215 Diag(NameLoc
, diag::warn_redefinition_in_param_list
) << Name
;
17217 Diag(NameLoc
, diag::err_redefinition
) << Name
;
17218 notePreviousDefinition(Def
,
17219 NameLoc
.isValid() ? NameLoc
: KWLoc
);
17220 // If this is a redefinition, recover by making this
17221 // struct be anonymous, which will make any later
17222 // references get the previous definition.
17228 // If the type is currently being defined, complain
17229 // about a nested redefinition.
17230 auto *TD
= Context
.getTagDeclType(PrevTagDecl
)->getAsTagDecl();
17231 if (TD
->isBeingDefined()) {
17232 Diag(NameLoc
, diag::err_nested_redefinition
) << Name
;
17233 Diag(PrevTagDecl
->getLocation(),
17234 diag::note_previous_definition
);
17241 // Okay, this is definition of a previously declared or referenced
17242 // tag. We're going to create a new Decl for it.
17245 // Okay, we're going to make a redeclaration. If this is some kind
17246 // of reference, make sure we build the redeclaration in the same DC
17247 // as the original, and ignore the current access specifier.
17248 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
17249 SearchDC
= PrevTagDecl
->getDeclContext();
17253 // If we get here we have (another) forward declaration or we
17254 // have a definition. Just create a new decl.
17257 // If we get here, this is a definition of a new tag type in a nested
17258 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17259 // new decl/type. We set PrevDecl to NULL so that the entities
17260 // have distinct types.
17263 // If we get here, we're going to create a new Decl. If PrevDecl
17264 // is non-NULL, it's a definition of the tag declared by
17265 // PrevDecl. If it's NULL, we have a new definition.
17267 // Otherwise, PrevDecl is not a tag, but was found with tag
17268 // lookup. This is only actually possible in C++, where a few
17269 // things like templates still live in the tag namespace.
17271 // Use a better diagnostic if an elaborated-type-specifier
17272 // found the wrong kind of type on the first
17273 // (non-redeclaration) lookup.
17274 if ((TUK
== TUK_Reference
|| TUK
== TUK_Friend
) &&
17275 !Previous
.isForRedeclaration()) {
17276 NonTagKind NTK
= getNonTagTypeDeclKind(PrevDecl
, Kind
);
17277 Diag(NameLoc
, diag::err_tag_reference_non_tag
) << PrevDecl
<< NTK
17279 Diag(PrevDecl
->getLocation(), diag::note_declared_at
);
17282 // Otherwise, only diagnose if the declaration is in scope.
17283 } else if (!isDeclInScope(DirectPrevDecl
, SearchDC
, S
,
17284 SS
.isNotEmpty() || isMemberSpecialization
)) {
17287 // Diagnose implicit declarations introduced by elaborated types.
17288 } else if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
17289 NonTagKind NTK
= getNonTagTypeDeclKind(PrevDecl
, Kind
);
17290 Diag(NameLoc
, diag::err_tag_reference_conflict
) << NTK
;
17291 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
17294 // Otherwise it's a declaration. Call out a particularly common
17296 } else if (TypedefNameDecl
*TND
= dyn_cast
<TypedefNameDecl
>(PrevDecl
)) {
17298 if (isa
<TypeAliasDecl
>(PrevDecl
)) Kind
= 1;
17299 Diag(NameLoc
, diag::err_tag_definition_of_typedef
)
17300 << Name
<< Kind
<< TND
->getUnderlyingType();
17301 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
17304 // Otherwise, diagnose.
17306 // The tag name clashes with something else in the target scope,
17307 // issue an error and recover by making this tag be anonymous.
17308 Diag(NameLoc
, diag::err_redefinition_different_kind
) << Name
;
17309 notePreviousDefinition(PrevDecl
, NameLoc
);
17314 // The existing declaration isn't relevant to us; we're in a
17315 // new scope, so clear out the previous declaration.
17322 TagDecl
*PrevDecl
= nullptr;
17323 if (Previous
.isSingleResult())
17324 PrevDecl
= cast
<TagDecl
>(Previous
.getFoundDecl());
17326 // If there is an identifier, use the location of the identifier as the
17327 // location of the decl, otherwise use the location of the struct/union
17329 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
17331 // Otherwise, create a new declaration. If there is a previous
17332 // declaration of the same entity, the two will be linked via
17336 if (Kind
== TTK_Enum
) {
17337 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17338 // enum X { A, B, C } D; D should chain to X.
17339 New
= EnumDecl::Create(Context
, SearchDC
, KWLoc
, Loc
, Name
,
17340 cast_or_null
<EnumDecl
>(PrevDecl
), ScopedEnum
,
17341 ScopedEnumUsesClassTag
, IsFixed
);
17343 if (isStdAlignValT
&& (!StdAlignValT
|| getStdAlignValT()->isImplicit()))
17344 StdAlignValT
= cast
<EnumDecl
>(New
);
17346 // If this is an undefined enum, warn.
17347 if (TUK
!= TUK_Definition
&& !Invalid
) {
17349 if (IsFixed
&& cast
<EnumDecl
>(New
)->isFixed()) {
17350 // C++0x: 7.2p2: opaque-enum-declaration.
17351 // Conflicts are diagnosed above. Do nothing.
17353 else if (PrevDecl
&& (Def
= cast
<EnumDecl
>(PrevDecl
)->getDefinition())) {
17354 Diag(Loc
, diag::ext_forward_ref_enum_def
)
17356 Diag(Def
->getLocation(), diag::note_previous_definition
);
17358 unsigned DiagID
= diag::ext_forward_ref_enum
;
17359 if (getLangOpts().MSVCCompat
)
17360 DiagID
= diag::ext_ms_forward_ref_enum
;
17361 else if (getLangOpts().CPlusPlus
)
17362 DiagID
= diag::err_forward_ref_enum
;
17367 if (EnumUnderlying
) {
17368 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
17369 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
17370 ED
->setIntegerTypeSourceInfo(TI
);
17372 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
17373 QualType EnumTy
= ED
->getIntegerType();
17374 ED
->setPromotionType(Context
.isPromotableIntegerType(EnumTy
)
17375 ? Context
.getPromotedIntegerType(EnumTy
)
17377 assert(ED
->isComplete() && "enum with type should be complete");
17380 // struct/union/class
17382 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17383 // struct X { int A; } D; D should chain to X.
17384 if (getLangOpts().CPlusPlus
) {
17385 // FIXME: Look for a way to use RecordDecl for simple structs.
17386 New
= CXXRecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17387 cast_or_null
<CXXRecordDecl
>(PrevDecl
));
17389 if (isStdBadAlloc
&& (!StdBadAlloc
|| getStdBadAlloc()->isImplicit()))
17390 StdBadAlloc
= cast
<CXXRecordDecl
>(New
);
17392 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, KWLoc
, Loc
, Name
,
17393 cast_or_null
<RecordDecl
>(PrevDecl
));
17396 if (OOK
!= OOK_Outside
&& TUK
== TUK_Definition
&& !getLangOpts().CPlusPlus
)
17397 Diag(New
->getLocation(), diag::ext_type_defined_in_offsetof
)
17398 << (OOK
== OOK_Macro
) << New
->getSourceRange();
17400 // C++11 [dcl.type]p3:
17401 // A type-specifier-seq shall not define a class or enumeration [...].
17402 if (!Invalid
&& getLangOpts().CPlusPlus
&&
17403 (IsTypeSpecifier
|| IsTemplateParamOrArg
) && TUK
== TUK_Definition
) {
17404 Diag(New
->getLocation(), diag::err_type_defined_in_type_specifier
)
17405 << Context
.getTagDeclType(New
);
17409 if (!Invalid
&& getLangOpts().CPlusPlus
&& TUK
== TUK_Definition
&&
17410 DC
->getDeclKind() == Decl::Enum
) {
17411 Diag(New
->getLocation(), diag::err_type_defined_in_enum
)
17412 << Context
.getTagDeclType(New
);
17416 // Maybe add qualifier info.
17417 if (SS
.isNotEmpty()) {
17419 // If this is either a declaration or a definition, check the
17420 // nested-name-specifier against the current context.
17421 if ((TUK
== TUK_Definition
|| TUK
== TUK_Declaration
) &&
17422 diagnoseQualifiedDeclaration(SS
, DC
, OrigName
, Loc
,
17423 isMemberSpecialization
))
17426 New
->setQualifierInfo(SS
.getWithLocInContext(Context
));
17427 if (TemplateParameterLists
.size() > 0) {
17428 New
->setTemplateParameterListsInfo(Context
, TemplateParameterLists
);
17435 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
17436 // Add alignment attributes if necessary; these attributes are checked when
17437 // the ASTContext lays out the structure.
17439 // It is important for implementing the correct semantics that this
17440 // happen here (in ActOnTag). The #pragma pack stack is
17441 // maintained as a result of parser callbacks which can occur at
17442 // many points during the parsing of a struct declaration (because
17443 // the #pragma tokens are effectively skipped over during the
17444 // parsing of the struct).
17445 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
17446 AddAlignmentAttributesForRecord(RD
);
17447 AddMsStructLayoutForRecord(RD
);
17451 if (ModulePrivateLoc
.isValid()) {
17452 if (isMemberSpecialization
)
17453 Diag(New
->getLocation(), diag::err_module_private_specialization
)
17455 << FixItHint::CreateRemoval(ModulePrivateLoc
);
17456 // __module_private__ does not apply to local classes. However, we only
17457 // diagnose this as an error when the declaration specifiers are
17458 // freestanding. Here, we just ignore the __module_private__.
17459 else if (!SearchDC
->isFunctionOrMethod())
17460 New
->setModulePrivate();
17463 // If this is a specialization of a member class (of a class template),
17464 // check the specialization.
17465 if (isMemberSpecialization
&& CheckMemberSpecialization(New
, Previous
))
17468 // If we're declaring or defining a tag in function prototype scope in C,
17469 // note that this type can only be used within the function and add it to
17470 // the list of decls to inject into the function definition scope.
17471 if ((Name
|| Kind
== TTK_Enum
) &&
17472 getNonFieldDeclScope(S
)->isFunctionPrototypeScope()) {
17473 if (getLangOpts().CPlusPlus
) {
17474 // C++ [dcl.fct]p6:
17475 // Types shall not be defined in return or parameter types.
17476 if (TUK
== TUK_Definition
&& !IsTypeSpecifier
) {
17477 Diag(Loc
, diag::err_type_defined_in_param_type
)
17481 } else if (!PrevDecl
) {
17482 Diag(Loc
, diag::warn_decl_in_param_list
) << Context
.getTagDeclType(New
);
17487 New
->setInvalidDecl();
17489 // Set the lexical context. If the tag has a C++ scope specifier, the
17490 // lexical context will be different from the semantic context.
17491 New
->setLexicalDeclContext(CurContext
);
17493 // Mark this as a friend decl if applicable.
17494 // In Microsoft mode, a friend declaration also acts as a forward
17495 // declaration so we always pass true to setObjectOfFriendDecl to make
17496 // the tag name visible.
17497 if (TUK
== TUK_Friend
)
17498 New
->setObjectOfFriendDecl(getLangOpts().MSVCCompat
);
17500 // Set the access specifier.
17501 if (!Invalid
&& SearchDC
->isRecord())
17502 SetMemberAccessSpecifier(New
, PrevDecl
, AS
);
17505 CheckRedeclarationInModule(New
, PrevDecl
);
17507 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
))
17508 New
->startDefinition();
17510 ProcessDeclAttributeList(S
, New
, Attrs
);
17511 AddPragmaAttributes(S
, New
);
17513 // If this has an identifier, add it to the scope stack.
17514 if (TUK
== TUK_Friend
) {
17515 // We might be replacing an existing declaration in the lookup tables;
17516 // if so, borrow its access specifier.
17518 New
->setAccess(PrevDecl
->getAccess());
17520 DeclContext
*DC
= New
->getDeclContext()->getRedeclContext();
17521 DC
->makeDeclVisibleInContext(New
);
17522 if (Name
) // can be null along some error paths
17523 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
17524 PushOnScopeChains(New
, EnclosingScope
, /* AddToContext = */ false);
17526 S
= getNonFieldDeclScope(S
);
17527 PushOnScopeChains(New
, S
, true);
17529 CurContext
->addDecl(New
);
17532 // If this is the C FILE type, notify the AST context.
17533 if (IdentifierInfo
*II
= New
->getIdentifier())
17534 if (!New
->isInvalidDecl() &&
17535 New
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
17537 Context
.setFILEDecl(New
);
17540 mergeDeclAttributes(New
, PrevDecl
);
17542 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(New
))
17543 inferGslOwnerPointerAttribute(CXXRD
);
17545 // If there's a #pragma GCC visibility in scope, set the visibility of this
17547 AddPushedVisibilityAttribute(New
);
17549 if (isMemberSpecialization
&& !New
->isInvalidDecl())
17550 CompleteMemberSpecialization(New
, Previous
);
17553 // In C++, don't return an invalid declaration. We can't recover well from
17554 // the cases where we make the type anonymous.
17555 if (Invalid
&& getLangOpts().CPlusPlus
) {
17556 if (New
->isBeingDefined())
17557 if (auto RD
= dyn_cast
<RecordDecl
>(New
))
17558 RD
->completeDefinition();
17560 } else if (SkipBody
&& SkipBody
->ShouldSkip
) {
17561 return SkipBody
->Previous
;
17567 void Sema::ActOnTagStartDefinition(Scope
*S
, Decl
*TagD
) {
17568 AdjustDeclIfTemplate(TagD
);
17569 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17571 // Enter the tag context.
17572 PushDeclContext(S
, Tag
);
17574 ActOnDocumentableDecl(TagD
);
17576 // If there's a #pragma GCC visibility in scope, set the visibility of this
17578 AddPushedVisibilityAttribute(Tag
);
17581 bool Sema::ActOnDuplicateDefinition(Decl
*Prev
, SkipBodyInfo
&SkipBody
) {
17582 if (!hasStructuralCompatLayout(Prev
, SkipBody
.New
))
17585 // Make the previous decl visible.
17586 makeMergedDefinitionVisible(SkipBody
.Previous
);
17590 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl
*IDecl
) {
17591 assert(IDecl
->getLexicalParent() == CurContext
&&
17592 "The next DeclContext should be lexically contained in the current one.");
17593 CurContext
= IDecl
;
17596 void Sema::ActOnStartCXXMemberDeclarations(Scope
*S
, Decl
*TagD
,
17597 SourceLocation FinalLoc
,
17598 bool IsFinalSpelledSealed
,
17600 SourceLocation LBraceLoc
) {
17601 AdjustDeclIfTemplate(TagD
);
17602 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(TagD
);
17604 FieldCollector
->StartClass();
17606 if (!Record
->getIdentifier())
17610 Record
->markAbstract();
17612 if (FinalLoc
.isValid()) {
17613 Record
->addAttr(FinalAttr::Create(
17614 Context
, FinalLoc
, AttributeCommonInfo::AS_Keyword
,
17615 static_cast<FinalAttr::Spelling
>(IsFinalSpelledSealed
)));
17618 // [...] The class-name is also inserted into the scope of the
17619 // class itself; this is known as the injected-class-name. For
17620 // purposes of access checking, the injected-class-name is treated
17621 // as if it were a public member name.
17622 CXXRecordDecl
*InjectedClassName
= CXXRecordDecl::Create(
17623 Context
, Record
->getTagKind(), CurContext
, Record
->getBeginLoc(),
17624 Record
->getLocation(), Record
->getIdentifier(),
17625 /*PrevDecl=*/nullptr,
17626 /*DelayTypeCreation=*/true);
17627 Context
.getTypeDeclType(InjectedClassName
, Record
);
17628 InjectedClassName
->setImplicit();
17629 InjectedClassName
->setAccess(AS_public
);
17630 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate())
17631 InjectedClassName
->setDescribedClassTemplate(Template
);
17632 PushOnScopeChains(InjectedClassName
, S
);
17633 assert(InjectedClassName
->isInjectedClassName() &&
17634 "Broken injected-class-name");
17637 void Sema::ActOnTagFinishDefinition(Scope
*S
, Decl
*TagD
,
17638 SourceRange BraceRange
) {
17639 AdjustDeclIfTemplate(TagD
);
17640 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17641 Tag
->setBraceRange(BraceRange
);
17643 // Make sure we "complete" the definition even it is invalid.
17644 if (Tag
->isBeingDefined()) {
17645 assert(Tag
->isInvalidDecl() && "We should already have completed it");
17646 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
))
17647 RD
->completeDefinition();
17650 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
17651 FieldCollector
->FinishClass();
17652 if (RD
->hasAttr
<SYCLSpecialClassAttr
>()) {
17653 auto *Def
= RD
->getDefinition();
17654 assert(Def
&& "The record is expected to have a completed definition");
17655 unsigned NumInitMethods
= 0;
17656 for (auto *Method
: Def
->methods()) {
17657 if (!Method
->getIdentifier())
17659 if (Method
->getName() == "__init")
17662 if (NumInitMethods
> 1 || !Def
->hasInitMethod())
17663 Diag(RD
->getLocation(), diag::err_sycl_special_type_num_init_method
);
17667 // Exit this scope of this tag's definition.
17670 if (getCurLexicalContext()->isObjCContainer() &&
17671 Tag
->getDeclContext()->isFileContext())
17672 Tag
->setTopLevelDeclInObjCContainer();
17674 // Notify the consumer that we've defined a tag.
17675 if (!Tag
->isInvalidDecl())
17676 Consumer
.HandleTagDeclDefinition(Tag
);
17678 // Clangs implementation of #pragma align(packed) differs in bitfield layout
17679 // from XLs and instead matches the XL #pragma pack(1) behavior.
17680 if (Context
.getTargetInfo().getTriple().isOSAIX() &&
17681 AlignPackStack
.hasValue()) {
17682 AlignPackInfo APInfo
= AlignPackStack
.CurrentValue
;
17683 // Only diagnose #pragma align(packed).
17684 if (!APInfo
.IsAlignAttr() || APInfo
.getAlignMode() != AlignPackInfo::Packed
)
17686 const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
);
17689 // Only warn if there is at least 1 bitfield member.
17690 if (llvm::any_of(RD
->fields(),
17691 [](const FieldDecl
*FD
) { return FD
->isBitField(); }))
17692 Diag(BraceRange
.getBegin(), diag::warn_pragma_align_not_xl_compatible
);
17696 void Sema::ActOnObjCContainerFinishDefinition() {
17697 // Exit this scope of this interface definition.
17701 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl
*ObjCCtx
) {
17702 assert(ObjCCtx
== CurContext
&& "Mismatch of container contexts");
17703 OriginalLexicalContext
= ObjCCtx
;
17704 ActOnObjCContainerFinishDefinition();
17707 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl
*ObjCCtx
) {
17708 ActOnObjCContainerStartDefinition(ObjCCtx
);
17709 OriginalLexicalContext
= nullptr;
17712 void Sema::ActOnTagDefinitionError(Scope
*S
, Decl
*TagD
) {
17713 AdjustDeclIfTemplate(TagD
);
17714 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
17715 Tag
->setInvalidDecl();
17717 // Make sure we "complete" the definition even it is invalid.
17718 if (Tag
->isBeingDefined()) {
17719 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(Tag
))
17720 RD
->completeDefinition();
17723 // We're undoing ActOnTagStartDefinition here, not
17724 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17725 // the FieldCollector.
17730 // Note that FieldName may be null for anonymous bitfields.
17731 ExprResult
Sema::VerifyBitField(SourceLocation FieldLoc
,
17732 IdentifierInfo
*FieldName
, QualType FieldTy
,
17733 bool IsMsStruct
, Expr
*BitWidth
) {
17735 if (BitWidth
->containsErrors())
17736 return ExprError();
17738 // C99 6.7.2.1p4 - verify the field type.
17739 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17740 if (!FieldTy
->isDependentType() && !FieldTy
->isIntegralOrEnumerationType()) {
17741 // Handle incomplete and sizeless types with a specific error.
17742 if (RequireCompleteSizedType(FieldLoc
, FieldTy
,
17743 diag::err_field_incomplete_or_sizeless
))
17744 return ExprError();
17746 return Diag(FieldLoc
, diag::err_not_integral_type_bitfield
)
17747 << FieldName
<< FieldTy
<< BitWidth
->getSourceRange();
17748 return Diag(FieldLoc
, diag::err_not_integral_type_anon_bitfield
)
17749 << FieldTy
<< BitWidth
->getSourceRange();
17750 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr
*>(BitWidth
),
17751 UPPC_BitFieldWidth
))
17752 return ExprError();
17754 // If the bit-width is type- or value-dependent, don't try to check
17756 if (BitWidth
->isValueDependent() || BitWidth
->isTypeDependent())
17759 llvm::APSInt Value
;
17760 ExprResult ICE
= VerifyIntegerConstantExpression(BitWidth
, &Value
, AllowFold
);
17761 if (ICE
.isInvalid())
17763 BitWidth
= ICE
.get();
17765 // Zero-width bitfield is ok for anonymous field.
17766 if (Value
== 0 && FieldName
)
17767 return Diag(FieldLoc
, diag::err_bitfield_has_zero_width
) << FieldName
;
17769 if (Value
.isSigned() && Value
.isNegative()) {
17771 return Diag(FieldLoc
, diag::err_bitfield_has_negative_width
)
17772 << FieldName
<< toString(Value
, 10);
17773 return Diag(FieldLoc
, diag::err_anon_bitfield_has_negative_width
)
17774 << toString(Value
, 10);
17777 // The size of the bit-field must not exceed our maximum permitted object
17779 if (Value
.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context
)) {
17780 return Diag(FieldLoc
, diag::err_bitfield_too_wide
)
17781 << !FieldName
<< FieldName
<< toString(Value
, 10);
17784 if (!FieldTy
->isDependentType()) {
17785 uint64_t TypeStorageSize
= Context
.getTypeSize(FieldTy
);
17786 uint64_t TypeWidth
= Context
.getIntWidth(FieldTy
);
17787 bool BitfieldIsOverwide
= Value
.ugt(TypeWidth
);
17789 // Over-wide bitfields are an error in C or when using the MSVC bitfield
17791 bool CStdConstraintViolation
=
17792 BitfieldIsOverwide
&& !getLangOpts().CPlusPlus
;
17793 bool MSBitfieldViolation
=
17794 Value
.ugt(TypeStorageSize
) &&
17795 (IsMsStruct
|| Context
.getTargetInfo().getCXXABI().isMicrosoft());
17796 if (CStdConstraintViolation
|| MSBitfieldViolation
) {
17797 unsigned DiagWidth
=
17798 CStdConstraintViolation
? TypeWidth
: TypeStorageSize
;
17799 return Diag(FieldLoc
, diag::err_bitfield_width_exceeds_type_width
)
17800 << (bool)FieldName
<< FieldName
<< toString(Value
, 10)
17801 << !CStdConstraintViolation
<< DiagWidth
;
17804 // Warn on types where the user might conceivably expect to get all
17805 // specified bits as value bits: that's all integral types other than
17807 if (BitfieldIsOverwide
&& !FieldTy
->isBooleanType() && FieldName
) {
17808 Diag(FieldLoc
, diag::warn_bitfield_width_exceeds_type_width
)
17809 << FieldName
<< toString(Value
, 10)
17810 << (unsigned)TypeWidth
;
17817 /// ActOnField - Each field of a C struct/union is passed into this in order
17818 /// to create a FieldDecl object for it.
17819 Decl
*Sema::ActOnField(Scope
*S
, Decl
*TagD
, SourceLocation DeclStart
,
17820 Declarator
&D
, Expr
*BitfieldWidth
) {
17821 FieldDecl
*Res
= HandleField(S
, cast_or_null
<RecordDecl
>(TagD
),
17822 DeclStart
, D
, static_cast<Expr
*>(BitfieldWidth
),
17823 /*InitStyle=*/ICIS_NoInit
, AS_public
);
17827 /// HandleField - Analyze a field of a C struct or a C++ data member.
17829 FieldDecl
*Sema::HandleField(Scope
*S
, RecordDecl
*Record
,
17830 SourceLocation DeclStart
,
17831 Declarator
&D
, Expr
*BitWidth
,
17832 InClassInitStyle InitStyle
,
17833 AccessSpecifier AS
) {
17834 if (D
.isDecompositionDeclarator()) {
17835 const DecompositionDeclarator
&Decomp
= D
.getDecompositionDeclarator();
17836 Diag(Decomp
.getLSquareLoc(), diag::err_decomp_decl_context
)
17837 << Decomp
.getSourceRange();
17841 IdentifierInfo
*II
= D
.getIdentifier();
17842 SourceLocation Loc
= DeclStart
;
17843 if (II
) Loc
= D
.getIdentifierLoc();
17845 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
17846 QualType T
= TInfo
->getType();
17847 if (getLangOpts().CPlusPlus
) {
17848 CheckExtraCXXDefaultArguments(D
);
17850 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
17851 UPPC_DataMemberType
)) {
17852 D
.setInvalidType();
17854 TInfo
= Context
.getTrivialTypeSourceInfo(T
, Loc
);
17858 DiagnoseFunctionSpecifiers(D
.getDeclSpec());
17860 if (D
.getDeclSpec().isInlineSpecified())
17861 Diag(D
.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function
)
17862 << getLangOpts().CPlusPlus17
;
17863 if (DeclSpec::TSCS TSCS
= D
.getDeclSpec().getThreadStorageClassSpec())
17864 Diag(D
.getDeclSpec().getThreadStorageClassSpecLoc(),
17865 diag::err_invalid_thread
)
17866 << DeclSpec::getSpecifierName(TSCS
);
17868 // Check to see if this name was declared as a member previously
17869 NamedDecl
*PrevDecl
= nullptr;
17870 LookupResult
Previous(*this, II
, Loc
, LookupMemberName
,
17871 ForVisibleRedeclaration
);
17872 LookupName(Previous
, S
);
17873 switch (Previous
.getResultKind()) {
17874 case LookupResult::Found
:
17875 case LookupResult::FoundUnresolvedValue
:
17876 PrevDecl
= Previous
.getAsSingle
<NamedDecl
>();
17879 case LookupResult::FoundOverloaded
:
17880 PrevDecl
= Previous
.getRepresentativeDecl();
17883 case LookupResult::NotFound
:
17884 case LookupResult::NotFoundInCurrentInstantiation
:
17885 case LookupResult::Ambiguous
:
17888 Previous
.suppressDiagnostics();
17890 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
17891 // Maybe we will complain about the shadowed template parameter.
17892 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
17893 // Just pretend that we didn't see the previous declaration.
17894 PrevDecl
= nullptr;
17897 if (PrevDecl
&& !isDeclInScope(PrevDecl
, Record
, S
))
17898 PrevDecl
= nullptr;
17901 = (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable
);
17902 SourceLocation TSSL
= D
.getBeginLoc();
17904 = CheckFieldDecl(II
, T
, TInfo
, Record
, Loc
, Mutable
, BitWidth
, InitStyle
,
17905 TSSL
, AS
, PrevDecl
, &D
);
17907 if (NewFD
->isInvalidDecl())
17908 Record
->setInvalidDecl();
17910 if (D
.getDeclSpec().isModulePrivateSpecified())
17911 NewFD
->setModulePrivate();
17913 if (NewFD
->isInvalidDecl() && PrevDecl
) {
17914 // Don't introduce NewFD into scope; there's already something
17915 // with the same name in the same scope.
17917 PushOnScopeChains(NewFD
, S
);
17919 Record
->addDecl(NewFD
);
17924 /// Build a new FieldDecl and check its well-formedness.
17926 /// This routine builds a new FieldDecl given the fields name, type,
17927 /// record, etc. \p PrevDecl should refer to any previous declaration
17928 /// with the same name and in the same scope as the field to be
17931 /// \returns a new FieldDecl.
17933 /// \todo The Declarator argument is a hack. It will be removed once
17934 FieldDecl
*Sema::CheckFieldDecl(DeclarationName Name
, QualType T
,
17935 TypeSourceInfo
*TInfo
,
17936 RecordDecl
*Record
, SourceLocation Loc
,
17937 bool Mutable
, Expr
*BitWidth
,
17938 InClassInitStyle InitStyle
,
17939 SourceLocation TSSL
,
17940 AccessSpecifier AS
, NamedDecl
*PrevDecl
,
17942 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
17943 bool InvalidDecl
= false;
17944 if (D
) InvalidDecl
= D
->isInvalidType();
17946 // If we receive a broken type, recover by assuming 'int' and
17947 // marking this declaration as invalid.
17948 if (T
.isNull() || T
->containsErrors()) {
17949 InvalidDecl
= true;
17953 QualType EltTy
= Context
.getBaseElementType(T
);
17954 if (!EltTy
->isDependentType() && !EltTy
->containsErrors()) {
17955 if (RequireCompleteSizedType(Loc
, EltTy
,
17956 diag::err_field_incomplete_or_sizeless
)) {
17957 // Fields of incomplete type force their record to be invalid.
17958 Record
->setInvalidDecl();
17959 InvalidDecl
= true;
17962 EltTy
->isIncompleteType(&Def
);
17963 if (Def
&& Def
->isInvalidDecl()) {
17964 Record
->setInvalidDecl();
17965 InvalidDecl
= true;
17970 // TR 18037 does not allow fields to be declared with address space
17971 if (T
.hasAddressSpace() || T
->isDependentAddressSpaceType() ||
17972 T
->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
17973 Diag(Loc
, diag::err_field_with_address_space
);
17974 Record
->setInvalidDecl();
17975 InvalidDecl
= true;
17978 if (LangOpts
.OpenCL
) {
17979 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17980 // used as structure or union field: image, sampler, event or block types.
17981 if (T
->isEventT() || T
->isImageType() || T
->isSamplerT() ||
17982 T
->isBlockPointerType()) {
17983 Diag(Loc
, diag::err_opencl_type_struct_or_union_field
) << T
;
17984 Record
->setInvalidDecl();
17985 InvalidDecl
= true;
17987 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17989 if (BitWidth
&& !getOpenCLOptions().isAvailableOption(
17990 "__cl_clang_bitfields", LangOpts
)) {
17991 Diag(Loc
, diag::err_opencl_bitfields
);
17992 InvalidDecl
= true;
17996 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17997 if (!InvalidDecl
&& getLangOpts().CPlusPlus
&& !II
&& BitWidth
&&
17998 T
.hasQualifiers()) {
17999 InvalidDecl
= true;
18000 Diag(Loc
, diag::err_anon_bitfield_qualifiers
);
18003 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18004 // than a variably modified type.
18005 if (!InvalidDecl
&& T
->isVariablyModifiedType()) {
18006 if (!tryToFixVariablyModifiedVarType(
18007 TInfo
, T
, Loc
, diag::err_typecheck_field_variable_size
))
18008 InvalidDecl
= true;
18011 // Fields can not have abstract class types
18012 if (!InvalidDecl
&& RequireNonAbstractType(Loc
, T
,
18013 diag::err_abstract_type_in_decl
,
18014 AbstractFieldType
))
18015 InvalidDecl
= true;
18018 BitWidth
= nullptr;
18019 // If this is declared as a bit-field, check the bit-field.
18022 VerifyBitField(Loc
, II
, T
, Record
->isMsStruct(Context
), BitWidth
).get();
18024 InvalidDecl
= true;
18025 BitWidth
= nullptr;
18029 // Check that 'mutable' is consistent with the type of the declaration.
18030 if (!InvalidDecl
&& Mutable
) {
18031 unsigned DiagID
= 0;
18032 if (T
->isReferenceType())
18033 DiagID
= getLangOpts().MSVCCompat
? diag::ext_mutable_reference
18034 : diag::err_mutable_reference
;
18035 else if (T
.isConstQualified())
18036 DiagID
= diag::err_mutable_const
;
18039 SourceLocation ErrLoc
= Loc
;
18040 if (D
&& D
->getDeclSpec().getStorageClassSpecLoc().isValid())
18041 ErrLoc
= D
->getDeclSpec().getStorageClassSpecLoc();
18042 Diag(ErrLoc
, DiagID
);
18043 if (DiagID
!= diag::ext_mutable_reference
) {
18045 InvalidDecl
= true;
18050 // C++11 [class.union]p8 (DR1460):
18051 // At most one variant member of a union may have a
18052 // brace-or-equal-initializer.
18053 if (InitStyle
!= ICIS_NoInit
)
18054 checkDuplicateDefaultInit(*this, cast
<CXXRecordDecl
>(Record
), Loc
);
18056 FieldDecl
*NewFD
= FieldDecl::Create(Context
, Record
, TSSL
, Loc
, II
, T
, TInfo
,
18057 BitWidth
, Mutable
, InitStyle
);
18059 NewFD
->setInvalidDecl();
18061 if (PrevDecl
&& !isa
<TagDecl
>(PrevDecl
)) {
18062 Diag(Loc
, diag::err_duplicate_member
) << II
;
18063 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
18064 NewFD
->setInvalidDecl();
18067 if (!InvalidDecl
&& getLangOpts().CPlusPlus
) {
18068 if (Record
->isUnion()) {
18069 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
18070 CXXRecordDecl
* RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
18071 if (RDecl
->getDefinition()) {
18072 // C++ [class.union]p1: An object of a class with a non-trivial
18073 // constructor, a non-trivial copy constructor, a non-trivial
18074 // destructor, or a non-trivial copy assignment operator
18075 // cannot be a member of a union, nor can an array of such
18077 if (CheckNontrivialField(NewFD
))
18078 NewFD
->setInvalidDecl();
18082 // C++ [class.union]p1: If a union contains a member of reference type,
18083 // the program is ill-formed, except when compiling with MSVC extensions
18085 if (EltTy
->isReferenceType()) {
18086 Diag(NewFD
->getLocation(), getLangOpts().MicrosoftExt
?
18087 diag::ext_union_member_of_reference_type
:
18088 diag::err_union_member_of_reference_type
)
18089 << NewFD
->getDeclName() << EltTy
;
18090 if (!getLangOpts().MicrosoftExt
)
18091 NewFD
->setInvalidDecl();
18096 // FIXME: We need to pass in the attributes given an AST
18097 // representation, not a parser representation.
18099 // FIXME: The current scope is almost... but not entirely... correct here.
18100 ProcessDeclAttributes(getCurScope(), NewFD
, *D
);
18102 if (NewFD
->hasAttrs())
18103 CheckAlignasUnderalignment(NewFD
);
18106 // In auto-retain/release, infer strong retension for fields of
18107 // retainable type.
18108 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewFD
))
18109 NewFD
->setInvalidDecl();
18111 if (T
.isObjCGCWeak())
18112 Diag(Loc
, diag::warn_attribute_weak_on_field
);
18114 // PPC MMA non-pointer types are not allowed as field types.
18115 if (Context
.getTargetInfo().getTriple().isPPC64() &&
18116 CheckPPCMMAType(T
, NewFD
->getLocation()))
18117 NewFD
->setInvalidDecl();
18119 NewFD
->setAccess(AS
);
18123 bool Sema::CheckNontrivialField(FieldDecl
*FD
) {
18125 assert(getLangOpts().CPlusPlus
&& "valid check only for C++");
18127 if (FD
->isInvalidDecl() || FD
->getType()->isDependentType())
18130 QualType EltTy
= Context
.getBaseElementType(FD
->getType());
18131 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
18132 CXXRecordDecl
*RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
18133 if (RDecl
->getDefinition()) {
18134 // We check for copy constructors before constructors
18135 // because otherwise we'll never get complaints about
18136 // copy constructors.
18138 CXXSpecialMember member
= CXXInvalid
;
18139 // We're required to check for any non-trivial constructors. Since the
18140 // implicit default constructor is suppressed if there are any
18141 // user-declared constructors, we just need to check that there is a
18142 // trivial default constructor and a trivial copy constructor. (We don't
18143 // worry about move constructors here, since this is a C++98 check.)
18144 if (RDecl
->hasNonTrivialCopyConstructor())
18145 member
= CXXCopyConstructor
;
18146 else if (!RDecl
->hasTrivialDefaultConstructor())
18147 member
= CXXDefaultConstructor
;
18148 else if (RDecl
->hasNonTrivialCopyAssignment())
18149 member
= CXXCopyAssignment
;
18150 else if (RDecl
->hasNonTrivialDestructor())
18151 member
= CXXDestructor
;
18153 if (member
!= CXXInvalid
) {
18154 if (!getLangOpts().CPlusPlus11
&&
18155 getLangOpts().ObjCAutoRefCount
&& RDecl
->hasObjectMember()) {
18156 // Objective-C++ ARC: it is an error to have a non-trivial field of
18157 // a union. However, system headers in Objective-C programs
18158 // occasionally have Objective-C lifetime objects within unions,
18159 // and rather than cause the program to fail, we make those
18160 // members unavailable.
18161 SourceLocation Loc
= FD
->getLocation();
18162 if (getSourceManager().isInSystemHeader(Loc
)) {
18163 if (!FD
->hasAttr
<UnavailableAttr
>())
18164 FD
->addAttr(UnavailableAttr::CreateImplicit(Context
, "",
18165 UnavailableAttr::IR_ARCFieldWithOwnership
, Loc
));
18170 Diag(FD
->getLocation(), getLangOpts().CPlusPlus11
?
18171 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
:
18172 diag::err_illegal_union_or_anon_struct_member
)
18173 << FD
->getParent()->isUnion() << FD
->getDeclName() << member
;
18174 DiagnoseNontrivial(RDecl
, member
);
18175 return !getLangOpts().CPlusPlus11
;
18183 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18184 /// AST enum value.
18185 static ObjCIvarDecl::AccessControl
18186 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility
) {
18187 switch (ivarVisibility
) {
18188 default: llvm_unreachable("Unknown visitibility kind");
18189 case tok::objc_private
: return ObjCIvarDecl::Private
;
18190 case tok::objc_public
: return ObjCIvarDecl::Public
;
18191 case tok::objc_protected
: return ObjCIvarDecl::Protected
;
18192 case tok::objc_package
: return ObjCIvarDecl::Package
;
18196 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18197 /// in order to create an IvarDecl object for it.
18198 Decl
*Sema::ActOnIvar(Scope
*S
,
18199 SourceLocation DeclStart
,
18200 Declarator
&D
, Expr
*BitfieldWidth
,
18201 tok::ObjCKeywordKind Visibility
) {
18203 IdentifierInfo
*II
= D
.getIdentifier();
18204 Expr
*BitWidth
= (Expr
*)BitfieldWidth
;
18205 SourceLocation Loc
= DeclStart
;
18206 if (II
) Loc
= D
.getIdentifierLoc();
18208 // FIXME: Unnamed fields can be handled in various different ways, for
18209 // example, unnamed unions inject all members into the struct namespace!
18211 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
18212 QualType T
= TInfo
->getType();
18215 // 6.7.2.1p3, 6.7.2.1p4
18216 BitWidth
= VerifyBitField(Loc
, II
, T
, /*IsMsStruct*/false, BitWidth
).get();
18218 D
.setInvalidType();
18225 if (T
->isReferenceType()) {
18226 Diag(Loc
, diag::err_ivar_reference_type
);
18227 D
.setInvalidType();
18229 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18230 // than a variably modified type.
18231 else if (T
->isVariablyModifiedType()) {
18232 if (!tryToFixVariablyModifiedVarType(
18233 TInfo
, T
, Loc
, diag::err_typecheck_ivar_variable_size
))
18234 D
.setInvalidType();
18237 // Get the visibility (access control) for this ivar.
18238 ObjCIvarDecl::AccessControl ac
=
18239 Visibility
!= tok::objc_not_keyword
? TranslateIvarVisibility(Visibility
)
18240 : ObjCIvarDecl::None
;
18241 // Must set ivar's DeclContext to its enclosing interface.
18242 ObjCContainerDecl
*EnclosingDecl
= cast
<ObjCContainerDecl
>(CurContext
);
18243 if (!EnclosingDecl
|| EnclosingDecl
->isInvalidDecl())
18245 ObjCContainerDecl
*EnclosingContext
;
18246 if (ObjCImplementationDecl
*IMPDecl
=
18247 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
18248 if (LangOpts
.ObjCRuntime
.isFragile()) {
18249 // Case of ivar declared in an implementation. Context is that of its class.
18250 EnclosingContext
= IMPDecl
->getClassInterface();
18251 assert(EnclosingContext
&& "Implementation has no class interface!");
18254 EnclosingContext
= EnclosingDecl
;
18256 if (ObjCCategoryDecl
*CDecl
=
18257 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
18258 if (LangOpts
.ObjCRuntime
.isFragile() || !CDecl
->IsClassExtension()) {
18259 Diag(Loc
, diag::err_misplaced_ivar
) << CDecl
->IsClassExtension();
18263 EnclosingContext
= EnclosingDecl
;
18266 // Construct the decl.
18267 ObjCIvarDecl
*NewID
= ObjCIvarDecl::Create(Context
, EnclosingContext
,
18268 DeclStart
, Loc
, II
, T
,
18269 TInfo
, ac
, (Expr
*)BitfieldWidth
);
18272 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, Loc
, LookupMemberName
,
18273 ForVisibleRedeclaration
);
18274 if (PrevDecl
&& isDeclInScope(PrevDecl
, EnclosingContext
, S
)
18275 && !isa
<TagDecl
>(PrevDecl
)) {
18276 Diag(Loc
, diag::err_duplicate_member
) << II
;
18277 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
18278 NewID
->setInvalidDecl();
18282 // Process attributes attached to the ivar.
18283 ProcessDeclAttributes(S
, NewID
, D
);
18285 if (D
.isInvalidType())
18286 NewID
->setInvalidDecl();
18288 // In ARC, infer 'retaining' for ivars of retainable type.
18289 if (getLangOpts().ObjCAutoRefCount
&& inferObjCARCLifetime(NewID
))
18290 NewID
->setInvalidDecl();
18292 if (D
.getDeclSpec().isModulePrivateSpecified())
18293 NewID
->setModulePrivate();
18296 // FIXME: When interfaces are DeclContexts, we'll need to add
18297 // these to the interface.
18299 IdResolver
.AddDecl(NewID
);
18302 if (LangOpts
.ObjCRuntime
.isNonFragile() &&
18303 !NewID
->isInvalidDecl() && isa
<ObjCInterfaceDecl
>(EnclosingDecl
))
18304 Diag(Loc
, diag::warn_ivars_in_interface
);
18309 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18310 /// class and class extensions. For every class \@interface and class
18311 /// extension \@interface, if the last ivar is a bitfield of any type,
18312 /// then add an implicit `char :0` ivar to the end of that interface.
18313 void Sema::ActOnLastBitfield(SourceLocation DeclLoc
,
18314 SmallVectorImpl
<Decl
*> &AllIvarDecls
) {
18315 if (LangOpts
.ObjCRuntime
.isFragile() || AllIvarDecls
.empty())
18318 Decl
*ivarDecl
= AllIvarDecls
[AllIvarDecls
.size()-1];
18319 ObjCIvarDecl
*Ivar
= cast
<ObjCIvarDecl
>(ivarDecl
);
18321 if (!Ivar
->isBitField() || Ivar
->isZeroLengthBitField(Context
))
18323 ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(CurContext
);
18325 if (ObjCCategoryDecl
*CD
= dyn_cast
<ObjCCategoryDecl
>(CurContext
)) {
18326 if (!CD
->IsClassExtension())
18329 // No need to add this to end of @implementation.
18333 // All conditions are met. Add a new bitfield to the tail end of ivars.
18334 llvm::APInt
Zero(Context
.getTypeSize(Context
.IntTy
), 0);
18335 Expr
* BW
= IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
, DeclLoc
);
18337 Ivar
= ObjCIvarDecl::Create(Context
, cast
<ObjCContainerDecl
>(CurContext
),
18338 DeclLoc
, DeclLoc
, nullptr,
18340 Context
.getTrivialTypeSourceInfo(Context
.CharTy
,
18342 ObjCIvarDecl::Private
, BW
,
18344 AllIvarDecls
.push_back(Ivar
);
18347 /// [class.dtor]p4:
18348 /// At the end of the definition of a class, overload resolution is
18349 /// performed among the prospective destructors declared in that class with
18350 /// an empty argument list to select the destructor for the class, also
18351 /// known as the selected destructor.
18353 /// We do the overload resolution here, then mark the selected constructor in the AST.
18354 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18355 static void ComputeSelectedDestructor(Sema
&S
, CXXRecordDecl
*Record
) {
18356 if (!Record
->hasUserDeclaredDestructor()) {
18360 SourceLocation Loc
= Record
->getLocation();
18361 OverloadCandidateSet
OCS(Loc
, OverloadCandidateSet::CSK_Normal
);
18363 for (auto *Decl
: Record
->decls()) {
18364 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(Decl
)) {
18365 if (DD
->isInvalidDecl())
18367 S
.AddOverloadCandidate(DD
, DeclAccessPair::make(DD
, DD
->getAccess()), {},
18369 assert(DD
->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18376 OverloadCandidateSet::iterator Best
;
18378 OverloadCandidateDisplayKind DisplayKind
;
18380 switch (OCS
.BestViableFunction(S
, Loc
, Best
)) {
18383 Record
->addedSelectedDestructor(dyn_cast
<CXXDestructorDecl
>(Best
->Function
));
18387 Msg
= diag::err_ambiguous_destructor
;
18388 DisplayKind
= OCD_AmbiguousCandidates
;
18391 case OR_No_Viable_Function
:
18392 Msg
= diag::err_no_viable_destructor
;
18393 DisplayKind
= OCD_AllCandidates
;
18398 // OpenCL have got their own thing going with destructors. It's slightly broken,
18399 // but we allow it.
18400 if (!S
.LangOpts
.OpenCL
) {
18401 PartialDiagnostic Diag
= S
.PDiag(Msg
) << Record
;
18402 OCS
.NoteCandidates(PartialDiagnosticAt(Loc
, Diag
), S
, DisplayKind
, {});
18403 Record
->setInvalidDecl();
18405 // It's a bit hacky: At this point we've raised an error but we want the
18406 // rest of the compiler to continue somehow working. However almost
18407 // everything we'll try to do with the class will depend on there being a
18408 // destructor. So let's pretend the first one is selected and hope for the
18410 Record
->addedSelectedDestructor(dyn_cast
<CXXDestructorDecl
>(OCS
.begin()->Function
));
18414 /// [class.mem.special]p5
18415 /// Two special member functions are of the same kind if:
18416 /// - they are both default constructors,
18417 /// - they are both copy or move constructors with the same first parameter
18419 /// - they are both copy or move assignment operators with the same first
18420 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18421 static bool AreSpecialMemberFunctionsSameKind(ASTContext
&Context
,
18424 Sema::CXXSpecialMember CSM
) {
18425 // We don't want to compare templates to non-templates: See
18426 // https://github.com/llvm/llvm-project/issues/59206
18427 if (CSM
== Sema::CXXDefaultConstructor
)
18428 return bool(M1
->getDescribedFunctionTemplate()) ==
18429 bool(M2
->getDescribedFunctionTemplate());
18430 if (!Context
.hasSameType(M1
->getParamDecl(0)->getType(),
18431 M2
->getParamDecl(0)->getType()))
18433 if (!Context
.hasSameType(M1
->getThisType(), M2
->getThisType()))
18439 /// [class.mem.special]p6:
18440 /// An eligible special member function is a special member function for which:
18441 /// - the function is not deleted,
18442 /// - the associated constraints, if any, are satisfied, and
18443 /// - no special member function of the same kind whose associated constraints
18444 /// [CWG2595], if any, are satisfied is more constrained.
18445 static void SetEligibleMethods(Sema
&S
, CXXRecordDecl
*Record
,
18446 ArrayRef
<CXXMethodDecl
*> Methods
,
18447 Sema::CXXSpecialMember CSM
) {
18448 SmallVector
<bool, 4> SatisfactionStatus
;
18450 for (CXXMethodDecl
*Method
: Methods
) {
18451 const Expr
*Constraints
= Method
->getTrailingRequiresClause();
18453 SatisfactionStatus
.push_back(true);
18455 ConstraintSatisfaction Satisfaction
;
18456 if (S
.CheckFunctionConstraints(Method
, Satisfaction
))
18457 SatisfactionStatus
.push_back(false);
18459 SatisfactionStatus
.push_back(Satisfaction
.IsSatisfied
);
18463 for (size_t i
= 0; i
< Methods
.size(); i
++) {
18464 if (!SatisfactionStatus
[i
])
18466 CXXMethodDecl
*Method
= Methods
[i
];
18467 CXXMethodDecl
*OrigMethod
= Method
;
18468 if (FunctionDecl
*MF
= OrigMethod
->getInstantiatedFromMemberFunction())
18469 OrigMethod
= cast
<CXXMethodDecl
>(MF
);
18471 const Expr
*Constraints
= OrigMethod
->getTrailingRequiresClause();
18472 bool AnotherMethodIsMoreConstrained
= false;
18473 for (size_t j
= 0; j
< Methods
.size(); j
++) {
18474 if (i
== j
|| !SatisfactionStatus
[j
])
18476 CXXMethodDecl
*OtherMethod
= Methods
[j
];
18477 if (FunctionDecl
*MF
= OtherMethod
->getInstantiatedFromMemberFunction())
18478 OtherMethod
= cast
<CXXMethodDecl
>(MF
);
18480 if (!AreSpecialMemberFunctionsSameKind(S
.Context
, OrigMethod
, OtherMethod
,
18484 const Expr
*OtherConstraints
= OtherMethod
->getTrailingRequiresClause();
18485 if (!OtherConstraints
)
18487 if (!Constraints
) {
18488 AnotherMethodIsMoreConstrained
= true;
18491 if (S
.IsAtLeastAsConstrained(OtherMethod
, {OtherConstraints
}, OrigMethod
,
18493 AnotherMethodIsMoreConstrained
)) {
18494 // There was an error with the constraints comparison. Exit the loop
18495 // and don't consider this function eligible.
18496 AnotherMethodIsMoreConstrained
= true;
18498 if (AnotherMethodIsMoreConstrained
)
18501 // FIXME: Do not consider deleted methods as eligible after implementing
18502 // DR1734 and DR1496.
18503 if (!AnotherMethodIsMoreConstrained
) {
18504 Method
->setIneligibleOrNotSelected(false);
18505 Record
->addedEligibleSpecialMemberFunction(Method
, 1 << CSM
);
18510 static void ComputeSpecialMemberFunctionsEligiblity(Sema
&S
,
18511 CXXRecordDecl
*Record
) {
18512 SmallVector
<CXXMethodDecl
*, 4> DefaultConstructors
;
18513 SmallVector
<CXXMethodDecl
*, 4> CopyConstructors
;
18514 SmallVector
<CXXMethodDecl
*, 4> MoveConstructors
;
18515 SmallVector
<CXXMethodDecl
*, 4> CopyAssignmentOperators
;
18516 SmallVector
<CXXMethodDecl
*, 4> MoveAssignmentOperators
;
18518 for (auto *Decl
: Record
->decls()) {
18519 auto *MD
= dyn_cast
<CXXMethodDecl
>(Decl
);
18521 auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(Decl
);
18523 MD
= dyn_cast
<CXXMethodDecl
>(FTD
->getTemplatedDecl());
18527 if (auto *CD
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
18528 if (CD
->isInvalidDecl())
18530 if (CD
->isDefaultConstructor())
18531 DefaultConstructors
.push_back(MD
);
18532 else if (CD
->isCopyConstructor())
18533 CopyConstructors
.push_back(MD
);
18534 else if (CD
->isMoveConstructor())
18535 MoveConstructors
.push_back(MD
);
18536 } else if (MD
->isCopyAssignmentOperator()) {
18537 CopyAssignmentOperators
.push_back(MD
);
18538 } else if (MD
->isMoveAssignmentOperator()) {
18539 MoveAssignmentOperators
.push_back(MD
);
18543 SetEligibleMethods(S
, Record
, DefaultConstructors
,
18544 Sema::CXXDefaultConstructor
);
18545 SetEligibleMethods(S
, Record
, CopyConstructors
, Sema::CXXCopyConstructor
);
18546 SetEligibleMethods(S
, Record
, MoveConstructors
, Sema::CXXMoveConstructor
);
18547 SetEligibleMethods(S
, Record
, CopyAssignmentOperators
,
18548 Sema::CXXCopyAssignment
);
18549 SetEligibleMethods(S
, Record
, MoveAssignmentOperators
,
18550 Sema::CXXMoveAssignment
);
18553 void Sema::ActOnFields(Scope
*S
, SourceLocation RecLoc
, Decl
*EnclosingDecl
,
18554 ArrayRef
<Decl
*> Fields
, SourceLocation LBrac
,
18555 SourceLocation RBrac
,
18556 const ParsedAttributesView
&Attrs
) {
18557 assert(EnclosingDecl
&& "missing record or interface decl");
18559 // If this is an Objective-C @implementation or category and we have
18560 // new fields here we should reset the layout of the interface since
18561 // it will now change.
18562 if (!Fields
.empty() && isa
<ObjCContainerDecl
>(EnclosingDecl
)) {
18563 ObjCContainerDecl
*DC
= cast
<ObjCContainerDecl
>(EnclosingDecl
);
18564 switch (DC
->getKind()) {
18566 case Decl::ObjCCategory
:
18567 Context
.ResetObjCLayout(cast
<ObjCCategoryDecl
>(DC
)->getClassInterface());
18569 case Decl::ObjCImplementation
:
18571 ResetObjCLayout(cast
<ObjCImplementationDecl
>(DC
)->getClassInterface());
18576 RecordDecl
*Record
= dyn_cast
<RecordDecl
>(EnclosingDecl
);
18577 CXXRecordDecl
*CXXRecord
= dyn_cast
<CXXRecordDecl
>(EnclosingDecl
);
18579 // Start counting up the number of named members; make sure to include
18580 // members of anonymous structs and unions in the total.
18581 unsigned NumNamedMembers
= 0;
18583 for (const auto *I
: Record
->decls()) {
18584 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(I
))
18585 if (IFD
->getDeclName())
18590 // Verify that all the fields are okay.
18591 SmallVector
<FieldDecl
*, 32> RecFields
;
18593 for (ArrayRef
<Decl
*>::iterator i
= Fields
.begin(), end
= Fields
.end();
18595 FieldDecl
*FD
= cast
<FieldDecl
>(*i
);
18597 // Get the type for the field.
18598 const Type
*FDTy
= FD
->getType().getTypePtr();
18600 if (!FD
->isAnonymousStructOrUnion()) {
18601 // Remember all fields written by the user.
18602 RecFields
.push_back(FD
);
18605 // If the field is already invalid for some reason, don't emit more
18606 // diagnostics about it.
18607 if (FD
->isInvalidDecl()) {
18608 EnclosingDecl
->setInvalidDecl();
18613 // A structure or union shall not contain a member with
18614 // incomplete or function type (hence, a structure shall not
18615 // contain an instance of itself, but may contain a pointer to
18616 // an instance of itself), except that the last member of a
18617 // structure with more than one named member may have incomplete
18618 // array type; such a structure (and any union containing,
18619 // possibly recursively, a member that is such a structure)
18620 // shall not be a member of a structure or an element of an
18622 bool IsLastField
= (i
+ 1 == Fields
.end());
18623 if (FDTy
->isFunctionType()) {
18624 // Field declared as a function.
18625 Diag(FD
->getLocation(), diag::err_field_declared_as_function
)
18626 << FD
->getDeclName();
18627 FD
->setInvalidDecl();
18628 EnclosingDecl
->setInvalidDecl();
18630 } else if (FDTy
->isIncompleteArrayType() &&
18631 (Record
|| isa
<ObjCContainerDecl
>(EnclosingDecl
))) {
18633 // Flexible array member.
18634 // Microsoft and g++ is more permissive regarding flexible array.
18635 // It will accept flexible array in union and also
18636 // as the sole element of a struct/class.
18637 unsigned DiagID
= 0;
18638 if (!Record
->isUnion() && !IsLastField
) {
18639 Diag(FD
->getLocation(), diag::err_flexible_array_not_at_end
)
18640 << FD
->getDeclName() << FD
->getType() << Record
->getTagKind();
18641 Diag((*(i
+ 1))->getLocation(), diag::note_next_field_declaration
);
18642 FD
->setInvalidDecl();
18643 EnclosingDecl
->setInvalidDecl();
18645 } else if (Record
->isUnion())
18646 DiagID
= getLangOpts().MicrosoftExt
18647 ? diag::ext_flexible_array_union_ms
18648 : getLangOpts().CPlusPlus
18649 ? diag::ext_flexible_array_union_gnu
18650 : diag::err_flexible_array_union
;
18651 else if (NumNamedMembers
< 1)
18652 DiagID
= getLangOpts().MicrosoftExt
18653 ? diag::ext_flexible_array_empty_aggregate_ms
18654 : getLangOpts().CPlusPlus
18655 ? diag::ext_flexible_array_empty_aggregate_gnu
18656 : diag::err_flexible_array_empty_aggregate
;
18659 Diag(FD
->getLocation(), DiagID
) << FD
->getDeclName()
18660 << Record
->getTagKind();
18661 // While the layout of types that contain virtual bases is not specified
18662 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18663 // virtual bases after the derived members. This would make a flexible
18664 // array member declared at the end of an object not adjacent to the end
18666 if (CXXRecord
&& CXXRecord
->getNumVBases() != 0)
18667 Diag(FD
->getLocation(), diag::err_flexible_array_virtual_base
)
18668 << FD
->getDeclName() << Record
->getTagKind();
18669 if (!getLangOpts().C99
)
18670 Diag(FD
->getLocation(), diag::ext_c99_flexible_array_member
)
18671 << FD
->getDeclName() << Record
->getTagKind();
18673 // If the element type has a non-trivial destructor, we would not
18674 // implicitly destroy the elements, so disallow it for now.
18676 // FIXME: GCC allows this. We should probably either implicitly delete
18677 // the destructor of the containing class, or just allow this.
18678 QualType BaseElem
= Context
.getBaseElementType(FD
->getType());
18679 if (!BaseElem
->isDependentType() && BaseElem
.isDestructedType()) {
18680 Diag(FD
->getLocation(), diag::err_flexible_array_has_nontrivial_dtor
)
18681 << FD
->getDeclName() << FD
->getType();
18682 FD
->setInvalidDecl();
18683 EnclosingDecl
->setInvalidDecl();
18686 // Okay, we have a legal flexible array member at the end of the struct.
18687 Record
->setHasFlexibleArrayMember(true);
18689 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18690 // unless they are followed by another ivar. That check is done
18691 // elsewhere, after synthesized ivars are known.
18693 } else if (!FDTy
->isDependentType() &&
18694 RequireCompleteSizedType(
18695 FD
->getLocation(), FD
->getType(),
18696 diag::err_field_incomplete_or_sizeless
)) {
18698 FD
->setInvalidDecl();
18699 EnclosingDecl
->setInvalidDecl();
18701 } else if (const RecordType
*FDTTy
= FDTy
->getAs
<RecordType
>()) {
18702 if (Record
&& FDTTy
->getDecl()->hasFlexibleArrayMember()) {
18703 // A type which contains a flexible array member is considered to be a
18704 // flexible array member.
18705 Record
->setHasFlexibleArrayMember(true);
18706 if (!Record
->isUnion()) {
18707 // If this is a struct/class and this is not the last element, reject
18708 // it. Note that GCC supports variable sized arrays in the middle of
18711 Diag(FD
->getLocation(), diag::ext_variable_sized_type_in_struct
)
18712 << FD
->getDeclName() << FD
->getType();
18714 // We support flexible arrays at the end of structs in
18715 // other structs as an extension.
18716 Diag(FD
->getLocation(), diag::ext_flexible_array_in_struct
)
18717 << FD
->getDeclName();
18721 if (isa
<ObjCContainerDecl
>(EnclosingDecl
) &&
18722 RequireNonAbstractType(FD
->getLocation(), FD
->getType(),
18723 diag::err_abstract_type_in_decl
,
18724 AbstractIvarType
)) {
18725 // Ivars can not have abstract class types
18726 FD
->setInvalidDecl();
18728 if (Record
&& FDTTy
->getDecl()->hasObjectMember())
18729 Record
->setHasObjectMember(true);
18730 if (Record
&& FDTTy
->getDecl()->hasVolatileMember())
18731 Record
->setHasVolatileMember(true);
18732 } else if (FDTy
->isObjCObjectType()) {
18733 /// A field cannot be an Objective-c object
18734 Diag(FD
->getLocation(), diag::err_statically_allocated_object
)
18735 << FixItHint::CreateInsertion(FD
->getLocation(), "*");
18736 QualType T
= Context
.getObjCObjectPointerType(FD
->getType());
18738 } else if (Record
&& Record
->isUnion() &&
18739 FD
->getType().hasNonTrivialObjCLifetime() &&
18740 getSourceManager().isInSystemHeader(FD
->getLocation()) &&
18741 !getLangOpts().CPlusPlus
&& !FD
->hasAttr
<UnavailableAttr
>() &&
18742 (FD
->getType().getObjCLifetime() != Qualifiers::OCL_Strong
||
18743 !Context
.hasDirectOwnershipQualifier(FD
->getType()))) {
18744 // For backward compatibility, fields of C unions declared in system
18745 // headers that have non-trivial ObjC ownership qualifications are marked
18746 // as unavailable unless the qualifier is explicit and __strong. This can
18747 // break ABI compatibility between programs compiled with ARC and MRR, but
18748 // is a better option than rejecting programs using those unions under
18750 FD
->addAttr(UnavailableAttr::CreateImplicit(
18751 Context
, "", UnavailableAttr::IR_ARCFieldWithOwnership
,
18752 FD
->getLocation()));
18753 } else if (getLangOpts().ObjC
&&
18754 getLangOpts().getGC() != LangOptions::NonGC
&& Record
&&
18755 !Record
->hasObjectMember()) {
18756 if (FD
->getType()->isObjCObjectPointerType() ||
18757 FD
->getType().isObjCGCStrong())
18758 Record
->setHasObjectMember(true);
18759 else if (Context
.getAsArrayType(FD
->getType())) {
18760 QualType BaseType
= Context
.getBaseElementType(FD
->getType());
18761 if (BaseType
->isRecordType() &&
18762 BaseType
->castAs
<RecordType
>()->getDecl()->hasObjectMember())
18763 Record
->setHasObjectMember(true);
18764 else if (BaseType
->isObjCObjectPointerType() ||
18765 BaseType
.isObjCGCStrong())
18766 Record
->setHasObjectMember(true);
18770 if (Record
&& !getLangOpts().CPlusPlus
&&
18771 !shouldIgnoreForRecordTriviality(FD
)) {
18772 QualType FT
= FD
->getType();
18773 if (FT
.isNonTrivialToPrimitiveDefaultInitialize()) {
18774 Record
->setNonTrivialToPrimitiveDefaultInitialize(true);
18775 if (FT
.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
18777 Record
->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18779 QualType::PrimitiveCopyKind PCK
= FT
.isNonTrivialToPrimitiveCopy();
18780 if (PCK
!= QualType::PCK_Trivial
&& PCK
!= QualType::PCK_VolatileTrivial
) {
18781 Record
->setNonTrivialToPrimitiveCopy(true);
18782 if (FT
.hasNonTrivialToPrimitiveCopyCUnion() || Record
->isUnion())
18783 Record
->setHasNonTrivialToPrimitiveCopyCUnion(true);
18785 if (FT
.isDestructedType()) {
18786 Record
->setNonTrivialToPrimitiveDestroy(true);
18787 Record
->setParamDestroyedInCallee(true);
18788 if (FT
.hasNonTrivialToPrimitiveDestructCUnion() || Record
->isUnion())
18789 Record
->setHasNonTrivialToPrimitiveDestructCUnion(true);
18792 if (const auto *RT
= FT
->getAs
<RecordType
>()) {
18793 if (RT
->getDecl()->getArgPassingRestrictions() ==
18794 RecordDecl::APK_CanNeverPassInRegs
)
18795 Record
->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs
);
18796 } else if (FT
.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak
)
18797 Record
->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs
);
18800 if (Record
&& FD
->getType().isVolatileQualified())
18801 Record
->setHasVolatileMember(true);
18802 // Keep track of the number of named members.
18803 if (FD
->getIdentifier())
18807 // Okay, we successfully defined 'Record'.
18809 bool Completed
= false;
18811 if (!CXXRecord
->isInvalidDecl()) {
18812 // Set access bits correctly on the directly-declared conversions.
18813 for (CXXRecordDecl::conversion_iterator
18814 I
= CXXRecord
->conversion_begin(),
18815 E
= CXXRecord
->conversion_end(); I
!= E
; ++I
)
18816 I
.setAccess((*I
)->getAccess());
18819 // Add any implicitly-declared members to this class.
18820 AddImplicitlyDeclaredMembersToClass(CXXRecord
);
18822 if (!CXXRecord
->isDependentType()) {
18823 if (!CXXRecord
->isInvalidDecl()) {
18824 // If we have virtual base classes, we may end up finding multiple
18825 // final overriders for a given virtual function. Check for this
18827 if (CXXRecord
->getNumVBases()) {
18828 CXXFinalOverriderMap FinalOverriders
;
18829 CXXRecord
->getFinalOverriders(FinalOverriders
);
18831 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
18832 MEnd
= FinalOverriders
.end();
18834 for (OverridingMethods::iterator SO
= M
->second
.begin(),
18835 SOEnd
= M
->second
.end();
18836 SO
!= SOEnd
; ++SO
) {
18837 assert(SO
->second
.size() > 0 &&
18838 "Virtual function without overriding functions?");
18839 if (SO
->second
.size() == 1)
18842 // C++ [class.virtual]p2:
18843 // In a derived class, if a virtual member function of a base
18844 // class subobject has more than one final overrider the
18845 // program is ill-formed.
18846 Diag(Record
->getLocation(), diag::err_multiple_final_overriders
)
18847 << (const NamedDecl
*)M
->first
<< Record
;
18848 Diag(M
->first
->getLocation(),
18849 diag::note_overridden_virtual_function
);
18850 for (OverridingMethods::overriding_iterator
18851 OM
= SO
->second
.begin(),
18852 OMEnd
= SO
->second
.end();
18854 Diag(OM
->Method
->getLocation(), diag::note_final_overrider
)
18855 << (const NamedDecl
*)M
->first
<< OM
->Method
->getParent();
18857 Record
->setInvalidDecl();
18860 CXXRecord
->completeDefinition(&FinalOverriders
);
18864 ComputeSelectedDestructor(*this, CXXRecord
);
18865 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord
);
18870 Record
->completeDefinition();
18872 // Handle attributes before checking the layout.
18873 ProcessDeclAttributeList(S
, Record
, Attrs
);
18875 // Check to see if a FieldDecl is a pointer to a function.
18876 auto IsFunctionPointerOrForwardDecl
= [&](const Decl
*D
) {
18877 const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
);
18879 // Check whether this is a forward declaration that was inserted by
18880 // Clang. This happens when a non-forward declared / defined type is
18884 // struct bar *(*f)();
18885 // struct bar *(*g)();
18888 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
18889 // incomplete definition.
18890 if (const auto *TD
= dyn_cast
<TagDecl
>(D
))
18891 return !TD
->isCompleteDefinition();
18894 QualType FieldType
= FD
->getType().getDesugaredType(Context
);
18895 if (isa
<PointerType
>(FieldType
)) {
18896 QualType PointeeType
= cast
<PointerType
>(FieldType
)->getPointeeType();
18897 return PointeeType
.getDesugaredType(Context
)->isFunctionType();
18902 // Maybe randomize the record's decls. We automatically randomize a record
18903 // of function pointers, unless it has the "no_randomize_layout" attribute.
18904 if (!getLangOpts().CPlusPlus
&&
18905 (Record
->hasAttr
<RandomizeLayoutAttr
>() ||
18906 (!Record
->hasAttr
<NoRandomizeLayoutAttr
>() &&
18907 llvm::all_of(Record
->decls(), IsFunctionPointerOrForwardDecl
))) &&
18908 !Record
->isUnion() && !getLangOpts().RandstructSeed
.empty() &&
18909 !Record
->isRandomized()) {
18910 SmallVector
<Decl
*, 32> NewDeclOrdering
;
18911 if (randstruct::randomizeStructureLayout(Context
, Record
,
18913 Record
->reorderDecls(NewDeclOrdering
);
18916 // We may have deferred checking for a deleted destructor. Check now.
18918 auto *Dtor
= CXXRecord
->getDestructor();
18919 if (Dtor
&& Dtor
->isImplicit() &&
18920 ShouldDeleteSpecialMember(Dtor
, CXXDestructor
)) {
18921 CXXRecord
->setImplicitDestructorIsDeleted();
18922 SetDeclDeleted(Dtor
, CXXRecord
->getLocation());
18926 if (Record
->hasAttrs()) {
18927 CheckAlignasUnderalignment(Record
);
18929 if (const MSInheritanceAttr
*IA
= Record
->getAttr
<MSInheritanceAttr
>())
18930 checkMSInheritanceAttrOnDefinition(cast
<CXXRecordDecl
>(Record
),
18931 IA
->getRange(), IA
->getBestCase(),
18932 IA
->getInheritanceModel());
18935 // Check if the structure/union declaration is a type that can have zero
18936 // size in C. For C this is a language extension, for C++ it may cause
18937 // compatibility problems.
18938 bool CheckForZeroSize
;
18939 if (!getLangOpts().CPlusPlus
) {
18940 CheckForZeroSize
= true;
18942 // For C++ filter out types that cannot be referenced in C code.
18943 CXXRecordDecl
*CXXRecord
= cast
<CXXRecordDecl
>(Record
);
18945 CXXRecord
->getLexicalDeclContext()->isExternCContext() &&
18946 !CXXRecord
->isDependentType() && !inTemplateInstantiation() &&
18947 CXXRecord
->isCLike();
18949 if (CheckForZeroSize
) {
18950 bool ZeroSize
= true;
18951 bool IsEmpty
= true;
18952 unsigned NonBitFields
= 0;
18953 for (RecordDecl::field_iterator I
= Record
->field_begin(),
18954 E
= Record
->field_end();
18955 (NonBitFields
== 0 || ZeroSize
) && I
!= E
; ++I
) {
18957 if (I
->isUnnamedBitfield()) {
18958 if (!I
->isZeroLengthBitField(Context
))
18962 QualType FieldType
= I
->getType();
18963 if (FieldType
->isIncompleteType() ||
18964 !Context
.getTypeSizeInChars(FieldType
).isZero())
18969 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
18970 // allowed in C++, but warn if its declaration is inside
18971 // extern "C" block.
18973 Diag(RecLoc
, getLangOpts().CPlusPlus
?
18974 diag::warn_zero_size_struct_union_in_extern_c
:
18975 diag::warn_zero_size_struct_union_compat
)
18976 << IsEmpty
<< Record
->isUnion() << (NonBitFields
> 1);
18979 // Structs without named members are extension in C (C99 6.7.2.1p7),
18980 // but are accepted by GCC.
18981 if (NonBitFields
== 0 && !getLangOpts().CPlusPlus
) {
18982 Diag(RecLoc
, IsEmpty
? diag::ext_empty_struct_union
:
18983 diag::ext_no_named_members_in_struct_union
)
18984 << Record
->isUnion();
18988 ObjCIvarDecl
**ClsFields
=
18989 reinterpret_cast<ObjCIvarDecl
**>(RecFields
.data());
18990 if (ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(EnclosingDecl
)) {
18991 ID
->setEndOfDefinitionLoc(RBrac
);
18992 // Add ivar's to class's DeclContext.
18993 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
18994 ClsFields
[i
]->setLexicalDeclContext(ID
);
18995 ID
->addDecl(ClsFields
[i
]);
18997 // Must enforce the rule that ivars in the base classes may not be
18999 if (ID
->getSuperClass())
19000 DiagnoseDuplicateIvars(ID
, ID
->getSuperClass());
19001 } else if (ObjCImplementationDecl
*IMPDecl
=
19002 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
19003 assert(IMPDecl
&& "ActOnFields - missing ObjCImplementationDecl");
19004 for (unsigned I
= 0, N
= RecFields
.size(); I
!= N
; ++I
)
19005 // Ivar declared in @implementation never belongs to the implementation.
19006 // Only it is in implementation's lexical context.
19007 ClsFields
[I
]->setLexicalDeclContext(IMPDecl
);
19008 CheckImplementationIvars(IMPDecl
, ClsFields
, RecFields
.size(), RBrac
);
19009 IMPDecl
->setIvarLBraceLoc(LBrac
);
19010 IMPDecl
->setIvarRBraceLoc(RBrac
);
19011 } else if (ObjCCategoryDecl
*CDecl
=
19012 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
19013 // case of ivars in class extension; all other cases have been
19014 // reported as errors elsewhere.
19015 // FIXME. Class extension does not have a LocEnd field.
19016 // CDecl->setLocEnd(RBrac);
19017 // Add ivar's to class extension's DeclContext.
19018 // Diagnose redeclaration of private ivars.
19019 ObjCInterfaceDecl
*IDecl
= CDecl
->getClassInterface();
19020 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
19022 if (const ObjCIvarDecl
*ClsIvar
=
19023 IDecl
->getIvarDecl(ClsFields
[i
]->getIdentifier())) {
19024 Diag(ClsFields
[i
]->getLocation(),
19025 diag::err_duplicate_ivar_declaration
);
19026 Diag(ClsIvar
->getLocation(), diag::note_previous_definition
);
19029 for (const auto *Ext
: IDecl
->known_extensions()) {
19030 if (const ObjCIvarDecl
*ClsExtIvar
19031 = Ext
->getIvarDecl(ClsFields
[i
]->getIdentifier())) {
19032 Diag(ClsFields
[i
]->getLocation(),
19033 diag::err_duplicate_ivar_declaration
);
19034 Diag(ClsExtIvar
->getLocation(), diag::note_previous_definition
);
19039 ClsFields
[i
]->setLexicalDeclContext(CDecl
);
19040 CDecl
->addDecl(ClsFields
[i
]);
19042 CDecl
->setIvarLBraceLoc(LBrac
);
19043 CDecl
->setIvarRBraceLoc(RBrac
);
19048 /// Determine whether the given integral value is representable within
19049 /// the given type T.
19050 static bool isRepresentableIntegerValue(ASTContext
&Context
,
19051 llvm::APSInt
&Value
,
19053 assert((T
->isIntegralType(Context
) || T
->isEnumeralType()) &&
19054 "Integral type required!");
19055 unsigned BitWidth
= Context
.getIntWidth(T
);
19057 if (Value
.isUnsigned() || Value
.isNonNegative()) {
19058 if (T
->isSignedIntegerOrEnumerationType())
19060 return Value
.getActiveBits() <= BitWidth
;
19062 return Value
.getMinSignedBits() <= BitWidth
;
19065 // Given an integral type, return the next larger integral type
19066 // (or a NULL type of no such type exists).
19067 static QualType
getNextLargerIntegralType(ASTContext
&Context
, QualType T
) {
19068 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19069 // enum checking below.
19070 assert((T
->isIntegralType(Context
) ||
19071 T
->isEnumeralType()) && "Integral type required!");
19072 const unsigned NumTypes
= 4;
19073 QualType SignedIntegralTypes
[NumTypes
] = {
19074 Context
.ShortTy
, Context
.IntTy
, Context
.LongTy
, Context
.LongLongTy
19076 QualType UnsignedIntegralTypes
[NumTypes
] = {
19077 Context
.UnsignedShortTy
, Context
.UnsignedIntTy
, Context
.UnsignedLongTy
,
19078 Context
.UnsignedLongLongTy
19081 unsigned BitWidth
= Context
.getTypeSize(T
);
19082 QualType
*Types
= T
->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19083 : UnsignedIntegralTypes
;
19084 for (unsigned I
= 0; I
!= NumTypes
; ++I
)
19085 if (Context
.getTypeSize(Types
[I
]) > BitWidth
)
19091 EnumConstantDecl
*Sema::CheckEnumConstant(EnumDecl
*Enum
,
19092 EnumConstantDecl
*LastEnumConst
,
19093 SourceLocation IdLoc
,
19094 IdentifierInfo
*Id
,
19096 unsigned IntWidth
= Context
.getTargetInfo().getIntWidth();
19097 llvm::APSInt
EnumVal(IntWidth
);
19100 if (Val
&& DiagnoseUnexpandedParameterPack(Val
, UPPC_EnumeratorValue
))
19104 Val
= DefaultLvalueConversion(Val
).get();
19107 if (Enum
->isDependentType() || Val
->isTypeDependent() ||
19108 Val
->containsErrors())
19109 EltTy
= Context
.DependentTy
;
19111 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19112 // underlying type, but do allow it in all other contexts.
19113 if (getLangOpts().CPlusPlus11
&& Enum
->isFixed()) {
19114 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19115 // constant-expression in the enumerator-definition shall be a converted
19116 // constant expression of the underlying type.
19117 EltTy
= Enum
->getIntegerType();
19118 ExprResult Converted
=
19119 CheckConvertedConstantExpression(Val
, EltTy
, EnumVal
,
19121 if (Converted
.isInvalid())
19124 Val
= Converted
.get();
19125 } else if (!Val
->isValueDependent() &&
19127 VerifyIntegerConstantExpression(Val
, &EnumVal
, AllowFold
)
19129 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19131 if (Enum
->isComplete()) {
19132 EltTy
= Enum
->getIntegerType();
19134 // In Obj-C and Microsoft mode, require the enumeration value to be
19135 // representable in the underlying type of the enumeration. In C++11,
19136 // we perform a non-narrowing conversion as part of converted constant
19137 // expression checking.
19138 if (!isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
19139 if (Context
.getTargetInfo()
19141 .isWindowsMSVCEnvironment()) {
19142 Diag(IdLoc
, diag::ext_enumerator_too_large
) << EltTy
;
19144 Diag(IdLoc
, diag::err_enumerator_too_large
) << EltTy
;
19148 // Cast to the underlying type.
19149 Val
= ImpCastExprToType(Val
, EltTy
,
19150 EltTy
->isBooleanType() ? CK_IntegralToBoolean
19153 } else if (getLangOpts().CPlusPlus
) {
19154 // C++11 [dcl.enum]p5:
19155 // If the underlying type is not fixed, the type of each enumerator
19156 // is the type of its initializing value:
19157 // - If an initializer is specified for an enumerator, the
19158 // initializing value has the same type as the expression.
19159 EltTy
= Val
->getType();
19162 // The expression that defines the value of an enumeration constant
19163 // shall be an integer constant expression that has a value
19164 // representable as an int.
19166 // Complain if the value is not representable in an int.
19167 if (!isRepresentableIntegerValue(Context
, EnumVal
, Context
.IntTy
))
19168 Diag(IdLoc
, diag::ext_enum_value_not_int
)
19169 << toString(EnumVal
, 10) << Val
->getSourceRange()
19170 << (EnumVal
.isUnsigned() || EnumVal
.isNonNegative());
19171 else if (!Context
.hasSameType(Val
->getType(), Context
.IntTy
)) {
19172 // Force the type of the expression to 'int'.
19173 Val
= ImpCastExprToType(Val
, Context
.IntTy
, CK_IntegralCast
).get();
19175 EltTy
= Val
->getType();
19182 if (Enum
->isDependentType())
19183 EltTy
= Context
.DependentTy
;
19184 else if (!LastEnumConst
) {
19185 // C++0x [dcl.enum]p5:
19186 // If the underlying type is not fixed, the type of each enumerator
19187 // is the type of its initializing value:
19188 // - If no initializer is specified for the first enumerator, the
19189 // initializing value has an unspecified integral type.
19191 // GCC uses 'int' for its unspecified integral type, as does
19193 if (Enum
->isFixed()) {
19194 EltTy
= Enum
->getIntegerType();
19197 EltTy
= Context
.IntTy
;
19200 // Assign the last value + 1.
19201 EnumVal
= LastEnumConst
->getInitVal();
19203 EltTy
= LastEnumConst
->getType();
19205 // Check for overflow on increment.
19206 if (EnumVal
< LastEnumConst
->getInitVal()) {
19207 // C++0x [dcl.enum]p5:
19208 // If the underlying type is not fixed, the type of each enumerator
19209 // is the type of its initializing value:
19211 // - Otherwise the type of the initializing value is the same as
19212 // the type of the initializing value of the preceding enumerator
19213 // unless the incremented value is not representable in that type,
19214 // in which case the type is an unspecified integral type
19215 // sufficient to contain the incremented value. If no such type
19216 // exists, the program is ill-formed.
19217 QualType T
= getNextLargerIntegralType(Context
, EltTy
);
19218 if (T
.isNull() || Enum
->isFixed()) {
19219 // There is no integral type larger enough to represent this
19220 // value. Complain, then allow the value to wrap around.
19221 EnumVal
= LastEnumConst
->getInitVal();
19222 EnumVal
= EnumVal
.zext(EnumVal
.getBitWidth() * 2);
19224 if (Enum
->isFixed())
19225 // When the underlying type is fixed, this is ill-formed.
19226 Diag(IdLoc
, diag::err_enumerator_wrapped
)
19227 << toString(EnumVal
, 10)
19230 Diag(IdLoc
, diag::ext_enumerator_increment_too_large
)
19231 << toString(EnumVal
, 10);
19236 // Retrieve the last enumerator's value, extent that type to the
19237 // type that is supposed to be large enough to represent the incremented
19238 // value, then increment.
19239 EnumVal
= LastEnumConst
->getInitVal();
19240 EnumVal
.setIsSigned(EltTy
->isSignedIntegerOrEnumerationType());
19241 EnumVal
= EnumVal
.zextOrTrunc(Context
.getIntWidth(EltTy
));
19244 // If we're not in C++, diagnose the overflow of enumerator values,
19245 // which in C99 means that the enumerator value is not representable in
19246 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19247 // permits enumerator values that are representable in some larger
19249 if (!getLangOpts().CPlusPlus
&& !T
.isNull())
19250 Diag(IdLoc
, diag::warn_enum_value_overflow
);
19251 } else if (!getLangOpts().CPlusPlus
&&
19252 !isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
19253 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19254 Diag(IdLoc
, diag::ext_enum_value_not_int
)
19255 << toString(EnumVal
, 10) << 1;
19260 if (!EltTy
->isDependentType()) {
19261 // Make the enumerator value match the signedness and size of the
19262 // enumerator's type.
19263 EnumVal
= EnumVal
.extOrTrunc(Context
.getIntWidth(EltTy
));
19264 EnumVal
.setIsSigned(EltTy
->isSignedIntegerOrEnumerationType());
19267 return EnumConstantDecl::Create(Context
, Enum
, IdLoc
, Id
, EltTy
,
19271 Sema::SkipBodyInfo
Sema::shouldSkipAnonEnumBody(Scope
*S
, IdentifierInfo
*II
,
19272 SourceLocation IILoc
) {
19273 if (!(getLangOpts().Modules
|| getLangOpts().ModulesLocalVisibility
) ||
19274 !getLangOpts().CPlusPlus
)
19275 return SkipBodyInfo();
19277 // We have an anonymous enum definition. Look up the first enumerator to
19278 // determine if we should merge the definition with an existing one and
19280 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, IILoc
, LookupOrdinaryName
,
19281 forRedeclarationInCurContext());
19282 auto *PrevECD
= dyn_cast_or_null
<EnumConstantDecl
>(PrevDecl
);
19284 return SkipBodyInfo();
19286 EnumDecl
*PrevED
= cast
<EnumDecl
>(PrevECD
->getDeclContext());
19288 if (!PrevED
->getDeclName() && !hasVisibleDefinition(PrevED
, &Hidden
)) {
19290 Skip
.Previous
= Hidden
;
19294 return SkipBodyInfo();
19297 Decl
*Sema::ActOnEnumConstant(Scope
*S
, Decl
*theEnumDecl
, Decl
*lastEnumConst
,
19298 SourceLocation IdLoc
, IdentifierInfo
*Id
,
19299 const ParsedAttributesView
&Attrs
,
19300 SourceLocation EqualLoc
, Expr
*Val
) {
19301 EnumDecl
*TheEnumDecl
= cast
<EnumDecl
>(theEnumDecl
);
19302 EnumConstantDecl
*LastEnumConst
=
19303 cast_or_null
<EnumConstantDecl
>(lastEnumConst
);
19305 // The scope passed in may not be a decl scope. Zip up the scope tree until
19306 // we find one that is.
19307 S
= getNonFieldDeclScope(S
);
19309 // Verify that there isn't already something declared with this name in this
19311 LookupResult
R(*this, Id
, IdLoc
, LookupOrdinaryName
, ForVisibleRedeclaration
);
19313 NamedDecl
*PrevDecl
= R
.getAsSingle
<NamedDecl
>();
19315 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
19316 // Maybe we will complain about the shadowed template parameter.
19317 DiagnoseTemplateParameterShadow(IdLoc
, PrevDecl
);
19318 // Just pretend that we didn't see the previous declaration.
19319 PrevDecl
= nullptr;
19322 // C++ [class.mem]p15:
19323 // If T is the name of a class, then each of the following shall have a name
19324 // different from T:
19325 // - every enumerator of every member of class T that is an unscoped
19327 if (getLangOpts().CPlusPlus
&& !TheEnumDecl
->isScoped())
19328 DiagnoseClassNameShadow(TheEnumDecl
->getDeclContext(),
19329 DeclarationNameInfo(Id
, IdLoc
));
19331 EnumConstantDecl
*New
=
19332 CheckEnumConstant(TheEnumDecl
, LastEnumConst
, IdLoc
, Id
, Val
);
19337 if (!TheEnumDecl
->isScoped() && isa
<ValueDecl
>(PrevDecl
)) {
19338 // Check for other kinds of shadowing not already handled.
19339 CheckShadow(New
, PrevDecl
, R
);
19342 // When in C++, we may get a TagDecl with the same name; in this case the
19343 // enum constant will 'hide' the tag.
19344 assert((getLangOpts().CPlusPlus
|| !isa
<TagDecl
>(PrevDecl
)) &&
19345 "Received TagDecl when not in C++!");
19346 if (!isa
<TagDecl
>(PrevDecl
) && isDeclInScope(PrevDecl
, CurContext
, S
)) {
19347 if (isa
<EnumConstantDecl
>(PrevDecl
))
19348 Diag(IdLoc
, diag::err_redefinition_of_enumerator
) << Id
;
19350 Diag(IdLoc
, diag::err_redefinition
) << Id
;
19351 notePreviousDefinition(PrevDecl
, IdLoc
);
19356 // Process attributes.
19357 ProcessDeclAttributeList(S
, New
, Attrs
);
19358 AddPragmaAttributes(S
, New
);
19360 // Register this decl in the current scope stack.
19361 New
->setAccess(TheEnumDecl
->getAccess());
19362 PushOnScopeChains(New
, S
);
19364 ActOnDocumentableDecl(New
);
19369 // Returns true when the enum initial expression does not trigger the
19370 // duplicate enum warning. A few common cases are exempted as follows:
19371 // Element2 = Element1
19372 // Element2 = Element1 + 1
19373 // Element2 = Element1 - 1
19374 // Where Element2 and Element1 are from the same enum.
19375 static bool ValidDuplicateEnum(EnumConstantDecl
*ECD
, EnumDecl
*Enum
) {
19376 Expr
*InitExpr
= ECD
->getInitExpr();
19379 InitExpr
= InitExpr
->IgnoreImpCasts();
19381 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(InitExpr
)) {
19382 if (!BO
->isAdditiveOp())
19384 IntegerLiteral
*IL
= dyn_cast
<IntegerLiteral
>(BO
->getRHS());
19387 if (IL
->getValue() != 1)
19390 InitExpr
= BO
->getLHS();
19393 // This checks if the elements are from the same enum.
19394 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(InitExpr
);
19398 EnumConstantDecl
*EnumConstant
= dyn_cast
<EnumConstantDecl
>(DRE
->getDecl());
19402 if (cast
<EnumDecl
>(TagDecl::castFromDeclContext(ECD
->getDeclContext())) !=
19409 // Emits a warning when an element is implicitly set a value that
19410 // a previous element has already been set to.
19411 static void CheckForDuplicateEnumValues(Sema
&S
, ArrayRef
<Decl
*> Elements
,
19412 EnumDecl
*Enum
, QualType EnumType
) {
19413 // Avoid anonymous enums
19414 if (!Enum
->getIdentifier())
19417 // Only check for small enums.
19418 if (Enum
->getNumPositiveBits() > 63 || Enum
->getNumNegativeBits() > 64)
19421 if (S
.Diags
.isIgnored(diag::warn_duplicate_enum_values
, Enum
->getLocation()))
19424 typedef SmallVector
<EnumConstantDecl
*, 3> ECDVector
;
19425 typedef SmallVector
<std::unique_ptr
<ECDVector
>, 3> DuplicatesVector
;
19427 typedef llvm::PointerUnion
<EnumConstantDecl
*, ECDVector
*> DeclOrVector
;
19429 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19430 typedef std::unordered_map
<int64_t, DeclOrVector
> ValueToVectorMap
;
19432 // Use int64_t as a key to avoid needing special handling for map keys.
19433 auto EnumConstantToKey
= [](const EnumConstantDecl
*D
) {
19434 llvm::APSInt Val
= D
->getInitVal();
19435 return Val
.isSigned() ? Val
.getSExtValue() : Val
.getZExtValue();
19438 DuplicatesVector DupVector
;
19439 ValueToVectorMap EnumMap
;
19441 // Populate the EnumMap with all values represented by enum constants without
19443 for (auto *Element
: Elements
) {
19444 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(Element
);
19446 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19447 // this constant. Skip this enum since it may be ill-formed.
19452 // Constants with initalizers are handled in the next loop.
19453 if (ECD
->getInitExpr())
19456 // Duplicate values are handled in the next loop.
19457 EnumMap
.insert({EnumConstantToKey(ECD
), ECD
});
19460 if (EnumMap
.size() == 0)
19463 // Create vectors for any values that has duplicates.
19464 for (auto *Element
: Elements
) {
19465 // The last loop returned if any constant was null.
19466 EnumConstantDecl
*ECD
= cast
<EnumConstantDecl
>(Element
);
19467 if (!ValidDuplicateEnum(ECD
, Enum
))
19470 auto Iter
= EnumMap
.find(EnumConstantToKey(ECD
));
19471 if (Iter
== EnumMap
.end())
19474 DeclOrVector
& Entry
= Iter
->second
;
19475 if (EnumConstantDecl
*D
= Entry
.dyn_cast
<EnumConstantDecl
*>()) {
19476 // Ensure constants are different.
19480 // Create new vector and push values onto it.
19481 auto Vec
= std::make_unique
<ECDVector
>();
19483 Vec
->push_back(ECD
);
19485 // Update entry to point to the duplicates vector.
19488 // Store the vector somewhere we can consult later for quick emission of
19490 DupVector
.emplace_back(std::move(Vec
));
19494 ECDVector
*Vec
= Entry
.get
<ECDVector
*>();
19495 // Make sure constants are not added more than once.
19496 if (*Vec
->begin() == ECD
)
19499 Vec
->push_back(ECD
);
19502 // Emit diagnostics.
19503 for (const auto &Vec
: DupVector
) {
19504 assert(Vec
->size() > 1 && "ECDVector should have at least 2 elements.");
19506 // Emit warning for one enum constant.
19507 auto *FirstECD
= Vec
->front();
19508 S
.Diag(FirstECD
->getLocation(), diag::warn_duplicate_enum_values
)
19509 << FirstECD
<< toString(FirstECD
->getInitVal(), 10)
19510 << FirstECD
->getSourceRange();
19512 // Emit one note for each of the remaining enum constants with
19514 for (auto *ECD
: llvm::drop_begin(*Vec
))
19515 S
.Diag(ECD
->getLocation(), diag::note_duplicate_element
)
19516 << ECD
<< toString(ECD
->getInitVal(), 10)
19517 << ECD
->getSourceRange();
19521 bool Sema::IsValueInFlagEnum(const EnumDecl
*ED
, const llvm::APInt
&Val
,
19522 bool AllowMask
) const {
19523 assert(ED
->isClosedFlag() && "looking for value in non-flag or open enum");
19524 assert(ED
->isCompleteDefinition() && "expected enum definition");
19526 auto R
= FlagBitsCache
.insert(std::make_pair(ED
, llvm::APInt()));
19527 llvm::APInt
&FlagBits
= R
.first
->second
;
19530 for (auto *E
: ED
->enumerators()) {
19531 const auto &EVal
= E
->getInitVal();
19532 // Only single-bit enumerators introduce new flag values.
19533 if (EVal
.isPowerOf2())
19534 FlagBits
= FlagBits
.zext(EVal
.getBitWidth()) | EVal
;
19538 // A value is in a flag enum if either its bits are a subset of the enum's
19539 // flag bits (the first condition) or we are allowing masks and the same is
19540 // true of its complement (the second condition). When masks are allowed, we
19541 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19543 // While it's true that any value could be used as a mask, the assumption is
19544 // that a mask will have all of the insignificant bits set. Anything else is
19545 // likely a logic error.
19546 llvm::APInt FlagMask
= ~FlagBits
.zextOrTrunc(Val
.getBitWidth());
19547 return !(FlagMask
& Val
) || (AllowMask
&& !(FlagMask
& ~Val
));
19550 void Sema::ActOnEnumBody(SourceLocation EnumLoc
, SourceRange BraceRange
,
19551 Decl
*EnumDeclX
, ArrayRef
<Decl
*> Elements
, Scope
*S
,
19552 const ParsedAttributesView
&Attrs
) {
19553 EnumDecl
*Enum
= cast
<EnumDecl
>(EnumDeclX
);
19554 QualType EnumType
= Context
.getTypeDeclType(Enum
);
19556 ProcessDeclAttributeList(S
, Enum
, Attrs
);
19558 if (Enum
->isDependentType()) {
19559 for (unsigned i
= 0, e
= Elements
.size(); i
!= e
; ++i
) {
19560 EnumConstantDecl
*ECD
=
19561 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
19562 if (!ECD
) continue;
19564 ECD
->setType(EnumType
);
19567 Enum
->completeDefinition(Context
.DependentTy
, Context
.DependentTy
, 0, 0);
19571 // TODO: If the result value doesn't fit in an int, it must be a long or long
19572 // long value. ISO C does not support this, but GCC does as an extension,
19574 unsigned IntWidth
= Context
.getTargetInfo().getIntWidth();
19575 unsigned CharWidth
= Context
.getTargetInfo().getCharWidth();
19576 unsigned ShortWidth
= Context
.getTargetInfo().getShortWidth();
19578 // Verify that all the values are okay, compute the size of the values, and
19579 // reverse the list.
19580 unsigned NumNegativeBits
= 0;
19581 unsigned NumPositiveBits
= 0;
19583 for (unsigned i
= 0, e
= Elements
.size(); i
!= e
; ++i
) {
19584 EnumConstantDecl
*ECD
=
19585 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
19586 if (!ECD
) continue; // Already issued a diagnostic.
19588 const llvm::APSInt
&InitVal
= ECD
->getInitVal();
19590 // Keep track of the size of positive and negative values.
19591 if (InitVal
.isUnsigned() || InitVal
.isNonNegative()) {
19592 // If the enumerator is zero that should still be counted as a positive
19593 // bit since we need a bit to store the value zero.
19594 unsigned ActiveBits
= InitVal
.getActiveBits();
19595 NumPositiveBits
= std::max({NumPositiveBits
, ActiveBits
, 1u});
19597 NumNegativeBits
= std::max(NumNegativeBits
,
19598 (unsigned)InitVal
.getMinSignedBits());
19602 // If we have an empty set of enumerators we still need one bit.
19603 // From [dcl.enum]p8
19604 // If the enumerator-list is empty, the values of the enumeration are as if
19605 // the enumeration had a single enumerator with value 0
19606 if (!NumPositiveBits
&& !NumNegativeBits
)
19607 NumPositiveBits
= 1;
19609 // Figure out the type that should be used for this enum.
19611 unsigned BestWidth
;
19613 // C++0x N3000 [conv.prom]p3:
19614 // An rvalue of an unscoped enumeration type whose underlying
19615 // type is not fixed can be converted to an rvalue of the first
19616 // of the following types that can represent all the values of
19617 // the enumeration: int, unsigned int, long int, unsigned long
19618 // int, long long int, or unsigned long long int.
19620 // An identifier declared as an enumeration constant has type int.
19621 // The C99 rule is modified by a gcc extension
19622 QualType BestPromotionType
;
19624 bool Packed
= Enum
->hasAttr
<PackedAttr
>();
19625 // -fshort-enums is the equivalent to specifying the packed attribute on all
19626 // enum definitions.
19627 if (LangOpts
.ShortEnums
)
19630 // If the enum already has a type because it is fixed or dictated by the
19631 // target, promote that type instead of analyzing the enumerators.
19632 if (Enum
->isComplete()) {
19633 BestType
= Enum
->getIntegerType();
19634 if (Context
.isPromotableIntegerType(BestType
))
19635 BestPromotionType
= Context
.getPromotedIntegerType(BestType
);
19637 BestPromotionType
= BestType
;
19639 BestWidth
= Context
.getIntWidth(BestType
);
19641 else if (NumNegativeBits
) {
19642 // If there is a negative value, figure out the smallest integer type (of
19643 // int/long/longlong) that fits.
19644 // If it's packed, check also if it fits a char or a short.
19645 if (Packed
&& NumNegativeBits
<= CharWidth
&& NumPositiveBits
< CharWidth
) {
19646 BestType
= Context
.SignedCharTy
;
19647 BestWidth
= CharWidth
;
19648 } else if (Packed
&& NumNegativeBits
<= ShortWidth
&&
19649 NumPositiveBits
< ShortWidth
) {
19650 BestType
= Context
.ShortTy
;
19651 BestWidth
= ShortWidth
;
19652 } else if (NumNegativeBits
<= IntWidth
&& NumPositiveBits
< IntWidth
) {
19653 BestType
= Context
.IntTy
;
19654 BestWidth
= IntWidth
;
19656 BestWidth
= Context
.getTargetInfo().getLongWidth();
19658 if (NumNegativeBits
<= BestWidth
&& NumPositiveBits
< BestWidth
) {
19659 BestType
= Context
.LongTy
;
19661 BestWidth
= Context
.getTargetInfo().getLongLongWidth();
19663 if (NumNegativeBits
> BestWidth
|| NumPositiveBits
>= BestWidth
)
19664 Diag(Enum
->getLocation(), diag::ext_enum_too_large
);
19665 BestType
= Context
.LongLongTy
;
19668 BestPromotionType
= (BestWidth
<= IntWidth
? Context
.IntTy
: BestType
);
19670 // If there is no negative value, figure out the smallest type that fits
19671 // all of the enumerator values.
19672 // If it's packed, check also if it fits a char or a short.
19673 if (Packed
&& NumPositiveBits
<= CharWidth
) {
19674 BestType
= Context
.UnsignedCharTy
;
19675 BestPromotionType
= Context
.IntTy
;
19676 BestWidth
= CharWidth
;
19677 } else if (Packed
&& NumPositiveBits
<= ShortWidth
) {
19678 BestType
= Context
.UnsignedShortTy
;
19679 BestPromotionType
= Context
.IntTy
;
19680 BestWidth
= ShortWidth
;
19681 } else if (NumPositiveBits
<= IntWidth
) {
19682 BestType
= Context
.UnsignedIntTy
;
19683 BestWidth
= IntWidth
;
19685 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
19686 ? Context
.UnsignedIntTy
: Context
.IntTy
;
19687 } else if (NumPositiveBits
<=
19688 (BestWidth
= Context
.getTargetInfo().getLongWidth())) {
19689 BestType
= Context
.UnsignedLongTy
;
19691 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
19692 ? Context
.UnsignedLongTy
: Context
.LongTy
;
19694 BestWidth
= Context
.getTargetInfo().getLongLongWidth();
19695 assert(NumPositiveBits
<= BestWidth
&&
19696 "How could an initializer get larger than ULL?");
19697 BestType
= Context
.UnsignedLongLongTy
;
19699 = (NumPositiveBits
== BestWidth
|| !getLangOpts().CPlusPlus
)
19700 ? Context
.UnsignedLongLongTy
: Context
.LongLongTy
;
19704 // Loop over all of the enumerator constants, changing their types to match
19705 // the type of the enum if needed.
19706 for (auto *D
: Elements
) {
19707 auto *ECD
= cast_or_null
<EnumConstantDecl
>(D
);
19708 if (!ECD
) continue; // Already issued a diagnostic.
19710 // Standard C says the enumerators have int type, but we allow, as an
19711 // extension, the enumerators to be larger than int size. If each
19712 // enumerator value fits in an int, type it as an int, otherwise type it the
19713 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19714 // that X has type 'int', not 'unsigned'.
19716 // Determine whether the value fits into an int.
19717 llvm::APSInt InitVal
= ECD
->getInitVal();
19719 // If it fits into an integer type, force it. Otherwise force it to match
19720 // the enum decl type.
19724 if (!getLangOpts().CPlusPlus
&&
19725 !Enum
->isFixed() &&
19726 isRepresentableIntegerValue(Context
, InitVal
, Context
.IntTy
)) {
19727 NewTy
= Context
.IntTy
;
19728 NewWidth
= IntWidth
;
19730 } else if (ECD
->getType() == BestType
) {
19731 // Already the right type!
19732 if (getLangOpts().CPlusPlus
)
19733 // C++ [dcl.enum]p4: Following the closing brace of an
19734 // enum-specifier, each enumerator has the type of its
19736 ECD
->setType(EnumType
);
19740 NewWidth
= BestWidth
;
19741 NewSign
= BestType
->isSignedIntegerOrEnumerationType();
19744 // Adjust the APSInt value.
19745 InitVal
= InitVal
.extOrTrunc(NewWidth
);
19746 InitVal
.setIsSigned(NewSign
);
19747 ECD
->setInitVal(InitVal
);
19749 // Adjust the Expr initializer and type.
19750 if (ECD
->getInitExpr() &&
19751 !Context
.hasSameType(NewTy
, ECD
->getInitExpr()->getType()))
19752 ECD
->setInitExpr(ImplicitCastExpr::Create(
19753 Context
, NewTy
, CK_IntegralCast
, ECD
->getInitExpr(),
19754 /*base paths*/ nullptr, VK_PRValue
, FPOptionsOverride()));
19755 if (getLangOpts().CPlusPlus
)
19756 // C++ [dcl.enum]p4: Following the closing brace of an
19757 // enum-specifier, each enumerator has the type of its
19759 ECD
->setType(EnumType
);
19761 ECD
->setType(NewTy
);
19764 Enum
->completeDefinition(BestType
, BestPromotionType
,
19765 NumPositiveBits
, NumNegativeBits
);
19767 CheckForDuplicateEnumValues(*this, Elements
, Enum
, EnumType
);
19769 if (Enum
->isClosedFlag()) {
19770 for (Decl
*D
: Elements
) {
19771 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(D
);
19772 if (!ECD
) continue; // Already issued a diagnostic.
19774 llvm::APSInt InitVal
= ECD
->getInitVal();
19775 if (InitVal
!= 0 && !InitVal
.isPowerOf2() &&
19776 !IsValueInFlagEnum(Enum
, InitVal
, true))
19777 Diag(ECD
->getLocation(), diag::warn_flag_enum_constant_out_of_range
)
19782 // Now that the enum type is defined, ensure it's not been underaligned.
19783 if (Enum
->hasAttrs())
19784 CheckAlignasUnderalignment(Enum
);
19787 Decl
*Sema::ActOnFileScopeAsmDecl(Expr
*expr
,
19788 SourceLocation StartLoc
,
19789 SourceLocation EndLoc
) {
19790 StringLiteral
*AsmString
= cast
<StringLiteral
>(expr
);
19792 FileScopeAsmDecl
*New
= FileScopeAsmDecl::Create(Context
, CurContext
,
19793 AsmString
, StartLoc
,
19795 CurContext
->addDecl(New
);
19799 Decl
*Sema::ActOnTopLevelStmtDecl(Stmt
*Statement
) {
19800 auto *New
= TopLevelStmtDecl::Create(Context
, Statement
);
19801 Context
.getTranslationUnitDecl()->addDecl(New
);
19805 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo
* Name
,
19806 IdentifierInfo
* AliasName
,
19807 SourceLocation PragmaLoc
,
19808 SourceLocation NameLoc
,
19809 SourceLocation AliasNameLoc
) {
19810 NamedDecl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
,
19811 LookupOrdinaryName
);
19812 AttributeCommonInfo
Info(AliasName
, SourceRange(AliasNameLoc
),
19813 AttributeCommonInfo::AS_Pragma
);
19814 AsmLabelAttr
*Attr
= AsmLabelAttr::CreateImplicit(
19815 Context
, AliasName
->getName(), /*IsLiteralLabel=*/true, Info
);
19817 // If a declaration that:
19818 // 1) declares a function or a variable
19819 // 2) has external linkage
19820 // already exists, add a label attribute to it.
19821 if (PrevDecl
&& (isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
))) {
19822 if (isDeclExternC(PrevDecl
))
19823 PrevDecl
->addAttr(Attr
);
19825 Diag(PrevDecl
->getLocation(), diag::warn_redefine_extname_not_applied
)
19826 << /*Variable*/(isa
<FunctionDecl
>(PrevDecl
) ? 0 : 1) << PrevDecl
;
19827 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19829 (void)ExtnameUndeclaredIdentifiers
.insert(std::make_pair(Name
, Attr
));
19832 void Sema::ActOnPragmaWeakID(IdentifierInfo
* Name
,
19833 SourceLocation PragmaLoc
,
19834 SourceLocation NameLoc
) {
19835 Decl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
, LookupOrdinaryName
);
19838 PrevDecl
->addAttr(WeakAttr::CreateImplicit(Context
, PragmaLoc
, AttributeCommonInfo::AS_Pragma
));
19840 (void)WeakUndeclaredIdentifiers
[Name
].insert(WeakInfo(nullptr, NameLoc
));
19844 void Sema::ActOnPragmaWeakAlias(IdentifierInfo
* Name
,
19845 IdentifierInfo
* AliasName
,
19846 SourceLocation PragmaLoc
,
19847 SourceLocation NameLoc
,
19848 SourceLocation AliasNameLoc
) {
19849 Decl
*PrevDecl
= LookupSingleName(TUScope
, AliasName
, AliasNameLoc
,
19850 LookupOrdinaryName
);
19851 WeakInfo W
= WeakInfo(Name
, NameLoc
);
19853 if (PrevDecl
&& (isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
))) {
19854 if (!PrevDecl
->hasAttr
<AliasAttr
>())
19855 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(PrevDecl
))
19856 DeclApplyPragmaWeak(TUScope
, ND
, W
);
19858 (void)WeakUndeclaredIdentifiers
[AliasName
].insert(W
);
19862 ObjCContainerDecl
*Sema::getObjCDeclContext() const {
19863 return (dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
));
19866 Sema::FunctionEmissionStatus
Sema::getEmissionStatus(FunctionDecl
*FD
,
19868 assert(FD
&& "Expected non-null FunctionDecl");
19870 // SYCL functions can be template, so we check if they have appropriate
19871 // attribute prior to checking if it is a template.
19872 if (LangOpts
.SYCLIsDevice
&& FD
->hasAttr
<SYCLKernelAttr
>())
19873 return FunctionEmissionStatus::Emitted
;
19875 // Templates are emitted when they're instantiated.
19876 if (FD
->isDependentContext())
19877 return FunctionEmissionStatus::TemplateDiscarded
;
19879 // Check whether this function is an externally visible definition.
19880 auto IsEmittedForExternalSymbol
= [this, FD
]() {
19881 // We have to check the GVA linkage of the function's *definition* -- if we
19882 // only have a declaration, we don't know whether or not the function will
19883 // be emitted, because (say) the definition could include "inline".
19884 FunctionDecl
*Def
= FD
->getDefinition();
19886 return Def
&& !isDiscardableGVALinkage(
19887 getASTContext().GetGVALinkageForFunction(Def
));
19890 if (LangOpts
.OpenMPIsDevice
) {
19891 // In OpenMP device mode we will not emit host only functions, or functions
19892 // we don't need due to their linkage.
19893 std::optional
<OMPDeclareTargetDeclAttr::DevTypeTy
> DevTy
=
19894 OMPDeclareTargetDeclAttr::getDeviceType(FD
->getCanonicalDecl());
19895 // DevTy may be changed later by
19896 // #pragma omp declare target to(*) device_type(*).
19897 // Therefore DevTy having no value does not imply host. The emission status
19898 // will be checked again at the end of compilation unit with Final = true.
19900 if (*DevTy
== OMPDeclareTargetDeclAttr::DT_Host
)
19901 return FunctionEmissionStatus::OMPDiscarded
;
19902 // If we have an explicit value for the device type, or we are in a target
19903 // declare context, we need to emit all extern and used symbols.
19904 if (isInOpenMPDeclareTargetContext() || DevTy
)
19905 if (IsEmittedForExternalSymbol())
19906 return FunctionEmissionStatus::Emitted
;
19907 // Device mode only emits what it must, if it wasn't tagged yet and needed,
19910 return FunctionEmissionStatus::OMPDiscarded
;
19911 } else if (LangOpts
.OpenMP
> 45) {
19912 // In OpenMP host compilation prior to 5.0 everything was an emitted host
19913 // function. In 5.0, no_host was introduced which might cause a function to
19915 std::optional
<OMPDeclareTargetDeclAttr::DevTypeTy
> DevTy
=
19916 OMPDeclareTargetDeclAttr::getDeviceType(FD
->getCanonicalDecl());
19918 if (*DevTy
== OMPDeclareTargetDeclAttr::DT_NoHost
)
19919 return FunctionEmissionStatus::OMPDiscarded
;
19922 if (Final
&& LangOpts
.OpenMP
&& !LangOpts
.CUDA
)
19923 return FunctionEmissionStatus::Emitted
;
19925 if (LangOpts
.CUDA
) {
19926 // When compiling for device, host functions are never emitted. Similarly,
19927 // when compiling for host, device and global functions are never emitted.
19928 // (Technically, we do emit a host-side stub for global functions, but this
19929 // doesn't count for our purposes here.)
19930 Sema::CUDAFunctionTarget T
= IdentifyCUDATarget(FD
);
19931 if (LangOpts
.CUDAIsDevice
&& T
== Sema::CFT_Host
)
19932 return FunctionEmissionStatus::CUDADiscarded
;
19933 if (!LangOpts
.CUDAIsDevice
&&
19934 (T
== Sema::CFT_Device
|| T
== Sema::CFT_Global
))
19935 return FunctionEmissionStatus::CUDADiscarded
;
19937 if (IsEmittedForExternalSymbol())
19938 return FunctionEmissionStatus::Emitted
;
19941 // Otherwise, the function is known-emitted if it's in our set of
19942 // known-emitted functions.
19943 return FunctionEmissionStatus::Unknown
;
19946 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl
*Callee
) {
19947 // Host-side references to a __global__ function refer to the stub, so the
19948 // function itself is never emitted and therefore should not be marked.
19949 // If we have host fn calls kernel fn calls host+device, the HD function
19950 // does not get instantiated on the host. We model this by omitting at the
19951 // call to the kernel from the callgraph. This ensures that, when compiling
19952 // for host, only HD functions actually called from the host get marked as
19954 return LangOpts
.CUDA
&& !LangOpts
.CUDAIsDevice
&&
19955 IdentifyCUDATarget(Callee
) == CFT_Global
;