Allow 'inline' on some declarations in MS compatibility mode (#125250)
[llvm-project.git] / clang / lib / Sema / SemaDecl.cpp
blob1755b37fc8f2950ce3facfe2591a73370fb5112c
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements 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/Decl.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/MangleNumberingContext.h"
27 #include "clang/AST/NonTrivialTypeVisitor.h"
28 #include "clang/AST/Randstruct.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Basic/Builtins.h"
32 #include "clang/Basic/DiagnosticComment.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40 #include "clang/Sema/CXXFieldCollector.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Initialization.h"
44 #include "clang/Sema/Lookup.h"
45 #include "clang/Sema/ParsedTemplate.h"
46 #include "clang/Sema/Scope.h"
47 #include "clang/Sema/ScopeInfo.h"
48 #include "clang/Sema/SemaARM.h"
49 #include "clang/Sema/SemaCUDA.h"
50 #include "clang/Sema/SemaHLSL.h"
51 #include "clang/Sema/SemaInternal.h"
52 #include "clang/Sema/SemaObjC.h"
53 #include "clang/Sema/SemaOpenMP.h"
54 #include "clang/Sema/SemaPPC.h"
55 #include "clang/Sema/SemaRISCV.h"
56 #include "clang/Sema/SemaSYCL.h"
57 #include "clang/Sema/SemaSwift.h"
58 #include "clang/Sema/SemaWasm.h"
59 #include "clang/Sema/Template.h"
60 #include "llvm/ADT/STLForwardCompat.h"
61 #include "llvm/ADT/SmallString.h"
62 #include "llvm/ADT/StringExtras.h"
63 #include "llvm/TargetParser/Triple.h"
64 #include <algorithm>
65 #include <cstring>
66 #include <optional>
67 #include <unordered_map>
69 using namespace clang;
70 using namespace sema;
72 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
73 if (OwnedType) {
74 Decl *Group[2] = { OwnedType, Ptr };
75 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
78 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
81 namespace {
83 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
84 public:
85 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
86 bool AllowTemplates = false,
87 bool AllowNonTemplates = true)
88 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
89 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
90 WantExpressionKeywords = false;
91 WantCXXNamedCasts = false;
92 WantRemainingKeywords = false;
95 bool ValidateCandidate(const TypoCorrection &candidate) override {
96 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
97 if (!AllowInvalidDecl && ND->isInvalidDecl())
98 return false;
100 if (getAsTypeTemplateDecl(ND))
101 return AllowTemplates;
103 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
104 if (!IsType)
105 return false;
107 if (AllowNonTemplates)
108 return true;
110 // An injected-class-name of a class template (specialization) is valid
111 // as a template or as a non-template.
112 if (AllowTemplates) {
113 auto *RD = dyn_cast<CXXRecordDecl>(ND);
114 if (!RD || !RD->isInjectedClassName())
115 return false;
116 RD = cast<CXXRecordDecl>(RD->getDeclContext());
117 return RD->getDescribedClassTemplate() ||
118 isa<ClassTemplateSpecializationDecl>(RD);
121 return false;
124 return !WantClassName && candidate.isKeyword();
127 std::unique_ptr<CorrectionCandidateCallback> clone() override {
128 return std::make_unique<TypeNameValidatorCCC>(*this);
131 private:
132 bool AllowInvalidDecl;
133 bool WantClassName;
134 bool AllowTemplates;
135 bool AllowNonTemplates;
138 } // end anonymous namespace
140 namespace {
141 enum class UnqualifiedTypeNameLookupResult {
142 NotFound,
143 FoundNonType,
144 FoundType
146 } // end anonymous namespace
148 /// Tries to perform unqualified lookup of the type decls in bases for
149 /// dependent class.
150 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
151 /// type decl, \a FoundType if only type decls are found.
152 static UnqualifiedTypeNameLookupResult
153 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
154 SourceLocation NameLoc,
155 const CXXRecordDecl *RD) {
156 if (!RD->hasDefinition())
157 return UnqualifiedTypeNameLookupResult::NotFound;
158 // Look for type decls in base classes.
159 UnqualifiedTypeNameLookupResult FoundTypeDecl =
160 UnqualifiedTypeNameLookupResult::NotFound;
161 for (const auto &Base : RD->bases()) {
162 const CXXRecordDecl *BaseRD = nullptr;
163 if (auto *BaseTT = Base.getType()->getAs<TagType>())
164 BaseRD = BaseTT->getAsCXXRecordDecl();
165 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
166 // Look for type decls in dependent base classes that have known primary
167 // templates.
168 if (!TST || !TST->isDependentType())
169 continue;
170 auto *TD = TST->getTemplateName().getAsTemplateDecl();
171 if (!TD)
172 continue;
173 if (auto *BasePrimaryTemplate =
174 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
175 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
176 BaseRD = BasePrimaryTemplate;
177 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
178 if (const ClassTemplatePartialSpecializationDecl *PS =
179 CTD->findPartialSpecialization(Base.getType()))
180 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
181 BaseRD = PS;
185 if (BaseRD) {
186 for (NamedDecl *ND : BaseRD->lookup(&II)) {
187 if (!isa<TypeDecl>(ND))
188 return UnqualifiedTypeNameLookupResult::FoundNonType;
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
191 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
192 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
193 case UnqualifiedTypeNameLookupResult::FoundNonType:
194 return UnqualifiedTypeNameLookupResult::FoundNonType;
195 case UnqualifiedTypeNameLookupResult::FoundType:
196 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
197 break;
198 case UnqualifiedTypeNameLookupResult::NotFound:
199 break;
205 return FoundTypeDecl;
208 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
209 const IdentifierInfo &II,
210 SourceLocation NameLoc) {
211 // Lookup in the parent class template context, if any.
212 const CXXRecordDecl *RD = nullptr;
213 UnqualifiedTypeNameLookupResult FoundTypeDecl =
214 UnqualifiedTypeNameLookupResult::NotFound;
215 for (DeclContext *DC = S.CurContext;
216 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
217 DC = DC->getParent()) {
218 // Look for type decls in dependent base classes that have known primary
219 // templates.
220 RD = dyn_cast<CXXRecordDecl>(DC);
221 if (RD && RD->getDescribedClassTemplate())
222 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
224 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
225 return nullptr;
227 // We found some types in dependent base classes. Recover as if the user
228 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
229 // lookup during template instantiation.
230 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
232 ASTContext &Context = S.Context;
233 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
234 cast<Type>(Context.getRecordType(RD)));
235 QualType T =
236 Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);
238 CXXScopeSpec SS;
239 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
241 TypeLocBuilder Builder;
242 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
243 DepTL.setNameLoc(NameLoc);
244 DepTL.setElaboratedKeywordLoc(SourceLocation());
245 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
246 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
249 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
250 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
251 SourceLocation NameLoc,
252 bool WantNontrivialTypeSourceInfo = true) {
253 switch (T->getTypeClass()) {
254 case Type::DeducedTemplateSpecialization:
255 case Type::Enum:
256 case Type::InjectedClassName:
257 case Type::Record:
258 case Type::Typedef:
259 case Type::UnresolvedUsing:
260 case Type::Using:
261 break;
262 // These can never be qualified so an ElaboratedType node
263 // would carry no additional meaning.
264 case Type::ObjCInterface:
265 case Type::ObjCTypeParam:
266 case Type::TemplateTypeParm:
267 return ParsedType::make(T);
268 default:
269 llvm_unreachable("Unexpected Type Class");
272 if (!SS || SS->isEmpty())
273 return ParsedType::make(S.Context.getElaboratedType(
274 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
276 QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);
277 if (!WantNontrivialTypeSourceInfo)
278 return ParsedType::make(ElTy);
280 TypeLocBuilder Builder;
281 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
282 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
283 ElabTL.setElaboratedKeywordLoc(SourceLocation());
284 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
285 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
288 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
289 Scope *S, CXXScopeSpec *SS, bool isClassName,
290 bool HasTrailingDot, ParsedType ObjectTypePtr,
291 bool IsCtorOrDtorName,
292 bool WantNontrivialTypeSourceInfo,
293 bool IsClassTemplateDeductionContext,
294 ImplicitTypenameContext AllowImplicitTypename,
295 IdentifierInfo **CorrectedII) {
296 // FIXME: Consider allowing this outside C++1z mode as an extension.
297 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
298 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
299 !isClassName && !HasTrailingDot;
301 // Determine where we will perform name lookup.
302 DeclContext *LookupCtx = nullptr;
303 if (ObjectTypePtr) {
304 QualType ObjectType = ObjectTypePtr.get();
305 if (ObjectType->isRecordType())
306 LookupCtx = computeDeclContext(ObjectType);
307 } else if (SS && SS->isNotEmpty()) {
308 LookupCtx = computeDeclContext(*SS, false);
310 if (!LookupCtx) {
311 if (isDependentScopeSpecifier(*SS)) {
312 // C++ [temp.res]p3:
313 // A qualified-id that refers to a type and in which the
314 // nested-name-specifier depends on a template-parameter (14.6.2)
315 // shall be prefixed by the keyword typename to indicate that the
316 // qualified-id denotes a type, forming an
317 // elaborated-type-specifier (7.1.5.3).
319 // We therefore do not perform any name lookup if the result would
320 // refer to a member of an unknown specialization.
321 // In C++2a, in several contexts a 'typename' is not required. Also
322 // allow this as an extension.
323 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
324 !isClassName && !IsCtorOrDtorName)
325 return nullptr;
326 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
327 if (IsImplicitTypename) {
328 SourceLocation QualifiedLoc = SS->getRange().getBegin();
329 if (getLangOpts().CPlusPlus20)
330 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
331 else
332 Diag(QualifiedLoc, diag::ext_implicit_typename)
333 << SS->getScopeRep() << II.getName()
334 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
337 // We know from the grammar that this name refers to a type,
338 // so build a dependent node to describe the type.
339 if (WantNontrivialTypeSourceInfo)
340 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
341 (ImplicitTypenameContext)IsImplicitTypename)
342 .get();
344 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
345 QualType T = CheckTypenameType(
346 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
347 : ElaboratedTypeKeyword::None,
348 SourceLocation(), QualifierLoc, II, NameLoc);
349 return ParsedType::make(T);
352 return nullptr;
355 if (!LookupCtx->isDependentContext() &&
356 RequireCompleteDeclContext(*SS, LookupCtx))
357 return nullptr;
360 // In the case where we know that the identifier is a class name, we know that
361 // it is a type declaration (struct, class, union or enum) so we can use tag
362 // name lookup.
364 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
365 // the component name of the type-name or simple-template-id is type-only.
366 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
367 LookupResult Result(*this, &II, NameLoc, Kind);
368 if (LookupCtx) {
369 // Perform "qualified" name lookup into the declaration context we
370 // computed, which is either the type of the base of a member access
371 // expression or the declaration context associated with a prior
372 // nested-name-specifier.
373 LookupQualifiedName(Result, LookupCtx);
375 if (ObjectTypePtr && Result.empty()) {
376 // C++ [basic.lookup.classref]p3:
377 // If the unqualified-id is ~type-name, the type-name is looked up
378 // in the context of the entire postfix-expression. If the type T of
379 // the object expression is of a class type C, the type-name is also
380 // looked up in the scope of class C. At least one of the lookups shall
381 // find a name that refers to (possibly cv-qualified) T.
382 LookupName(Result, S);
384 } else {
385 // Perform unqualified name lookup.
386 LookupName(Result, S);
388 // For unqualified lookup in a class template in MSVC mode, look into
389 // dependent base classes where the primary class template is known.
390 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
391 if (ParsedType TypeInBase =
392 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
393 return TypeInBase;
397 NamedDecl *IIDecl = nullptr;
398 UsingShadowDecl *FoundUsingShadow = nullptr;
399 switch (Result.getResultKind()) {
400 case LookupResult::NotFound:
401 if (CorrectedII) {
402 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
403 AllowDeducedTemplate);
404 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
405 S, SS, CCC, CTK_ErrorRecovery);
406 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
407 TemplateTy Template;
408 bool MemberOfUnknownSpecialization;
409 UnqualifiedId TemplateName;
410 TemplateName.setIdentifier(NewII, NameLoc);
411 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
412 CXXScopeSpec NewSS, *NewSSPtr = SS;
413 if (SS && NNS) {
414 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
415 NewSSPtr = &NewSS;
417 if (Correction && (NNS || NewII != &II) &&
418 // Ignore a correction to a template type as the to-be-corrected
419 // identifier is not a template (typo correction for template names
420 // is handled elsewhere).
421 !(getLangOpts().CPlusPlus && NewSSPtr &&
422 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
423 Template, MemberOfUnknownSpecialization))) {
424 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
425 isClassName, HasTrailingDot, ObjectTypePtr,
426 IsCtorOrDtorName,
427 WantNontrivialTypeSourceInfo,
428 IsClassTemplateDeductionContext);
429 if (Ty) {
430 diagnoseTypo(Correction,
431 PDiag(diag::err_unknown_type_or_class_name_suggest)
432 << Result.getLookupName() << isClassName);
433 if (SS && NNS)
434 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
435 *CorrectedII = NewII;
436 return Ty;
440 Result.suppressDiagnostics();
441 return nullptr;
442 case LookupResult::NotFoundInCurrentInstantiation:
443 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
444 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
445 SS->getScopeRep(), &II);
446 TypeLocBuilder TLB;
447 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
448 TL.setElaboratedKeywordLoc(SourceLocation());
449 TL.setQualifierLoc(SS->getWithLocInContext(Context));
450 TL.setNameLoc(NameLoc);
451 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
453 [[fallthrough]];
454 case LookupResult::FoundOverloaded:
455 case LookupResult::FoundUnresolvedValue:
456 Result.suppressDiagnostics();
457 return nullptr;
459 case LookupResult::Ambiguous:
460 // Recover from type-hiding ambiguities by hiding the type. We'll
461 // do the lookup again when looking for an object, and we can
462 // diagnose the error then. If we don't do this, then the error
463 // about hiding the type will be immediately followed by an error
464 // that only makes sense if the identifier was treated like a type.
465 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
466 Result.suppressDiagnostics();
467 return nullptr;
470 // Look to see if we have a type anywhere in the list of results.
471 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
472 Res != ResEnd; ++Res) {
473 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
474 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
475 RealRes) ||
476 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
477 if (!IIDecl ||
478 // Make the selection of the recovery decl deterministic.
479 RealRes->getLocation() < IIDecl->getLocation()) {
480 IIDecl = RealRes;
481 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
486 if (!IIDecl) {
487 // None of the entities we found is a type, so there is no way
488 // to even assume that the result is a type. In this case, don't
489 // complain about the ambiguity. The parser will either try to
490 // perform this lookup again (e.g., as an object name), which
491 // will produce the ambiguity, or will complain that it expected
492 // a type name.
493 Result.suppressDiagnostics();
494 return nullptr;
497 // We found a type within the ambiguous lookup; diagnose the
498 // ambiguity and then return that type. This might be the right
499 // answer, or it might not be, but it suppresses any attempt to
500 // perform the name lookup again.
501 break;
503 case LookupResult::Found:
504 IIDecl = Result.getFoundDecl();
505 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
506 break;
509 assert(IIDecl && "Didn't find decl");
511 QualType T;
512 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
513 // C++ [class.qual]p2: A lookup that would find the injected-class-name
514 // instead names the constructors of the class, except when naming a class.
515 // This is ill-formed when we're not actually forming a ctor or dtor name.
516 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
517 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
518 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
519 FoundRD->isInjectedClassName() &&
520 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
521 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
522 << &II << /*Type*/1;
524 DiagnoseUseOfDecl(IIDecl, NameLoc);
526 T = Context.getTypeDeclType(TD);
527 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
528 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
529 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
530 if (!HasTrailingDot)
531 T = Context.getObjCInterfaceType(IDecl);
532 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
533 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
534 (void)DiagnoseUseOfDecl(UD, NameLoc);
535 // Recover with 'int'
536 return ParsedType::make(Context.IntTy);
537 } else if (AllowDeducedTemplate) {
538 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
539 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
540 TemplateName Template = Context.getQualifiedTemplateName(
541 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
542 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
543 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
544 false);
545 // Don't wrap in a further UsingType.
546 FoundUsingShadow = nullptr;
550 if (T.isNull()) {
551 // If it's not plausibly a type, suppress diagnostics.
552 Result.suppressDiagnostics();
553 return nullptr;
556 if (FoundUsingShadow)
557 T = Context.getUsingType(FoundUsingShadow, T);
559 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
562 // Builds a fake NNS for the given decl context.
563 static NestedNameSpecifier *
564 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
565 for (;; DC = DC->getLookupParent()) {
566 DC = DC->getPrimaryContext();
567 auto *ND = dyn_cast<NamespaceDecl>(DC);
568 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
569 return NestedNameSpecifier::Create(Context, nullptr, ND);
570 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
571 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572 RD->getTypeForDecl());
573 else if (isa<TranslationUnitDecl>(DC))
574 return NestedNameSpecifier::GlobalSpecifier(Context);
576 llvm_unreachable("something isn't in TU scope?");
579 /// Find the parent class with dependent bases of the innermost enclosing method
580 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
581 /// up allowing unqualified dependent type names at class-level, which MSVC
582 /// correctly rejects.
583 static const CXXRecordDecl *
584 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
585 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
586 DC = DC->getPrimaryContext();
587 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
588 if (MD->getParent()->hasAnyDependentBases())
589 return MD->getParent();
591 return nullptr;
594 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
595 SourceLocation NameLoc,
596 bool IsTemplateTypeArg) {
597 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
599 NestedNameSpecifier *NNS = nullptr;
600 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
601 // If we weren't able to parse a default template argument, delay lookup
602 // until instantiation time by making a non-dependent DependentTypeName. We
603 // pretend we saw a NestedNameSpecifier referring to the current scope, and
604 // lookup is retried.
605 // FIXME: This hurts our diagnostic quality, since we get errors like "no
606 // type named 'Foo' in 'current_namespace'" when the user didn't write any
607 // name specifiers.
608 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
609 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
610 } else if (const CXXRecordDecl *RD =
611 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
612 // Build a DependentNameType that will perform lookup into RD at
613 // instantiation time.
614 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
615 RD->getTypeForDecl());
617 // Diagnose that this identifier was undeclared, and retry the lookup during
618 // template instantiation.
619 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
620 << RD;
621 } else {
622 // This is not a situation that we should recover from.
623 return ParsedType();
626 QualType T =
627 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
629 // Build type location information. We synthesized the qualifier, so we have
630 // to build a fake NestedNameSpecifierLoc.
631 NestedNameSpecifierLocBuilder NNSLocBuilder;
632 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
633 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
635 TypeLocBuilder Builder;
636 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
637 DepTL.setNameLoc(NameLoc);
638 DepTL.setElaboratedKeywordLoc(SourceLocation());
639 DepTL.setQualifierLoc(QualifierLoc);
640 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
643 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
644 // Do a tag name lookup in this scope.
645 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
646 LookupName(R, S, false);
647 R.suppressDiagnostics();
648 if (R.getResultKind() == LookupResult::Found)
649 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
650 switch (TD->getTagKind()) {
651 case TagTypeKind::Struct:
652 return DeclSpec::TST_struct;
653 case TagTypeKind::Interface:
654 return DeclSpec::TST_interface;
655 case TagTypeKind::Union:
656 return DeclSpec::TST_union;
657 case TagTypeKind::Class:
658 return DeclSpec::TST_class;
659 case TagTypeKind::Enum:
660 return DeclSpec::TST_enum;
664 return DeclSpec::TST_unspecified;
667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
668 if (CurContext->isRecord()) {
669 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
670 return true;
672 const Type *Ty = SS->getScopeRep()->getAsType();
674 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
675 for (const auto &Base : RD->bases())
676 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
677 return true;
678 return S->isFunctionPrototypeScope();
680 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
684 SourceLocation IILoc,
685 Scope *S,
686 CXXScopeSpec *SS,
687 ParsedType &SuggestedType,
688 bool IsTemplateName) {
689 // Don't report typename errors for editor placeholders.
690 if (II->isEditorPlaceholder())
691 return;
692 // We don't have anything to suggest (yet).
693 SuggestedType = nullptr;
695 // There may have been a typo in the name of the type. Look up typo
696 // results, in case we have something that we can suggest.
697 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
698 /*AllowTemplates=*/IsTemplateName,
699 /*AllowNonTemplates=*/!IsTemplateName);
700 if (TypoCorrection Corrected =
701 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
702 CCC, CTK_ErrorRecovery)) {
703 // FIXME: Support error recovery for the template-name case.
704 bool CanRecover = !IsTemplateName;
705 if (Corrected.isKeyword()) {
706 // We corrected to a keyword.
707 diagnoseTypo(Corrected,
708 PDiag(IsTemplateName ? diag::err_no_template_suggest
709 : diag::err_unknown_typename_suggest)
710 << II);
711 II = Corrected.getCorrectionAsIdentifierInfo();
712 } else {
713 // We found a similarly-named type or interface; suggest that.
714 if (!SS || !SS->isSet()) {
715 diagnoseTypo(Corrected,
716 PDiag(IsTemplateName ? diag::err_no_template_suggest
717 : diag::err_unknown_typename_suggest)
718 << II, CanRecover);
719 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
720 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
721 bool DroppedSpecifier =
722 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
723 diagnoseTypo(Corrected,
724 PDiag(IsTemplateName
725 ? diag::err_no_member_template_suggest
726 : diag::err_unknown_nested_typename_suggest)
727 << II << DC << DroppedSpecifier << SS->getRange(),
728 CanRecover);
729 } else {
730 llvm_unreachable("could not have corrected a typo here");
733 if (!CanRecover)
734 return;
736 CXXScopeSpec tmpSS;
737 if (Corrected.getCorrectionSpecifier())
738 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
739 SourceRange(IILoc));
740 // FIXME: Support class template argument deduction here.
741 SuggestedType =
742 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
743 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
744 /*IsCtorOrDtorName=*/false,
745 /*WantNontrivialTypeSourceInfo=*/true);
747 return;
750 if (getLangOpts().CPlusPlus && !IsTemplateName) {
751 // See if II is a class template that the user forgot to pass arguments to.
752 UnqualifiedId Name;
753 Name.setIdentifier(II, IILoc);
754 CXXScopeSpec EmptySS;
755 TemplateTy TemplateResult;
756 bool MemberOfUnknownSpecialization;
757 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
758 Name, nullptr, true, TemplateResult,
759 MemberOfUnknownSpecialization) == TNK_Type_template) {
760 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
761 return;
765 // FIXME: Should we move the logic that tries to recover from a missing tag
766 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
768 if (!SS || (!SS->isSet() && !SS->isInvalid()))
769 Diag(IILoc, IsTemplateName ? diag::err_no_template
770 : diag::err_unknown_typename)
771 << II;
772 else if (DeclContext *DC = computeDeclContext(*SS, false))
773 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
774 : diag::err_typename_nested_not_found)
775 << II << DC << SS->getRange();
776 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
777 SuggestedType =
778 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
779 } else if (isDependentScopeSpecifier(*SS)) {
780 unsigned DiagID = diag::err_typename_missing;
781 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
782 DiagID = diag::ext_typename_missing;
784 Diag(SS->getRange().getBegin(), DiagID)
785 << SS->getScopeRep() << II->getName()
786 << SourceRange(SS->getRange().getBegin(), IILoc)
787 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
788 SuggestedType = ActOnTypenameType(S, SourceLocation(),
789 *SS, *II, IILoc).get();
790 } else {
791 assert(SS && SS->isInvalid() &&
792 "Invalid scope specifier has already been diagnosed");
796 /// Determine whether the given result set contains either a type name
797 /// or
798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
799 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
800 NextToken.is(tok::less);
802 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
803 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
804 return true;
806 if (CheckTemplate && isa<TemplateDecl>(*I))
807 return true;
810 return false;
813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
814 Scope *S, CXXScopeSpec &SS,
815 IdentifierInfo *&Name,
816 SourceLocation NameLoc) {
817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
818 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
819 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
820 StringRef FixItTagName;
821 switch (Tag->getTagKind()) {
822 case TagTypeKind::Class:
823 FixItTagName = "class ";
824 break;
826 case TagTypeKind::Enum:
827 FixItTagName = "enum ";
828 break;
830 case TagTypeKind::Struct:
831 FixItTagName = "struct ";
832 break;
834 case TagTypeKind::Interface:
835 FixItTagName = "__interface ";
836 break;
838 case TagTypeKind::Union:
839 FixItTagName = "union ";
840 break;
843 StringRef TagName = FixItTagName.drop_back();
844 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
845 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
846 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
848 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
849 I != IEnd; ++I)
850 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
851 << Name << TagName;
853 // Replace lookup results with just the tag decl.
854 Result.clear(Sema::LookupTagName);
855 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
856 return true;
859 return false;
862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
863 IdentifierInfo *&Name,
864 SourceLocation NameLoc,
865 const Token &NextToken,
866 CorrectionCandidateCallback *CCC) {
867 DeclarationNameInfo NameInfo(Name, NameLoc);
868 ObjCMethodDecl *CurMethod = getCurMethodDecl();
870 assert(NextToken.isNot(tok::coloncolon) &&
871 "parse nested name specifiers before calling ClassifyName");
872 if (getLangOpts().CPlusPlus && SS.isSet() &&
873 isCurrentClassName(*Name, S, &SS)) {
874 // Per [class.qual]p2, this names the constructors of SS, not the
875 // injected-class-name. We don't have a classification for that.
876 // There's not much point caching this result, since the parser
877 // will reject it later.
878 return NameClassification::Unknown();
881 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
882 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
883 /*AllowBuiltinCreation=*/!CurMethod);
885 if (SS.isInvalid())
886 return NameClassification::Error();
888 // For unqualified lookup in a class template in MSVC mode, look into
889 // dependent base classes where the primary class template is known.
890 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
891 if (ParsedType TypeInBase =
892 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
893 return TypeInBase;
896 // Perform lookup for Objective-C instance variables (including automatically
897 // synthesized instance variables), if we're in an Objective-C method.
898 // FIXME: This lookup really, really needs to be folded in to the normal
899 // unqualified lookup mechanism.
900 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
901 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
902 if (Ivar.isInvalid())
903 return NameClassification::Error();
904 if (Ivar.isUsable())
905 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
907 // We defer builtin creation until after ivar lookup inside ObjC methods.
908 if (Result.empty())
909 LookupBuiltin(Result);
912 bool SecondTry = false;
913 bool IsFilteredTemplateName = false;
915 Corrected:
916 switch (Result.getResultKind()) {
917 case LookupResult::NotFound:
918 // If an unqualified-id is followed by a '(', then we have a function
919 // call.
920 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
921 // In C++, this is an ADL-only call.
922 // FIXME: Reference?
923 if (getLangOpts().CPlusPlus)
924 return NameClassification::UndeclaredNonType();
926 // C90 6.3.2.2:
927 // If the expression that precedes the parenthesized argument list in a
928 // function call consists solely of an identifier, and if no
929 // declaration is visible for this identifier, the identifier is
930 // implicitly declared exactly as if, in the innermost block containing
931 // the function call, the declaration
933 // extern int identifier ();
935 // appeared.
937 // We also allow this in C99 as an extension. However, this is not
938 // allowed in all language modes as functions without prototypes may not
939 // be supported.
940 if (getLangOpts().implicitFunctionsAllowed()) {
941 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
942 return NameClassification::NonType(D);
946 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
947 // In C++20 onwards, this could be an ADL-only call to a function
948 // template, and we're required to assume that this is a template name.
950 // FIXME: Find a way to still do typo correction in this case.
951 TemplateName Template =
952 Context.getAssumedTemplateName(NameInfo.getName());
953 return NameClassification::UndeclaredTemplate(Template);
956 // In C, we first see whether there is a tag type by the same name, in
957 // which case it's likely that the user just forgot to write "enum",
958 // "struct", or "union".
959 if (!getLangOpts().CPlusPlus && !SecondTry &&
960 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
961 break;
964 // Perform typo correction to determine if there is another name that is
965 // close to this name.
966 if (!SecondTry && CCC) {
967 SecondTry = true;
968 if (TypoCorrection Corrected =
969 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
970 &SS, *CCC, CTK_ErrorRecovery)) {
971 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
972 unsigned QualifiedDiag = diag::err_no_member_suggest;
974 NamedDecl *FirstDecl = Corrected.getFoundDecl();
975 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
976 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
977 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
978 UnqualifiedDiag = diag::err_no_template_suggest;
979 QualifiedDiag = diag::err_no_member_template_suggest;
980 } else if (UnderlyingFirstDecl &&
981 (isa<TypeDecl>(UnderlyingFirstDecl) ||
982 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
983 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
984 UnqualifiedDiag = diag::err_unknown_typename_suggest;
985 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
988 if (SS.isEmpty()) {
989 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
990 } else {// FIXME: is this even reachable? Test it.
991 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
992 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
993 Name->getName() == CorrectedStr;
994 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
995 << Name << computeDeclContext(SS, false)
996 << DroppedSpecifier << SS.getRange());
999 // Update the name, so that the caller has the new name.
1000 Name = Corrected.getCorrectionAsIdentifierInfo();
1002 // Typo correction corrected to a keyword.
1003 if (Corrected.isKeyword())
1004 return Name;
1006 // Also update the LookupResult...
1007 // FIXME: This should probably go away at some point
1008 Result.clear();
1009 Result.setLookupName(Corrected.getCorrection());
1010 if (FirstDecl)
1011 Result.addDecl(FirstDecl);
1013 // If we found an Objective-C instance variable, let
1014 // LookupInObjCMethod build the appropriate expression to
1015 // reference the ivar.
1016 // FIXME: This is a gross hack.
1017 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1018 DeclResult R =
1019 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1020 if (R.isInvalid())
1021 return NameClassification::Error();
1022 if (R.isUsable())
1023 return NameClassification::NonType(Ivar);
1026 goto Corrected;
1030 // We failed to correct; just fall through and let the parser deal with it.
1031 Result.suppressDiagnostics();
1032 return NameClassification::Unknown();
1034 case LookupResult::NotFoundInCurrentInstantiation: {
1035 // We performed name lookup into the current instantiation, and there were
1036 // dependent bases, so we treat this result the same way as any other
1037 // dependent nested-name-specifier.
1039 // C++ [temp.res]p2:
1040 // A name used in a template declaration or definition and that is
1041 // dependent on a template-parameter is assumed not to name a type
1042 // unless the applicable name lookup finds a type name or the name is
1043 // qualified by the keyword typename.
1045 // FIXME: If the next token is '<', we might want to ask the parser to
1046 // perform some heroics to see if we actually have a
1047 // template-argument-list, which would indicate a missing 'template'
1048 // keyword here.
1049 return NameClassification::DependentNonType();
1052 case LookupResult::Found:
1053 case LookupResult::FoundOverloaded:
1054 case LookupResult::FoundUnresolvedValue:
1055 break;
1057 case LookupResult::Ambiguous:
1058 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1059 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1060 /*AllowDependent=*/false)) {
1061 // C++ [temp.local]p3:
1062 // A lookup that finds an injected-class-name (10.2) can result in an
1063 // ambiguity in certain cases (for example, if it is found in more than
1064 // one base class). If all of the injected-class-names that are found
1065 // refer to specializations of the same class template, and if the name
1066 // is followed by a template-argument-list, the reference refers to the
1067 // class template itself and not a specialization thereof, and is not
1068 // ambiguous.
1070 // This filtering can make an ambiguous result into an unambiguous one,
1071 // so try again after filtering out template names.
1072 FilterAcceptableTemplateNames(Result);
1073 if (!Result.isAmbiguous()) {
1074 IsFilteredTemplateName = true;
1075 break;
1079 // Diagnose the ambiguity and return an error.
1080 return NameClassification::Error();
1083 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1084 (IsFilteredTemplateName ||
1085 hasAnyAcceptableTemplateNames(
1086 Result, /*AllowFunctionTemplates=*/true,
1087 /*AllowDependent=*/false,
1088 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1089 getLangOpts().CPlusPlus20))) {
1090 // C++ [temp.names]p3:
1091 // After name lookup (3.4) finds that a name is a template-name or that
1092 // an operator-function-id or a literal- operator-id refers to a set of
1093 // overloaded functions any member of which is a function template if
1094 // this is followed by a <, the < is always taken as the delimiter of a
1095 // template-argument-list and never as the less-than operator.
1096 // C++2a [temp.names]p2:
1097 // A name is also considered to refer to a template if it is an
1098 // unqualified-id followed by a < and name lookup finds either one
1099 // or more functions or finds nothing.
1100 if (!IsFilteredTemplateName)
1101 FilterAcceptableTemplateNames(Result);
1103 bool IsFunctionTemplate;
1104 bool IsVarTemplate;
1105 TemplateName Template;
1106 if (Result.end() - Result.begin() > 1) {
1107 IsFunctionTemplate = true;
1108 Template = Context.getOverloadedTemplateName(Result.begin(),
1109 Result.end());
1110 } else if (!Result.empty()) {
1111 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1112 *Result.begin(), /*AllowFunctionTemplates=*/true,
1113 /*AllowDependent=*/false));
1114 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1115 IsVarTemplate = isa<VarTemplateDecl>(TD);
1117 UsingShadowDecl *FoundUsingShadow =
1118 dyn_cast<UsingShadowDecl>(*Result.begin());
1119 assert(!FoundUsingShadow ||
1120 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1121 Template = Context.getQualifiedTemplateName(
1122 SS.getScopeRep(),
1123 /*TemplateKeyword=*/false,
1124 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1125 } else {
1126 // All results were non-template functions. This is a function template
1127 // name.
1128 IsFunctionTemplate = true;
1129 Template = Context.getAssumedTemplateName(NameInfo.getName());
1132 if (IsFunctionTemplate) {
1133 // Function templates always go through overload resolution, at which
1134 // point we'll perform the various checks (e.g., accessibility) we need
1135 // to based on which function we selected.
1136 Result.suppressDiagnostics();
1138 return NameClassification::FunctionTemplate(Template);
1141 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1142 : NameClassification::TypeTemplate(Template);
1145 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1146 QualType T = Context.getTypeDeclType(Type);
1147 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1148 T = Context.getUsingType(USD, T);
1149 return buildNamedType(*this, &SS, T, NameLoc);
1152 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154 DiagnoseUseOfDecl(Type, NameLoc);
1155 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156 return BuildTypeFor(Type, *Result.begin());
1159 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160 if (!Class) {
1161 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162 if (ObjCCompatibleAliasDecl *Alias =
1163 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164 Class = Alias->getClassInterface();
1167 if (Class) {
1168 DiagnoseUseOfDecl(Class, NameLoc);
1170 if (NextToken.is(tok::period)) {
1171 // Interface. <something> is parsed as a property reference expression.
1172 // Just return "unknown" as a fall-through for now.
1173 Result.suppressDiagnostics();
1174 return NameClassification::Unknown();
1177 QualType T = Context.getObjCInterfaceType(Class);
1178 return ParsedType::make(T);
1181 if (isa<ConceptDecl>(FirstDecl)) {
1182 // We want to preserve the UsingShadowDecl for concepts.
1183 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1184 return NameClassification::Concept(TemplateName(USD));
1185 return NameClassification::Concept(
1186 TemplateName(cast<TemplateDecl>(FirstDecl)));
1189 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1190 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1191 return NameClassification::Error();
1194 // We can have a type template here if we're classifying a template argument.
1195 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1196 !isa<VarTemplateDecl>(FirstDecl))
1197 return NameClassification::TypeTemplate(
1198 TemplateName(cast<TemplateDecl>(FirstDecl)));
1200 // Check for a tag type hidden by a non-type decl in a few cases where it
1201 // seems likely a type is wanted instead of the non-type that was found.
1202 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1203 if ((NextToken.is(tok::identifier) ||
1204 (NextIsOp &&
1205 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1206 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1207 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1208 DiagnoseUseOfDecl(Type, NameLoc);
1209 return BuildTypeFor(Type, *Result.begin());
1212 // If we already know which single declaration is referenced, just annotate
1213 // that declaration directly. Defer resolving even non-overloaded class
1214 // member accesses, as we need to defer certain access checks until we know
1215 // the context.
1216 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1217 if (Result.isSingleResult() && !ADL &&
1218 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1219 return NameClassification::NonType(Result.getRepresentativeDecl());
1221 // Otherwise, this is an overload set that we will need to resolve later.
1222 Result.suppressDiagnostics();
1223 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1224 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1225 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1226 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1229 ExprResult
1230 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1231 SourceLocation NameLoc) {
1232 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1233 CXXScopeSpec SS;
1234 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1235 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1238 ExprResult
1239 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1240 IdentifierInfo *Name,
1241 SourceLocation NameLoc,
1242 bool IsAddressOfOperand) {
1243 DeclarationNameInfo NameInfo(Name, NameLoc);
1244 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1245 NameInfo, IsAddressOfOperand,
1246 /*TemplateArgs=*/nullptr);
1249 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1250 NamedDecl *Found,
1251 SourceLocation NameLoc,
1252 const Token &NextToken) {
1253 if (getCurMethodDecl() && SS.isEmpty())
1254 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1255 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1257 // Reconstruct the lookup result.
1258 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1259 Result.addDecl(Found);
1260 Result.resolveKind();
1262 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1263 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1266 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1267 // For an implicit class member access, transform the result into a member
1268 // access expression if necessary.
1269 auto *ULE = cast<UnresolvedLookupExpr>(E);
1270 if ((*ULE->decls_begin())->isCXXClassMember()) {
1271 CXXScopeSpec SS;
1272 SS.Adopt(ULE->getQualifierLoc());
1274 // Reconstruct the lookup result.
1275 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1276 LookupOrdinaryName);
1277 Result.setNamingClass(ULE->getNamingClass());
1278 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1279 Result.addDecl(*I, I.getAccess());
1280 Result.resolveKind();
1281 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1282 nullptr, S);
1285 // Otherwise, this is already in the form we needed, and no further checks
1286 // are necessary.
1287 return ULE;
1290 Sema::TemplateNameKindForDiagnostics
1291 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1292 auto *TD = Name.getAsTemplateDecl();
1293 if (!TD)
1294 return TemplateNameKindForDiagnostics::DependentTemplate;
1295 if (isa<ClassTemplateDecl>(TD))
1296 return TemplateNameKindForDiagnostics::ClassTemplate;
1297 if (isa<FunctionTemplateDecl>(TD))
1298 return TemplateNameKindForDiagnostics::FunctionTemplate;
1299 if (isa<VarTemplateDecl>(TD))
1300 return TemplateNameKindForDiagnostics::VarTemplate;
1301 if (isa<TypeAliasTemplateDecl>(TD))
1302 return TemplateNameKindForDiagnostics::AliasTemplate;
1303 if (isa<TemplateTemplateParmDecl>(TD))
1304 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1305 if (isa<ConceptDecl>(TD))
1306 return TemplateNameKindForDiagnostics::Concept;
1307 return TemplateNameKindForDiagnostics::DependentTemplate;
1310 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1311 assert(DC->getLexicalParent() == CurContext &&
1312 "The next DeclContext should be lexically contained in the current one.");
1313 CurContext = DC;
1314 S->setEntity(DC);
1317 void Sema::PopDeclContext() {
1318 assert(CurContext && "DeclContext imbalance!");
1320 CurContext = CurContext->getLexicalParent();
1321 assert(CurContext && "Popped translation unit!");
1324 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1325 Decl *D) {
1326 // Unlike PushDeclContext, the context to which we return is not necessarily
1327 // the containing DC of TD, because the new context will be some pre-existing
1328 // TagDecl definition instead of a fresh one.
1329 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1330 CurContext = cast<TagDecl>(D)->getDefinition();
1331 assert(CurContext && "skipping definition of undefined tag");
1332 // Start lookups from the parent of the current context; we don't want to look
1333 // into the pre-existing complete definition.
1334 S->setEntity(CurContext->getLookupParent());
1335 return Result;
1338 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1339 CurContext = static_cast<decltype(CurContext)>(Context);
1342 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1343 // C++0x [basic.lookup.unqual]p13:
1344 // A name used in the definition of a static data member of class
1345 // X (after the qualified-id of the static member) is looked up as
1346 // if the name was used in a member function of X.
1347 // C++0x [basic.lookup.unqual]p14:
1348 // If a variable member of a namespace is defined outside of the
1349 // scope of its namespace then any name used in the definition of
1350 // the variable member (after the declarator-id) is looked up as
1351 // if the definition of the variable member occurred in its
1352 // namespace.
1353 // Both of these imply that we should push a scope whose context
1354 // is the semantic context of the declaration. We can't use
1355 // PushDeclContext here because that context is not necessarily
1356 // lexically contained in the current context. Fortunately,
1357 // the containing scope should have the appropriate information.
1359 assert(!S->getEntity() && "scope already has entity");
1361 #ifndef NDEBUG
1362 Scope *Ancestor = S->getParent();
1363 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1364 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1365 #endif
1367 CurContext = DC;
1368 S->setEntity(DC);
1370 if (S->getParent()->isTemplateParamScope()) {
1371 // Also set the corresponding entities for all immediately-enclosing
1372 // template parameter scopes.
1373 EnterTemplatedContext(S->getParent(), DC);
1377 void Sema::ExitDeclaratorContext(Scope *S) {
1378 assert(S->getEntity() == CurContext && "Context imbalance!");
1380 // Switch back to the lexical context. The safety of this is
1381 // enforced by an assert in EnterDeclaratorContext.
1382 Scope *Ancestor = S->getParent();
1383 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1384 CurContext = Ancestor->getEntity();
1386 // We don't need to do anything with the scope, which is going to
1387 // disappear.
1390 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1391 assert(S->isTemplateParamScope() &&
1392 "expected to be initializing a template parameter scope");
1394 // C++20 [temp.local]p7:
1395 // In the definition of a member of a class template that appears outside
1396 // of the class template definition, the name of a member of the class
1397 // template hides the name of a template-parameter of any enclosing class
1398 // templates (but not a template-parameter of the member if the member is a
1399 // class or function template).
1400 // C++20 [temp.local]p9:
1401 // In the definition of a class template or in the definition of a member
1402 // of such a template that appears outside of the template definition, for
1403 // each non-dependent base class (13.8.2.1), if the name of the base class
1404 // or the name of a member of the base class is the same as the name of a
1405 // template-parameter, the base class name or member name hides the
1406 // template-parameter name (6.4.10).
1408 // This means that a template parameter scope should be searched immediately
1409 // after searching the DeclContext for which it is a template parameter
1410 // scope. For example, for
1411 // template<typename T> template<typename U> template<typename V>
1412 // void N::A<T>::B<U>::f(...)
1413 // we search V then B<U> (and base classes) then U then A<T> (and base
1414 // classes) then T then N then ::.
1415 unsigned ScopeDepth = getTemplateDepth(S);
1416 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1417 DeclContext *SearchDCAfterScope = DC;
1418 for (; DC; DC = DC->getLookupParent()) {
1419 if (const TemplateParameterList *TPL =
1420 cast<Decl>(DC)->getDescribedTemplateParams()) {
1421 unsigned DCDepth = TPL->getDepth() + 1;
1422 if (DCDepth > ScopeDepth)
1423 continue;
1424 if (ScopeDepth == DCDepth)
1425 SearchDCAfterScope = DC = DC->getLookupParent();
1426 break;
1429 S->setLookupEntity(SearchDCAfterScope);
1433 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1434 // We assume that the caller has already called
1435 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1436 FunctionDecl *FD = D->getAsFunction();
1437 if (!FD)
1438 return;
1440 // Same implementation as PushDeclContext, but enters the context
1441 // from the lexical parent, rather than the top-level class.
1442 assert(CurContext == FD->getLexicalParent() &&
1443 "The next DeclContext should be lexically contained in the current one.");
1444 CurContext = FD;
1445 S->setEntity(CurContext);
1447 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1448 ParmVarDecl *Param = FD->getParamDecl(P);
1449 // If the parameter has an identifier, then add it to the scope
1450 if (Param->getIdentifier()) {
1451 S->AddDecl(Param);
1452 IdResolver.AddDecl(Param);
1457 void Sema::ActOnExitFunctionContext() {
1458 // Same implementation as PopDeclContext, but returns to the lexical parent,
1459 // rather than the top-level class.
1460 assert(CurContext && "DeclContext imbalance!");
1461 CurContext = CurContext->getLexicalParent();
1462 assert(CurContext && "Popped translation unit!");
1465 /// Determine whether overloading is allowed for a new function
1466 /// declaration considering prior declarations of the same name.
1468 /// This routine determines whether overloading is possible, not
1469 /// whether a new declaration actually overloads a previous one.
1470 /// It will return true in C++ (where overloads are always permitted)
1471 /// or, as a C extension, when either the new declaration or a
1472 /// previous one is declared with the 'overloadable' attribute.
1473 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1474 ASTContext &Context,
1475 const FunctionDecl *New) {
1476 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1477 return true;
1479 // Multiversion function declarations are not overloads in the
1480 // usual sense of that term, but lookup will report that an
1481 // overload set was found if more than one multiversion function
1482 // declaration is present for the same name. It is therefore
1483 // inadequate to assume that some prior declaration(s) had
1484 // the overloadable attribute; checking is required. Since one
1485 // declaration is permitted to omit the attribute, it is necessary
1486 // to check at least two; hence the 'any_of' check below. Note that
1487 // the overloadable attribute is implicitly added to declarations
1488 // that were required to have it but did not.
1489 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1490 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1491 return ND->hasAttr<OverloadableAttr>();
1493 } else if (Previous.getResultKind() == LookupResult::Found)
1494 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1496 return false;
1499 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1500 // Move up the scope chain until we find the nearest enclosing
1501 // non-transparent context. The declaration will be introduced into this
1502 // scope.
1503 while (S->getEntity() && S->getEntity()->isTransparentContext())
1504 S = S->getParent();
1506 // Add scoped declarations into their context, so that they can be
1507 // found later. Declarations without a context won't be inserted
1508 // into any context.
1509 if (AddToContext)
1510 CurContext->addDecl(D);
1512 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1513 // are function-local declarations.
1514 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1515 return;
1517 // Template instantiations should also not be pushed into scope.
1518 if (isa<FunctionDecl>(D) &&
1519 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1520 return;
1522 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1523 S->AddDecl(D);
1524 return;
1526 // If this replaces anything in the current scope,
1527 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1528 IEnd = IdResolver.end();
1529 for (; I != IEnd; ++I) {
1530 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1531 S->RemoveDecl(*I);
1532 IdResolver.RemoveDecl(*I);
1534 // Should only need to replace one decl.
1535 break;
1539 S->AddDecl(D);
1541 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1542 // Implicitly-generated labels may end up getting generated in an order that
1543 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1544 // the label at the appropriate place in the identifier chain.
1545 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1546 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1547 if (IDC == CurContext) {
1548 if (!S->isDeclScope(*I))
1549 continue;
1550 } else if (IDC->Encloses(CurContext))
1551 break;
1554 IdResolver.InsertDeclAfter(I, D);
1555 } else {
1556 IdResolver.AddDecl(D);
1558 warnOnReservedIdentifier(D);
1561 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1562 bool AllowInlineNamespace) const {
1563 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1566 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1567 DeclContext *TargetDC = DC->getPrimaryContext();
1568 do {
1569 if (DeclContext *ScopeDC = S->getEntity())
1570 if (ScopeDC->getPrimaryContext() == TargetDC)
1571 return S;
1572 } while ((S = S->getParent()));
1574 return nullptr;
1577 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1578 DeclContext*,
1579 ASTContext&);
1581 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1582 bool ConsiderLinkage,
1583 bool AllowInlineNamespace) {
1584 LookupResult::Filter F = R.makeFilter();
1585 while (F.hasNext()) {
1586 NamedDecl *D = F.next();
1588 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1589 continue;
1591 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1592 continue;
1594 F.erase();
1597 F.done();
1600 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1601 // [module.interface]p7:
1602 // A declaration is attached to a module as follows:
1603 // - If the declaration is a non-dependent friend declaration that nominates a
1604 // function with a declarator-id that is a qualified-id or template-id or that
1605 // nominates a class other than with an elaborated-type-specifier with neither
1606 // a nested-name-specifier nor a simple-template-id, it is attached to the
1607 // module to which the friend is attached ([basic.link]).
1608 if (New->getFriendObjectKind() &&
1609 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1610 New->setLocalOwningModule(Old->getOwningModule());
1611 makeMergedDefinitionVisible(New);
1612 return false;
1615 Module *NewM = New->getOwningModule();
1616 Module *OldM = Old->getOwningModule();
1618 if (NewM && NewM->isPrivateModule())
1619 NewM = NewM->Parent;
1620 if (OldM && OldM->isPrivateModule())
1621 OldM = OldM->Parent;
1623 if (NewM == OldM)
1624 return false;
1626 if (NewM && OldM) {
1627 // A module implementation unit has visibility of the decls in its
1628 // implicitly imported interface.
1629 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1630 return false;
1632 // Partitions are part of the module, but a partition could import another
1633 // module, so verify that the PMIs agree.
1634 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1635 getASTContext().isInSameModule(NewM, OldM))
1636 return false;
1639 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1640 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1641 if (NewIsModuleInterface || OldIsModuleInterface) {
1642 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1643 // if a declaration of D [...] appears in the purview of a module, all
1644 // other such declarations shall appear in the purview of the same module
1645 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1646 << New
1647 << NewIsModuleInterface
1648 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1649 << OldIsModuleInterface
1650 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1651 Diag(Old->getLocation(), diag::note_previous_declaration);
1652 New->setInvalidDecl();
1653 return true;
1656 return false;
1659 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1660 // [module.interface]p1:
1661 // An export-declaration shall inhabit a namespace scope.
1663 // So it is meaningless to talk about redeclaration which is not at namespace
1664 // scope.
1665 if (!New->getLexicalDeclContext()
1666 ->getNonTransparentContext()
1667 ->isFileContext() ||
1668 !Old->getLexicalDeclContext()
1669 ->getNonTransparentContext()
1670 ->isFileContext())
1671 return false;
1673 bool IsNewExported = New->isInExportDeclContext();
1674 bool IsOldExported = Old->isInExportDeclContext();
1676 // It should be irrevelant if both of them are not exported.
1677 if (!IsNewExported && !IsOldExported)
1678 return false;
1680 if (IsOldExported)
1681 return false;
1683 // If the Old declaration are not attached to named modules
1684 // and the New declaration are attached to global module.
1685 // It should be fine to allow the export since it doesn't change
1686 // the linkage of declarations. See
1687 // https://github.com/llvm/llvm-project/issues/98583 for details.
1688 if (!Old->isInNamedModule() && New->getOwningModule() &&
1689 New->getOwningModule()->isImplicitGlobalModule())
1690 return false;
1692 assert(IsNewExported);
1694 auto Lk = Old->getFormalLinkage();
1695 int S = 0;
1696 if (Lk == Linkage::Internal)
1697 S = 1;
1698 else if (Lk == Linkage::Module)
1699 S = 2;
1700 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1701 Diag(Old->getLocation(), diag::note_previous_declaration);
1702 return true;
1705 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1706 if (CheckRedeclarationModuleOwnership(New, Old))
1707 return true;
1709 if (CheckRedeclarationExported(New, Old))
1710 return true;
1712 return false;
1715 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1716 const NamedDecl *Old) const {
1717 assert(getASTContext().isSameEntity(New, Old) &&
1718 "New and Old are not the same definition, we should diagnostic it "
1719 "immediately instead of checking it.");
1720 assert(const_cast<Sema *>(this)->isReachable(New) &&
1721 const_cast<Sema *>(this)->isReachable(Old) &&
1722 "We shouldn't see unreachable definitions here.");
1724 Module *NewM = New->getOwningModule();
1725 Module *OldM = Old->getOwningModule();
1727 // We only checks for named modules here. The header like modules is skipped.
1728 // FIXME: This is not right if we import the header like modules in the module
1729 // purview.
1731 // For example, assuming "header.h" provides definition for `D`.
1732 // ```C++
1733 // //--- M.cppm
1734 // export module M;
1735 // import "header.h"; // or #include "header.h" but import it by clang modules
1736 // actually.
1738 // //--- Use.cpp
1739 // import M;
1740 // import "header.h"; // or uses clang modules.
1741 // ```
1743 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1744 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1745 // reject it. But the current implementation couldn't detect the case since we
1746 // don't record the information about the importee modules.
1748 // But this might not be painful in practice. Since the design of C++20 Named
1749 // Modules suggests us to use headers in global module fragment instead of
1750 // module purview.
1751 if (NewM && NewM->isHeaderLikeModule())
1752 NewM = nullptr;
1753 if (OldM && OldM->isHeaderLikeModule())
1754 OldM = nullptr;
1756 if (!NewM && !OldM)
1757 return true;
1759 // [basic.def.odr]p14.3
1760 // Each such definition shall not be attached to a named module
1761 // ([module.unit]).
1762 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1763 return true;
1765 // Then New and Old lives in the same TU if their share one same module unit.
1766 if (NewM)
1767 NewM = NewM->getTopLevelModule();
1768 if (OldM)
1769 OldM = OldM->getTopLevelModule();
1770 return OldM == NewM;
1773 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1774 if (D->getDeclContext()->isFileContext())
1775 return false;
1777 return isa<UsingShadowDecl>(D) ||
1778 isa<UnresolvedUsingTypenameDecl>(D) ||
1779 isa<UnresolvedUsingValueDecl>(D);
1782 /// Removes using shadow declarations not at class scope from the lookup
1783 /// results.
1784 static void RemoveUsingDecls(LookupResult &R) {
1785 LookupResult::Filter F = R.makeFilter();
1786 while (F.hasNext())
1787 if (isUsingDeclNotAtClassScope(F.next()))
1788 F.erase();
1790 F.done();
1793 /// Check for this common pattern:
1794 /// @code
1795 /// class S {
1796 /// S(const S&); // DO NOT IMPLEMENT
1797 /// void operator=(const S&); // DO NOT IMPLEMENT
1798 /// };
1799 /// @endcode
1800 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1801 // FIXME: Should check for private access too but access is set after we get
1802 // the decl here.
1803 if (D->doesThisDeclarationHaveABody())
1804 return false;
1806 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1807 return CD->isCopyConstructor();
1808 return D->isCopyAssignmentOperator();
1811 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1812 const DeclContext *DC = D->getDeclContext();
1813 while (!DC->isTranslationUnit()) {
1814 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1815 if (!RD->hasNameForLinkage())
1816 return true;
1818 DC = DC->getParent();
1821 return !D->isExternallyVisible();
1824 // FIXME: This needs to be refactored; some other isInMainFile users want
1825 // these semantics.
1826 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1827 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1828 return false;
1829 return S.SourceMgr.isInMainFile(Loc);
1832 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1833 assert(D);
1835 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1836 return false;
1838 // Ignore all entities declared within templates, and out-of-line definitions
1839 // of members of class templates.
1840 if (D->getDeclContext()->isDependentContext() ||
1841 D->getLexicalDeclContext()->isDependentContext())
1842 return false;
1844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1845 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1846 return false;
1847 // A non-out-of-line declaration of a member specialization was implicitly
1848 // instantiated; it's the out-of-line declaration that we're interested in.
1849 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1850 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1851 return false;
1853 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1854 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1855 return false;
1856 } else {
1857 // 'static inline' functions are defined in headers; don't warn.
1858 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1859 return false;
1862 if (FD->doesThisDeclarationHaveABody() &&
1863 Context.DeclMustBeEmitted(FD))
1864 return false;
1865 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1866 // Constants and utility variables are defined in headers with internal
1867 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1868 // like "inline".)
1869 if (!isMainFileLoc(*this, VD->getLocation()))
1870 return false;
1872 if (Context.DeclMustBeEmitted(VD))
1873 return false;
1875 if (VD->isStaticDataMember() &&
1876 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1877 return false;
1878 if (VD->isStaticDataMember() &&
1879 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1880 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1881 return false;
1883 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1884 return false;
1885 } else {
1886 return false;
1889 // Only warn for unused decls internal to the translation unit.
1890 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1891 // for inline functions defined in the main source file, for instance.
1892 return mightHaveNonExternalLinkage(D);
1895 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1896 if (!D)
1897 return;
1899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1900 const FunctionDecl *First = FD->getFirstDecl();
1901 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1902 return; // First should already be in the vector.
1905 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1906 const VarDecl *First = VD->getFirstDecl();
1907 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1908 return; // First should already be in the vector.
1911 if (ShouldWarnIfUnusedFileScopedDecl(D))
1912 UnusedFileScopedDecls.push_back(D);
1915 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1916 const NamedDecl *D) {
1917 if (D->isInvalidDecl())
1918 return false;
1920 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1921 // For a decomposition declaration, warn if none of the bindings are
1922 // referenced, instead of if the variable itself is referenced (which
1923 // it is, by the bindings' expressions).
1924 bool IsAllPlaceholders = true;
1925 for (const auto *BD : DD->bindings()) {
1926 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1927 return false;
1928 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1930 if (IsAllPlaceholders)
1931 return false;
1932 } else if (!D->getDeclName()) {
1933 return false;
1934 } else if (D->isReferenced() || D->isUsed()) {
1935 return false;
1938 if (D->isPlaceholderVar(LangOpts))
1939 return false;
1941 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1942 D->hasAttr<CleanupAttr>())
1943 return false;
1945 if (isa<LabelDecl>(D))
1946 return true;
1948 // Except for labels, we only care about unused decls that are local to
1949 // functions.
1950 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1951 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1952 // For dependent types, the diagnostic is deferred.
1953 WithinFunction =
1954 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1955 if (!WithinFunction)
1956 return false;
1958 if (isa<TypedefNameDecl>(D))
1959 return true;
1961 // White-list anything that isn't a local variable.
1962 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1963 return false;
1965 // Types of valid local variables should be complete, so this should succeed.
1966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1968 const Expr *Init = VD->getInit();
1969 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1970 Init = Cleanups->getSubExpr();
1972 const auto *Ty = VD->getType().getTypePtr();
1974 // Only look at the outermost level of typedef.
1975 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1976 // Allow anything marked with __attribute__((unused)).
1977 if (TT->getDecl()->hasAttr<UnusedAttr>())
1978 return false;
1981 // Warn for reference variables whose initializtion performs lifetime
1982 // extension.
1983 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1984 MTE && MTE->getExtendingDecl()) {
1985 Ty = VD->getType().getNonReferenceType().getTypePtr();
1986 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1989 // If we failed to complete the type for some reason, or if the type is
1990 // dependent, don't diagnose the variable.
1991 if (Ty->isIncompleteType() || Ty->isDependentType())
1992 return false;
1994 // Look at the element type to ensure that the warning behaviour is
1995 // consistent for both scalars and arrays.
1996 Ty = Ty->getBaseElementTypeUnsafe();
1998 if (const TagType *TT = Ty->getAs<TagType>()) {
1999 const TagDecl *Tag = TT->getDecl();
2000 if (Tag->hasAttr<UnusedAttr>())
2001 return false;
2003 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2004 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2005 return false;
2007 if (Init) {
2008 const auto *Construct =
2009 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2010 if (Construct && !Construct->isElidable()) {
2011 const CXXConstructorDecl *CD = Construct->getConstructor();
2012 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2013 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2014 return false;
2017 // Suppress the warning if we don't know how this is constructed, and
2018 // it could possibly be non-trivial constructor.
2019 if (Init->isTypeDependent()) {
2020 for (const CXXConstructorDecl *Ctor : RD->ctors())
2021 if (!Ctor->isTrivial())
2022 return false;
2025 // Suppress the warning if the constructor is unresolved because
2026 // its arguments are dependent.
2027 if (isa<CXXUnresolvedConstructExpr>(Init))
2028 return false;
2033 // TODO: __attribute__((unused)) templates?
2036 return true;
2039 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2040 FixItHint &Hint) {
2041 if (isa<LabelDecl>(D)) {
2042 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2043 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2044 /*SkipTrailingWhitespaceAndNewline=*/false);
2045 if (AfterColon.isInvalid())
2046 return;
2047 Hint = FixItHint::CreateRemoval(
2048 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2052 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2053 DiagnoseUnusedNestedTypedefs(
2054 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2057 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2058 DiagReceiverTy DiagReceiver) {
2059 if (D->getTypeForDecl()->isDependentType())
2060 return;
2062 for (auto *TmpD : D->decls()) {
2063 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2064 DiagnoseUnusedDecl(T, DiagReceiver);
2065 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2066 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2070 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2071 DiagnoseUnusedDecl(
2072 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2075 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2076 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2077 return;
2079 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2080 // typedefs can be referenced later on, so the diagnostics are emitted
2081 // at end-of-translation-unit.
2082 UnusedLocalTypedefNameCandidates.insert(TD);
2083 return;
2086 FixItHint Hint;
2087 GenerateFixForUnusedDecl(D, Context, Hint);
2089 unsigned DiagID;
2090 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2091 DiagID = diag::warn_unused_exception_param;
2092 else if (isa<LabelDecl>(D))
2093 DiagID = diag::warn_unused_label;
2094 else
2095 DiagID = diag::warn_unused_variable;
2097 SourceLocation DiagLoc = D->getLocation();
2098 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2101 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2102 DiagReceiverTy DiagReceiver) {
2103 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2104 // it's not really unused.
2105 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2106 return;
2108 // In C++, `_` variables behave as if they were maybe_unused
2109 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2110 return;
2112 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2114 if (Ty->isReferenceType() || Ty->isDependentType())
2115 return;
2117 if (const TagType *TT = Ty->getAs<TagType>()) {
2118 const TagDecl *Tag = TT->getDecl();
2119 if (Tag->hasAttr<UnusedAttr>())
2120 return;
2121 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2122 // mimic gcc's behavior.
2123 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2124 RD && !RD->hasAttr<WarnUnusedAttr>())
2125 return;
2128 // Don't warn about __block Objective-C pointer variables, as they might
2129 // be assigned in the block but not used elsewhere for the purpose of lifetime
2130 // extension.
2131 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2132 return;
2134 // Don't warn about Objective-C pointer variables with precise lifetime
2135 // semantics; they can be used to ensure ARC releases the object at a known
2136 // time, which may mean assignment but no other references.
2137 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2138 return;
2140 auto iter = RefsMinusAssignments.find(VD);
2141 if (iter == RefsMinusAssignments.end())
2142 return;
2144 assert(iter->getSecond() >= 0 &&
2145 "Found a negative number of references to a VarDecl");
2146 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2147 // Assume the given VarDecl is "used" if its ref count stored in
2148 // `RefMinusAssignments` is positive, with one exception.
2150 // For a C++ variable whose decl (with initializer) entirely consist the
2151 // condition expression of a if/while/for construct,
2152 // Clang creates a DeclRefExpr for the condition expression rather than a
2153 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2154 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2155 // used in the body of the if/while/for construct.
2156 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2157 if (!UnusedCXXCondDecl)
2158 return;
2161 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2162 : diag::warn_unused_but_set_variable;
2163 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2166 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2167 Sema::DiagReceiverTy DiagReceiver) {
2168 // Verify that we have no forward references left. If so, there was a goto
2169 // or address of a label taken, but no definition of it. Label fwd
2170 // definitions are indicated with a null substmt which is also not a resolved
2171 // MS inline assembly label name.
2172 bool Diagnose = false;
2173 if (L->isMSAsmLabel())
2174 Diagnose = !L->isResolvedMSAsmLabel();
2175 else
2176 Diagnose = L->getStmt() == nullptr;
2177 if (Diagnose)
2178 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2179 << L);
2182 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2183 S->applyNRVO();
2185 if (S->decl_empty()) return;
2186 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2187 "Scope shouldn't contain decls!");
2189 /// We visit the decls in non-deterministic order, but we want diagnostics
2190 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2191 /// and sort the diagnostics before emitting them, after we visited all decls.
2192 struct LocAndDiag {
2193 SourceLocation Loc;
2194 std::optional<SourceLocation> PreviousDeclLoc;
2195 PartialDiagnostic PD;
2197 SmallVector<LocAndDiag, 16> DeclDiags;
2198 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2199 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2201 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2202 SourceLocation PreviousDeclLoc,
2203 PartialDiagnostic PD) {
2204 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2207 for (auto *TmpD : S->decls()) {
2208 assert(TmpD && "This decl didn't get pushed??");
2210 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2211 NamedDecl *D = cast<NamedDecl>(TmpD);
2213 // Diagnose unused variables in this scope.
2214 if (!S->hasUnrecoverableErrorOccurred()) {
2215 DiagnoseUnusedDecl(D, addDiag);
2216 if (const auto *RD = dyn_cast<RecordDecl>(D))
2217 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2218 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2219 DiagnoseUnusedButSetDecl(VD, addDiag);
2220 RefsMinusAssignments.erase(VD);
2224 if (!D->getDeclName()) continue;
2226 // If this was a forward reference to a label, verify it was defined.
2227 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2228 CheckPoppedLabel(LD, *this, addDiag);
2230 // Partial translation units that are created in incremental processing must
2231 // not clean up the IdResolver because PTUs should take into account the
2232 // declarations that came from previous PTUs.
2233 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2234 getLangOpts().CPlusPlus)
2235 IdResolver.RemoveDecl(D);
2237 // Warn on it if we are shadowing a declaration.
2238 auto ShadowI = ShadowingDecls.find(D);
2239 if (ShadowI != ShadowingDecls.end()) {
2240 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2241 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2242 PDiag(diag::warn_ctor_parm_shadows_field)
2243 << D << FD << FD->getParent());
2245 ShadowingDecls.erase(ShadowI);
2249 llvm::sort(DeclDiags,
2250 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2251 // The particular order for diagnostics is not important, as long
2252 // as the order is deterministic. Using the raw location is going
2253 // to generally be in source order unless there are macro
2254 // expansions involved.
2255 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2257 for (const LocAndDiag &D : DeclDiags) {
2258 Diag(D.Loc, D.PD);
2259 if (D.PreviousDeclLoc)
2260 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2264 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2265 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2266 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2267 (S->isClassScope() && !getLangOpts().CPlusPlus))
2268 S = S->getParent();
2269 return S;
2272 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2273 ASTContext::GetBuiltinTypeError Error) {
2274 switch (Error) {
2275 case ASTContext::GE_None:
2276 return "";
2277 case ASTContext::GE_Missing_type:
2278 return BuiltinInfo.getHeaderName(ID);
2279 case ASTContext::GE_Missing_stdio:
2280 return "stdio.h";
2281 case ASTContext::GE_Missing_setjmp:
2282 return "setjmp.h";
2283 case ASTContext::GE_Missing_ucontext:
2284 return "ucontext.h";
2286 llvm_unreachable("unhandled error kind");
2289 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2290 unsigned ID, SourceLocation Loc) {
2291 DeclContext *Parent = Context.getTranslationUnitDecl();
2293 if (getLangOpts().CPlusPlus) {
2294 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2295 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2296 CLinkageDecl->setImplicit();
2297 Parent->addDecl(CLinkageDecl);
2298 Parent = CLinkageDecl;
2301 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2302 if (Context.BuiltinInfo.isImmediate(ID)) {
2303 assert(getLangOpts().CPlusPlus20 &&
2304 "consteval builtins should only be available in C++20 mode");
2305 ConstexprKind = ConstexprSpecKind::Consteval;
2308 FunctionDecl *New = FunctionDecl::Create(
2309 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2310 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2311 Type->isFunctionProtoType(), ConstexprKind);
2312 New->setImplicit();
2313 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2315 // Create Decl objects for each parameter, adding them to the
2316 // FunctionDecl.
2317 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2318 SmallVector<ParmVarDecl *, 16> Params;
2319 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2320 ParmVarDecl *parm = ParmVarDecl::Create(
2321 Context, New, SourceLocation(), SourceLocation(), nullptr,
2322 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2323 parm->setScopeInfo(0, i);
2324 Params.push_back(parm);
2326 New->setParams(Params);
2329 AddKnownFunctionAttributes(New);
2330 return New;
2333 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2334 Scope *S, bool ForRedeclaration,
2335 SourceLocation Loc) {
2336 LookupNecessaryTypesForBuiltin(S, ID);
2338 ASTContext::GetBuiltinTypeError Error;
2339 QualType R = Context.GetBuiltinType(ID, Error);
2340 if (Error) {
2341 if (!ForRedeclaration)
2342 return nullptr;
2344 // If we have a builtin without an associated type we should not emit a
2345 // warning when we were not able to find a type for it.
2346 if (Error == ASTContext::GE_Missing_type ||
2347 Context.BuiltinInfo.allowTypeMismatch(ID))
2348 return nullptr;
2350 // If we could not find a type for setjmp it is because the jmp_buf type was
2351 // not defined prior to the setjmp declaration.
2352 if (Error == ASTContext::GE_Missing_setjmp) {
2353 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2354 << Context.BuiltinInfo.getName(ID);
2355 return nullptr;
2358 // Generally, we emit a warning that the declaration requires the
2359 // appropriate header.
2360 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2361 << getHeaderName(Context.BuiltinInfo, ID, Error)
2362 << Context.BuiltinInfo.getName(ID);
2363 return nullptr;
2366 if (!ForRedeclaration &&
2367 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2368 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2369 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2370 : diag::ext_implicit_lib_function_decl)
2371 << Context.BuiltinInfo.getName(ID) << R;
2372 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2373 Diag(Loc, diag::note_include_header_or_declare)
2374 << Header << Context.BuiltinInfo.getName(ID);
2377 if (R.isNull())
2378 return nullptr;
2380 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2381 RegisterLocallyScopedExternCDecl(New, S);
2383 // TUScope is the translation-unit scope to insert this function into.
2384 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2385 // relate Scopes to DeclContexts, and probably eliminate CurContext
2386 // entirely, but we're not there yet.
2387 DeclContext *SavedContext = CurContext;
2388 CurContext = New->getDeclContext();
2389 PushOnScopeChains(New, TUScope);
2390 CurContext = SavedContext;
2391 return New;
2394 /// Typedef declarations don't have linkage, but they still denote the same
2395 /// entity if their types are the same.
2396 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2397 /// isSameEntity.
2398 static void
2399 filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2400 LookupResult &Previous) {
2401 // This is only interesting when modules are enabled.
2402 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2403 return;
2405 // Empty sets are uninteresting.
2406 if (Previous.empty())
2407 return;
2409 LookupResult::Filter Filter = Previous.makeFilter();
2410 while (Filter.hasNext()) {
2411 NamedDecl *Old = Filter.next();
2413 // Non-hidden declarations are never ignored.
2414 if (S.isVisible(Old))
2415 continue;
2417 // Declarations of the same entity are not ignored, even if they have
2418 // different linkages.
2419 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2420 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2421 Decl->getUnderlyingType()))
2422 continue;
2424 // If both declarations give a tag declaration a typedef name for linkage
2425 // purposes, then they declare the same entity.
2426 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2427 Decl->getAnonDeclWithTypedefName())
2428 continue;
2431 Filter.erase();
2434 Filter.done();
2437 bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2438 QualType OldType;
2439 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2440 OldType = OldTypedef->getUnderlyingType();
2441 else
2442 OldType = Context.getTypeDeclType(Old);
2443 QualType NewType = New->getUnderlyingType();
2445 if (NewType->isVariablyModifiedType()) {
2446 // Must not redefine a typedef with a variably-modified type.
2447 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2448 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2449 << Kind << NewType;
2450 if (Old->getLocation().isValid())
2451 notePreviousDefinition(Old, New->getLocation());
2452 New->setInvalidDecl();
2453 return true;
2456 if (OldType != NewType &&
2457 !OldType->isDependentType() &&
2458 !NewType->isDependentType() &&
2459 !Context.hasSameType(OldType, NewType)) {
2460 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2461 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2462 << Kind << NewType << OldType;
2463 if (Old->getLocation().isValid())
2464 notePreviousDefinition(Old, New->getLocation());
2465 New->setInvalidDecl();
2466 return true;
2468 return false;
2471 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2472 LookupResult &OldDecls) {
2473 // If the new decl is known invalid already, don't bother doing any
2474 // merging checks.
2475 if (New->isInvalidDecl()) return;
2477 // Allow multiple definitions for ObjC built-in typedefs.
2478 // FIXME: Verify the underlying types are equivalent!
2479 if (getLangOpts().ObjC) {
2480 const IdentifierInfo *TypeID = New->getIdentifier();
2481 switch (TypeID->getLength()) {
2482 default: break;
2483 case 2:
2485 if (!TypeID->isStr("id"))
2486 break;
2487 QualType T = New->getUnderlyingType();
2488 if (!T->isPointerType())
2489 break;
2490 if (!T->isVoidPointerType()) {
2491 QualType PT = T->castAs<PointerType>()->getPointeeType();
2492 if (!PT->isStructureType())
2493 break;
2495 Context.setObjCIdRedefinitionType(T);
2496 // Install the built-in type for 'id', ignoring the current definition.
2497 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2498 return;
2500 case 5:
2501 if (!TypeID->isStr("Class"))
2502 break;
2503 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2504 // Install the built-in type for 'Class', ignoring the current definition.
2505 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2506 return;
2507 case 3:
2508 if (!TypeID->isStr("SEL"))
2509 break;
2510 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2511 // Install the built-in type for 'SEL', ignoring the current definition.
2512 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2513 return;
2515 // Fall through - the typedef name was not a builtin type.
2518 // Verify the old decl was also a type.
2519 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2520 if (!Old) {
2521 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2522 << New->getDeclName();
2524 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2525 if (OldD->getLocation().isValid())
2526 notePreviousDefinition(OldD, New->getLocation());
2528 return New->setInvalidDecl();
2531 // If the old declaration is invalid, just give up here.
2532 if (Old->isInvalidDecl())
2533 return New->setInvalidDecl();
2535 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2536 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2537 auto *NewTag = New->getAnonDeclWithTypedefName();
2538 NamedDecl *Hidden = nullptr;
2539 if (OldTag && NewTag &&
2540 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2541 !hasVisibleDefinition(OldTag, &Hidden)) {
2542 // There is a definition of this tag, but it is not visible. Use it
2543 // instead of our tag.
2544 New->setTypeForDecl(OldTD->getTypeForDecl());
2545 if (OldTD->isModed())
2546 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2547 OldTD->getUnderlyingType());
2548 else
2549 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2551 // Make the old tag definition visible.
2552 makeMergedDefinitionVisible(Hidden);
2554 // If this was an unscoped enumeration, yank all of its enumerators
2555 // out of the scope.
2556 if (isa<EnumDecl>(NewTag)) {
2557 Scope *EnumScope = getNonFieldDeclScope(S);
2558 for (auto *D : NewTag->decls()) {
2559 auto *ED = cast<EnumConstantDecl>(D);
2560 assert(EnumScope->isDeclScope(ED));
2561 EnumScope->RemoveDecl(ED);
2562 IdResolver.RemoveDecl(ED);
2563 ED->getLexicalDeclContext()->removeDecl(ED);
2569 // If the typedef types are not identical, reject them in all languages and
2570 // with any extensions enabled.
2571 if (isIncompatibleTypedef(Old, New))
2572 return;
2574 // The types match. Link up the redeclaration chain and merge attributes if
2575 // the old declaration was a typedef.
2576 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2577 New->setPreviousDecl(Typedef);
2578 mergeDeclAttributes(New, Old);
2581 if (getLangOpts().MicrosoftExt)
2582 return;
2584 if (getLangOpts().CPlusPlus) {
2585 // C++ [dcl.typedef]p2:
2586 // In a given non-class scope, a typedef specifier can be used to
2587 // redefine the name of any type declared in that scope to refer
2588 // to the type to which it already refers.
2589 if (!isa<CXXRecordDecl>(CurContext))
2590 return;
2592 // C++0x [dcl.typedef]p4:
2593 // In a given class scope, a typedef specifier can be used to redefine
2594 // any class-name declared in that scope that is not also a typedef-name
2595 // to refer to the type to which it already refers.
2597 // This wording came in via DR424, which was a correction to the
2598 // wording in DR56, which accidentally banned code like:
2600 // struct S {
2601 // typedef struct A { } A;
2602 // };
2604 // in the C++03 standard. We implement the C++0x semantics, which
2605 // allow the above but disallow
2607 // struct S {
2608 // typedef int I;
2609 // typedef int I;
2610 // };
2612 // since that was the intent of DR56.
2613 if (!isa<TypedefNameDecl>(Old))
2614 return;
2616 Diag(New->getLocation(), diag::err_redefinition)
2617 << New->getDeclName();
2618 notePreviousDefinition(Old, New->getLocation());
2619 return New->setInvalidDecl();
2622 // Modules always permit redefinition of typedefs, as does C11.
2623 if (getLangOpts().Modules || getLangOpts().C11)
2624 return;
2626 // If we have a redefinition of a typedef in C, emit a warning. This warning
2627 // is normally mapped to an error, but can be controlled with
2628 // -Wtypedef-redefinition. If either the original or the redefinition is
2629 // in a system header, don't emit this for compatibility with GCC.
2630 if (getDiagnostics().getSuppressSystemWarnings() &&
2631 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2632 (Old->isImplicit() ||
2633 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2634 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2635 return;
2637 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2638 << New->getDeclName();
2639 notePreviousDefinition(Old, New->getLocation());
2642 /// DeclhasAttr - returns true if decl Declaration already has the target
2643 /// attribute.
2644 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2645 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2646 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2647 for (const auto *i : D->attrs())
2648 if (i->getKind() == A->getKind()) {
2649 if (Ann) {
2650 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2651 return true;
2652 continue;
2654 // FIXME: Don't hardcode this check
2655 if (OA && isa<OwnershipAttr>(i))
2656 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2657 return true;
2660 return false;
2663 static bool isAttributeTargetADefinition(Decl *D) {
2664 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2665 return VD->isThisDeclarationADefinition();
2666 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2667 return TD->isCompleteDefinition() || TD->isBeingDefined();
2668 return true;
2671 /// Merge alignment attributes from \p Old to \p New, taking into account the
2672 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2674 /// \return \c true if any attributes were added to \p New.
2675 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2676 // Look for alignas attributes on Old, and pick out whichever attribute
2677 // specifies the strictest alignment requirement.
2678 AlignedAttr *OldAlignasAttr = nullptr;
2679 AlignedAttr *OldStrictestAlignAttr = nullptr;
2680 unsigned OldAlign = 0;
2681 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2682 // FIXME: We have no way of representing inherited dependent alignments
2683 // in a case like:
2684 // template<int A, int B> struct alignas(A) X;
2685 // template<int A, int B> struct alignas(B) X {};
2686 // For now, we just ignore any alignas attributes which are not on the
2687 // definition in such a case.
2688 if (I->isAlignmentDependent())
2689 return false;
2691 if (I->isAlignas())
2692 OldAlignasAttr = I;
2694 unsigned Align = I->getAlignment(S.Context);
2695 if (Align > OldAlign) {
2696 OldAlign = Align;
2697 OldStrictestAlignAttr = I;
2701 // Look for alignas attributes on New.
2702 AlignedAttr *NewAlignasAttr = nullptr;
2703 unsigned NewAlign = 0;
2704 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2705 if (I->isAlignmentDependent())
2706 return false;
2708 if (I->isAlignas())
2709 NewAlignasAttr = I;
2711 unsigned Align = I->getAlignment(S.Context);
2712 if (Align > NewAlign)
2713 NewAlign = Align;
2716 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2717 // Both declarations have 'alignas' attributes. We require them to match.
2718 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2719 // fall short. (If two declarations both have alignas, they must both match
2720 // every definition, and so must match each other if there is a definition.)
2722 // If either declaration only contains 'alignas(0)' specifiers, then it
2723 // specifies the natural alignment for the type.
2724 if (OldAlign == 0 || NewAlign == 0) {
2725 QualType Ty;
2726 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2727 Ty = VD->getType();
2728 else
2729 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2731 if (OldAlign == 0)
2732 OldAlign = S.Context.getTypeAlign(Ty);
2733 if (NewAlign == 0)
2734 NewAlign = S.Context.getTypeAlign(Ty);
2737 if (OldAlign != NewAlign) {
2738 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2739 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2740 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2741 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2745 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2746 // C++11 [dcl.align]p6:
2747 // if any declaration of an entity has an alignment-specifier,
2748 // every defining declaration of that entity shall specify an
2749 // equivalent alignment.
2750 // C11 6.7.5/7:
2751 // If the definition of an object does not have an alignment
2752 // specifier, any other declaration of that object shall also
2753 // have no alignment specifier.
2754 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2755 << OldAlignasAttr;
2756 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2757 << OldAlignasAttr;
2760 bool AnyAdded = false;
2762 // Ensure we have an attribute representing the strictest alignment.
2763 if (OldAlign > NewAlign) {
2764 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2765 Clone->setInherited(true);
2766 New->addAttr(Clone);
2767 AnyAdded = true;
2770 // Ensure we have an alignas attribute if the old declaration had one.
2771 if (OldAlignasAttr && !NewAlignasAttr &&
2772 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2773 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2774 Clone->setInherited(true);
2775 New->addAttr(Clone);
2776 AnyAdded = true;
2779 return AnyAdded;
2782 #define WANT_DECL_MERGE_LOGIC
2783 #include "clang/Sema/AttrParsedAttrImpl.inc"
2784 #undef WANT_DECL_MERGE_LOGIC
2786 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2787 const InheritableAttr *Attr,
2788 Sema::AvailabilityMergeKind AMK) {
2789 // Diagnose any mutual exclusions between the attribute that we want to add
2790 // and attributes that already exist on the declaration.
2791 if (!DiagnoseMutualExclusions(S, D, Attr))
2792 return false;
2794 // This function copies an attribute Attr from a previous declaration to the
2795 // new declaration D if the new declaration doesn't itself have that attribute
2796 // yet or if that attribute allows duplicates.
2797 // If you're adding a new attribute that requires logic different from
2798 // "use explicit attribute on decl if present, else use attribute from
2799 // previous decl", for example if the attribute needs to be consistent
2800 // between redeclarations, you need to call a custom merge function here.
2801 InheritableAttr *NewAttr = nullptr;
2802 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2803 NewAttr = S.mergeAvailabilityAttr(
2804 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2805 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2806 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2807 AA->getPriority(), AA->getEnvironment());
2808 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2809 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2810 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2811 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2812 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2813 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2814 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2815 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2816 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2817 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2818 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2819 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2820 FA->getFirstArg());
2821 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2822 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2823 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2824 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2825 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2826 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2827 IA->getInheritanceModel());
2828 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2829 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2830 &S.Context.Idents.get(AA->getSpelling()));
2831 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2832 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2833 isa<CUDAGlobalAttr>(Attr))) {
2834 // CUDA target attributes are part of function signature for
2835 // overloading purposes and must not be merged.
2836 return false;
2837 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2838 NewAttr = S.mergeMinSizeAttr(D, *MA);
2839 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2840 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2841 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2842 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2843 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2844 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2845 else if (isa<AlignedAttr>(Attr))
2846 // AlignedAttrs are handled separately, because we need to handle all
2847 // such attributes on a declaration at the same time.
2848 NewAttr = nullptr;
2849 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2850 (AMK == Sema::AMK_Override ||
2851 AMK == Sema::AMK_ProtocolImplementation ||
2852 AMK == Sema::AMK_OptionalProtocolImplementation))
2853 NewAttr = nullptr;
2854 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2855 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2856 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2857 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2858 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2859 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2860 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2861 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2862 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2863 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2864 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2865 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2866 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2867 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2868 NT->getZ());
2869 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2870 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2871 WS->getPreferred(),
2872 WS->getSpelledArgsCount());
2873 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2874 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2875 else if (isa<SuppressAttr>(Attr))
2876 // Do nothing. Each redeclaration should be suppressed separately.
2877 NewAttr = nullptr;
2878 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2879 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2881 if (NewAttr) {
2882 NewAttr->setInherited(true);
2883 D->addAttr(NewAttr);
2884 if (isa<MSInheritanceAttr>(NewAttr))
2885 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2886 return true;
2889 return false;
2892 static const NamedDecl *getDefinition(const Decl *D) {
2893 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2894 return TD->getDefinition();
2895 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2896 const VarDecl *Def = VD->getDefinition();
2897 if (Def)
2898 return Def;
2899 return VD->getActingDefinition();
2901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2902 const FunctionDecl *Def = nullptr;
2903 if (FD->isDefined(Def, true))
2904 return Def;
2906 return nullptr;
2909 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2910 for (const auto *Attribute : D->attrs())
2911 if (Attribute->getKind() == Kind)
2912 return true;
2913 return false;
2916 /// checkNewAttributesAfterDef - If we already have a definition, check that
2917 /// there are no new attributes in this declaration.
2918 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2919 if (!New->hasAttrs())
2920 return;
2922 const NamedDecl *Def = getDefinition(Old);
2923 if (!Def || Def == New)
2924 return;
2926 AttrVec &NewAttributes = New->getAttrs();
2927 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2928 Attr *NewAttribute = NewAttributes[I];
2930 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2932 SkipBodyInfo SkipBody;
2933 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2935 // If we're skipping this definition, drop the "alias" attribute.
2936 if (SkipBody.ShouldSkip) {
2937 NewAttributes.erase(NewAttributes.begin() + I);
2938 --E;
2939 continue;
2941 } else {
2942 VarDecl *VD = cast<VarDecl>(New);
2943 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2944 VarDecl::TentativeDefinition
2945 ? diag::err_alias_after_tentative
2946 : diag::err_redefinition;
2947 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2948 if (Diag == diag::err_redefinition)
2949 S.notePreviousDefinition(Def, VD->getLocation());
2950 else
2951 S.Diag(Def->getLocation(), diag::note_previous_definition);
2952 VD->setInvalidDecl();
2954 ++I;
2955 continue;
2958 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2959 // Tentative definitions are only interesting for the alias check above.
2960 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2961 ++I;
2962 continue;
2966 if (hasAttribute(Def, NewAttribute->getKind())) {
2967 ++I;
2968 continue; // regular attr merging will take care of validating this.
2971 if (isa<C11NoReturnAttr>(NewAttribute)) {
2972 // C's _Noreturn is allowed to be added to a function after it is defined.
2973 ++I;
2974 continue;
2975 } else if (isa<UuidAttr>(NewAttribute)) {
2976 // msvc will allow a subsequent definition to add an uuid to a class
2977 ++I;
2978 continue;
2979 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2980 if (AA->isAlignas()) {
2981 // C++11 [dcl.align]p6:
2982 // if any declaration of an entity has an alignment-specifier,
2983 // every defining declaration of that entity shall specify an
2984 // equivalent alignment.
2985 // C11 6.7.5/7:
2986 // If the definition of an object does not have an alignment
2987 // specifier, any other declaration of that object shall also
2988 // have no alignment specifier.
2989 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2990 << AA;
2991 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2992 << AA;
2993 NewAttributes.erase(NewAttributes.begin() + I);
2994 --E;
2995 continue;
2997 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2998 // If there is a C definition followed by a redeclaration with this
2999 // attribute then there are two different definitions. In C++, prefer the
3000 // standard diagnostics.
3001 if (!S.getLangOpts().CPlusPlus) {
3002 S.Diag(NewAttribute->getLocation(),
3003 diag::err_loader_uninitialized_redeclaration);
3004 S.Diag(Def->getLocation(), diag::note_previous_definition);
3005 NewAttributes.erase(NewAttributes.begin() + I);
3006 --E;
3007 continue;
3009 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3010 cast<VarDecl>(New)->isInline() &&
3011 !cast<VarDecl>(New)->isInlineSpecified()) {
3012 // Don't warn about applying selectany to implicitly inline variables.
3013 // Older compilers and language modes would require the use of selectany
3014 // to make such variables inline, and it would have no effect if we
3015 // honored it.
3016 ++I;
3017 continue;
3018 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3019 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3020 // declarations after definitions.
3021 ++I;
3022 continue;
3023 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3024 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3025 // error since the definition will have already been created without
3026 // the semantic effects of the attribute having been applied.
3027 S.Diag(NewAttribute->getLocation(),
3028 diag::err_sycl_entry_point_after_definition);
3029 S.Diag(Def->getLocation(), diag::note_previous_definition);
3030 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3031 ++I;
3032 continue;
3035 S.Diag(NewAttribute->getLocation(),
3036 diag::warn_attribute_precede_definition);
3037 S.Diag(Def->getLocation(), diag::note_previous_definition);
3038 NewAttributes.erase(NewAttributes.begin() + I);
3039 --E;
3043 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3044 const ConstInitAttr *CIAttr,
3045 bool AttrBeforeInit) {
3046 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3048 // Figure out a good way to write this specifier on the old declaration.
3049 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3050 // enough of the attribute list spelling information to extract that without
3051 // heroics.
3052 std::string SuitableSpelling;
3053 if (S.getLangOpts().CPlusPlus20)
3054 SuitableSpelling = std::string(
3055 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3056 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3057 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3058 InsertLoc, {tok::l_square, tok::l_square,
3059 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3060 S.PP.getIdentifierInfo("require_constant_initialization"),
3061 tok::r_square, tok::r_square}));
3062 if (SuitableSpelling.empty())
3063 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3064 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3065 S.PP.getIdentifierInfo("require_constant_initialization"),
3066 tok::r_paren, tok::r_paren}));
3067 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3068 SuitableSpelling = "constinit";
3069 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3070 SuitableSpelling = "[[clang::require_constant_initialization]]";
3071 if (SuitableSpelling.empty())
3072 SuitableSpelling = "__attribute__((require_constant_initialization))";
3073 SuitableSpelling += " ";
3075 if (AttrBeforeInit) {
3076 // extern constinit int a;
3077 // int a = 0; // error (missing 'constinit'), accepted as extension
3078 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3079 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3080 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3081 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3082 } else {
3083 // int a = 0;
3084 // constinit extern int a; // error (missing 'constinit')
3085 S.Diag(CIAttr->getLocation(),
3086 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3087 : diag::warn_require_const_init_added_too_late)
3088 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3089 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3090 << CIAttr->isConstinit()
3091 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3095 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3096 AvailabilityMergeKind AMK) {
3097 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3098 UsedAttr *NewAttr = OldAttr->clone(Context);
3099 NewAttr->setInherited(true);
3100 New->addAttr(NewAttr);
3102 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3103 RetainAttr *NewAttr = OldAttr->clone(Context);
3104 NewAttr->setInherited(true);
3105 New->addAttr(NewAttr);
3108 if (!Old->hasAttrs() && !New->hasAttrs())
3109 return;
3111 // [dcl.constinit]p1:
3112 // If the [constinit] specifier is applied to any declaration of a
3113 // variable, it shall be applied to the initializing declaration.
3114 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3115 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3116 if (bool(OldConstInit) != bool(NewConstInit)) {
3117 const auto *OldVD = cast<VarDecl>(Old);
3118 auto *NewVD = cast<VarDecl>(New);
3120 // Find the initializing declaration. Note that we might not have linked
3121 // the new declaration into the redeclaration chain yet.
3122 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3123 if (!InitDecl &&
3124 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3125 InitDecl = NewVD;
3127 if (InitDecl == NewVD) {
3128 // This is the initializing declaration. If it would inherit 'constinit',
3129 // that's ill-formed. (Note that we do not apply this to the attribute
3130 // form).
3131 if (OldConstInit && OldConstInit->isConstinit())
3132 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3133 /*AttrBeforeInit=*/true);
3134 } else if (NewConstInit) {
3135 // This is the first time we've been told that this declaration should
3136 // have a constant initializer. If we already saw the initializing
3137 // declaration, this is too late.
3138 if (InitDecl && InitDecl != NewVD) {
3139 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3140 /*AttrBeforeInit=*/false);
3141 NewVD->dropAttr<ConstInitAttr>();
3146 // Attributes declared post-definition are currently ignored.
3147 checkNewAttributesAfterDef(*this, New, Old);
3149 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3150 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3151 if (!OldA->isEquivalent(NewA)) {
3152 // This redeclaration changes __asm__ label.
3153 Diag(New->getLocation(), diag::err_different_asm_label);
3154 Diag(OldA->getLocation(), diag::note_previous_declaration);
3156 } else if (Old->isUsed()) {
3157 // This redeclaration adds an __asm__ label to a declaration that has
3158 // already been ODR-used.
3159 Diag(New->getLocation(), diag::err_late_asm_label_name)
3160 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3164 // Re-declaration cannot add abi_tag's.
3165 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3166 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3167 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3168 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3169 Diag(NewAbiTagAttr->getLocation(),
3170 diag::err_new_abi_tag_on_redeclaration)
3171 << NewTag;
3172 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3175 } else {
3176 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3177 Diag(Old->getLocation(), diag::note_previous_declaration);
3181 // This redeclaration adds a section attribute.
3182 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3183 if (auto *VD = dyn_cast<VarDecl>(New)) {
3184 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3185 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3186 Diag(Old->getLocation(), diag::note_previous_declaration);
3191 // Redeclaration adds code-seg attribute.
3192 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3193 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3194 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3195 Diag(New->getLocation(), diag::warn_mismatched_section)
3196 << 0 /*codeseg*/;
3197 Diag(Old->getLocation(), diag::note_previous_declaration);
3200 if (!Old->hasAttrs())
3201 return;
3203 bool foundAny = New->hasAttrs();
3205 // Ensure that any moving of objects within the allocated map is done before
3206 // we process them.
3207 if (!foundAny) New->setAttrs(AttrVec());
3209 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3210 // Ignore deprecated/unavailable/availability attributes if requested.
3211 AvailabilityMergeKind LocalAMK = AMK_None;
3212 if (isa<DeprecatedAttr>(I) ||
3213 isa<UnavailableAttr>(I) ||
3214 isa<AvailabilityAttr>(I)) {
3215 switch (AMK) {
3216 case AMK_None:
3217 continue;
3219 case AMK_Redeclaration:
3220 case AMK_Override:
3221 case AMK_ProtocolImplementation:
3222 case AMK_OptionalProtocolImplementation:
3223 LocalAMK = AMK;
3224 break;
3228 // Already handled.
3229 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3230 continue;
3232 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3233 foundAny = true;
3236 if (mergeAlignedAttrs(*this, New, Old))
3237 foundAny = true;
3239 if (!foundAny) New->dropAttrs();
3242 // Returns the number of added attributes.
3243 template <class T>
3244 static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3245 Sema &S) {
3246 unsigned found = 0;
3247 for (const auto *I : From->specific_attrs<T>()) {
3248 if (!DeclHasAttr(To, I)) {
3249 T *newAttr = cast<T>(I->clone(S.Context));
3250 newAttr->setInherited(true);
3251 To->addAttr(newAttr);
3252 ++found;
3255 return found;
3258 template <class F>
3259 static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3260 F &&propagator) {
3261 if (!From->hasAttrs()) {
3262 return;
3265 bool foundAny = To->hasAttrs();
3267 // Ensure that any moving of objects within the allocated map is
3268 // done before we process them.
3269 if (!foundAny)
3270 To->setAttrs(AttrVec());
3272 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3274 if (!foundAny)
3275 To->dropAttrs();
3278 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3279 /// to the new one.
3280 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3281 const ParmVarDecl *oldDecl,
3282 Sema &S) {
3283 // C++11 [dcl.attr.depend]p2:
3284 // The first declaration of a function shall specify the
3285 // carries_dependency attribute for its declarator-id if any declaration
3286 // of the function specifies the carries_dependency attribute.
3287 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3288 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3289 S.Diag(CDA->getLocation(),
3290 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3291 // Find the first declaration of the parameter.
3292 // FIXME: Should we build redeclaration chains for function parameters?
3293 const FunctionDecl *FirstFD =
3294 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3295 const ParmVarDecl *FirstVD =
3296 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3297 S.Diag(FirstVD->getLocation(),
3298 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3301 propagateAttributes(
3302 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3303 unsigned found = 0;
3304 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3305 // Propagate the lifetimebound attribute from parameters to the
3306 // most recent declaration. Note that this doesn't include the implicit
3307 // 'this' parameter, as the attribute is applied to the function type in
3308 // that case.
3309 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3310 return found;
3314 static bool EquivalentArrayTypes(QualType Old, QualType New,
3315 const ASTContext &Ctx) {
3317 auto NoSizeInfo = [&Ctx](QualType Ty) {
3318 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3319 return true;
3320 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3321 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3322 return false;
3325 // `type[]` is equivalent to `type *` and `type[*]`.
3326 if (NoSizeInfo(Old) && NoSizeInfo(New))
3327 return true;
3329 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3330 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3331 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3332 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3333 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3334 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3335 return false;
3336 return true;
3339 // Only compare size, ignore Size modifiers and CVR.
3340 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3341 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3342 Ctx.getAsConstantArrayType(New)->getSize();
3345 // Don't try to compare dependent sized array
3346 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3347 return true;
3350 return Old == New;
3353 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3354 const ParmVarDecl *OldParam,
3355 Sema &S) {
3356 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3357 if (auto Newnullability = NewParam->getType()->getNullability()) {
3358 if (*Oldnullability != *Newnullability) {
3359 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3360 << DiagNullabilityKind(
3361 *Newnullability,
3362 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3363 != 0))
3364 << DiagNullabilityKind(
3365 *Oldnullability,
3366 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3367 != 0));
3368 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3370 } else {
3371 QualType NewT = NewParam->getType();
3372 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3373 NewParam->setType(NewT);
3376 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3377 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3378 if (OldParamDT && NewParamDT &&
3379 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3380 QualType OldParamOT = OldParamDT->getOriginalType();
3381 QualType NewParamOT = NewParamDT->getOriginalType();
3382 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3383 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3384 << NewParam << NewParamOT;
3385 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3386 << OldParamOT;
3391 namespace {
3393 /// Used in MergeFunctionDecl to keep track of function parameters in
3394 /// C.
3395 struct GNUCompatibleParamWarning {
3396 ParmVarDecl *OldParm;
3397 ParmVarDecl *NewParm;
3398 QualType PromotedType;
3401 } // end anonymous namespace
3403 // Determine whether the previous declaration was a definition, implicit
3404 // declaration, or a declaration.
3405 template <typename T>
3406 static std::pair<diag::kind, SourceLocation>
3407 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3408 diag::kind PrevDiag;
3409 SourceLocation OldLocation = Old->getLocation();
3410 if (Old->isThisDeclarationADefinition())
3411 PrevDiag = diag::note_previous_definition;
3412 else if (Old->isImplicit()) {
3413 PrevDiag = diag::note_previous_implicit_declaration;
3414 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3415 if (FD->getBuiltinID())
3416 PrevDiag = diag::note_previous_builtin_declaration;
3418 if (OldLocation.isInvalid())
3419 OldLocation = New->getLocation();
3420 } else
3421 PrevDiag = diag::note_previous_declaration;
3422 return std::make_pair(PrevDiag, OldLocation);
3425 /// canRedefineFunction - checks if a function can be redefined. Currently,
3426 /// only extern inline functions can be redefined, and even then only in
3427 /// GNU89 mode.
3428 static bool canRedefineFunction(const FunctionDecl *FD,
3429 const LangOptions& LangOpts) {
3430 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3431 !LangOpts.CPlusPlus &&
3432 FD->isInlineSpecified() &&
3433 FD->getStorageClass() == SC_Extern);
3436 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3437 const AttributedType *AT = T->getAs<AttributedType>();
3438 while (AT && !AT->isCallingConv())
3439 AT = AT->getModifiedType()->getAs<AttributedType>();
3440 return AT;
3443 template <typename T>
3444 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3445 const DeclContext *DC = Old->getDeclContext();
3446 if (DC->isRecord())
3447 return false;
3449 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3450 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3451 return true;
3452 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3453 return true;
3454 return false;
3457 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3458 static bool isExternC(VarTemplateDecl *) { return false; }
3459 static bool isExternC(FunctionTemplateDecl *) { return false; }
3461 /// Check whether a redeclaration of an entity introduced by a
3462 /// using-declaration is valid, given that we know it's not an overload
3463 /// (nor a hidden tag declaration).
3464 template<typename ExpectedDecl>
3465 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3466 ExpectedDecl *New) {
3467 // C++11 [basic.scope.declarative]p4:
3468 // Given a set of declarations in a single declarative region, each of
3469 // which specifies the same unqualified name,
3470 // -- they shall all refer to the same entity, or all refer to functions
3471 // and function templates; or
3472 // -- exactly one declaration shall declare a class name or enumeration
3473 // name that is not a typedef name and the other declarations shall all
3474 // refer to the same variable or enumerator, or all refer to functions
3475 // and function templates; in this case the class name or enumeration
3476 // name is hidden (3.3.10).
3478 // C++11 [namespace.udecl]p14:
3479 // If a function declaration in namespace scope or block scope has the
3480 // same name and the same parameter-type-list as a function introduced
3481 // by a using-declaration, and the declarations do not declare the same
3482 // function, the program is ill-formed.
3484 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3485 if (Old &&
3486 !Old->getDeclContext()->getRedeclContext()->Equals(
3487 New->getDeclContext()->getRedeclContext()) &&
3488 !(isExternC(Old) && isExternC(New)))
3489 Old = nullptr;
3491 if (!Old) {
3492 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3493 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3494 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3495 return true;
3497 return false;
3500 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3501 const FunctionDecl *B) {
3502 assert(A->getNumParams() == B->getNumParams());
3504 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3505 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3506 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3507 if (AttrA == AttrB)
3508 return true;
3509 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3510 AttrA->isDynamic() == AttrB->isDynamic();
3513 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3516 /// If necessary, adjust the semantic declaration context for a qualified
3517 /// declaration to name the correct inline namespace within the qualifier.
3518 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3519 DeclaratorDecl *OldD) {
3520 // The only case where we need to update the DeclContext is when
3521 // redeclaration lookup for a qualified name finds a declaration
3522 // in an inline namespace within the context named by the qualifier:
3524 // inline namespace N { int f(); }
3525 // int ::f(); // Sema DC needs adjusting from :: to N::.
3527 // For unqualified declarations, the semantic context *can* change
3528 // along the redeclaration chain (for local extern declarations,
3529 // extern "C" declarations, and friend declarations in particular).
3530 if (!NewD->getQualifier())
3531 return;
3533 // NewD is probably already in the right context.
3534 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3535 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3536 if (NamedDC->Equals(SemaDC))
3537 return;
3539 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3540 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3541 "unexpected context for redeclaration");
3543 auto *LexDC = NewD->getLexicalDeclContext();
3544 auto FixSemaDC = [=](NamedDecl *D) {
3545 if (!D)
3546 return;
3547 D->setDeclContext(SemaDC);
3548 D->setLexicalDeclContext(LexDC);
3551 FixSemaDC(NewD);
3552 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3553 FixSemaDC(FD->getDescribedFunctionTemplate());
3554 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3555 FixSemaDC(VD->getDescribedVarTemplate());
3558 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3559 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3560 // Verify the old decl was also a function.
3561 FunctionDecl *Old = OldD->getAsFunction();
3562 if (!Old) {
3563 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3564 if (New->getFriendObjectKind()) {
3565 Diag(New->getLocation(), diag::err_using_decl_friend);
3566 Diag(Shadow->getTargetDecl()->getLocation(),
3567 diag::note_using_decl_target);
3568 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3569 << 0;
3570 return true;
3573 // Check whether the two declarations might declare the same function or
3574 // function template.
3575 if (FunctionTemplateDecl *NewTemplate =
3576 New->getDescribedFunctionTemplate()) {
3577 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3578 NewTemplate))
3579 return true;
3580 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3581 ->getAsFunction();
3582 } else {
3583 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3584 return true;
3585 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3587 } else {
3588 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3589 << New->getDeclName();
3590 notePreviousDefinition(OldD, New->getLocation());
3591 return true;
3595 // If the old declaration was found in an inline namespace and the new
3596 // declaration was qualified, update the DeclContext to match.
3597 adjustDeclContextForDeclaratorDecl(New, Old);
3599 // If the old declaration is invalid, just give up here.
3600 if (Old->isInvalidDecl())
3601 return true;
3603 // Disallow redeclaration of some builtins.
3604 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3605 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3606 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3607 << Old << Old->getType();
3608 return true;
3611 diag::kind PrevDiag;
3612 SourceLocation OldLocation;
3613 std::tie(PrevDiag, OldLocation) =
3614 getNoteDiagForInvalidRedeclaration(Old, New);
3616 // Don't complain about this if we're in GNU89 mode and the old function
3617 // is an extern inline function.
3618 // Don't complain about specializations. They are not supposed to have
3619 // storage classes.
3620 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3621 New->getStorageClass() == SC_Static &&
3622 Old->hasExternalFormalLinkage() &&
3623 !New->getTemplateSpecializationInfo() &&
3624 !canRedefineFunction(Old, getLangOpts())) {
3625 if (getLangOpts().MicrosoftExt) {
3626 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3627 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3628 } else {
3629 Diag(New->getLocation(), diag::err_static_non_static) << New;
3630 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3631 return true;
3635 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3636 if (!Old->hasAttr<InternalLinkageAttr>()) {
3637 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3638 << ILA;
3639 Diag(Old->getLocation(), diag::note_previous_declaration);
3640 New->dropAttr<InternalLinkageAttr>();
3643 if (auto *EA = New->getAttr<ErrorAttr>()) {
3644 if (!Old->hasAttr<ErrorAttr>()) {
3645 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3646 Diag(Old->getLocation(), diag::note_previous_declaration);
3647 New->dropAttr<ErrorAttr>();
3651 if (CheckRedeclarationInModule(New, Old))
3652 return true;
3654 if (!getLangOpts().CPlusPlus) {
3655 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3656 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3657 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3658 << New << OldOvl;
3660 // Try our best to find a decl that actually has the overloadable
3661 // attribute for the note. In most cases (e.g. programs with only one
3662 // broken declaration/definition), this won't matter.
3664 // FIXME: We could do this if we juggled some extra state in
3665 // OverloadableAttr, rather than just removing it.
3666 const Decl *DiagOld = Old;
3667 if (OldOvl) {
3668 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3669 const auto *A = D->getAttr<OverloadableAttr>();
3670 return A && !A->isImplicit();
3672 // If we've implicitly added *all* of the overloadable attrs to this
3673 // chain, emitting a "previous redecl" note is pointless.
3674 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3677 if (DiagOld)
3678 Diag(DiagOld->getLocation(),
3679 diag::note_attribute_overloadable_prev_overload)
3680 << OldOvl;
3682 if (OldOvl)
3683 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3684 else
3685 New->dropAttr<OverloadableAttr>();
3689 // It is not permitted to redeclare an SME function with different SME
3690 // attributes.
3691 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3692 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3693 << New->getType() << Old->getType();
3694 Diag(OldLocation, diag::note_previous_declaration);
3695 return true;
3698 // If a function is first declared with a calling convention, but is later
3699 // declared or defined without one, all following decls assume the calling
3700 // convention of the first.
3702 // It's OK if a function is first declared without a calling convention,
3703 // but is later declared or defined with the default calling convention.
3705 // To test if either decl has an explicit calling convention, we look for
3706 // AttributedType sugar nodes on the type as written. If they are missing or
3707 // were canonicalized away, we assume the calling convention was implicit.
3709 // Note also that we DO NOT return at this point, because we still have
3710 // other tests to run.
3711 QualType OldQType = Context.getCanonicalType(Old->getType());
3712 QualType NewQType = Context.getCanonicalType(New->getType());
3713 const FunctionType *OldType = cast<FunctionType>(OldQType);
3714 const FunctionType *NewType = cast<FunctionType>(NewQType);
3715 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3716 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3717 bool RequiresAdjustment = false;
3719 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3720 FunctionDecl *First = Old->getFirstDecl();
3721 const FunctionType *FT =
3722 First->getType().getCanonicalType()->castAs<FunctionType>();
3723 FunctionType::ExtInfo FI = FT->getExtInfo();
3724 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3725 if (!NewCCExplicit) {
3726 // Inherit the CC from the previous declaration if it was specified
3727 // there but not here.
3728 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3729 RequiresAdjustment = true;
3730 } else if (Old->getBuiltinID()) {
3731 // Builtin attribute isn't propagated to the new one yet at this point,
3732 // so we check if the old one is a builtin.
3734 // Calling Conventions on a Builtin aren't really useful and setting a
3735 // default calling convention and cdecl'ing some builtin redeclarations is
3736 // common, so warn and ignore the calling convention on the redeclaration.
3737 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3738 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3739 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3740 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3741 RequiresAdjustment = true;
3742 } else {
3743 // Calling conventions aren't compatible, so complain.
3744 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3745 Diag(New->getLocation(), diag::err_cconv_change)
3746 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3747 << !FirstCCExplicit
3748 << (!FirstCCExplicit ? "" :
3749 FunctionType::getNameForCallConv(FI.getCC()));
3751 // Put the note on the first decl, since it is the one that matters.
3752 Diag(First->getLocation(), diag::note_previous_declaration);
3753 return true;
3757 // FIXME: diagnose the other way around?
3758 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3759 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3760 RequiresAdjustment = true;
3763 // Merge regparm attribute.
3764 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3765 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3766 if (NewTypeInfo.getHasRegParm()) {
3767 Diag(New->getLocation(), diag::err_regparm_mismatch)
3768 << NewType->getRegParmType()
3769 << OldType->getRegParmType();
3770 Diag(OldLocation, diag::note_previous_declaration);
3771 return true;
3774 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3775 RequiresAdjustment = true;
3778 // Merge ns_returns_retained attribute.
3779 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3780 if (NewTypeInfo.getProducesResult()) {
3781 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3782 << "'ns_returns_retained'";
3783 Diag(OldLocation, diag::note_previous_declaration);
3784 return true;
3787 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3788 RequiresAdjustment = true;
3791 if (OldTypeInfo.getNoCallerSavedRegs() !=
3792 NewTypeInfo.getNoCallerSavedRegs()) {
3793 if (NewTypeInfo.getNoCallerSavedRegs()) {
3794 AnyX86NoCallerSavedRegistersAttr *Attr =
3795 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3796 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3797 Diag(OldLocation, diag::note_previous_declaration);
3798 return true;
3801 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3802 RequiresAdjustment = true;
3805 if (RequiresAdjustment) {
3806 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3807 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3808 New->setType(QualType(AdjustedType, 0));
3809 NewQType = Context.getCanonicalType(New->getType());
3812 // If this redeclaration makes the function inline, we may need to add it to
3813 // UndefinedButUsed.
3814 if (!Old->isInlined() && New->isInlined() &&
3815 !New->hasAttr<GNUInlineAttr>() &&
3816 !getLangOpts().GNUInline &&
3817 Old->isUsed(false) &&
3818 !Old->isDefined() && !New->isThisDeclarationADefinition())
3819 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3820 SourceLocation()));
3822 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3823 // about it.
3824 if (New->hasAttr<GNUInlineAttr>() &&
3825 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3826 UndefinedButUsed.erase(Old->getCanonicalDecl());
3829 // If pass_object_size params don't match up perfectly, this isn't a valid
3830 // redeclaration.
3831 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3832 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3833 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3834 << New->getDeclName();
3835 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3836 return true;
3839 QualType OldQTypeForComparison = OldQType;
3840 if (Context.hasAnyFunctionEffects()) {
3841 const auto OldFX = Old->getFunctionEffects();
3842 const auto NewFX = New->getFunctionEffects();
3843 if (OldFX != NewFX) {
3844 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3845 for (const auto &Diff : Diffs) {
3846 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3847 Diag(New->getLocation(),
3848 diag::warn_mismatched_func_effect_redeclaration)
3849 << Diff.effectName();
3850 Diag(Old->getLocation(), diag::note_previous_declaration);
3853 // Following a warning, we could skip merging effects from the previous
3854 // declaration, but that would trigger an additional "conflicting types"
3855 // error.
3856 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3857 FunctionEffectSet::Conflicts MergeErrs;
3858 FunctionEffectSet MergedFX =
3859 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3860 if (!MergeErrs.empty())
3861 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
3862 Old->getLocation());
3864 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3865 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3866 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3867 NewFPT->getParamTypes(), EPI);
3869 New->setType(ModQT);
3870 NewQType = New->getType();
3872 // Revise OldQTForComparison to include the merged effects,
3873 // so as not to fail due to differences later.
3874 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3875 EPI = OldFPT->getExtProtoInfo();
3876 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3877 OldQTypeForComparison = Context.getFunctionType(
3878 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3880 if (OldFX.empty()) {
3881 // A redeclaration may add the attribute to a previously seen function
3882 // body which needs to be verified.
3883 maybeAddDeclWithEffects(Old, MergedFX);
3889 if (getLangOpts().CPlusPlus) {
3890 OldQType = Context.getCanonicalType(Old->getType());
3891 NewQType = Context.getCanonicalType(New->getType());
3893 // Go back to the type source info to compare the declared return types,
3894 // per C++1y [dcl.type.auto]p13:
3895 // Redeclarations or specializations of a function or function template
3896 // with a declared return type that uses a placeholder type shall also
3897 // use that placeholder, not a deduced type.
3898 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3899 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3900 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3901 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3902 OldDeclaredReturnType)) {
3903 QualType ResQT;
3904 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3905 OldDeclaredReturnType->isObjCObjectPointerType())
3906 // FIXME: This does the wrong thing for a deduced return type.
3907 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3908 if (ResQT.isNull()) {
3909 if (New->isCXXClassMember() && New->isOutOfLine())
3910 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3911 << New << New->getReturnTypeSourceRange();
3912 else if (Old->isExternC() && New->isExternC() &&
3913 !Old->hasAttr<OverloadableAttr>() &&
3914 !New->hasAttr<OverloadableAttr>())
3915 Diag(New->getLocation(), diag::err_conflicting_types) << New;
3916 else
3917 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3918 << New->getReturnTypeSourceRange();
3919 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3920 << Old->getReturnTypeSourceRange();
3921 return true;
3923 else
3924 NewQType = ResQT;
3927 QualType OldReturnType = OldType->getReturnType();
3928 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3929 if (OldReturnType != NewReturnType) {
3930 // If this function has a deduced return type and has already been
3931 // defined, copy the deduced value from the old declaration.
3932 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3933 if (OldAT && OldAT->isDeduced()) {
3934 QualType DT = OldAT->getDeducedType();
3935 if (DT.isNull()) {
3936 New->setType(SubstAutoTypeDependent(New->getType()));
3937 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3938 } else {
3939 New->setType(SubstAutoType(New->getType(), DT));
3940 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3945 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3946 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3947 if (OldMethod && NewMethod) {
3948 // Preserve triviality.
3949 NewMethod->setTrivial(OldMethod->isTrivial());
3951 // MSVC allows explicit template specialization at class scope:
3952 // 2 CXXMethodDecls referring to the same function will be injected.
3953 // We don't want a redeclaration error.
3954 bool IsClassScopeExplicitSpecialization =
3955 OldMethod->isFunctionTemplateSpecialization() &&
3956 NewMethod->isFunctionTemplateSpecialization();
3957 bool isFriend = NewMethod->getFriendObjectKind();
3959 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3960 !IsClassScopeExplicitSpecialization) {
3961 // -- Member function declarations with the same name and the
3962 // same parameter types cannot be overloaded if any of them
3963 // is a static member function declaration.
3964 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3965 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3966 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3967 return true;
3970 // C++ [class.mem]p1:
3971 // [...] A member shall not be declared twice in the
3972 // member-specification, except that a nested class or member
3973 // class template can be declared and then later defined.
3974 if (!inTemplateInstantiation()) {
3975 unsigned NewDiag;
3976 if (isa<CXXConstructorDecl>(OldMethod))
3977 NewDiag = diag::err_constructor_redeclared;
3978 else if (isa<CXXDestructorDecl>(NewMethod))
3979 NewDiag = diag::err_destructor_redeclared;
3980 else if (isa<CXXConversionDecl>(NewMethod))
3981 NewDiag = diag::err_conv_function_redeclared;
3982 else
3983 NewDiag = diag::err_member_redeclared;
3985 Diag(New->getLocation(), NewDiag);
3986 } else {
3987 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3988 << New << New->getType();
3990 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3991 return true;
3993 // Complain if this is an explicit declaration of a special
3994 // member that was initially declared implicitly.
3996 // As an exception, it's okay to befriend such methods in order
3997 // to permit the implicit constructor/destructor/operator calls.
3998 } else if (OldMethod->isImplicit()) {
3999 if (isFriend) {
4000 NewMethod->setImplicit();
4001 } else {
4002 Diag(NewMethod->getLocation(),
4003 diag::err_definition_of_implicitly_declared_member)
4004 << New << llvm::to_underlying(getSpecialMember(OldMethod));
4005 return true;
4007 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4008 Diag(NewMethod->getLocation(),
4009 diag::err_definition_of_explicitly_defaulted_member)
4010 << llvm::to_underlying(getSpecialMember(OldMethod));
4011 return true;
4015 // C++1z [over.load]p2
4016 // Certain function declarations cannot be overloaded:
4017 // -- Function declarations that differ only in the return type,
4018 // the exception specification, or both cannot be overloaded.
4020 // Check the exception specifications match. This may recompute the type of
4021 // both Old and New if it resolved exception specifications, so grab the
4022 // types again after this. Because this updates the type, we do this before
4023 // any of the other checks below, which may update the "de facto" NewQType
4024 // but do not necessarily update the type of New.
4025 if (CheckEquivalentExceptionSpec(Old, New))
4026 return true;
4028 // C++11 [dcl.attr.noreturn]p1:
4029 // The first declaration of a function shall specify the noreturn
4030 // attribute if any declaration of that function specifies the noreturn
4031 // attribute.
4032 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4033 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4034 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4035 << NRA;
4036 Diag(Old->getLocation(), diag::note_previous_declaration);
4039 // C++11 [dcl.attr.depend]p2:
4040 // The first declaration of a function shall specify the
4041 // carries_dependency attribute for its declarator-id if any declaration
4042 // of the function specifies the carries_dependency attribute.
4043 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4044 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4045 Diag(CDA->getLocation(),
4046 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4047 Diag(Old->getFirstDecl()->getLocation(),
4048 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4051 // (C++98 8.3.5p3):
4052 // All declarations for a function shall agree exactly in both the
4053 // return type and the parameter-type-list.
4054 // We also want to respect all the extended bits except noreturn.
4056 // noreturn should now match unless the old type info didn't have it.
4057 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4058 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4059 const FunctionType *OldTypeForComparison
4060 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4061 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4062 assert(OldQTypeForComparison.isCanonical());
4065 if (haveIncompatibleLanguageLinkages(Old, New)) {
4066 // As a special case, retain the language linkage from previous
4067 // declarations of a friend function as an extension.
4069 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4070 // and is useful because there's otherwise no way to specify language
4071 // linkage within class scope.
4073 // Check cautiously as the friend object kind isn't yet complete.
4074 if (New->getFriendObjectKind() != Decl::FOK_None) {
4075 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4076 Diag(OldLocation, PrevDiag);
4077 } else {
4078 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4079 Diag(OldLocation, PrevDiag);
4080 return true;
4084 // HLSL check parameters for matching ABI specifications.
4085 if (getLangOpts().HLSL) {
4086 if (HLSL().CheckCompatibleParameterABI(New, Old))
4087 return true;
4089 // If no errors are generated when checking parameter ABIs we can check if
4090 // the two declarations have the same type ignoring the ABIs and if so,
4091 // the declarations can be merged. This case for merging is only valid in
4092 // HLSL because there are no valid cases of merging mismatched parameter
4093 // ABIs except the HLSL implicit in and explicit in.
4094 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4095 NewQType))
4096 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4097 // Fall through for conflicting redeclarations and redefinitions.
4100 // If the function types are compatible, merge the declarations. Ignore the
4101 // exception specifier because it was already checked above in
4102 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4103 // about incompatible types under -fms-compatibility.
4104 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4105 NewQType))
4106 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4108 // If the types are imprecise (due to dependent constructs in friends or
4109 // local extern declarations), it's OK if they differ. We'll check again
4110 // during instantiation.
4111 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4112 return false;
4114 // Fall through for conflicting redeclarations and redefinitions.
4117 // C: Function types need to be compatible, not identical. This handles
4118 // duplicate function decls like "void f(int); void f(enum X);" properly.
4119 if (!getLangOpts().CPlusPlus) {
4120 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4121 // type is specified by a function definition that contains a (possibly
4122 // empty) identifier list, both shall agree in the number of parameters
4123 // and the type of each parameter shall be compatible with the type that
4124 // results from the application of default argument promotions to the
4125 // type of the corresponding identifier. ...
4126 // This cannot be handled by ASTContext::typesAreCompatible() because that
4127 // doesn't know whether the function type is for a definition or not when
4128 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4129 // we need to cover here is that the number of arguments agree as the
4130 // default argument promotion rules were already checked by
4131 // ASTContext::typesAreCompatible().
4132 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4133 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4134 if (Old->hasInheritedPrototype())
4135 Old = Old->getCanonicalDecl();
4136 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4137 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4138 return true;
4141 // If we are merging two functions where only one of them has a prototype,
4142 // we may have enough information to decide to issue a diagnostic that the
4143 // function without a prototype will change behavior in C23. This handles
4144 // cases like:
4145 // void i(); void i(int j);
4146 // void i(int j); void i();
4147 // void i(); void i(int j) {}
4148 // See ActOnFinishFunctionBody() for other cases of the behavior change
4149 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4150 // type without a prototype.
4151 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4152 !New->isImplicit() && !Old->isImplicit()) {
4153 const FunctionDecl *WithProto, *WithoutProto;
4154 if (New->hasWrittenPrototype()) {
4155 WithProto = New;
4156 WithoutProto = Old;
4157 } else {
4158 WithProto = Old;
4159 WithoutProto = New;
4162 if (WithProto->getNumParams() != 0) {
4163 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4164 // The one without the prototype will be changing behavior in C23, so
4165 // warn about that one so long as it's a user-visible declaration.
4166 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4167 if (WithoutProto == New)
4168 IsWithoutProtoADef = NewDeclIsDefn;
4169 else
4170 IsWithProtoADef = NewDeclIsDefn;
4171 Diag(WithoutProto->getLocation(),
4172 diag::warn_non_prototype_changes_behavior)
4173 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4174 << (WithoutProto == Old) << IsWithProtoADef;
4176 // The reason the one without the prototype will be changing behavior
4177 // is because of the one with the prototype, so note that so long as
4178 // it's a user-visible declaration. There is one exception to this:
4179 // when the new declaration is a definition without a prototype, the
4180 // old declaration with a prototype is not the cause of the issue,
4181 // and that does not need to be noted because the one with a
4182 // prototype will not change behavior in C23.
4183 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4184 !IsWithoutProtoADef)
4185 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4190 if (Context.typesAreCompatible(OldQType, NewQType)) {
4191 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4192 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4193 const FunctionProtoType *OldProto = nullptr;
4194 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4195 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4196 // The old declaration provided a function prototype, but the
4197 // new declaration does not. Merge in the prototype.
4198 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4199 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4200 OldProto->getParamTypes(),
4201 OldProto->getExtProtoInfo());
4202 New->setType(NewQType);
4203 New->setHasInheritedPrototype();
4205 // Synthesize parameters with the same types.
4206 SmallVector<ParmVarDecl *, 16> Params;
4207 for (const auto &ParamType : OldProto->param_types()) {
4208 ParmVarDecl *Param = ParmVarDecl::Create(
4209 Context, New, SourceLocation(), SourceLocation(), nullptr,
4210 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4211 Param->setScopeInfo(0, Params.size());
4212 Param->setImplicit();
4213 Params.push_back(Param);
4216 New->setParams(Params);
4219 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4223 // Check if the function types are compatible when pointer size address
4224 // spaces are ignored.
4225 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4226 return false;
4228 // GNU C permits a K&R definition to follow a prototype declaration
4229 // if the declared types of the parameters in the K&R definition
4230 // match the types in the prototype declaration, even when the
4231 // promoted types of the parameters from the K&R definition differ
4232 // from the types in the prototype. GCC then keeps the types from
4233 // the prototype.
4235 // If a variadic prototype is followed by a non-variadic K&R definition,
4236 // the K&R definition becomes variadic. This is sort of an edge case, but
4237 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4238 // C99 6.9.1p8.
4239 if (!getLangOpts().CPlusPlus &&
4240 Old->hasPrototype() && !New->hasPrototype() &&
4241 New->getType()->getAs<FunctionProtoType>() &&
4242 Old->getNumParams() == New->getNumParams()) {
4243 SmallVector<QualType, 16> ArgTypes;
4244 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4245 const FunctionProtoType *OldProto
4246 = Old->getType()->getAs<FunctionProtoType>();
4247 const FunctionProtoType *NewProto
4248 = New->getType()->getAs<FunctionProtoType>();
4250 // Determine whether this is the GNU C extension.
4251 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4252 NewProto->getReturnType());
4253 bool LooseCompatible = !MergedReturn.isNull();
4254 for (unsigned Idx = 0, End = Old->getNumParams();
4255 LooseCompatible && Idx != End; ++Idx) {
4256 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4257 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4258 if (Context.typesAreCompatible(OldParm->getType(),
4259 NewProto->getParamType(Idx))) {
4260 ArgTypes.push_back(NewParm->getType());
4261 } else if (Context.typesAreCompatible(OldParm->getType(),
4262 NewParm->getType(),
4263 /*CompareUnqualified=*/true)) {
4264 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4265 NewProto->getParamType(Idx) };
4266 Warnings.push_back(Warn);
4267 ArgTypes.push_back(NewParm->getType());
4268 } else
4269 LooseCompatible = false;
4272 if (LooseCompatible) {
4273 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4274 Diag(Warnings[Warn].NewParm->getLocation(),
4275 diag::ext_param_promoted_not_compatible_with_prototype)
4276 << Warnings[Warn].PromotedType
4277 << Warnings[Warn].OldParm->getType();
4278 if (Warnings[Warn].OldParm->getLocation().isValid())
4279 Diag(Warnings[Warn].OldParm->getLocation(),
4280 diag::note_previous_declaration);
4283 if (MergeTypeWithOld)
4284 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4285 OldProto->getExtProtoInfo()));
4286 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4289 // Fall through to diagnose conflicting types.
4292 // A function that has already been declared has been redeclared or
4293 // defined with a different type; show an appropriate diagnostic.
4295 // If the previous declaration was an implicitly-generated builtin
4296 // declaration, then at the very least we should use a specialized note.
4297 unsigned BuiltinID;
4298 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4299 // If it's actually a library-defined builtin function like 'malloc'
4300 // or 'printf', just warn about the incompatible redeclaration.
4301 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4302 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4303 Diag(OldLocation, diag::note_previous_builtin_declaration)
4304 << Old << Old->getType();
4305 return false;
4308 PrevDiag = diag::note_previous_builtin_declaration;
4311 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4312 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4313 return true;
4316 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4317 Scope *S, bool MergeTypeWithOld) {
4318 // Merge the attributes
4319 mergeDeclAttributes(New, Old);
4321 // Merge "pure" flag.
4322 if (Old->isPureVirtual())
4323 New->setIsPureVirtual();
4325 // Merge "used" flag.
4326 if (Old->getMostRecentDecl()->isUsed(false))
4327 New->setIsUsed();
4329 // Merge attributes from the parameters. These can mismatch with K&R
4330 // declarations.
4331 if (New->getNumParams() == Old->getNumParams())
4332 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4333 ParmVarDecl *NewParam = New->getParamDecl(i);
4334 ParmVarDecl *OldParam = Old->getParamDecl(i);
4335 mergeParamDeclAttributes(NewParam, OldParam, *this);
4336 mergeParamDeclTypes(NewParam, OldParam, *this);
4339 if (getLangOpts().CPlusPlus)
4340 return MergeCXXFunctionDecl(New, Old, S);
4342 // Merge the function types so the we get the composite types for the return
4343 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4344 // was visible.
4345 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4346 if (!Merged.isNull() && MergeTypeWithOld)
4347 New->setType(Merged);
4349 return false;
4352 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4353 ObjCMethodDecl *oldMethod) {
4354 // Merge the attributes, including deprecated/unavailable
4355 AvailabilityMergeKind MergeKind =
4356 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4357 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4358 : AMK_ProtocolImplementation)
4359 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4360 : AMK_Override;
4362 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4364 // Merge attributes from the parameters.
4365 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4366 oe = oldMethod->param_end();
4367 for (ObjCMethodDecl::param_iterator
4368 ni = newMethod->param_begin(), ne = newMethod->param_end();
4369 ni != ne && oi != oe; ++ni, ++oi)
4370 mergeParamDeclAttributes(*ni, *oi, *this);
4372 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4375 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4376 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4378 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4379 ? diag::err_redefinition_different_type
4380 : diag::err_redeclaration_different_type)
4381 << New->getDeclName() << New->getType() << Old->getType();
4383 diag::kind PrevDiag;
4384 SourceLocation OldLocation;
4385 std::tie(PrevDiag, OldLocation)
4386 = getNoteDiagForInvalidRedeclaration(Old, New);
4387 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4388 New->setInvalidDecl();
4391 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4392 bool MergeTypeWithOld) {
4393 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4394 return;
4396 QualType MergedT;
4397 if (getLangOpts().CPlusPlus) {
4398 if (New->getType()->isUndeducedType()) {
4399 // We don't know what the new type is until the initializer is attached.
4400 return;
4401 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4402 // These could still be something that needs exception specs checked.
4403 return MergeVarDeclExceptionSpecs(New, Old);
4405 // C++ [basic.link]p10:
4406 // [...] the types specified by all declarations referring to a given
4407 // object or function shall be identical, except that declarations for an
4408 // array object can specify array types that differ by the presence or
4409 // absence of a major array bound (8.3.4).
4410 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4411 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4412 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4414 // We are merging a variable declaration New into Old. If it has an array
4415 // bound, and that bound differs from Old's bound, we should diagnose the
4416 // mismatch.
4417 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4418 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4419 PrevVD = PrevVD->getPreviousDecl()) {
4420 QualType PrevVDTy = PrevVD->getType();
4421 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4422 continue;
4424 if (!Context.hasSameType(New->getType(), PrevVDTy))
4425 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4429 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4430 if (Context.hasSameType(OldArray->getElementType(),
4431 NewArray->getElementType()))
4432 MergedT = New->getType();
4434 // FIXME: Check visibility. New is hidden but has a complete type. If New
4435 // has no array bound, it should not inherit one from Old, if Old is not
4436 // visible.
4437 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4438 if (Context.hasSameType(OldArray->getElementType(),
4439 NewArray->getElementType()))
4440 MergedT = Old->getType();
4443 else if (New->getType()->isObjCObjectPointerType() &&
4444 Old->getType()->isObjCObjectPointerType()) {
4445 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4446 Old->getType());
4448 } else {
4449 // C 6.2.7p2:
4450 // All declarations that refer to the same object or function shall have
4451 // compatible type.
4452 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4454 if (MergedT.isNull()) {
4455 // It's OK if we couldn't merge types if either type is dependent, for a
4456 // block-scope variable. In other cases (static data members of class
4457 // templates, variable templates, ...), we require the types to be
4458 // equivalent.
4459 // FIXME: The C++ standard doesn't say anything about this.
4460 if ((New->getType()->isDependentType() ||
4461 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4462 // If the old type was dependent, we can't merge with it, so the new type
4463 // becomes dependent for now. We'll reproduce the original type when we
4464 // instantiate the TypeSourceInfo for the variable.
4465 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4466 New->setType(Context.DependentTy);
4467 return;
4469 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4472 // Don't actually update the type on the new declaration if the old
4473 // declaration was an extern declaration in a different scope.
4474 if (MergeTypeWithOld)
4475 New->setType(MergedT);
4478 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4479 LookupResult &Previous) {
4480 // C11 6.2.7p4:
4481 // For an identifier with internal or external linkage declared
4482 // in a scope in which a prior declaration of that identifier is
4483 // visible, if the prior declaration specifies internal or
4484 // external linkage, the type of the identifier at the later
4485 // declaration becomes the composite type.
4487 // If the variable isn't visible, we do not merge with its type.
4488 if (Previous.isShadowed())
4489 return false;
4491 if (S.getLangOpts().CPlusPlus) {
4492 // C++11 [dcl.array]p3:
4493 // If there is a preceding declaration of the entity in the same
4494 // scope in which the bound was specified, an omitted array bound
4495 // is taken to be the same as in that earlier declaration.
4496 return NewVD->isPreviousDeclInSameBlockScope() ||
4497 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4498 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4499 } else {
4500 // If the old declaration was function-local, don't merge with its
4501 // type unless we're in the same function.
4502 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4503 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4507 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4508 // If the new decl is already invalid, don't do any other checking.
4509 if (New->isInvalidDecl())
4510 return;
4512 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4513 return;
4515 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4517 // Verify the old decl was also a variable or variable template.
4518 VarDecl *Old = nullptr;
4519 VarTemplateDecl *OldTemplate = nullptr;
4520 if (Previous.isSingleResult()) {
4521 if (NewTemplate) {
4522 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4523 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4525 if (auto *Shadow =
4526 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4527 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4528 return New->setInvalidDecl();
4529 } else {
4530 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4532 if (auto *Shadow =
4533 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4534 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4535 return New->setInvalidDecl();
4538 if (!Old) {
4539 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4540 << New->getDeclName();
4541 notePreviousDefinition(Previous.getRepresentativeDecl(),
4542 New->getLocation());
4543 return New->setInvalidDecl();
4546 // If the old declaration was found in an inline namespace and the new
4547 // declaration was qualified, update the DeclContext to match.
4548 adjustDeclContextForDeclaratorDecl(New, Old);
4550 // Ensure the template parameters are compatible.
4551 if (NewTemplate &&
4552 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4553 OldTemplate->getTemplateParameters(),
4554 /*Complain=*/true, TPL_TemplateMatch))
4555 return New->setInvalidDecl();
4557 // C++ [class.mem]p1:
4558 // A member shall not be declared twice in the member-specification [...]
4560 // Here, we need only consider static data members.
4561 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4562 Diag(New->getLocation(), diag::err_duplicate_member)
4563 << New->getIdentifier();
4564 Diag(Old->getLocation(), diag::note_previous_declaration);
4565 New->setInvalidDecl();
4568 mergeDeclAttributes(New, Old);
4569 // Warn if an already-defined variable is made a weak_import in a subsequent
4570 // declaration
4571 if (New->hasAttr<WeakImportAttr>())
4572 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4573 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4574 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4575 Diag(D->getLocation(), diag::note_previous_definition);
4576 // Remove weak_import attribute on new declaration.
4577 New->dropAttr<WeakImportAttr>();
4578 break;
4582 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4583 if (!Old->hasAttr<InternalLinkageAttr>()) {
4584 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4585 << ILA;
4586 Diag(Old->getLocation(), diag::note_previous_declaration);
4587 New->dropAttr<InternalLinkageAttr>();
4590 // Merge the types.
4591 VarDecl *MostRecent = Old->getMostRecentDecl();
4592 if (MostRecent != Old) {
4593 MergeVarDeclTypes(New, MostRecent,
4594 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4595 if (New->isInvalidDecl())
4596 return;
4599 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4600 if (New->isInvalidDecl())
4601 return;
4603 diag::kind PrevDiag;
4604 SourceLocation OldLocation;
4605 std::tie(PrevDiag, OldLocation) =
4606 getNoteDiagForInvalidRedeclaration(Old, New);
4608 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4609 if (New->getStorageClass() == SC_Static &&
4610 !New->isStaticDataMember() &&
4611 Old->hasExternalFormalLinkage()) {
4612 if (getLangOpts().MicrosoftExt) {
4613 Diag(New->getLocation(), diag::ext_static_non_static)
4614 << New->getDeclName();
4615 Diag(OldLocation, PrevDiag);
4616 } else {
4617 Diag(New->getLocation(), diag::err_static_non_static)
4618 << New->getDeclName();
4619 Diag(OldLocation, PrevDiag);
4620 return New->setInvalidDecl();
4623 // C99 6.2.2p4:
4624 // For an identifier declared with the storage-class specifier
4625 // extern in a scope in which a prior declaration of that
4626 // identifier is visible,23) if the prior declaration specifies
4627 // internal or external linkage, the linkage of the identifier at
4628 // the later declaration is the same as the linkage specified at
4629 // the prior declaration. If no prior declaration is visible, or
4630 // if the prior declaration specifies no linkage, then the
4631 // identifier has external linkage.
4632 if (New->hasExternalStorage() && Old->hasLinkage())
4633 /* Okay */;
4634 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4635 !New->isStaticDataMember() &&
4636 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4637 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4638 Diag(OldLocation, PrevDiag);
4639 return New->setInvalidDecl();
4642 // Check if extern is followed by non-extern and vice-versa.
4643 if (New->hasExternalStorage() &&
4644 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4645 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4646 Diag(OldLocation, PrevDiag);
4647 return New->setInvalidDecl();
4649 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4650 !New->hasExternalStorage()) {
4651 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4652 Diag(OldLocation, PrevDiag);
4653 return New->setInvalidDecl();
4656 if (CheckRedeclarationInModule(New, Old))
4657 return;
4659 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4661 // FIXME: The test for external storage here seems wrong? We still
4662 // need to check for mismatches.
4663 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4664 // Don't complain about out-of-line definitions of static members.
4665 !(Old->getLexicalDeclContext()->isRecord() &&
4666 !New->getLexicalDeclContext()->isRecord())) {
4667 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4668 Diag(OldLocation, PrevDiag);
4669 return New->setInvalidDecl();
4672 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4673 if (VarDecl *Def = Old->getDefinition()) {
4674 // C++1z [dcl.fcn.spec]p4:
4675 // If the definition of a variable appears in a translation unit before
4676 // its first declaration as inline, the program is ill-formed.
4677 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4678 Diag(Def->getLocation(), diag::note_previous_definition);
4682 // If this redeclaration makes the variable inline, we may need to add it to
4683 // UndefinedButUsed.
4684 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4685 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4686 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4687 SourceLocation()));
4689 if (New->getTLSKind() != Old->getTLSKind()) {
4690 if (!Old->getTLSKind()) {
4691 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4692 Diag(OldLocation, PrevDiag);
4693 } else if (!New->getTLSKind()) {
4694 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4695 Diag(OldLocation, PrevDiag);
4696 } else {
4697 // Do not allow redeclaration to change the variable between requiring
4698 // static and dynamic initialization.
4699 // FIXME: GCC allows this, but uses the TLS keyword on the first
4700 // declaration to determine the kind. Do we need to be compatible here?
4701 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4702 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4703 Diag(OldLocation, PrevDiag);
4707 // C++ doesn't have tentative definitions, so go right ahead and check here.
4708 if (getLangOpts().CPlusPlus) {
4709 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4710 Old->getCanonicalDecl()->isConstexpr()) {
4711 // This definition won't be a definition any more once it's been merged.
4712 Diag(New->getLocation(),
4713 diag::warn_deprecated_redundant_constexpr_static_def);
4714 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4715 VarDecl *Def = Old->getDefinition();
4716 if (Def && checkVarDeclRedefinition(Def, New))
4717 return;
4721 if (haveIncompatibleLanguageLinkages(Old, New)) {
4722 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4723 Diag(OldLocation, PrevDiag);
4724 New->setInvalidDecl();
4725 return;
4728 // Merge "used" flag.
4729 if (Old->getMostRecentDecl()->isUsed(false))
4730 New->setIsUsed();
4732 // Keep a chain of previous declarations.
4733 New->setPreviousDecl(Old);
4734 if (NewTemplate)
4735 NewTemplate->setPreviousDecl(OldTemplate);
4737 // Inherit access appropriately.
4738 New->setAccess(Old->getAccess());
4739 if (NewTemplate)
4740 NewTemplate->setAccess(New->getAccess());
4742 if (Old->isInline())
4743 New->setImplicitlyInline();
4746 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4747 SourceManager &SrcMgr = getSourceManager();
4748 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4749 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4750 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4751 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4752 auto &HSI = PP.getHeaderSearchInfo();
4753 StringRef HdrFilename =
4754 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4756 auto noteFromModuleOrInclude = [&](Module *Mod,
4757 SourceLocation IncLoc) -> bool {
4758 // Redefinition errors with modules are common with non modular mapped
4759 // headers, example: a non-modular header H in module A that also gets
4760 // included directly in a TU. Pointing twice to the same header/definition
4761 // is confusing, try to get better diagnostics when modules is on.
4762 if (IncLoc.isValid()) {
4763 if (Mod) {
4764 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4765 << HdrFilename.str() << Mod->getFullModuleName();
4766 if (!Mod->DefinitionLoc.isInvalid())
4767 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4768 << Mod->getFullModuleName();
4769 } else {
4770 Diag(IncLoc, diag::note_redefinition_include_same_file)
4771 << HdrFilename.str();
4773 return true;
4776 return false;
4779 // Is it the same file and same offset? Provide more information on why
4780 // this leads to a redefinition error.
4781 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4782 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4783 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4784 bool EmittedDiag =
4785 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4786 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4788 // If the header has no guards, emit a note suggesting one.
4789 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4790 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4792 if (EmittedDiag)
4793 return;
4796 // Redefinition coming from different files or couldn't do better above.
4797 if (Old->getLocation().isValid())
4798 Diag(Old->getLocation(), diag::note_previous_definition);
4801 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4802 if (!hasVisibleDefinition(Old) &&
4803 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4804 isa<VarTemplateSpecializationDecl>(New) ||
4805 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4806 New->getDeclContext()->isDependentContext())) {
4807 // The previous definition is hidden, and multiple definitions are
4808 // permitted (in separate TUs). Demote this to a declaration.
4809 New->demoteThisDefinitionToDeclaration();
4811 // Make the canonical definition visible.
4812 if (auto *OldTD = Old->getDescribedVarTemplate())
4813 makeMergedDefinitionVisible(OldTD);
4814 makeMergedDefinitionVisible(Old);
4815 return false;
4816 } else {
4817 Diag(New->getLocation(), diag::err_redefinition) << New;
4818 notePreviousDefinition(Old, New->getLocation());
4819 New->setInvalidDecl();
4820 return true;
4824 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4825 DeclSpec &DS,
4826 const ParsedAttributesView &DeclAttrs,
4827 RecordDecl *&AnonRecord) {
4828 return ParsedFreeStandingDeclSpec(
4829 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4832 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4833 // disambiguate entities defined in different scopes.
4834 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4835 // compatibility.
4836 // We will pick our mangling number depending on which version of MSVC is being
4837 // targeted.
4838 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4839 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4840 ? S->getMSCurManglingNumber()
4841 : S->getMSLastManglingNumber();
4844 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4845 if (!Context.getLangOpts().CPlusPlus)
4846 return;
4848 if (isa<CXXRecordDecl>(Tag->getParent())) {
4849 // If this tag is the direct child of a class, number it if
4850 // it is anonymous.
4851 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4852 return;
4853 MangleNumberingContext &MCtx =
4854 Context.getManglingNumberContext(Tag->getParent());
4855 Context.setManglingNumber(
4856 Tag, MCtx.getManglingNumber(
4857 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4858 return;
4861 // If this tag isn't a direct child of a class, number it if it is local.
4862 MangleNumberingContext *MCtx;
4863 Decl *ManglingContextDecl;
4864 std::tie(MCtx, ManglingContextDecl) =
4865 getCurrentMangleNumberContext(Tag->getDeclContext());
4866 if (MCtx) {
4867 Context.setManglingNumber(
4868 Tag, MCtx->getManglingNumber(
4869 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4873 namespace {
4874 struct NonCLikeKind {
4875 enum {
4876 None,
4877 BaseClass,
4878 DefaultMemberInit,
4879 Lambda,
4880 Friend,
4881 OtherMember,
4882 Invalid,
4883 } Kind = None;
4884 SourceRange Range;
4886 explicit operator bool() { return Kind != None; }
4890 /// Determine whether a class is C-like, according to the rules of C++
4891 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4892 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4893 if (RD->isInvalidDecl())
4894 return {NonCLikeKind::Invalid, {}};
4896 // C++ [dcl.typedef]p9: [P1766R1]
4897 // An unnamed class with a typedef name for linkage purposes shall not
4899 // -- have any base classes
4900 if (RD->getNumBases())
4901 return {NonCLikeKind::BaseClass,
4902 SourceRange(RD->bases_begin()->getBeginLoc(),
4903 RD->bases_end()[-1].getEndLoc())};
4904 bool Invalid = false;
4905 for (Decl *D : RD->decls()) {
4906 // Don't complain about things we already diagnosed.
4907 if (D->isInvalidDecl()) {
4908 Invalid = true;
4909 continue;
4912 // -- have any [...] default member initializers
4913 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4914 if (FD->hasInClassInitializer()) {
4915 auto *Init = FD->getInClassInitializer();
4916 return {NonCLikeKind::DefaultMemberInit,
4917 Init ? Init->getSourceRange() : D->getSourceRange()};
4919 continue;
4922 // FIXME: We don't allow friend declarations. This violates the wording of
4923 // P1766, but not the intent.
4924 if (isa<FriendDecl>(D))
4925 return {NonCLikeKind::Friend, D->getSourceRange()};
4927 // -- declare any members other than non-static data members, member
4928 // enumerations, or member classes,
4929 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4930 isa<EnumDecl>(D))
4931 continue;
4932 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4933 if (!MemberRD) {
4934 if (D->isImplicit())
4935 continue;
4936 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4939 // -- contain a lambda-expression,
4940 if (MemberRD->isLambda())
4941 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4943 // and all member classes shall also satisfy these requirements
4944 // (recursively).
4945 if (MemberRD->isThisDeclarationADefinition()) {
4946 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4947 return Kind;
4951 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4954 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4955 TypedefNameDecl *NewTD) {
4956 if (TagFromDeclSpec->isInvalidDecl())
4957 return;
4959 // Do nothing if the tag already has a name for linkage purposes.
4960 if (TagFromDeclSpec->hasNameForLinkage())
4961 return;
4963 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4964 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4966 // The type must match the tag exactly; no qualifiers allowed.
4967 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4968 Context.getTagDeclType(TagFromDeclSpec))) {
4969 if (getLangOpts().CPlusPlus)
4970 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4971 return;
4974 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4975 // An unnamed class with a typedef name for linkage purposes shall [be
4976 // C-like].
4978 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4979 // shouldn't happen, but there are constructs that the language rule doesn't
4980 // disallow for which we can't reasonably avoid computing linkage early.
4981 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4982 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4983 : NonCLikeKind();
4984 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4985 if (NonCLike || ChangesLinkage) {
4986 if (NonCLike.Kind == NonCLikeKind::Invalid)
4987 return;
4989 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4990 if (ChangesLinkage) {
4991 // If the linkage changes, we can't accept this as an extension.
4992 if (NonCLike.Kind == NonCLikeKind::None)
4993 DiagID = diag::err_typedef_changes_linkage;
4994 else
4995 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4998 SourceLocation FixitLoc =
4999 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5000 llvm::SmallString<40> TextToInsert;
5001 TextToInsert += ' ';
5002 TextToInsert += NewTD->getIdentifier()->getName();
5004 Diag(FixitLoc, DiagID)
5005 << isa<TypeAliasDecl>(NewTD)
5006 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5007 if (NonCLike.Kind != NonCLikeKind::None) {
5008 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5009 << NonCLike.Kind - 1 << NonCLike.Range;
5011 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5012 << NewTD << isa<TypeAliasDecl>(NewTD);
5014 if (ChangesLinkage)
5015 return;
5018 // Otherwise, set this as the anon-decl typedef for the tag.
5019 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5021 // Now that we have a name for the tag, process API notes again.
5022 ProcessAPINotes(TagFromDeclSpec);
5025 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5026 DeclSpec::TST T = DS.getTypeSpecType();
5027 switch (T) {
5028 case DeclSpec::TST_class:
5029 return 0;
5030 case DeclSpec::TST_struct:
5031 return 1;
5032 case DeclSpec::TST_interface:
5033 return 2;
5034 case DeclSpec::TST_union:
5035 return 3;
5036 case DeclSpec::TST_enum:
5037 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5038 if (ED->isScopedUsingClassTag())
5039 return 5;
5040 if (ED->isScoped())
5041 return 6;
5043 return 4;
5044 default:
5045 llvm_unreachable("unexpected type specifier");
5049 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5050 DeclSpec &DS,
5051 const ParsedAttributesView &DeclAttrs,
5052 MultiTemplateParamsArg TemplateParams,
5053 bool IsExplicitInstantiation,
5054 RecordDecl *&AnonRecord,
5055 SourceLocation EllipsisLoc) {
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
5066 return nullptr;
5068 // Note that the above type specs guarantee that the
5069 // type rep is a Decl, whereas in many of the others
5070 // it's a Type.
5071 if (isa<TagDecl>(TagD))
5072 Tag = cast<TagDecl>(TagD);
5073 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5074 Tag = CTD->getTemplatedDecl();
5077 if (Tag) {
5078 handleTagNumbering(Tag, S);
5079 Tag->setFreeStanding();
5080 if (Tag->isInvalidDecl())
5081 return Tag;
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
5102 if (Tag)
5103 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5104 << GetDiagnosticTypeSpecifierID(DS)
5105 << static_cast<int>(DS.getConstexprSpecifier());
5106 else if (getLangOpts().C23)
5107 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5108 else
5109 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5110 << static_cast<int>(DS.getConstexprSpecifier());
5111 // Don't emit warnings after this error.
5112 return TagD;
5115 DiagnoseFunctionSpecifiers(DS);
5117 if (DS.isFriendSpecified()) {
5118 // If we're dealing with a decl but not a TagDecl, assume that
5119 // whatever routines created it handled the friendship aspect.
5120 if (TagD && !Tag)
5121 return nullptr;
5122 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5125 assert(EllipsisLoc.isInvalid() &&
5126 "Friend ellipsis but not friend-specified?");
5128 // Track whether this decl-specifier declares anything.
5129 bool DeclaresAnything = true;
5131 // Handle anonymous struct definitions.
5132 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5133 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5134 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5135 if (getLangOpts().CPlusPlus ||
5136 Record->getDeclContext()->isRecord()) {
5137 // If CurContext is a DeclContext that can contain statements,
5138 // RecursiveASTVisitor won't visit the decls that
5139 // BuildAnonymousStructOrUnion() will put into CurContext.
5140 // Also store them here so that they can be part of the
5141 // DeclStmt that gets created in this case.
5142 // FIXME: Also return the IndirectFieldDecls created by
5143 // BuildAnonymousStructOr union, for the same reason?
5144 if (CurContext->isFunctionOrMethod())
5145 AnonRecord = Record;
5146 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5147 Context.getPrintingPolicy());
5150 DeclaresAnything = false;
5154 // C11 6.7.2.1p2:
5155 // A struct-declaration that does not declare an anonymous structure or
5156 // anonymous union shall contain a struct-declarator-list.
5158 // This rule also existed in C89 and C99; the grammar for struct-declaration
5159 // did not permit a struct-declaration without a struct-declarator-list.
5160 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5161 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5162 // Check for Microsoft C extension: anonymous struct/union member.
5163 // Handle 2 kinds of anonymous struct/union:
5164 // struct STRUCT;
5165 // union UNION;
5166 // and
5167 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5168 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5169 if ((Tag && Tag->getDeclName()) ||
5170 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5171 RecordDecl *Record = nullptr;
5172 if (Tag)
5173 Record = dyn_cast<RecordDecl>(Tag);
5174 else if (const RecordType *RT =
5175 DS.getRepAsType().get()->getAsStructureType())
5176 Record = RT->getDecl();
5177 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5178 Record = UT->getDecl();
5180 if (Record && getLangOpts().MicrosoftExt) {
5181 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5182 << Record->isUnion() << DS.getSourceRange();
5183 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5186 DeclaresAnything = false;
5190 // Skip all the checks below if we have a type error.
5191 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5192 (TagD && TagD->isInvalidDecl()))
5193 return TagD;
5195 if (getLangOpts().CPlusPlus &&
5196 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5197 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5198 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5199 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5200 DeclaresAnything = false;
5202 if (!DS.isMissingDeclaratorOk()) {
5203 // Customize diagnostic for a typedef missing a name.
5204 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5205 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5206 << DS.getSourceRange();
5207 else
5208 DeclaresAnything = false;
5211 if (DS.isModulePrivateSpecified() &&
5212 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5213 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5214 << llvm::to_underlying(Tag->getTagKind())
5215 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5217 ActOnDocumentableDecl(TagD);
5219 // C 6.7/2:
5220 // A declaration [...] shall declare at least a declarator [...], a tag,
5221 // or the members of an enumeration.
5222 // C++ [dcl.dcl]p3:
5223 // [If there are no declarators], and except for the declaration of an
5224 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5225 // names into the program, or shall redeclare a name introduced by a
5226 // previous declaration.
5227 if (!DeclaresAnything) {
5228 // In C, we allow this as a (popular) extension / bug. Don't bother
5229 // producing further diagnostics for redundant qualifiers after this.
5230 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5231 ? diag::err_no_declarators
5232 : diag::ext_no_declarators)
5233 << DS.getSourceRange();
5234 return TagD;
5237 // C++ [dcl.stc]p1:
5238 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5239 // init-declarator-list of the declaration shall not be empty.
5240 // C++ [dcl.fct.spec]p1:
5241 // If a cv-qualifier appears in a decl-specifier-seq, the
5242 // init-declarator-list of the declaration shall not be empty.
5244 // Spurious qualifiers here appear to be valid in C.
5245 unsigned DiagID = diag::warn_standalone_specifier;
5246 if (getLangOpts().CPlusPlus)
5247 DiagID = diag::ext_standalone_specifier;
5249 // Note that a linkage-specification sets a storage class, but
5250 // 'extern "C" struct foo;' is actually valid and not theoretically
5251 // useless.
5252 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5253 if (SCS == DeclSpec::SCS_mutable)
5254 // Since mutable is not a viable storage class specifier in C, there is
5255 // no reason to treat it as an extension. Instead, diagnose as an error.
5256 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5257 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5258 Diag(DS.getStorageClassSpecLoc(), DiagID)
5259 << DeclSpec::getSpecifierName(SCS);
5262 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5263 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5264 << DeclSpec::getSpecifierName(TSCS);
5265 if (DS.getTypeQualifiers()) {
5266 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5267 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5268 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5269 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5270 // Restrict is covered above.
5271 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5272 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5273 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5274 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5277 // Warn about ignored type attributes, for example:
5278 // __attribute__((aligned)) struct A;
5279 // Attributes should be placed after tag to apply to type declaration.
5280 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5281 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5282 if (TypeSpecType == DeclSpec::TST_class ||
5283 TypeSpecType == DeclSpec::TST_struct ||
5284 TypeSpecType == DeclSpec::TST_interface ||
5285 TypeSpecType == DeclSpec::TST_union ||
5286 TypeSpecType == DeclSpec::TST_enum) {
5288 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5289 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5290 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5291 DiagnosticId = diag::warn_attribute_ignored;
5292 else if (AL.isRegularKeywordAttribute())
5293 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5294 else
5295 DiagnosticId = diag::warn_declspec_attribute_ignored;
5296 Diag(AL.getLoc(), DiagnosticId)
5297 << AL << GetDiagnosticTypeSpecifierID(DS);
5300 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5301 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5305 return TagD;
5308 /// We are trying to inject an anonymous member into the given scope;
5309 /// check if there's an existing declaration that can't be overloaded.
5311 /// \return true if this is a forbidden redeclaration
5312 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5313 DeclContext *Owner,
5314 DeclarationName Name,
5315 SourceLocation NameLoc, bool IsUnion,
5316 StorageClass SC) {
5317 LookupResult R(SemaRef, Name, NameLoc,
5318 Owner->isRecord() ? Sema::LookupMemberName
5319 : Sema::LookupOrdinaryName,
5320 RedeclarationKind::ForVisibleRedeclaration);
5321 if (!SemaRef.LookupName(R, S)) return false;
5323 // Pick a representative declaration.
5324 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5325 assert(PrevDecl && "Expected a non-null Decl");
5327 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5328 return false;
5330 if (SC == StorageClass::SC_None &&
5331 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5332 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5333 if (!Owner->isRecord())
5334 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5335 return false;
5338 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5339 << IsUnion << Name;
5340 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5342 return true;
5345 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5346 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5347 DiagPlaceholderFieldDeclDefinitions(RD);
5350 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5351 if (!getLangOpts().CPlusPlus)
5352 return;
5354 // This function can be parsed before we have validated the
5355 // structure as an anonymous struct
5356 if (Record->isAnonymousStructOrUnion())
5357 return;
5359 const NamedDecl *First = 0;
5360 for (const Decl *D : Record->decls()) {
5361 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5362 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5363 continue;
5364 if (!First)
5365 First = ND;
5366 else
5367 DiagPlaceholderVariableDefinition(ND->getLocation());
5371 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5372 /// anonymous struct or union AnonRecord into the owning context Owner
5373 /// and scope S. This routine will be invoked just after we realize
5374 /// that an unnamed union or struct is actually an anonymous union or
5375 /// struct, e.g.,
5377 /// @code
5378 /// union {
5379 /// int i;
5380 /// float f;
5381 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5382 /// // f into the surrounding scope.x
5383 /// @endcode
5385 /// This routine is recursive, injecting the names of nested anonymous
5386 /// structs/unions into the owning context and scope as well.
5387 static bool
5388 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5389 RecordDecl *AnonRecord, AccessSpecifier AS,
5390 StorageClass SC,
5391 SmallVectorImpl<NamedDecl *> &Chaining) {
5392 bool Invalid = false;
5394 // Look every FieldDecl and IndirectFieldDecl with a name.
5395 for (auto *D : AnonRecord->decls()) {
5396 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5397 cast<NamedDecl>(D)->getDeclName()) {
5398 ValueDecl *VD = cast<ValueDecl>(D);
5399 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5400 VD->getLocation(), AnonRecord->isUnion(),
5401 SC)) {
5402 // C++ [class.union]p2:
5403 // The names of the members of an anonymous union shall be
5404 // distinct from the names of any other entity in the
5405 // scope in which the anonymous union is declared.
5406 Invalid = true;
5407 } else {
5408 // C++ [class.union]p2:
5409 // For the purpose of name lookup, after the anonymous union
5410 // definition, the members of the anonymous union are
5411 // considered to have been defined in the scope in which the
5412 // anonymous union is declared.
5413 unsigned OldChainingSize = Chaining.size();
5414 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5415 Chaining.append(IF->chain_begin(), IF->chain_end());
5416 else
5417 Chaining.push_back(VD);
5419 assert(Chaining.size() >= 2);
5420 NamedDecl **NamedChain =
5421 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5422 for (unsigned i = 0; i < Chaining.size(); i++)
5423 NamedChain[i] = Chaining[i];
5425 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5426 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5427 VD->getType(), {NamedChain, Chaining.size()});
5429 for (const auto *Attr : VD->attrs())
5430 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5432 IndirectField->setAccess(AS);
5433 IndirectField->setImplicit();
5434 SemaRef.PushOnScopeChains(IndirectField, S);
5436 // That includes picking up the appropriate access specifier.
5437 if (AS != AS_none) IndirectField->setAccess(AS);
5439 Chaining.resize(OldChainingSize);
5444 return Invalid;
5447 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5448 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5449 /// illegal input values are mapped to SC_None.
5450 static StorageClass
5451 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5452 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5453 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5454 "Parser allowed 'typedef' as storage class VarDecl.");
5455 switch (StorageClassSpec) {
5456 case DeclSpec::SCS_unspecified: return SC_None;
5457 case DeclSpec::SCS_extern:
5458 if (DS.isExternInLinkageSpec())
5459 return SC_None;
5460 return SC_Extern;
5461 case DeclSpec::SCS_static: return SC_Static;
5462 case DeclSpec::SCS_auto: return SC_Auto;
5463 case DeclSpec::SCS_register: return SC_Register;
5464 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5465 // Illegal SCSs map to None: error reporting is up to the caller.
5466 case DeclSpec::SCS_mutable: // Fall through.
5467 case DeclSpec::SCS_typedef: return SC_None;
5469 llvm_unreachable("unknown storage class specifier");
5472 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5473 assert(Record->hasInClassInitializer());
5475 for (const auto *I : Record->decls()) {
5476 const auto *FD = dyn_cast<FieldDecl>(I);
5477 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5478 FD = IFD->getAnonField();
5479 if (FD && FD->hasInClassInitializer())
5480 return FD->getLocation();
5483 llvm_unreachable("couldn't find in-class initializer");
5486 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5487 SourceLocation DefaultInitLoc) {
5488 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5489 return;
5491 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5492 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5495 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5496 CXXRecordDecl *AnonUnion) {
5497 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5498 return;
5500 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5503 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5504 AccessSpecifier AS,
5505 RecordDecl *Record,
5506 const PrintingPolicy &Policy) {
5507 DeclContext *Owner = Record->getDeclContext();
5509 // Diagnose whether this anonymous struct/union is an extension.
5510 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5511 Diag(Record->getLocation(), diag::ext_anonymous_union);
5512 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5513 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5514 else if (!Record->isUnion() && !getLangOpts().C11)
5515 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5517 // C and C++ require different kinds of checks for anonymous
5518 // structs/unions.
5519 bool Invalid = false;
5520 if (getLangOpts().CPlusPlus) {
5521 const char *PrevSpec = nullptr;
5522 if (Record->isUnion()) {
5523 // C++ [class.union]p6:
5524 // C++17 [class.union.anon]p2:
5525 // Anonymous unions declared in a named namespace or in the
5526 // global namespace shall be declared static.
5527 unsigned DiagID;
5528 DeclContext *OwnerScope = Owner->getRedeclContext();
5529 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5530 (OwnerScope->isTranslationUnit() ||
5531 (OwnerScope->isNamespace() &&
5532 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5533 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5534 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5536 // Recover by adding 'static'.
5537 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5538 PrevSpec, DiagID, Policy);
5540 // C++ [class.union]p6:
5541 // A storage class is not allowed in a declaration of an
5542 // anonymous union in a class scope.
5543 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5544 isa<RecordDecl>(Owner)) {
5545 Diag(DS.getStorageClassSpecLoc(),
5546 diag::err_anonymous_union_with_storage_spec)
5547 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5549 // Recover by removing the storage specifier.
5550 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5551 SourceLocation(),
5552 PrevSpec, DiagID, Context.getPrintingPolicy());
5556 // Ignore const/volatile/restrict qualifiers.
5557 if (DS.getTypeQualifiers()) {
5558 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5559 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5560 << Record->isUnion() << "const"
5561 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5562 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5563 Diag(DS.getVolatileSpecLoc(),
5564 diag::ext_anonymous_struct_union_qualified)
5565 << Record->isUnion() << "volatile"
5566 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5567 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5568 Diag(DS.getRestrictSpecLoc(),
5569 diag::ext_anonymous_struct_union_qualified)
5570 << Record->isUnion() << "restrict"
5571 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5572 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5573 Diag(DS.getAtomicSpecLoc(),
5574 diag::ext_anonymous_struct_union_qualified)
5575 << Record->isUnion() << "_Atomic"
5576 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5577 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5578 Diag(DS.getUnalignedSpecLoc(),
5579 diag::ext_anonymous_struct_union_qualified)
5580 << Record->isUnion() << "__unaligned"
5581 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5583 DS.ClearTypeQualifiers();
5586 // C++ [class.union]p2:
5587 // The member-specification of an anonymous union shall only
5588 // define non-static data members. [Note: nested types and
5589 // functions cannot be declared within an anonymous union. ]
5590 for (auto *Mem : Record->decls()) {
5591 // Ignore invalid declarations; we already diagnosed them.
5592 if (Mem->isInvalidDecl())
5593 continue;
5595 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5596 // C++ [class.union]p3:
5597 // An anonymous union shall not have private or protected
5598 // members (clause 11).
5599 assert(FD->getAccess() != AS_none);
5600 if (FD->getAccess() != AS_public) {
5601 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5602 << Record->isUnion() << (FD->getAccess() == AS_protected);
5603 Invalid = true;
5606 // C++ [class.union]p1
5607 // An object of a class with a non-trivial constructor, a non-trivial
5608 // copy constructor, a non-trivial destructor, or a non-trivial copy
5609 // assignment operator cannot be a member of a union, nor can an
5610 // array of such objects.
5611 if (CheckNontrivialField(FD))
5612 Invalid = true;
5613 } else if (Mem->isImplicit()) {
5614 // Any implicit members are fine.
5615 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5616 // This is a type that showed up in an
5617 // elaborated-type-specifier inside the anonymous struct or
5618 // union, but which actually declares a type outside of the
5619 // anonymous struct or union. It's okay.
5620 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5621 if (!MemRecord->isAnonymousStructOrUnion() &&
5622 MemRecord->getDeclName()) {
5623 // Visual C++ allows type definition in anonymous struct or union.
5624 if (getLangOpts().MicrosoftExt)
5625 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5626 << Record->isUnion();
5627 else {
5628 // This is a nested type declaration.
5629 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5630 << Record->isUnion();
5631 Invalid = true;
5633 } else {
5634 // This is an anonymous type definition within another anonymous type.
5635 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5636 // not part of standard C++.
5637 Diag(MemRecord->getLocation(),
5638 diag::ext_anonymous_record_with_anonymous_type)
5639 << Record->isUnion();
5641 } else if (isa<AccessSpecDecl>(Mem)) {
5642 // Any access specifier is fine.
5643 } else if (isa<StaticAssertDecl>(Mem)) {
5644 // In C++1z, static_assert declarations are also fine.
5645 } else {
5646 // We have something that isn't a non-static data
5647 // member. Complain about it.
5648 unsigned DK = diag::err_anonymous_record_bad_member;
5649 if (isa<TypeDecl>(Mem))
5650 DK = diag::err_anonymous_record_with_type;
5651 else if (isa<FunctionDecl>(Mem))
5652 DK = diag::err_anonymous_record_with_function;
5653 else if (isa<VarDecl>(Mem))
5654 DK = diag::err_anonymous_record_with_static;
5656 // Visual C++ allows type definition in anonymous struct or union.
5657 if (getLangOpts().MicrosoftExt &&
5658 DK == diag::err_anonymous_record_with_type)
5659 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5660 << Record->isUnion();
5661 else {
5662 Diag(Mem->getLocation(), DK) << Record->isUnion();
5663 Invalid = true;
5668 // C++11 [class.union]p8 (DR1460):
5669 // At most one variant member of a union may have a
5670 // brace-or-equal-initializer.
5671 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5672 Owner->isRecord())
5673 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5674 cast<CXXRecordDecl>(Record));
5677 if (!Record->isUnion() && !Owner->isRecord()) {
5678 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5679 << getLangOpts().CPlusPlus;
5680 Invalid = true;
5683 // C++ [dcl.dcl]p3:
5684 // [If there are no declarators], and except for the declaration of an
5685 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5686 // names into the program
5687 // C++ [class.mem]p2:
5688 // each such member-declaration shall either declare at least one member
5689 // name of the class or declare at least one unnamed bit-field
5691 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5692 if (getLangOpts().CPlusPlus && Record->field_empty())
5693 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5695 // Mock up a declarator.
5696 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5697 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5698 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5699 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5701 // Create a declaration for this anonymous struct/union.
5702 NamedDecl *Anon = nullptr;
5703 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5704 Anon = FieldDecl::Create(
5705 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5706 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5707 /*BitWidth=*/nullptr, /*Mutable=*/false,
5708 /*InitStyle=*/ICIS_NoInit);
5709 Anon->setAccess(AS);
5710 ProcessDeclAttributes(S, Anon, Dc);
5712 if (getLangOpts().CPlusPlus)
5713 FieldCollector->Add(cast<FieldDecl>(Anon));
5714 } else {
5715 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5716 if (SCSpec == DeclSpec::SCS_mutable) {
5717 // mutable can only appear on non-static class members, so it's always
5718 // an error here
5719 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5720 Invalid = true;
5721 SC = SC_None;
5724 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5725 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5726 Context.getTypeDeclType(Record), TInfo, SC);
5727 if (Invalid)
5728 Anon->setInvalidDecl();
5730 ProcessDeclAttributes(S, Anon, Dc);
5732 // Default-initialize the implicit variable. This initialization will be
5733 // trivial in almost all cases, except if a union member has an in-class
5734 // initializer:
5735 // union { int n = 0; };
5736 ActOnUninitializedDecl(Anon);
5738 Anon->setImplicit();
5740 // Mark this as an anonymous struct/union type.
5741 Record->setAnonymousStructOrUnion(true);
5743 // Add the anonymous struct/union object to the current
5744 // context. We'll be referencing this object when we refer to one of
5745 // its members.
5746 Owner->addDecl(Anon);
5748 // Inject the members of the anonymous struct/union into the owning
5749 // context and into the identifier resolver chain for name lookup
5750 // purposes.
5751 SmallVector<NamedDecl*, 2> Chain;
5752 Chain.push_back(Anon);
5754 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5755 Chain))
5756 Invalid = true;
5758 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5759 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5760 MangleNumberingContext *MCtx;
5761 Decl *ManglingContextDecl;
5762 std::tie(MCtx, ManglingContextDecl) =
5763 getCurrentMangleNumberContext(NewVD->getDeclContext());
5764 if (MCtx) {
5765 Context.setManglingNumber(
5766 NewVD, MCtx->getManglingNumber(
5767 NewVD, getMSManglingNumber(getLangOpts(), S)));
5768 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5773 if (Invalid)
5774 Anon->setInvalidDecl();
5776 return Anon;
5779 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5780 RecordDecl *Record) {
5781 assert(Record && "expected a record!");
5783 // Mock up a declarator.
5784 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5785 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc);
5786 assert(TInfo && "couldn't build declarator info for anonymous struct");
5788 auto *ParentDecl = cast<RecordDecl>(CurContext);
5789 QualType RecTy = Context.getTypeDeclType(Record);
5791 // Create a declaration for this anonymous struct.
5792 NamedDecl *Anon =
5793 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5794 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5795 /*BitWidth=*/nullptr, /*Mutable=*/false,
5796 /*InitStyle=*/ICIS_NoInit);
5797 Anon->setImplicit();
5799 // Add the anonymous struct object to the current context.
5800 CurContext->addDecl(Anon);
5802 // Inject the members of the anonymous struct into the current
5803 // context and into the identifier resolver chain for name lookup
5804 // purposes.
5805 SmallVector<NamedDecl*, 2> Chain;
5806 Chain.push_back(Anon);
5808 RecordDecl *RecordDef = Record->getDefinition();
5809 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5810 diag::err_field_incomplete_or_sizeless) ||
5811 InjectAnonymousStructOrUnionMembers(
5812 *this, S, CurContext, RecordDef, AS_none,
5813 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5814 Anon->setInvalidDecl();
5815 ParentDecl->setInvalidDecl();
5818 return Anon;
5821 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5822 return GetNameFromUnqualifiedId(D.getName());
5825 DeclarationNameInfo
5826 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5827 DeclarationNameInfo NameInfo;
5828 NameInfo.setLoc(Name.StartLocation);
5830 switch (Name.getKind()) {
5832 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5833 case UnqualifiedIdKind::IK_Identifier:
5834 NameInfo.setName(Name.Identifier);
5835 return NameInfo;
5837 case UnqualifiedIdKind::IK_DeductionGuideName: {
5838 // C++ [temp.deduct.guide]p3:
5839 // The simple-template-id shall name a class template specialization.
5840 // The template-name shall be the same identifier as the template-name
5841 // of the simple-template-id.
5842 // These together intend to imply that the template-name shall name a
5843 // class template.
5844 // FIXME: template<typename T> struct X {};
5845 // template<typename T> using Y = X<T>;
5846 // Y(int) -> Y<int>;
5847 // satisfies these rules but does not name a class template.
5848 TemplateName TN = Name.TemplateName.get().get();
5849 auto *Template = TN.getAsTemplateDecl();
5850 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5851 Diag(Name.StartLocation,
5852 diag::err_deduction_guide_name_not_class_template)
5853 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5854 if (Template)
5855 NoteTemplateLocation(*Template);
5856 return DeclarationNameInfo();
5859 NameInfo.setName(
5860 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5861 return NameInfo;
5864 case UnqualifiedIdKind::IK_OperatorFunctionId:
5865 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5866 Name.OperatorFunctionId.Operator));
5867 NameInfo.setCXXOperatorNameRange(SourceRange(
5868 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5869 return NameInfo;
5871 case UnqualifiedIdKind::IK_LiteralOperatorId:
5872 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5873 Name.Identifier));
5874 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5875 return NameInfo;
5877 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5878 TypeSourceInfo *TInfo;
5879 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5880 if (Ty.isNull())
5881 return DeclarationNameInfo();
5882 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5883 Context.getCanonicalType(Ty)));
5884 NameInfo.setNamedTypeInfo(TInfo);
5885 return NameInfo;
5888 case UnqualifiedIdKind::IK_ConstructorName: {
5889 TypeSourceInfo *TInfo;
5890 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5891 if (Ty.isNull())
5892 return DeclarationNameInfo();
5893 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5894 Context.getCanonicalType(Ty)));
5895 NameInfo.setNamedTypeInfo(TInfo);
5896 return NameInfo;
5899 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5900 // In well-formed code, we can only have a constructor
5901 // template-id that refers to the current context, so go there
5902 // to find the actual type being constructed.
5903 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5904 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5905 return DeclarationNameInfo();
5907 // Determine the type of the class being constructed.
5908 QualType CurClassType = Context.getTypeDeclType(CurClass);
5910 // FIXME: Check two things: that the template-id names the same type as
5911 // CurClassType, and that the template-id does not occur when the name
5912 // was qualified.
5914 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5915 Context.getCanonicalType(CurClassType)));
5916 // FIXME: should we retrieve TypeSourceInfo?
5917 NameInfo.setNamedTypeInfo(nullptr);
5918 return NameInfo;
5921 case UnqualifiedIdKind::IK_DestructorName: {
5922 TypeSourceInfo *TInfo;
5923 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5924 if (Ty.isNull())
5925 return DeclarationNameInfo();
5926 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5927 Context.getCanonicalType(Ty)));
5928 NameInfo.setNamedTypeInfo(TInfo);
5929 return NameInfo;
5932 case UnqualifiedIdKind::IK_TemplateId: {
5933 TemplateName TName = Name.TemplateId->Template.get();
5934 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5935 return Context.getNameForTemplate(TName, TNameLoc);
5938 } // switch (Name.getKind())
5940 llvm_unreachable("Unknown name kind");
5943 static QualType getCoreType(QualType Ty) {
5944 do {
5945 if (Ty->isPointerOrReferenceType())
5946 Ty = Ty->getPointeeType();
5947 else if (Ty->isArrayType())
5948 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5949 else
5950 return Ty.withoutLocalFastQualifiers();
5951 } while (true);
5954 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5955 /// and Definition have "nearly" matching parameters. This heuristic is
5956 /// used to improve diagnostics in the case where an out-of-line function
5957 /// definition doesn't match any declaration within the class or namespace.
5958 /// Also sets Params to the list of indices to the parameters that differ
5959 /// between the declaration and the definition. If hasSimilarParameters
5960 /// returns true and Params is empty, then all of the parameters match.
5961 static bool hasSimilarParameters(ASTContext &Context,
5962 FunctionDecl *Declaration,
5963 FunctionDecl *Definition,
5964 SmallVectorImpl<unsigned> &Params) {
5965 Params.clear();
5966 if (Declaration->param_size() != Definition->param_size())
5967 return false;
5968 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5969 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5970 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5972 // The parameter types are identical
5973 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5974 continue;
5976 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5977 QualType DefParamBaseTy = getCoreType(DefParamTy);
5978 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5979 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5981 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5982 (DeclTyName && DeclTyName == DefTyName))
5983 Params.push_back(Idx);
5984 else // The two parameters aren't even close
5985 return false;
5988 return true;
5991 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5992 /// declarator needs to be rebuilt in the current instantiation.
5993 /// Any bits of declarator which appear before the name are valid for
5994 /// consideration here. That's specifically the type in the decl spec
5995 /// and the base type in any member-pointer chunks.
5996 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5997 DeclarationName Name) {
5998 // The types we specifically need to rebuild are:
5999 // - typenames, typeofs, and decltypes
6000 // - types which will become injected class names
6001 // Of course, we also need to rebuild any type referencing such a
6002 // type. It's safest to just say "dependent", but we call out a
6003 // few cases here.
6005 DeclSpec &DS = D.getMutableDeclSpec();
6006 switch (DS.getTypeSpecType()) {
6007 case DeclSpec::TST_typename:
6008 case DeclSpec::TST_typeofType:
6009 case DeclSpec::TST_typeof_unqualType:
6010 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6011 #include "clang/Basic/TransformTypeTraits.def"
6012 case DeclSpec::TST_atomic: {
6013 // Grab the type from the parser.
6014 TypeSourceInfo *TSI = nullptr;
6015 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6016 if (T.isNull() || !T->isInstantiationDependentType()) break;
6018 // Make sure there's a type source info. This isn't really much
6019 // of a waste; most dependent types should have type source info
6020 // attached already.
6021 if (!TSI)
6022 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6024 // Rebuild the type in the current instantiation.
6025 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6026 if (!TSI) return true;
6028 // Store the new type back in the decl spec.
6029 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6030 DS.UpdateTypeRep(LocType);
6031 break;
6034 case DeclSpec::TST_decltype:
6035 case DeclSpec::TST_typeof_unqualExpr:
6036 case DeclSpec::TST_typeofExpr: {
6037 Expr *E = DS.getRepAsExpr();
6038 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6039 if (Result.isInvalid()) return true;
6040 DS.UpdateExprRep(Result.get());
6041 break;
6044 default:
6045 // Nothing to do for these decl specs.
6046 break;
6049 // It doesn't matter what order we do this in.
6050 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6051 DeclaratorChunk &Chunk = D.getTypeObject(I);
6053 // The only type information in the declarator which can come
6054 // before the declaration name is the base type of a member
6055 // pointer.
6056 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6057 continue;
6059 // Rebuild the scope specifier in-place.
6060 CXXScopeSpec &SS = Chunk.Mem.Scope();
6061 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6062 return true;
6065 return false;
6068 /// Returns true if the declaration is declared in a system header or from a
6069 /// system macro.
6070 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6071 return SM.isInSystemHeader(D->getLocation()) ||
6072 SM.isInSystemMacro(D->getLocation());
6075 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6076 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6077 // of system decl.
6078 if (D->getPreviousDecl() || D->isImplicit())
6079 return;
6080 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6081 if (Status != ReservedIdentifierStatus::NotReserved &&
6082 !isFromSystemHeader(Context.getSourceManager(), D)) {
6083 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6084 << D << static_cast<int>(Status);
6088 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6089 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6091 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6092 // declaration only if the `bind_to_declaration` extension is set.
6093 SmallVector<FunctionDecl *, 4> Bases;
6094 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6095 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6096 llvm::omp::TraitProperty::
6097 implementation_extension_bind_to_declaration))
6098 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6099 S, D, MultiTemplateParamsArg(), Bases);
6101 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6103 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6104 Dcl && Dcl->getDeclContext()->isFileContext())
6105 Dcl->setTopLevelDeclInObjCContainer();
6107 if (!Bases.empty())
6108 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
6109 Bases);
6111 return Dcl;
6114 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6115 DeclarationNameInfo NameInfo) {
6116 DeclarationName Name = NameInfo.getName();
6118 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6119 while (Record && Record->isAnonymousStructOrUnion())
6120 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6121 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6122 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6123 return true;
6126 return false;
6129 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6130 DeclarationName Name,
6131 SourceLocation Loc,
6132 TemplateIdAnnotation *TemplateId,
6133 bool IsMemberSpecialization) {
6134 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6135 "without nested-name-specifier");
6136 DeclContext *Cur = CurContext;
6137 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6138 Cur = Cur->getParent();
6140 // If the user provided a superfluous scope specifier that refers back to the
6141 // class in which the entity is already declared, diagnose and ignore it.
6143 // class X {
6144 // void X::f();
6145 // };
6147 // Note, it was once ill-formed to give redundant qualification in all
6148 // contexts, but that rule was removed by DR482.
6149 if (Cur->Equals(DC)) {
6150 if (Cur->isRecord()) {
6151 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6152 : diag::err_member_extra_qualification)
6153 << Name << FixItHint::CreateRemoval(SS.getRange());
6154 SS.clear();
6155 } else {
6156 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6158 return false;
6161 // Check whether the qualifying scope encloses the scope of the original
6162 // declaration. For a template-id, we perform the checks in
6163 // CheckTemplateSpecializationScope.
6164 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6165 if (Cur->isRecord())
6166 Diag(Loc, diag::err_member_qualification)
6167 << Name << SS.getRange();
6168 else if (isa<TranslationUnitDecl>(DC))
6169 Diag(Loc, diag::err_invalid_declarator_global_scope)
6170 << Name << SS.getRange();
6171 else if (isa<FunctionDecl>(Cur))
6172 Diag(Loc, diag::err_invalid_declarator_in_function)
6173 << Name << SS.getRange();
6174 else if (isa<BlockDecl>(Cur))
6175 Diag(Loc, diag::err_invalid_declarator_in_block)
6176 << Name << SS.getRange();
6177 else if (isa<ExportDecl>(Cur)) {
6178 if (!isa<NamespaceDecl>(DC))
6179 Diag(Loc, diag::err_export_non_namespace_scope_name)
6180 << Name << SS.getRange();
6181 else
6182 // The cases that DC is not NamespaceDecl should be handled in
6183 // CheckRedeclarationExported.
6184 return false;
6185 } else
6186 Diag(Loc, diag::err_invalid_declarator_scope)
6187 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6189 return true;
6192 if (Cur->isRecord()) {
6193 // Cannot qualify members within a class.
6194 Diag(Loc, diag::err_member_qualification)
6195 << Name << SS.getRange();
6196 SS.clear();
6198 // C++ constructors and destructors with incorrect scopes can break
6199 // our AST invariants by having the wrong underlying types. If
6200 // that's the case, then drop this declaration entirely.
6201 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6202 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6203 !Context.hasSameType(Name.getCXXNameType(),
6204 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6205 return true;
6207 return false;
6210 // C++23 [temp.names]p5:
6211 // The keyword template shall not appear immediately after a declarative
6212 // nested-name-specifier.
6214 // First check the template-id (if any), and then check each component of the
6215 // nested-name-specifier in reverse order.
6217 // FIXME: nested-name-specifiers in friend declarations are declarative,
6218 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6219 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6220 Diag(Loc, diag::ext_template_after_declarative_nns)
6221 << FixItHint::CreateRemoval(TemplateId->TemplateKWLoc);
6223 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6224 do {
6225 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6226 NestedNameSpecifier::TypeSpecWithTemplate)
6227 Diag(Loc, diag::ext_template_after_declarative_nns)
6228 << FixItHint::CreateRemoval(
6229 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6231 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6232 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6233 // C++23 [expr.prim.id.qual]p3:
6234 // [...] If a nested-name-specifier N is declarative and has a
6235 // simple-template-id with a template argument list A that involves a
6236 // template parameter, let T be the template nominated by N without A.
6237 // T shall be a class template.
6238 if (TST->isDependentType() && TST->isTypeAlias())
6239 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6240 << SpecLoc.getLocalSourceRange();
6241 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6242 // C++23 [expr.prim.id.qual]p2:
6243 // [...] A declarative nested-name-specifier shall not have a
6244 // computed-type-specifier.
6246 // CWG2858 changed this from 'decltype-specifier' to
6247 // 'computed-type-specifier'.
6248 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6249 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6252 } while ((SpecLoc = SpecLoc.getPrefix()));
6254 return false;
6257 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6258 MultiTemplateParamsArg TemplateParamLists) {
6259 // TODO: consider using NameInfo for diagnostic.
6260 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6261 DeclarationName Name = NameInfo.getName();
6263 // All of these full declarators require an identifier. If it doesn't have
6264 // one, the ParsedFreeStandingDeclSpec action should be used.
6265 if (D.isDecompositionDeclarator()) {
6266 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6267 } else if (!Name) {
6268 if (!D.isInvalidType()) // Reject this if we think it is valid.
6269 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6270 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6271 return nullptr;
6272 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6273 return nullptr;
6275 DeclContext *DC = CurContext;
6276 if (D.getCXXScopeSpec().isInvalid())
6277 D.setInvalidType();
6278 else if (D.getCXXScopeSpec().isSet()) {
6279 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6280 UPPC_DeclarationQualifier))
6281 return nullptr;
6283 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6284 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6285 if (!DC || isa<EnumDecl>(DC)) {
6286 // If we could not compute the declaration context, it's because the
6287 // declaration context is dependent but does not refer to a class,
6288 // class template, or class template partial specialization. Complain
6289 // and return early, to avoid the coming semantic disaster.
6290 Diag(D.getIdentifierLoc(),
6291 diag::err_template_qualified_declarator_no_match)
6292 << D.getCXXScopeSpec().getScopeRep()
6293 << D.getCXXScopeSpec().getRange();
6294 return nullptr;
6296 bool IsDependentContext = DC->isDependentContext();
6298 if (!IsDependentContext &&
6299 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6300 return nullptr;
6302 // If a class is incomplete, do not parse entities inside it.
6303 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6304 Diag(D.getIdentifierLoc(),
6305 diag::err_member_def_undefined_record)
6306 << Name << DC << D.getCXXScopeSpec().getRange();
6307 return nullptr;
6309 if (!D.getDeclSpec().isFriendSpecified()) {
6310 TemplateIdAnnotation *TemplateId =
6311 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6312 ? D.getName().TemplateId
6313 : nullptr;
6314 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6315 D.getIdentifierLoc(), TemplateId,
6316 /*IsMemberSpecialization=*/false)) {
6317 if (DC->isRecord())
6318 return nullptr;
6320 D.setInvalidType();
6324 // Check whether we need to rebuild the type of the given
6325 // declaration in the current instantiation.
6326 if (EnteringContext && IsDependentContext &&
6327 TemplateParamLists.size() != 0) {
6328 ContextRAII SavedContext(*this, DC);
6329 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6330 D.setInvalidType();
6334 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6335 QualType R = TInfo->getType();
6337 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6338 UPPC_DeclarationType))
6339 D.setInvalidType();
6341 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6342 forRedeclarationInCurContext());
6344 // See if this is a redefinition of a variable in the same scope.
6345 if (!D.getCXXScopeSpec().isSet()) {
6346 bool IsLinkageLookup = false;
6347 bool CreateBuiltins = false;
6349 // If the declaration we're planning to build will be a function
6350 // or object with linkage, then look for another declaration with
6351 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6353 // If the declaration we're planning to build will be declared with
6354 // external linkage in the translation unit, create any builtin with
6355 // the same name.
6356 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6357 /* Do nothing*/;
6358 else if (CurContext->isFunctionOrMethod() &&
6359 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6360 R->isFunctionType())) {
6361 IsLinkageLookup = true;
6362 CreateBuiltins =
6363 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6364 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6365 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6366 CreateBuiltins = true;
6368 if (IsLinkageLookup) {
6369 Previous.clear(LookupRedeclarationWithLinkage);
6370 Previous.setRedeclarationKind(
6371 RedeclarationKind::ForExternalRedeclaration);
6374 LookupName(Previous, S, CreateBuiltins);
6375 } else { // Something like "int foo::x;"
6376 LookupQualifiedName(Previous, DC);
6378 // C++ [dcl.meaning]p1:
6379 // When the declarator-id is qualified, the declaration shall refer to a
6380 // previously declared member of the class or namespace to which the
6381 // qualifier refers (or, in the case of a namespace, of an element of the
6382 // inline namespace set of that namespace (7.3.1)) or to a specialization
6383 // thereof; [...]
6385 // Note that we already checked the context above, and that we do not have
6386 // enough information to make sure that Previous contains the declaration
6387 // we want to match. For example, given:
6389 // class X {
6390 // void f();
6391 // void f(float);
6392 // };
6394 // void X::f(int) { } // ill-formed
6396 // In this case, Previous will point to the overload set
6397 // containing the two f's declared in X, but neither of them
6398 // matches.
6400 RemoveUsingDecls(Previous);
6403 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6404 TPD && TPD->isTemplateParameter()) {
6405 // Older versions of clang allowed the names of function/variable templates
6406 // to shadow the names of their template parameters. For the compatibility
6407 // purposes we detect such cases and issue a default-to-error warning that
6408 // can be disabled with -Wno-strict-primary-template-shadow.
6409 if (!D.isInvalidType()) {
6410 bool AllowForCompatibility = false;
6411 if (Scope *DeclParent = S->getDeclParent();
6412 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6413 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6414 TemplateParamParent->isDeclScope(TPD);
6416 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6417 AllowForCompatibility);
6420 // Just pretend that we didn't see the previous declaration.
6421 Previous.clear();
6424 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6425 // Forget that the previous declaration is the injected-class-name.
6426 Previous.clear();
6428 // In C++, the previous declaration we find might be a tag type
6429 // (class or enum). In this case, the new declaration will hide the
6430 // tag type. Note that this applies to functions, function templates, and
6431 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6432 if (Previous.isSingleTagDecl() &&
6433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6434 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6435 Previous.clear();
6437 // Check that there are no default arguments other than in the parameters
6438 // of a function declaration (C++ only).
6439 if (getLangOpts().CPlusPlus)
6440 CheckExtraCXXDefaultArguments(D);
6442 /// Get the innermost enclosing declaration scope.
6443 S = S->getDeclParent();
6445 NamedDecl *New;
6447 bool AddToScope = true;
6448 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6449 if (TemplateParamLists.size()) {
6450 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6451 return nullptr;
6454 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6455 } else if (R->isFunctionType()) {
6456 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6457 TemplateParamLists,
6458 AddToScope);
6459 } else {
6460 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6461 AddToScope);
6464 if (!New)
6465 return nullptr;
6467 // If this has an identifier and is not a function template specialization,
6468 // add it to the scope stack.
6469 if (New->getDeclName() && AddToScope)
6470 PushOnScopeChains(New, S);
6472 if (OpenMP().isInOpenMPDeclareTargetContext())
6473 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6475 return New;
6478 /// Helper method to turn variable array types into constant array
6479 /// types in certain situations which would otherwise be errors (for
6480 /// GCC compatibility).
6481 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6482 ASTContext &Context,
6483 bool &SizeIsNegative,
6484 llvm::APSInt &Oversized) {
6485 // This method tries to turn a variable array into a constant
6486 // array even when the size isn't an ICE. This is necessary
6487 // for compatibility with code that depends on gcc's buggy
6488 // constant expression folding, like struct {char x[(int)(char*)2];}
6489 SizeIsNegative = false;
6490 Oversized = 0;
6492 if (T->isDependentType())
6493 return QualType();
6495 QualifierCollector Qs;
6496 const Type *Ty = Qs.strip(T);
6498 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6499 QualType Pointee = PTy->getPointeeType();
6500 QualType FixedType =
6501 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6502 Oversized);
6503 if (FixedType.isNull()) return FixedType;
6504 FixedType = Context.getPointerType(FixedType);
6505 return Qs.apply(Context, FixedType);
6507 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6508 QualType Inner = PTy->getInnerType();
6509 QualType FixedType =
6510 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6511 Oversized);
6512 if (FixedType.isNull()) return FixedType;
6513 FixedType = Context.getParenType(FixedType);
6514 return Qs.apply(Context, FixedType);
6517 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6518 if (!VLATy)
6519 return QualType();
6521 QualType ElemTy = VLATy->getElementType();
6522 if (ElemTy->isVariablyModifiedType()) {
6523 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6524 SizeIsNegative, Oversized);
6525 if (ElemTy.isNull())
6526 return QualType();
6529 Expr::EvalResult Result;
6530 if (!VLATy->getSizeExpr() ||
6531 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6532 return QualType();
6534 llvm::APSInt Res = Result.Val.getInt();
6536 // Check whether the array size is negative.
6537 if (Res.isSigned() && Res.isNegative()) {
6538 SizeIsNegative = true;
6539 return QualType();
6542 // Check whether the array is too large to be addressed.
6543 unsigned ActiveSizeBits =
6544 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6545 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6546 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6547 : Res.getActiveBits();
6548 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6549 Oversized = Res;
6550 return QualType();
6553 QualType FoldedArrayType = Context.getConstantArrayType(
6554 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6555 return Qs.apply(Context, FoldedArrayType);
6558 static void
6559 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6560 SrcTL = SrcTL.getUnqualifiedLoc();
6561 DstTL = DstTL.getUnqualifiedLoc();
6562 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6563 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6564 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6565 DstPTL.getPointeeLoc());
6566 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6567 return;
6569 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6570 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6571 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6572 DstPTL.getInnerLoc());
6573 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6574 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6575 return;
6577 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6578 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6579 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6580 TypeLoc DstElemTL = DstATL.getElementLoc();
6581 if (VariableArrayTypeLoc SrcElemATL =
6582 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6583 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6584 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6585 } else {
6586 DstElemTL.initializeFullCopy(SrcElemTL);
6588 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6589 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6590 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6593 /// Helper method to turn variable array types into constant array
6594 /// types in certain situations which would otherwise be errors (for
6595 /// GCC compatibility).
6596 static TypeSourceInfo*
6597 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6598 ASTContext &Context,
6599 bool &SizeIsNegative,
6600 llvm::APSInt &Oversized) {
6601 QualType FixedTy
6602 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6603 SizeIsNegative, Oversized);
6604 if (FixedTy.isNull())
6605 return nullptr;
6606 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6607 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6608 FixedTInfo->getTypeLoc());
6609 return FixedTInfo;
6612 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6613 QualType &T, SourceLocation Loc,
6614 unsigned FailedFoldDiagID) {
6615 bool SizeIsNegative;
6616 llvm::APSInt Oversized;
6617 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6618 TInfo, Context, SizeIsNegative, Oversized);
6619 if (FixedTInfo) {
6620 Diag(Loc, diag::ext_vla_folded_to_constant);
6621 TInfo = FixedTInfo;
6622 T = FixedTInfo->getType();
6623 return true;
6626 if (SizeIsNegative)
6627 Diag(Loc, diag::err_typecheck_negative_array_size);
6628 else if (Oversized.getBoolValue())
6629 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6630 else if (FailedFoldDiagID)
6631 Diag(Loc, FailedFoldDiagID);
6632 return false;
6635 void
6636 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6637 if (!getLangOpts().CPlusPlus &&
6638 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6639 // Don't need to track declarations in the TU in C.
6640 return;
6642 // Note that we have a locally-scoped external with this name.
6643 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6646 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6647 // FIXME: We can have multiple results via __attribute__((overloadable)).
6648 auto Result = Context.getExternCContextDecl()->lookup(Name);
6649 return Result.empty() ? nullptr : *Result.begin();
6652 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6653 // FIXME: We should probably indicate the identifier in question to avoid
6654 // confusion for constructs like "virtual int a(), b;"
6655 if (DS.isVirtualSpecified())
6656 Diag(DS.getVirtualSpecLoc(),
6657 diag::err_virtual_non_function);
6659 if (DS.hasExplicitSpecifier())
6660 Diag(DS.getExplicitSpecLoc(),
6661 diag::err_explicit_non_function);
6663 if (DS.isNoreturnSpecified())
6664 Diag(DS.getNoreturnSpecLoc(),
6665 diag::err_noreturn_non_function);
6668 NamedDecl*
6669 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6670 TypeSourceInfo *TInfo, LookupResult &Previous) {
6671 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6672 if (D.getCXXScopeSpec().isSet()) {
6673 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6674 << D.getCXXScopeSpec().getRange();
6675 D.setInvalidType();
6676 // Pretend we didn't see the scope specifier.
6677 DC = CurContext;
6678 Previous.clear();
6681 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6683 if (D.getDeclSpec().isInlineSpecified())
6684 Diag(D.getDeclSpec().getInlineSpecLoc(),
6685 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6686 ? diag::warn_ms_inline_non_function
6687 : diag::err_inline_non_function)
6688 << getLangOpts().CPlusPlus17;
6689 if (D.getDeclSpec().hasConstexprSpecifier())
6690 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6691 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6693 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6694 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6695 Diag(D.getName().StartLocation,
6696 diag::err_deduction_guide_invalid_specifier)
6697 << "typedef";
6698 else
6699 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6700 << D.getName().getSourceRange();
6701 return nullptr;
6704 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6705 if (!NewTD) return nullptr;
6707 // Handle attributes prior to checking for duplicates in MergeVarDecl
6708 ProcessDeclAttributes(S, NewTD, D);
6710 CheckTypedefForVariablyModifiedType(S, NewTD);
6712 bool Redeclaration = D.isRedeclaration();
6713 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6714 D.setRedeclaration(Redeclaration);
6715 return ND;
6718 void
6719 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6720 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6721 // then it shall have block scope.
6722 // Note that variably modified types must be fixed before merging the decl so
6723 // that redeclarations will match.
6724 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6725 QualType T = TInfo->getType();
6726 if (T->isVariablyModifiedType()) {
6727 setFunctionHasBranchProtectedScope();
6729 if (S->getFnParent() == nullptr) {
6730 bool SizeIsNegative;
6731 llvm::APSInt Oversized;
6732 TypeSourceInfo *FixedTInfo =
6733 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6734 SizeIsNegative,
6735 Oversized);
6736 if (FixedTInfo) {
6737 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6738 NewTD->setTypeSourceInfo(FixedTInfo);
6739 } else {
6740 if (SizeIsNegative)
6741 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6742 else if (T->isVariableArrayType())
6743 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6744 else if (Oversized.getBoolValue())
6745 Diag(NewTD->getLocation(), diag::err_array_too_large)
6746 << toString(Oversized, 10);
6747 else
6748 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6749 NewTD->setInvalidDecl();
6755 NamedDecl*
6756 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6757 LookupResult &Previous, bool &Redeclaration) {
6759 // Find the shadowed declaration before filtering for scope.
6760 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6762 // Merge the decl with the existing one if appropriate. If the decl is
6763 // in an outer scope, it isn't the same thing.
6764 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6765 /*AllowInlineNamespace*/false);
6766 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6767 if (!Previous.empty()) {
6768 Redeclaration = true;
6769 MergeTypedefNameDecl(S, NewTD, Previous);
6770 } else {
6771 inferGslPointerAttribute(NewTD);
6774 if (ShadowedDecl && !Redeclaration)
6775 CheckShadow(NewTD, ShadowedDecl, Previous);
6777 // If this is the C FILE type, notify the AST context.
6778 if (IdentifierInfo *II = NewTD->getIdentifier())
6779 if (!NewTD->isInvalidDecl() &&
6780 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6781 switch (II->getNotableIdentifierID()) {
6782 case tok::NotableIdentifierKind::FILE:
6783 Context.setFILEDecl(NewTD);
6784 break;
6785 case tok::NotableIdentifierKind::jmp_buf:
6786 Context.setjmp_bufDecl(NewTD);
6787 break;
6788 case tok::NotableIdentifierKind::sigjmp_buf:
6789 Context.setsigjmp_bufDecl(NewTD);
6790 break;
6791 case tok::NotableIdentifierKind::ucontext_t:
6792 Context.setucontext_tDecl(NewTD);
6793 break;
6794 case tok::NotableIdentifierKind::float_t:
6795 case tok::NotableIdentifierKind::double_t:
6796 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6797 break;
6798 default:
6799 break;
6803 return NewTD;
6806 /// Determines whether the given declaration is an out-of-scope
6807 /// previous declaration.
6809 /// This routine should be invoked when name lookup has found a
6810 /// previous declaration (PrevDecl) that is not in the scope where a
6811 /// new declaration by the same name is being introduced. If the new
6812 /// declaration occurs in a local scope, previous declarations with
6813 /// linkage may still be considered previous declarations (C99
6814 /// 6.2.2p4-5, C++ [basic.link]p6).
6816 /// \param PrevDecl the previous declaration found by name
6817 /// lookup
6819 /// \param DC the context in which the new declaration is being
6820 /// declared.
6822 /// \returns true if PrevDecl is an out-of-scope previous declaration
6823 /// for a new delcaration with the same name.
6824 static bool
6825 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6826 ASTContext &Context) {
6827 if (!PrevDecl)
6828 return false;
6830 if (!PrevDecl->hasLinkage())
6831 return false;
6833 if (Context.getLangOpts().CPlusPlus) {
6834 // C++ [basic.link]p6:
6835 // If there is a visible declaration of an entity with linkage
6836 // having the same name and type, ignoring entities declared
6837 // outside the innermost enclosing namespace scope, the block
6838 // scope declaration declares that same entity and receives the
6839 // linkage of the previous declaration.
6840 DeclContext *OuterContext = DC->getRedeclContext();
6841 if (!OuterContext->isFunctionOrMethod())
6842 // This rule only applies to block-scope declarations.
6843 return false;
6845 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6846 if (PrevOuterContext->isRecord())
6847 // We found a member function: ignore it.
6848 return false;
6850 // Find the innermost enclosing namespace for the new and
6851 // previous declarations.
6852 OuterContext = OuterContext->getEnclosingNamespaceContext();
6853 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6855 // The previous declaration is in a different namespace, so it
6856 // isn't the same function.
6857 if (!OuterContext->Equals(PrevOuterContext))
6858 return false;
6861 return true;
6864 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6865 CXXScopeSpec &SS = D.getCXXScopeSpec();
6866 if (!SS.isSet()) return;
6867 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6870 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6871 if (Decl->getType().hasAddressSpace())
6872 return;
6873 if (Decl->getType()->isDependentType())
6874 return;
6875 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6876 QualType Type = Var->getType();
6877 if (Type->isSamplerT() || Type->isVoidType())
6878 return;
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 checkWeakAttr(Sema &S, NamedDecl &ND) {
6912 // 'weak' only applies to declarations with external linkage.
6913 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6914 if (!ND.isExternallyVisible()) {
6915 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6916 ND.dropAttr<WeakAttr>();
6921 static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6922 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6923 if (ND.isExternallyVisible()) {
6924 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6925 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6930 static void checkAliasAttr(Sema &S, NamedDecl &ND) {
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>();
6943 static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
6944 // 'selectany' only applies to externally visible variable declarations.
6945 // It does not apply to functions.
6946 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6947 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6948 S.Diag(Attr->getLocation(),
6949 diag::err_attribute_selectany_non_extern_data);
6950 ND.dropAttr<SelectAnyAttr>();
6955 static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
6956 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6957 if (!ND.isExternallyVisible())
6958 S.Diag(Attr->getLocation(),
6959 diag::warn_attribute_hybrid_patchable_non_extern);
6963 static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
6964 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6965 auto *VD = dyn_cast<VarDecl>(&ND);
6966 bool IsAnonymousNS = false;
6967 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6968 if (VD) {
6969 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6970 while (NS && !IsAnonymousNS) {
6971 IsAnonymousNS = NS->isAnonymousNamespace();
6972 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6975 // dll attributes require external linkage. Static locals may have external
6976 // linkage but still cannot be explicitly imported or exported.
6977 // In Microsoft mode, a variable defined in anonymous namespace must have
6978 // external linkage in order to be exported.
6979 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6980 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6981 (!AnonNSInMicrosoftMode &&
6982 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6983 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6984 << &ND << Attr;
6985 ND.setInvalidDecl();
6990 static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
6991 // Check the attributes on the function type and function params, if any.
6992 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6993 FD = FD->getMostRecentDecl();
6994 // Don't declare this variable in the second operand of the for-statement;
6995 // GCC miscompiles that by ending its lifetime before evaluating the
6996 // third operand. See gcc.gnu.org/PR86769.
6997 AttributedTypeLoc ATL;
6998 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6999 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7000 TL = ATL.getModifiedLoc()) {
7001 // The [[lifetimebound]] attribute can be applied to the implicit object
7002 // parameter of a non-static member function (other than a ctor or dtor)
7003 // by applying it to the function type.
7004 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7005 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7006 int NoImplicitObjectError = -1;
7007 if (!MD)
7008 NoImplicitObjectError = 0;
7009 else if (MD->isStatic())
7010 NoImplicitObjectError = 1;
7011 else if (MD->isExplicitObjectMemberFunction())
7012 NoImplicitObjectError = 2;
7013 if (NoImplicitObjectError != -1) {
7014 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7015 << NoImplicitObjectError << A->getRange();
7016 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7017 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7018 << isa<CXXDestructorDecl>(MD) << A->getRange();
7019 } else if (MD->getReturnType()->isVoidType()) {
7020 S.Diag(
7021 MD->getLocation(),
7022 diag::
7023 err_lifetimebound_implicit_object_parameter_void_return_type);
7028 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7029 const ParmVarDecl *P = FD->getParamDecl(I);
7031 // The [[lifetimebound]] attribute can be applied to a function parameter
7032 // only if the function returns a value.
7033 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7034 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7035 S.Diag(A->getLocation(),
7036 diag::err_lifetimebound_parameter_void_return_type);
7043 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7044 // Ensure that an auto decl is deduced otherwise the checks below might cache
7045 // the wrong linkage.
7046 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7048 checkWeakAttr(S, ND);
7049 checkWeakRefAttr(S, ND);
7050 checkAliasAttr(S, ND);
7051 checkSelectAnyAttr(S, ND);
7052 checkHybridPatchableAttr(S, ND);
7053 checkInheritableAttr(S, ND);
7054 checkLifetimeBoundAttr(S, ND);
7057 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7058 NamedDecl *NewDecl,
7059 bool IsSpecialization,
7060 bool IsDefinition) {
7061 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7062 return;
7064 bool IsTemplate = false;
7065 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7066 OldDecl = OldTD->getTemplatedDecl();
7067 IsTemplate = true;
7068 if (!IsSpecialization)
7069 IsDefinition = false;
7071 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7072 NewDecl = NewTD->getTemplatedDecl();
7073 IsTemplate = true;
7076 if (!OldDecl || !NewDecl)
7077 return;
7079 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7080 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7081 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7082 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7084 // dllimport and dllexport are inheritable attributes so we have to exclude
7085 // inherited attribute instances.
7086 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7087 (NewExportAttr && !NewExportAttr->isInherited());
7089 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7090 // the only exception being explicit specializations.
7091 // Implicitly generated declarations are also excluded for now because there
7092 // is no other way to switch these to use dllimport or dllexport.
7093 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7095 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7096 // Allow with a warning for free functions and global variables.
7097 bool JustWarn = false;
7098 if (!OldDecl->isCXXClassMember()) {
7099 auto *VD = dyn_cast<VarDecl>(OldDecl);
7100 if (VD && !VD->getDescribedVarTemplate())
7101 JustWarn = true;
7102 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7103 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7104 JustWarn = true;
7107 // We cannot change a declaration that's been used because IR has already
7108 // been emitted. Dllimported functions will still work though (modulo
7109 // address equality) as they can use the thunk.
7110 if (OldDecl->isUsed())
7111 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7112 JustWarn = false;
7114 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7115 : diag::err_attribute_dll_redeclaration;
7116 S.Diag(NewDecl->getLocation(), DiagID)
7117 << NewDecl
7118 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7119 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7120 if (!JustWarn) {
7121 NewDecl->setInvalidDecl();
7122 return;
7126 // A redeclaration is not allowed to drop a dllimport attribute, the only
7127 // exceptions being inline function definitions (except for function
7128 // templates), local extern declarations, qualified friend declarations or
7129 // special MSVC extension: in the last case, the declaration is treated as if
7130 // it were marked dllexport.
7131 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7132 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7133 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7134 // Ignore static data because out-of-line definitions are diagnosed
7135 // separately.
7136 IsStaticDataMember = VD->isStaticDataMember();
7137 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7138 VarDecl::DeclarationOnly;
7139 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7140 IsInline = FD->isInlined();
7141 IsQualifiedFriend = FD->getQualifier() &&
7142 FD->getFriendObjectKind() == Decl::FOK_Declared;
7145 if (OldImportAttr && !HasNewAttr &&
7146 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7147 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7148 if (IsMicrosoftABI && IsDefinition) {
7149 if (IsSpecialization) {
7150 S.Diag(
7151 NewDecl->getLocation(),
7152 diag::err_attribute_dllimport_function_specialization_definition);
7153 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7154 NewDecl->dropAttr<DLLImportAttr>();
7155 } else {
7156 S.Diag(NewDecl->getLocation(),
7157 diag::warn_redeclaration_without_import_attribute)
7158 << NewDecl;
7159 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7160 NewDecl->dropAttr<DLLImportAttr>();
7161 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7162 S.Context, NewImportAttr->getRange()));
7164 } else if (IsMicrosoftABI && IsSpecialization) {
7165 assert(!IsDefinition);
7166 // MSVC allows this. Keep the inherited attribute.
7167 } else {
7168 S.Diag(NewDecl->getLocation(),
7169 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7170 << NewDecl << OldImportAttr;
7171 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7172 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7173 OldDecl->dropAttr<DLLImportAttr>();
7174 NewDecl->dropAttr<DLLImportAttr>();
7176 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7177 // In MinGW, seeing a function declared inline drops the dllimport
7178 // attribute.
7179 OldDecl->dropAttr<DLLImportAttr>();
7180 NewDecl->dropAttr<DLLImportAttr>();
7181 S.Diag(NewDecl->getLocation(),
7182 diag::warn_dllimport_dropped_from_inline_function)
7183 << NewDecl << OldImportAttr;
7186 // A specialization of a class template member function is processed here
7187 // since it's a redeclaration. If the parent class is dllexport, the
7188 // specialization inherits that attribute. This doesn't happen automatically
7189 // since the parent class isn't instantiated until later.
7190 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7191 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7192 !NewImportAttr && !NewExportAttr) {
7193 if (const DLLExportAttr *ParentExportAttr =
7194 MD->getParent()->getAttr<DLLExportAttr>()) {
7195 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7196 NewAttr->setInherited(true);
7197 NewDecl->addAttr(NewAttr);
7203 /// Given that we are within the definition of the given function,
7204 /// will that definition behave like C99's 'inline', where the
7205 /// definition is discarded except for optimization purposes?
7206 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7207 // Try to avoid calling GetGVALinkageForFunction.
7209 // All cases of this require the 'inline' keyword.
7210 if (!FD->isInlined()) return false;
7212 // This is only possible in C++ with the gnu_inline attribute.
7213 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7214 return false;
7216 // Okay, go ahead and call the relatively-more-expensive function.
7217 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7220 /// Determine whether a variable is extern "C" prior to attaching
7221 /// an initializer. We can't just call isExternC() here, because that
7222 /// will also compute and cache whether the declaration is externally
7223 /// visible, which might change when we attach the initializer.
7225 /// This can only be used if the declaration is known to not be a
7226 /// redeclaration of an internal linkage declaration.
7228 /// For instance:
7230 /// auto x = []{};
7232 /// Attaching the initializer here makes this declaration not externally
7233 /// visible, because its type has internal linkage.
7235 /// FIXME: This is a hack.
7236 template<typename T>
7237 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7238 if (S.getLangOpts().CPlusPlus) {
7239 // In C++, the overloadable attribute negates the effects of extern "C".
7240 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7241 return false;
7243 // So do CUDA's host/device attributes.
7244 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7245 D->template hasAttr<CUDAHostAttr>()))
7246 return false;
7248 return D->isExternC();
7251 static bool shouldConsiderLinkage(const VarDecl *VD) {
7252 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7253 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7254 isa<OMPDeclareMapperDecl>(DC))
7255 return VD->hasExternalStorage();
7256 if (DC->isFileContext())
7257 return true;
7258 if (DC->isRecord())
7259 return false;
7260 if (DC->getDeclKind() == Decl::HLSLBuffer)
7261 return false;
7263 if (isa<RequiresExprBodyDecl>(DC))
7264 return false;
7265 llvm_unreachable("Unexpected context");
7268 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7269 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7270 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7271 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7272 return true;
7273 if (DC->isRecord())
7274 return false;
7275 llvm_unreachable("Unexpected context");
7278 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7279 ParsedAttr::Kind Kind) {
7280 // Check decl attributes on the DeclSpec.
7281 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7282 return true;
7284 // Walk the declarator structure, checking decl attributes that were in a type
7285 // position to the decl itself.
7286 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7287 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7288 return true;
7291 // Finally, check attributes on the decl itself.
7292 return PD.getAttributes().hasAttribute(Kind) ||
7293 PD.getDeclarationAttributes().hasAttribute(Kind);
7296 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7297 if (!DC->isFunctionOrMethod())
7298 return false;
7300 // If this is a local extern function or variable declared within a function
7301 // template, don't add it into the enclosing namespace scope until it is
7302 // instantiated; it might have a dependent type right now.
7303 if (DC->isDependentContext())
7304 return true;
7306 // C++11 [basic.link]p7:
7307 // When a block scope declaration of an entity with linkage is not found to
7308 // refer to some other declaration, then that entity is a member of the
7309 // innermost enclosing namespace.
7311 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7312 // semantically-enclosing namespace, not a lexically-enclosing one.
7313 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7314 DC = DC->getParent();
7315 return true;
7318 /// Returns true if given declaration has external C language linkage.
7319 static bool isDeclExternC(const Decl *D) {
7320 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7321 return FD->isExternC();
7322 if (const auto *VD = dyn_cast<VarDecl>(D))
7323 return VD->isExternC();
7325 llvm_unreachable("Unknown type of decl!");
7328 /// Returns true if there hasn't been any invalid type diagnosed.
7329 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7330 DeclContext *DC = NewVD->getDeclContext();
7331 QualType R = NewVD->getType();
7333 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7334 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7335 // argument.
7336 if (R->isImageType() || R->isPipeType()) {
7337 Se.Diag(NewVD->getLocation(),
7338 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7339 << R;
7340 NewVD->setInvalidDecl();
7341 return false;
7344 // OpenCL v1.2 s6.9.r:
7345 // The event type cannot be used to declare a program scope variable.
7346 // OpenCL v2.0 s6.9.q:
7347 // The clk_event_t and reserve_id_t types cannot be declared in program
7348 // scope.
7349 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7350 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7351 Se.Diag(NewVD->getLocation(),
7352 diag::err_invalid_type_for_program_scope_var)
7353 << R;
7354 NewVD->setInvalidDecl();
7355 return false;
7359 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7360 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7361 Se.getLangOpts())) {
7362 QualType NR = R.getCanonicalType();
7363 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7364 NR->isReferenceType()) {
7365 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7366 NR->isFunctionReferenceType()) {
7367 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7368 << NR->isReferenceType();
7369 NewVD->setInvalidDecl();
7370 return false;
7372 NR = NR->getPointeeType();
7376 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7377 Se.getLangOpts())) {
7378 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7379 // half array type (unless the cl_khr_fp16 extension is enabled).
7380 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7381 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7382 NewVD->setInvalidDecl();
7383 return false;
7387 // OpenCL v1.2 s6.9.r:
7388 // The event type cannot be used with the __local, __constant and __global
7389 // address space qualifiers.
7390 if (R->isEventT()) {
7391 if (R.getAddressSpace() != LangAS::opencl_private) {
7392 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7393 NewVD->setInvalidDecl();
7394 return false;
7398 if (R->isSamplerT()) {
7399 // OpenCL v1.2 s6.9.b p4:
7400 // The sampler type cannot be used with the __local and __global address
7401 // space qualifiers.
7402 if (R.getAddressSpace() == LangAS::opencl_local ||
7403 R.getAddressSpace() == LangAS::opencl_global) {
7404 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7405 NewVD->setInvalidDecl();
7408 // OpenCL v1.2 s6.12.14.1:
7409 // A global sampler must be declared with either the constant address
7410 // space qualifier or with the const qualifier.
7411 if (DC->isTranslationUnit() &&
7412 !(R.getAddressSpace() == LangAS::opencl_constant ||
7413 R.isConstQualified())) {
7414 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7415 NewVD->setInvalidDecl();
7417 if (NewVD->isInvalidDecl())
7418 return false;
7421 return true;
7424 template <typename AttrTy>
7425 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7426 const TypedefNameDecl *TND = TT->getDecl();
7427 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7428 AttrTy *Clone = Attribute->clone(S.Context);
7429 Clone->setInherited(true);
7430 D->addAttr(Clone);
7434 // This function emits warning and a corresponding note based on the
7435 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7436 // declarations of an annotated type must be const qualified.
7437 static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7438 QualType VarType = VD->getType().getCanonicalType();
7440 // Ignore local declarations (for now) and those with const qualification.
7441 // TODO: Local variables should not be allowed if their type declaration has
7442 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7443 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7444 return;
7446 if (VarType->isArrayType()) {
7447 // Retrieve element type for array declarations.
7448 VarType = S.getASTContext().getBaseElementType(VarType);
7451 const RecordDecl *RD = VarType->getAsRecordDecl();
7453 // Check if the record declaration is present and if it has any attributes.
7454 if (RD == nullptr)
7455 return;
7457 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7458 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7459 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7460 return;
7464 // Checks if VD is declared at global scope or with C language linkage.
7465 static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7466 return Name.getAsIdentifierInfo() &&
7467 Name.getAsIdentifierInfo()->isStr("main") &&
7468 !VD->getDescribedVarTemplate() &&
7469 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7470 VD->isExternC());
7473 NamedDecl *Sema::ActOnVariableDeclarator(
7474 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7475 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7476 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7477 QualType R = TInfo->getType();
7478 DeclarationName Name = GetNameForDeclarator(D).getName();
7480 IdentifierInfo *II = Name.getAsIdentifierInfo();
7481 bool IsPlaceholderVariable = false;
7483 if (D.isDecompositionDeclarator()) {
7484 // Take the name of the first declarator as our name for diagnostic
7485 // purposes.
7486 auto &Decomp = D.getDecompositionDeclarator();
7487 if (!Decomp.bindings().empty()) {
7488 II = Decomp.bindings()[0].Name;
7489 Name = II;
7491 } else if (!II) {
7492 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7493 return nullptr;
7497 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7498 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7500 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7501 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7502 IsPlaceholderVariable = true;
7503 if (!Previous.empty()) {
7504 NamedDecl *PrevDecl = *Previous.begin();
7505 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7506 DC->getRedeclContext());
7507 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7508 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7512 // dllimport globals without explicit storage class are treated as extern. We
7513 // have to change the storage class this early to get the right DeclContext.
7514 if (SC == SC_None && !DC->isRecord() &&
7515 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7516 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7517 SC = SC_Extern;
7519 DeclContext *OriginalDC = DC;
7520 bool IsLocalExternDecl = SC == SC_Extern &&
7521 adjustContextForLocalExternDecl(DC);
7523 if (SCSpec == DeclSpec::SCS_mutable) {
7524 // mutable can only appear on non-static class members, so it's always
7525 // an error here
7526 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7527 D.setInvalidType();
7528 SC = SC_None;
7531 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7532 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7533 D.getDeclSpec().getStorageClassSpecLoc())) {
7534 // In C++11, the 'register' storage class specifier is deprecated.
7535 // Suppress the warning in system macros, it's used in macros in some
7536 // popular C system headers, such as in glibc's htonl() macro.
7537 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7538 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7539 : diag::warn_deprecated_register)
7540 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7543 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7545 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7546 // C99 6.9p2: The storage-class specifiers auto and register shall not
7547 // appear in the declaration specifiers in an external declaration.
7548 // Global Register+Asm is a GNU extension we support.
7549 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7550 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7551 D.setInvalidType();
7555 // If this variable has a VLA type and an initializer, try to
7556 // fold to a constant-sized type. This is otherwise invalid.
7557 if (D.hasInitializer() && R->isVariableArrayType())
7558 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7559 /*DiagID=*/0);
7561 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7562 const AutoType *AT = TL.getTypePtr();
7563 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7566 bool IsMemberSpecialization = false;
7567 bool IsVariableTemplateSpecialization = false;
7568 bool IsPartialSpecialization = false;
7569 bool IsVariableTemplate = false;
7570 VarDecl *NewVD = nullptr;
7571 VarTemplateDecl *NewTemplate = nullptr;
7572 TemplateParameterList *TemplateParams = nullptr;
7573 if (!getLangOpts().CPlusPlus) {
7574 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7575 II, R, TInfo, SC);
7577 if (R->getContainedDeducedType())
7578 ParsingInitForAutoVars.insert(NewVD);
7580 if (D.isInvalidType())
7581 NewVD->setInvalidDecl();
7583 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7584 NewVD->hasLocalStorage())
7585 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7586 NTCUC_AutoVar, NTCUK_Destruct);
7587 } else {
7588 bool Invalid = false;
7589 // Match up the template parameter lists with the scope specifier, then
7590 // determine whether we have a template or a template specialization.
7591 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7592 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7593 D.getCXXScopeSpec(),
7594 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7595 ? D.getName().TemplateId
7596 : nullptr,
7597 TemplateParamLists,
7598 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7600 if (TemplateParams) {
7601 if (DC->isDependentContext()) {
7602 ContextRAII SavedContext(*this, DC);
7603 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7604 Invalid = true;
7607 if (!TemplateParams->size() &&
7608 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7609 // There is an extraneous 'template<>' for this variable. Complain
7610 // about it, but allow the declaration of the variable.
7611 Diag(TemplateParams->getTemplateLoc(),
7612 diag::err_template_variable_noparams)
7613 << II
7614 << SourceRange(TemplateParams->getTemplateLoc(),
7615 TemplateParams->getRAngleLoc());
7616 TemplateParams = nullptr;
7617 } else {
7618 // Check that we can declare a template here.
7619 if (CheckTemplateDeclScope(S, TemplateParams))
7620 return nullptr;
7622 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7623 // This is an explicit specialization or a partial specialization.
7624 IsVariableTemplateSpecialization = true;
7625 IsPartialSpecialization = TemplateParams->size() > 0;
7626 } else { // if (TemplateParams->size() > 0)
7627 // This is a template declaration.
7628 IsVariableTemplate = true;
7630 // Only C++1y supports variable templates (N3651).
7631 Diag(D.getIdentifierLoc(),
7632 getLangOpts().CPlusPlus14
7633 ? diag::warn_cxx11_compat_variable_template
7634 : diag::ext_variable_template);
7637 } else {
7638 // Check that we can declare a member specialization here.
7639 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7640 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7641 return nullptr;
7642 assert((Invalid ||
7643 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7644 "should have a 'template<>' for this decl");
7647 bool IsExplicitSpecialization =
7648 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7650 // C++ [temp.expl.spec]p2:
7651 // The declaration in an explicit-specialization shall not be an
7652 // export-declaration. An explicit specialization shall not use a
7653 // storage-class-specifier other than thread_local.
7655 // We use the storage-class-specifier from DeclSpec because we may have
7656 // added implicit 'extern' for declarations with __declspec(dllimport)!
7657 if (SCSpec != DeclSpec::SCS_unspecified &&
7658 (IsExplicitSpecialization || IsMemberSpecialization)) {
7659 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7660 diag::ext_explicit_specialization_storage_class)
7661 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7664 if (CurContext->isRecord()) {
7665 if (SC == SC_Static) {
7666 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7667 // Walk up the enclosing DeclContexts to check for any that are
7668 // incompatible with static data members.
7669 const DeclContext *FunctionOrMethod = nullptr;
7670 const CXXRecordDecl *AnonStruct = nullptr;
7671 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7672 if (Ctxt->isFunctionOrMethod()) {
7673 FunctionOrMethod = Ctxt;
7674 break;
7676 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7677 if (ParentDecl && !ParentDecl->getDeclName()) {
7678 AnonStruct = ParentDecl;
7679 break;
7682 if (FunctionOrMethod) {
7683 // C++ [class.static.data]p5: A local class shall not have static
7684 // data members.
7685 Diag(D.getIdentifierLoc(),
7686 diag::err_static_data_member_not_allowed_in_local_class)
7687 << Name << RD->getDeclName()
7688 << llvm::to_underlying(RD->getTagKind());
7689 } else if (AnonStruct) {
7690 // C++ [class.static.data]p4: Unnamed classes and classes contained
7691 // directly or indirectly within unnamed classes shall not contain
7692 // static data members.
7693 Diag(D.getIdentifierLoc(),
7694 diag::err_static_data_member_not_allowed_in_anon_struct)
7695 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7696 Invalid = true;
7697 } else if (RD->isUnion()) {
7698 // C++98 [class.union]p1: If a union contains a static data member,
7699 // the program is ill-formed. C++11 drops this restriction.
7700 Diag(D.getIdentifierLoc(),
7701 getLangOpts().CPlusPlus11
7702 ? diag::warn_cxx98_compat_static_data_member_in_union
7703 : diag::ext_static_data_member_in_union)
7704 << Name;
7707 } else if (IsVariableTemplate || IsPartialSpecialization) {
7708 // There is no such thing as a member field template.
7709 Diag(D.getIdentifierLoc(), diag::err_template_member)
7710 << II << TemplateParams->getSourceRange();
7711 // Recover by pretending this is a static data member template.
7712 SC = SC_Static;
7714 } else if (DC->isRecord()) {
7715 // This is an out-of-line definition of a static data member.
7716 switch (SC) {
7717 case SC_None:
7718 break;
7719 case SC_Static:
7720 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7721 diag::err_static_out_of_line)
7722 << FixItHint::CreateRemoval(
7723 D.getDeclSpec().getStorageClassSpecLoc());
7724 break;
7725 case SC_Auto:
7726 case SC_Register:
7727 case SC_Extern:
7728 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7729 // to names of variables declared in a block or to function parameters.
7730 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7731 // of class members
7733 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7734 diag::err_storage_class_for_static_member)
7735 << FixItHint::CreateRemoval(
7736 D.getDeclSpec().getStorageClassSpecLoc());
7737 break;
7738 case SC_PrivateExtern:
7739 llvm_unreachable("C storage class in c++!");
7743 if (IsVariableTemplateSpecialization) {
7744 SourceLocation TemplateKWLoc =
7745 TemplateParamLists.size() > 0
7746 ? TemplateParamLists[0]->getTemplateLoc()
7747 : SourceLocation();
7748 DeclResult Res = ActOnVarTemplateSpecialization(
7749 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7750 IsPartialSpecialization);
7751 if (Res.isInvalid())
7752 return nullptr;
7753 NewVD = cast<VarDecl>(Res.get());
7754 AddToScope = false;
7755 } else if (D.isDecompositionDeclarator()) {
7756 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7757 D.getIdentifierLoc(), R, TInfo, SC,
7758 Bindings);
7759 } else
7760 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7761 D.getIdentifierLoc(), II, R, TInfo, SC);
7763 // If this is supposed to be a variable template, create it as such.
7764 if (IsVariableTemplate) {
7765 NewTemplate =
7766 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7767 TemplateParams, NewVD);
7768 NewVD->setDescribedVarTemplate(NewTemplate);
7771 // If this decl has an auto type in need of deduction, make a note of the
7772 // Decl so we can diagnose uses of it in its own initializer.
7773 if (R->getContainedDeducedType())
7774 ParsingInitForAutoVars.insert(NewVD);
7776 if (D.isInvalidType() || Invalid) {
7777 NewVD->setInvalidDecl();
7778 if (NewTemplate)
7779 NewTemplate->setInvalidDecl();
7782 SetNestedNameSpecifier(*this, NewVD, D);
7784 // If we have any template parameter lists that don't directly belong to
7785 // the variable (matching the scope specifier), store them.
7786 // An explicit variable template specialization does not own any template
7787 // parameter lists.
7788 unsigned VDTemplateParamLists =
7789 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7790 if (TemplateParamLists.size() > VDTemplateParamLists)
7791 NewVD->setTemplateParameterListsInfo(
7792 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7795 if (D.getDeclSpec().isInlineSpecified()) {
7796 if (!getLangOpts().CPlusPlus) {
7797 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7798 << 0;
7799 } else if (CurContext->isFunctionOrMethod()) {
7800 // 'inline' is not allowed on block scope variable declaration.
7801 Diag(D.getDeclSpec().getInlineSpecLoc(),
7802 diag::err_inline_declaration_block_scope) << Name
7803 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7804 } else {
7805 Diag(D.getDeclSpec().getInlineSpecLoc(),
7806 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7807 : diag::ext_inline_variable);
7808 NewVD->setInlineSpecified();
7812 // Set the lexical context. If the declarator has a C++ scope specifier, the
7813 // lexical context will be different from the semantic context.
7814 NewVD->setLexicalDeclContext(CurContext);
7815 if (NewTemplate)
7816 NewTemplate->setLexicalDeclContext(CurContext);
7818 if (IsLocalExternDecl) {
7819 if (D.isDecompositionDeclarator())
7820 for (auto *B : Bindings)
7821 B->setLocalExternDecl();
7822 else
7823 NewVD->setLocalExternDecl();
7826 bool EmitTLSUnsupportedError = false;
7827 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7828 // C++11 [dcl.stc]p4:
7829 // When thread_local is applied to a variable of block scope the
7830 // storage-class-specifier static is implied if it does not appear
7831 // explicitly.
7832 // Core issue: 'static' is not implied if the variable is declared
7833 // 'extern'.
7834 if (NewVD->hasLocalStorage() &&
7835 (SCSpec != DeclSpec::SCS_unspecified ||
7836 TSCS != DeclSpec::TSCS_thread_local ||
7837 !DC->isFunctionOrMethod()))
7838 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7839 diag::err_thread_non_global)
7840 << DeclSpec::getSpecifierName(TSCS);
7841 else if (!Context.getTargetInfo().isTLSSupported()) {
7842 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7843 getLangOpts().SYCLIsDevice) {
7844 // Postpone error emission until we've collected attributes required to
7845 // figure out whether it's a host or device variable and whether the
7846 // error should be ignored.
7847 EmitTLSUnsupportedError = true;
7848 // We still need to mark the variable as TLS so it shows up in AST with
7849 // proper storage class for other tools to use even if we're not going
7850 // to emit any code for it.
7851 NewVD->setTSCSpec(TSCS);
7852 } else
7853 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7854 diag::err_thread_unsupported);
7855 } else
7856 NewVD->setTSCSpec(TSCS);
7859 switch (D.getDeclSpec().getConstexprSpecifier()) {
7860 case ConstexprSpecKind::Unspecified:
7861 break;
7863 case ConstexprSpecKind::Consteval:
7864 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7865 diag::err_constexpr_wrong_decl_kind)
7866 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7867 [[fallthrough]];
7869 case ConstexprSpecKind::Constexpr:
7870 NewVD->setConstexpr(true);
7871 // C++1z [dcl.spec.constexpr]p1:
7872 // A static data member declared with the constexpr specifier is
7873 // implicitly an inline variable.
7874 if (NewVD->isStaticDataMember() &&
7875 (getLangOpts().CPlusPlus17 ||
7876 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7877 NewVD->setImplicitlyInline();
7878 break;
7880 case ConstexprSpecKind::Constinit:
7881 if (!NewVD->hasGlobalStorage())
7882 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7883 diag::err_constinit_local_variable);
7884 else
7885 NewVD->addAttr(
7886 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7887 ConstInitAttr::Keyword_constinit));
7888 break;
7891 // C99 6.7.4p3
7892 // An inline definition of a function with external linkage shall
7893 // not contain a definition of a modifiable object with static or
7894 // thread storage duration...
7895 // We only apply this when the function is required to be defined
7896 // elsewhere, i.e. when the function is not 'extern inline'. Note
7897 // that a local variable with thread storage duration still has to
7898 // be marked 'static'. Also note that it's possible to get these
7899 // semantics in C++ using __attribute__((gnu_inline)).
7900 if (SC == SC_Static && S->getFnParent() != nullptr &&
7901 !NewVD->getType().isConstQualified()) {
7902 FunctionDecl *CurFD = getCurFunctionDecl();
7903 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7904 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7905 diag::warn_static_local_in_extern_inline);
7906 MaybeSuggestAddingStaticToDecl(CurFD);
7910 if (D.getDeclSpec().isModulePrivateSpecified()) {
7911 if (IsVariableTemplateSpecialization)
7912 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7913 << (IsPartialSpecialization ? 1 : 0)
7914 << FixItHint::CreateRemoval(
7915 D.getDeclSpec().getModulePrivateSpecLoc());
7916 else if (IsMemberSpecialization)
7917 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7918 << 2
7919 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7920 else if (NewVD->hasLocalStorage())
7921 Diag(NewVD->getLocation(), diag::err_module_private_local)
7922 << 0 << NewVD
7923 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7924 << FixItHint::CreateRemoval(
7925 D.getDeclSpec().getModulePrivateSpecLoc());
7926 else {
7927 NewVD->setModulePrivate();
7928 if (NewTemplate)
7929 NewTemplate->setModulePrivate();
7930 for (auto *B : Bindings)
7931 B->setModulePrivate();
7935 if (getLangOpts().OpenCL) {
7936 deduceOpenCLAddressSpace(NewVD);
7938 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7939 if (TSC != TSCS_unspecified) {
7940 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7941 diag::err_opencl_unknown_type_specifier)
7942 << getLangOpts().getOpenCLVersionString()
7943 << DeclSpec::getSpecifierName(TSC) << 1;
7944 NewVD->setInvalidDecl();
7948 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7949 // address space if the table has local storage (semantic checks elsewhere
7950 // will produce an error anyway).
7951 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7952 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7953 !NewVD->hasLocalStorage()) {
7954 QualType Type = Context.getAddrSpaceQualType(
7955 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
7956 NewVD->setType(Type);
7960 // Handle attributes prior to checking for duplicates in MergeVarDecl
7961 ProcessDeclAttributes(S, NewVD, D);
7963 if (getLangOpts().HLSL)
7964 HLSL().ActOnVariableDeclarator(NewVD);
7966 // FIXME: This is probably the wrong location to be doing this and we should
7967 // probably be doing this for more attributes (especially for function
7968 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7969 // the code to copy attributes would be generated by TableGen.
7970 if (R->isFunctionPointerType())
7971 if (const auto *TT = R->getAs<TypedefType>())
7972 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7974 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7975 getLangOpts().SYCLIsDevice) {
7976 if (EmitTLSUnsupportedError &&
7977 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7978 (getLangOpts().OpenMPIsTargetDevice &&
7979 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7980 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7981 diag::err_thread_unsupported);
7983 if (EmitTLSUnsupportedError &&
7984 (LangOpts.SYCLIsDevice ||
7985 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7986 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7987 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7988 // storage [duration]."
7989 if (SC == SC_None && S->getFnParent() != nullptr &&
7990 (NewVD->hasAttr<CUDASharedAttr>() ||
7991 NewVD->hasAttr<CUDAConstantAttr>())) {
7992 NewVD->setStorageClass(SC_Static);
7996 // Ensure that dllimport globals without explicit storage class are treated as
7997 // extern. The storage class is set above using parsed attributes. Now we can
7998 // check the VarDecl itself.
7999 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8000 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8001 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8003 // In auto-retain/release, infer strong retension for variables of
8004 // retainable type.
8005 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8006 NewVD->setInvalidDecl();
8008 // Handle GNU asm-label extension (encoded as an attribute).
8009 if (Expr *E = (Expr*)D.getAsmLabel()) {
8010 // The parser guarantees this is a string.
8011 StringLiteral *SE = cast<StringLiteral>(E);
8012 StringRef Label = SE->getString();
8013 if (S->getFnParent() != nullptr) {
8014 switch (SC) {
8015 case SC_None:
8016 case SC_Auto:
8017 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8018 break;
8019 case SC_Register:
8020 // Local Named register
8021 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8022 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8023 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8024 break;
8025 case SC_Static:
8026 case SC_Extern:
8027 case SC_PrivateExtern:
8028 break;
8030 } else if (SC == SC_Register) {
8031 // Global Named register
8032 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8033 const auto &TI = Context.getTargetInfo();
8034 bool HasSizeMismatch;
8036 if (!TI.isValidGCCRegisterName(Label))
8037 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8038 else if (!TI.validateGlobalRegisterVariable(Label,
8039 Context.getTypeSize(R),
8040 HasSizeMismatch))
8041 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8042 else if (HasSizeMismatch)
8043 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8046 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8047 Diag(TInfo->getTypeLoc().getBeginLoc(),
8048 diag::err_asm_unsupported_register_type)
8049 << TInfo->getTypeLoc().getSourceRange();
8050 NewVD->setInvalidDecl(true);
8054 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8055 /*IsLiteralLabel=*/true,
8056 SE->getStrTokenLoc(0)));
8057 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8058 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8059 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8060 if (I != ExtnameUndeclaredIdentifiers.end()) {
8061 if (isDeclExternC(NewVD)) {
8062 NewVD->addAttr(I->second);
8063 ExtnameUndeclaredIdentifiers.erase(I);
8064 } else
8065 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8066 << /*Variable*/1 << NewVD;
8070 // Find the shadowed declaration before filtering for scope.
8071 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8072 ? getShadowedDeclaration(NewVD, Previous)
8073 : nullptr;
8075 // Don't consider existing declarations that are in a different
8076 // scope and are out-of-semantic-context declarations (if the new
8077 // declaration has linkage).
8078 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8079 D.getCXXScopeSpec().isNotEmpty() ||
8080 IsMemberSpecialization ||
8081 IsVariableTemplateSpecialization);
8083 // Check whether the previous declaration is in the same block scope. This
8084 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8085 if (getLangOpts().CPlusPlus &&
8086 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8087 NewVD->setPreviousDeclInSameBlockScope(
8088 Previous.isSingleResult() && !Previous.isShadowed() &&
8089 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8091 if (!getLangOpts().CPlusPlus) {
8092 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8093 } else {
8094 // If this is an explicit specialization of a static data member, check it.
8095 if (IsMemberSpecialization && !IsVariableTemplate &&
8096 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8097 CheckMemberSpecialization(NewVD, Previous))
8098 NewVD->setInvalidDecl();
8100 // Merge the decl with the existing one if appropriate.
8101 if (!Previous.empty()) {
8102 if (Previous.isSingleResult() &&
8103 isa<FieldDecl>(Previous.getFoundDecl()) &&
8104 D.getCXXScopeSpec().isSet()) {
8105 // The user tried to define a non-static data member
8106 // out-of-line (C++ [dcl.meaning]p1).
8107 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8108 << D.getCXXScopeSpec().getRange();
8109 Previous.clear();
8110 NewVD->setInvalidDecl();
8112 } else if (D.getCXXScopeSpec().isSet() &&
8113 !IsVariableTemplateSpecialization) {
8114 // No previous declaration in the qualifying scope.
8115 Diag(D.getIdentifierLoc(), diag::err_no_member)
8116 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8117 << D.getCXXScopeSpec().getRange();
8118 NewVD->setInvalidDecl();
8121 if (!IsPlaceholderVariable)
8122 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8124 // CheckVariableDeclaration will set NewVD as invalid if something is in
8125 // error like WebAssembly tables being declared as arrays with a non-zero
8126 // size, but then parsing continues and emits further errors on that line.
8127 // To avoid that we check here if it happened and return nullptr.
8128 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8129 return nullptr;
8131 if (NewTemplate) {
8132 VarTemplateDecl *PrevVarTemplate =
8133 NewVD->getPreviousDecl()
8134 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8135 : nullptr;
8137 // Check the template parameter list of this declaration, possibly
8138 // merging in the template parameter list from the previous variable
8139 // template declaration.
8140 if (CheckTemplateParameterList(
8141 TemplateParams,
8142 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8143 : nullptr,
8144 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8145 DC->isDependentContext())
8146 ? TPC_ClassTemplateMember
8147 : TPC_VarTemplate))
8148 NewVD->setInvalidDecl();
8150 // If we are providing an explicit specialization of a static variable
8151 // template, make a note of that.
8152 if (PrevVarTemplate &&
8153 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8154 PrevVarTemplate->setMemberSpecialization();
8158 // Diagnose shadowed variables iff this isn't a redeclaration.
8159 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8160 CheckShadow(NewVD, ShadowedDecl, Previous);
8162 ProcessPragmaWeak(S, NewVD);
8164 // If this is the first declaration of an extern C variable, update
8165 // the map of such variables.
8166 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8167 isIncompleteDeclExternC(*this, NewVD))
8168 RegisterLocallyScopedExternCDecl(NewVD, S);
8170 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8171 MangleNumberingContext *MCtx;
8172 Decl *ManglingContextDecl;
8173 std::tie(MCtx, ManglingContextDecl) =
8174 getCurrentMangleNumberContext(NewVD->getDeclContext());
8175 if (MCtx) {
8176 Context.setManglingNumber(
8177 NewVD, MCtx->getManglingNumber(
8178 NewVD, getMSManglingNumber(getLangOpts(), S)));
8179 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8183 // Special handling of variable named 'main'.
8184 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8185 // C++ [basic.start.main]p3:
8186 // A program that declares
8187 // - a variable main at global scope, or
8188 // - an entity named main with C language linkage (in any namespace)
8189 // is ill-formed
8190 if (getLangOpts().CPlusPlus)
8191 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8192 << NewVD->isExternC();
8194 // In C, and external-linkage variable named main results in undefined
8195 // behavior.
8196 else if (NewVD->hasExternalFormalLinkage())
8197 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8200 if (D.isRedeclaration() && !Previous.empty()) {
8201 NamedDecl *Prev = Previous.getRepresentativeDecl();
8202 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8203 D.isFunctionDefinition());
8206 if (NewTemplate) {
8207 if (NewVD->isInvalidDecl())
8208 NewTemplate->setInvalidDecl();
8209 ActOnDocumentableDecl(NewTemplate);
8210 return NewTemplate;
8213 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8214 CompleteMemberSpecialization(NewVD, Previous);
8216 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8218 return NewVD;
8221 /// Enum describing the %select options in diag::warn_decl_shadow.
8222 enum ShadowedDeclKind {
8223 SDK_Local,
8224 SDK_Global,
8225 SDK_StaticMember,
8226 SDK_Field,
8227 SDK_Typedef,
8228 SDK_Using,
8229 SDK_StructuredBinding
8232 /// Determine what kind of declaration we're shadowing.
8233 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8234 const DeclContext *OldDC) {
8235 if (isa<TypeAliasDecl>(ShadowedDecl))
8236 return SDK_Using;
8237 else if (isa<TypedefDecl>(ShadowedDecl))
8238 return SDK_Typedef;
8239 else if (isa<BindingDecl>(ShadowedDecl))
8240 return SDK_StructuredBinding;
8241 else if (isa<RecordDecl>(OldDC))
8242 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8244 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8247 /// Return the location of the capture if the given lambda captures the given
8248 /// variable \p VD, or an invalid source location otherwise.
8249 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8250 const VarDecl *VD) {
8251 for (const Capture &Capture : LSI->Captures) {
8252 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8253 return Capture.getLocation();
8255 return SourceLocation();
8258 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8259 const LookupResult &R) {
8260 // Only diagnose if we're shadowing an unambiguous field or variable.
8261 if (R.getResultKind() != LookupResult::Found)
8262 return false;
8264 // Return false if warning is ignored.
8265 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8268 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8269 const LookupResult &R) {
8270 if (!shouldWarnIfShadowedDecl(Diags, R))
8271 return nullptr;
8273 // Don't diagnose declarations at file scope.
8274 if (D->hasGlobalStorage() && !D->isStaticLocal())
8275 return nullptr;
8277 NamedDecl *ShadowedDecl = R.getFoundDecl();
8278 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8279 : nullptr;
8282 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8283 const LookupResult &R) {
8284 // Don't warn if typedef declaration is part of a class
8285 if (D->getDeclContext()->isRecord())
8286 return nullptr;
8288 if (!shouldWarnIfShadowedDecl(Diags, R))
8289 return nullptr;
8291 NamedDecl *ShadowedDecl = R.getFoundDecl();
8292 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8295 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8296 const LookupResult &R) {
8297 if (!shouldWarnIfShadowedDecl(Diags, R))
8298 return nullptr;
8300 NamedDecl *ShadowedDecl = R.getFoundDecl();
8301 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8302 : nullptr;
8305 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8306 const LookupResult &R) {
8307 DeclContext *NewDC = D->getDeclContext();
8309 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8310 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8311 // Fields are not shadowed by variables in C++ static methods.
8312 if (MD->isStatic())
8313 return;
8315 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8316 return;
8318 // Fields shadowed by constructor parameters are a special case. Usually
8319 // the constructor initializes the field with the parameter.
8320 if (isa<CXXConstructorDecl>(NewDC))
8321 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8322 // Remember that this was shadowed so we can either warn about its
8323 // modification or its existence depending on warning settings.
8324 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8325 return;
8329 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8330 if (shadowedVar->isExternC()) {
8331 // For shadowing external vars, make sure that we point to the global
8332 // declaration, not a locally scoped extern declaration.
8333 for (auto *I : shadowedVar->redecls())
8334 if (I->isFileVarDecl()) {
8335 ShadowedDecl = I;
8336 break;
8340 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8342 unsigned WarningDiag = diag::warn_decl_shadow;
8343 SourceLocation CaptureLoc;
8344 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8345 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8346 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8347 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8348 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8349 if (RD->getLambdaCaptureDefault() == LCD_None) {
8350 // Try to avoid warnings for lambdas with an explicit capture
8351 // list. Warn only when the lambda captures the shadowed decl
8352 // explicitly.
8353 CaptureLoc = getCaptureLocation(LSI, VD);
8354 if (CaptureLoc.isInvalid())
8355 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8356 } else {
8357 // Remember that this was shadowed so we can avoid the warning if
8358 // the shadowed decl isn't captured and the warning settings allow
8359 // it.
8360 cast<LambdaScopeInfo>(getCurFunction())
8361 ->ShadowingDecls.push_back({D, VD});
8362 return;
8365 if (isa<FieldDecl>(ShadowedDecl)) {
8366 // If lambda can capture this, then emit default shadowing warning,
8367 // Otherwise it is not really a shadowing case since field is not
8368 // available in lambda's body.
8369 // At this point we don't know that lambda can capture this, so
8370 // remember that this was shadowed and delay until we know.
8371 cast<LambdaScopeInfo>(getCurFunction())
8372 ->ShadowingDecls.push_back({D, ShadowedDecl});
8373 return;
8376 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8377 VD && VD->hasLocalStorage()) {
8378 // A variable can't shadow a local variable in an enclosing scope, if
8379 // they are separated by a non-capturing declaration context.
8380 for (DeclContext *ParentDC = NewDC;
8381 ParentDC && !ParentDC->Equals(OldDC);
8382 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8383 // Only block literals, captured statements, and lambda expressions
8384 // can capture; other scopes don't.
8385 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8386 !isLambdaCallOperator(ParentDC)) {
8387 return;
8394 // Never warn about shadowing a placeholder variable.
8395 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8396 return;
8398 // Only warn about certain kinds of shadowing for class members.
8399 if (NewDC) {
8400 // In particular, don't warn about shadowing non-class members.
8401 if (NewDC->isRecord() && !OldDC->isRecord())
8402 return;
8404 // Skip shadowing check if we're in a class scope, dealing with an enum
8405 // constant in a different context.
8406 DeclContext *ReDC = NewDC->getRedeclContext();
8407 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8408 return;
8410 // TODO: should we warn about static data members shadowing
8411 // static data members from base classes?
8413 // TODO: don't diagnose for inaccessible shadowed members.
8414 // This is hard to do perfectly because we might friend the
8415 // shadowing context, but that's just a false negative.
8418 DeclarationName Name = R.getLookupName();
8420 // Emit warning and note.
8421 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8422 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8423 if (!CaptureLoc.isInvalid())
8424 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8425 << Name << /*explicitly*/ 1;
8426 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8429 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8430 for (const auto &Shadow : LSI->ShadowingDecls) {
8431 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8432 // Try to avoid the warning when the shadowed decl isn't captured.
8433 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8434 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8435 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8436 Diag(Shadow.VD->getLocation(),
8437 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8438 : diag::warn_decl_shadow)
8439 << Shadow.VD->getDeclName()
8440 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8441 if (CaptureLoc.isValid())
8442 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8443 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8444 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8445 } else if (isa<FieldDecl>(ShadowedDecl)) {
8446 Diag(Shadow.VD->getLocation(),
8447 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8448 : diag::warn_decl_shadow_uncaptured_local)
8449 << Shadow.VD->getDeclName()
8450 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8451 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8456 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8457 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8458 return;
8460 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8461 Sema::LookupOrdinaryName,
8462 RedeclarationKind::ForVisibleRedeclaration);
8463 LookupName(R, S);
8464 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8465 CheckShadow(D, ShadowedDecl, R);
8468 /// Check if 'E', which is an expression that is about to be modified, refers
8469 /// to a constructor parameter that shadows a field.
8470 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8471 // Quickly ignore expressions that can't be shadowing ctor parameters.
8472 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8473 return;
8474 E = E->IgnoreParenImpCasts();
8475 auto *DRE = dyn_cast<DeclRefExpr>(E);
8476 if (!DRE)
8477 return;
8478 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8479 auto I = ShadowingDecls.find(D);
8480 if (I == ShadowingDecls.end())
8481 return;
8482 const NamedDecl *ShadowedDecl = I->second;
8483 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8484 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8485 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8486 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8488 // Avoid issuing multiple warnings about the same decl.
8489 ShadowingDecls.erase(I);
8492 /// Check for conflict between this global or extern "C" declaration and
8493 /// previous global or extern "C" declarations. This is only used in C++.
8494 template<typename T>
8495 static bool checkGlobalOrExternCConflict(
8496 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8497 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8498 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8500 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8501 // The common case: this global doesn't conflict with any extern "C"
8502 // declaration.
8503 return false;
8506 if (Prev) {
8507 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8508 // Both the old and new declarations have C language linkage. This is a
8509 // redeclaration.
8510 Previous.clear();
8511 Previous.addDecl(Prev);
8512 return true;
8515 // This is a global, non-extern "C" declaration, and there is a previous
8516 // non-global extern "C" declaration. Diagnose if this is a variable
8517 // declaration.
8518 if (!isa<VarDecl>(ND))
8519 return false;
8520 } else {
8521 // The declaration is extern "C". Check for any declaration in the
8522 // translation unit which might conflict.
8523 if (IsGlobal) {
8524 // We have already performed the lookup into the translation unit.
8525 IsGlobal = false;
8526 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8527 I != E; ++I) {
8528 if (isa<VarDecl>(*I)) {
8529 Prev = *I;
8530 break;
8533 } else {
8534 DeclContext::lookup_result R =
8535 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8536 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8537 I != E; ++I) {
8538 if (isa<VarDecl>(*I)) {
8539 Prev = *I;
8540 break;
8542 // FIXME: If we have any other entity with this name in global scope,
8543 // the declaration is ill-formed, but that is a defect: it breaks the
8544 // 'stat' hack, for instance. Only variables can have mangled name
8545 // clashes with extern "C" declarations, so only they deserve a
8546 // diagnostic.
8550 if (!Prev)
8551 return false;
8554 // Use the first declaration's location to ensure we point at something which
8555 // is lexically inside an extern "C" linkage-spec.
8556 assert(Prev && "should have found a previous declaration to diagnose");
8557 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8558 Prev = FD->getFirstDecl();
8559 else
8560 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8562 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8563 << IsGlobal << ND;
8564 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8565 << IsGlobal;
8566 return false;
8569 /// Apply special rules for handling extern "C" declarations. Returns \c true
8570 /// if we have found that this is a redeclaration of some prior entity.
8572 /// Per C++ [dcl.link]p6:
8573 /// Two declarations [for a function or variable] with C language linkage
8574 /// with the same name that appear in different scopes refer to the same
8575 /// [entity]. An entity with C language linkage shall not be declared with
8576 /// the same name as an entity in global scope.
8577 template<typename T>
8578 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8579 LookupResult &Previous) {
8580 if (!S.getLangOpts().CPlusPlus) {
8581 // In C, when declaring a global variable, look for a corresponding 'extern'
8582 // variable declared in function scope. We don't need this in C++, because
8583 // we find local extern decls in the surrounding file-scope DeclContext.
8584 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8585 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8586 Previous.clear();
8587 Previous.addDecl(Prev);
8588 return true;
8591 return false;
8594 // A declaration in the translation unit can conflict with an extern "C"
8595 // declaration.
8596 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8597 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8599 // An extern "C" declaration can conflict with a declaration in the
8600 // translation unit or can be a redeclaration of an extern "C" declaration
8601 // in another scope.
8602 if (isIncompleteDeclExternC(S,ND))
8603 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8605 // Neither global nor extern "C": nothing to do.
8606 return false;
8609 static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8610 QualType T) {
8611 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8612 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8613 // any of its members, even recursively, shall not have an atomic type, or a
8614 // variably modified type, or a type that is volatile or restrict qualified.
8615 if (CanonT->isVariablyModifiedType()) {
8616 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8617 return true;
8620 // Arrays are qualified by their element type, so get the base type (this
8621 // works on non-arrays as well).
8622 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8624 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8625 CanonT.isRestrictQualified()) {
8626 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8627 return true;
8630 if (CanonT->isRecordType()) {
8631 const RecordDecl *RD = CanonT->getAsRecordDecl();
8632 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8633 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8635 return true;
8638 return false;
8641 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8642 // If the decl is already known invalid, don't check it.
8643 if (NewVD->isInvalidDecl())
8644 return;
8646 QualType T = NewVD->getType();
8648 // Defer checking an 'auto' type until its initializer is attached.
8649 if (T->isUndeducedType())
8650 return;
8652 if (NewVD->hasAttrs())
8653 CheckAlignasUnderalignment(NewVD);
8655 if (T->isObjCObjectType()) {
8656 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8657 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8658 T = Context.getObjCObjectPointerType(T);
8659 NewVD->setType(T);
8662 // Emit an error if an address space was applied to decl with local storage.
8663 // This includes arrays of objects with address space qualifiers, but not
8664 // automatic variables that point to other address spaces.
8665 // ISO/IEC TR 18037 S5.1.2
8666 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8667 T.getAddressSpace() != LangAS::Default) {
8668 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8669 NewVD->setInvalidDecl();
8670 return;
8673 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8674 // scope.
8675 if (getLangOpts().OpenCLVersion == 120 &&
8676 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8677 getLangOpts()) &&
8678 NewVD->isStaticLocal()) {
8679 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8680 NewVD->setInvalidDecl();
8681 return;
8684 if (getLangOpts().OpenCL) {
8685 if (!diagnoseOpenCLTypes(*this, NewVD))
8686 return;
8688 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8689 if (NewVD->hasAttr<BlocksAttr>()) {
8690 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8691 return;
8694 if (T->isBlockPointerType()) {
8695 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8696 // can't use 'extern' storage class.
8697 if (!T.isConstQualified()) {
8698 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8699 << 0 /*const*/;
8700 NewVD->setInvalidDecl();
8701 return;
8703 if (NewVD->hasExternalStorage()) {
8704 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8705 NewVD->setInvalidDecl();
8706 return;
8710 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8711 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8712 NewVD->hasExternalStorage()) {
8713 if (!T->isSamplerT() && !T->isDependentType() &&
8714 !(T.getAddressSpace() == LangAS::opencl_constant ||
8715 (T.getAddressSpace() == LangAS::opencl_global &&
8716 getOpenCLOptions().areProgramScopeVariablesSupported(
8717 getLangOpts())))) {
8718 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8719 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8720 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8721 << Scope << "global or constant";
8722 else
8723 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8724 << Scope << "constant";
8725 NewVD->setInvalidDecl();
8726 return;
8728 } else {
8729 if (T.getAddressSpace() == LangAS::opencl_global) {
8730 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8731 << 1 /*is any function*/ << "global";
8732 NewVD->setInvalidDecl();
8733 return;
8735 if (T.getAddressSpace() == LangAS::opencl_constant ||
8736 T.getAddressSpace() == LangAS::opencl_local) {
8737 FunctionDecl *FD = getCurFunctionDecl();
8738 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8739 // in functions.
8740 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8741 if (T.getAddressSpace() == LangAS::opencl_constant)
8742 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8743 << 0 /*non-kernel only*/ << "constant";
8744 else
8745 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8746 << 0 /*non-kernel only*/ << "local";
8747 NewVD->setInvalidDecl();
8748 return;
8750 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8751 // in the outermost scope of a kernel function.
8752 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8753 if (!getCurScope()->isFunctionScope()) {
8754 if (T.getAddressSpace() == LangAS::opencl_constant)
8755 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8756 << "constant";
8757 else
8758 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8759 << "local";
8760 NewVD->setInvalidDecl();
8761 return;
8764 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8765 // If we are parsing a template we didn't deduce an addr
8766 // space yet.
8767 T.getAddressSpace() != LangAS::Default) {
8768 // Do not allow other address spaces on automatic variable.
8769 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8770 NewVD->setInvalidDecl();
8771 return;
8776 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8777 && !NewVD->hasAttr<BlocksAttr>()) {
8778 if (getLangOpts().getGC() != LangOptions::NonGC)
8779 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8780 else {
8781 assert(!getLangOpts().ObjCAutoRefCount);
8782 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8786 // WebAssembly tables must be static with a zero length and can't be
8787 // declared within functions.
8788 if (T->isWebAssemblyTableType()) {
8789 if (getCurScope()->getParent()) { // Parent is null at top-level
8790 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8791 NewVD->setInvalidDecl();
8792 return;
8794 if (NewVD->getStorageClass() != SC_Static) {
8795 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8796 NewVD->setInvalidDecl();
8797 return;
8799 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8800 if (!ATy || ATy->getZExtSize() != 0) {
8801 Diag(NewVD->getLocation(),
8802 diag::err_typecheck_wasm_table_must_have_zero_length);
8803 NewVD->setInvalidDecl();
8804 return;
8808 // zero sized static arrays are not allowed in HIP device functions
8809 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8810 if (FunctionDecl *FD = getCurFunctionDecl();
8811 FD &&
8812 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8813 if (const ConstantArrayType *ArrayT =
8814 getASTContext().getAsConstantArrayType(T);
8815 ArrayT && ArrayT->isZeroSize()) {
8816 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8821 bool isVM = T->isVariablyModifiedType();
8822 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8823 NewVD->hasAttr<BlocksAttr>())
8824 setFunctionHasBranchProtectedScope();
8826 if ((isVM && NewVD->hasLinkage()) ||
8827 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8828 bool SizeIsNegative;
8829 llvm::APSInt Oversized;
8830 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8831 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8832 QualType FixedT;
8833 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8834 FixedT = FixedTInfo->getType();
8835 else if (FixedTInfo) {
8836 // Type and type-as-written are canonically different. We need to fix up
8837 // both types separately.
8838 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8839 Oversized);
8841 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8842 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8843 // FIXME: This won't give the correct result for
8844 // int a[10][n];
8845 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8847 if (NewVD->isFileVarDecl())
8848 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8849 << SizeRange;
8850 else if (NewVD->isStaticLocal())
8851 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8852 << SizeRange;
8853 else
8854 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8855 << SizeRange;
8856 NewVD->setInvalidDecl();
8857 return;
8860 if (!FixedTInfo) {
8861 if (NewVD->isFileVarDecl())
8862 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8863 else
8864 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8865 NewVD->setInvalidDecl();
8866 return;
8869 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8870 NewVD->setType(FixedT);
8871 NewVD->setTypeSourceInfo(FixedTInfo);
8874 if (T->isVoidType()) {
8875 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8876 // of objects and functions.
8877 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8878 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8879 << T;
8880 NewVD->setInvalidDecl();
8881 return;
8885 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8886 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8887 NewVD->setInvalidDecl();
8888 return;
8891 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8892 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8893 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8894 NewVD->setInvalidDecl();
8895 return;
8898 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8899 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8900 NewVD->setInvalidDecl();
8901 return;
8904 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8905 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8906 NewVD->setInvalidDecl();
8907 return;
8910 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8911 !T->isDependentType() &&
8912 RequireLiteralType(NewVD->getLocation(), T,
8913 diag::err_constexpr_var_non_literal)) {
8914 NewVD->setInvalidDecl();
8915 return;
8918 // PPC MMA non-pointer types are not allowed as non-local variable types.
8919 if (Context.getTargetInfo().getTriple().isPPC64() &&
8920 !NewVD->isLocalVarDecl() &&
8921 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8922 NewVD->setInvalidDecl();
8923 return;
8926 // Check that SVE types are only used in functions with SVE available.
8927 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8928 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8929 llvm::StringMap<bool> CallerFeatureMap;
8930 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8932 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8933 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8934 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8935 NewVD->setInvalidDecl();
8936 return;
8937 } else if (!IsArmStreamingFunction(FD,
8938 /*IncludeLocallyStreaming=*/true)) {
8939 Diag(NewVD->getLocation(),
8940 diag::err_sve_vector_in_non_streaming_function)
8941 << T;
8942 NewVD->setInvalidDecl();
8943 return;
8948 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8949 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8950 llvm::StringMap<bool> CallerFeatureMap;
8951 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8952 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8953 CallerFeatureMap);
8957 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8958 CheckVariableDeclarationType(NewVD);
8960 // If the decl is already known invalid, don't check it.
8961 if (NewVD->isInvalidDecl())
8962 return false;
8964 // If we did not find anything by this name, look for a non-visible
8965 // extern "C" declaration with the same name.
8966 if (Previous.empty() &&
8967 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8968 Previous.setShadowed();
8970 if (!Previous.empty()) {
8971 MergeVarDecl(NewVD, Previous);
8972 return true;
8974 return false;
8977 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8978 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8980 // Look for methods in base classes that this method might override.
8981 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8982 /*DetectVirtual=*/false);
8983 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8984 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8985 DeclarationName Name = MD->getDeclName();
8987 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8988 // We really want to find the base class destructor here.
8989 QualType T = Context.getTypeDeclType(BaseRecord);
8990 CanQualType CT = Context.getCanonicalType(T);
8991 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8994 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8995 CXXMethodDecl *BaseMD =
8996 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8997 if (!BaseMD || !BaseMD->isVirtual() ||
8998 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8999 /*ConsiderCudaAttrs=*/true))
9000 continue;
9001 if (!CheckExplicitObjectOverride(MD, BaseMD))
9002 continue;
9003 if (Overridden.insert(BaseMD).second) {
9004 MD->addOverriddenMethod(BaseMD);
9005 CheckOverridingFunctionReturnType(MD, BaseMD);
9006 CheckOverridingFunctionAttributes(MD, BaseMD);
9007 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
9008 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
9011 // A method can only override one function from each base class. We
9012 // don't track indirectly overridden methods from bases of bases.
9013 return true;
9016 return false;
9019 DC->lookupInBases(VisitBase, Paths);
9020 return !Overridden.empty();
9023 namespace {
9024 // Struct for holding all of the extra arguments needed by
9025 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9026 struct ActOnFDArgs {
9027 Scope *S;
9028 Declarator &D;
9029 MultiTemplateParamsArg TemplateParamLists;
9030 bool AddToScope;
9032 } // end anonymous namespace
9034 namespace {
9036 // Callback to only accept typo corrections that have a non-zero edit distance.
9037 // Also only accept corrections that have the same parent decl.
9038 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9039 public:
9040 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9041 CXXRecordDecl *Parent)
9042 : Context(Context), OriginalFD(TypoFD),
9043 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9045 bool ValidateCandidate(const TypoCorrection &candidate) override {
9046 if (candidate.getEditDistance() == 0)
9047 return false;
9049 SmallVector<unsigned, 1> MismatchedParams;
9050 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9051 CDeclEnd = candidate.end();
9052 CDecl != CDeclEnd; ++CDecl) {
9053 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9055 if (FD && !FD->hasBody() &&
9056 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9057 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9058 CXXRecordDecl *Parent = MD->getParent();
9059 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9060 return true;
9061 } else if (!ExpectedParent) {
9062 return true;
9067 return false;
9070 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9071 return std::make_unique<DifferentNameValidatorCCC>(*this);
9074 private:
9075 ASTContext &Context;
9076 FunctionDecl *OriginalFD;
9077 CXXRecordDecl *ExpectedParent;
9080 } // end anonymous namespace
9082 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9083 TypoCorrectedFunctionDefinitions.insert(F);
9086 /// Generate diagnostics for an invalid function redeclaration.
9088 /// This routine handles generating the diagnostic messages for an invalid
9089 /// function redeclaration, including finding possible similar declarations
9090 /// or performing typo correction if there are no previous declarations with
9091 /// the same name.
9093 /// Returns a NamedDecl iff typo correction was performed and substituting in
9094 /// the new declaration name does not cause new errors.
9095 static NamedDecl *DiagnoseInvalidRedeclaration(
9096 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9097 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9098 DeclarationName Name = NewFD->getDeclName();
9099 DeclContext *NewDC = NewFD->getDeclContext();
9100 SmallVector<unsigned, 1> MismatchedParams;
9101 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9102 TypoCorrection Correction;
9103 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9104 unsigned DiagMsg =
9105 IsLocalFriend ? diag::err_no_matching_local_friend :
9106 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9107 diag::err_member_decl_does_not_match;
9108 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9109 IsLocalFriend ? Sema::LookupLocalFriendName
9110 : Sema::LookupOrdinaryName,
9111 RedeclarationKind::ForVisibleRedeclaration);
9113 NewFD->setInvalidDecl();
9114 if (IsLocalFriend)
9115 SemaRef.LookupName(Prev, S);
9116 else
9117 SemaRef.LookupQualifiedName(Prev, NewDC);
9118 assert(!Prev.isAmbiguous() &&
9119 "Cannot have an ambiguity in previous-declaration lookup");
9120 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9121 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9122 MD ? MD->getParent() : nullptr);
9123 if (!Prev.empty()) {
9124 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9125 Func != FuncEnd; ++Func) {
9126 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9127 if (FD &&
9128 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9129 // Add 1 to the index so that 0 can mean the mismatch didn't
9130 // involve a parameter
9131 unsigned ParamNum =
9132 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9133 NearMatches.push_back(std::make_pair(FD, ParamNum));
9136 // If the qualified name lookup yielded nothing, try typo correction
9137 } else if ((Correction = SemaRef.CorrectTypo(
9138 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9139 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9140 IsLocalFriend ? nullptr : NewDC))) {
9141 // Set up everything for the call to ActOnFunctionDeclarator
9142 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9143 ExtraArgs.D.getIdentifierLoc());
9144 Previous.clear();
9145 Previous.setLookupName(Correction.getCorrection());
9146 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9147 CDeclEnd = Correction.end();
9148 CDecl != CDeclEnd; ++CDecl) {
9149 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9150 if (FD && !FD->hasBody() &&
9151 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9152 Previous.addDecl(FD);
9155 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9157 NamedDecl *Result;
9158 // Retry building the function declaration with the new previous
9159 // declarations, and with errors suppressed.
9161 // Trap errors.
9162 Sema::SFINAETrap Trap(SemaRef);
9164 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9165 // pieces need to verify the typo-corrected C++ declaration and hopefully
9166 // eliminate the need for the parameter pack ExtraArgs.
9167 Result = SemaRef.ActOnFunctionDeclarator(
9168 ExtraArgs.S, ExtraArgs.D,
9169 Correction.getCorrectionDecl()->getDeclContext(),
9170 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9171 ExtraArgs.AddToScope);
9173 if (Trap.hasErrorOccurred())
9174 Result = nullptr;
9177 if (Result) {
9178 // Determine which correction we picked.
9179 Decl *Canonical = Result->getCanonicalDecl();
9180 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9181 I != E; ++I)
9182 if ((*I)->getCanonicalDecl() == Canonical)
9183 Correction.setCorrectionDecl(*I);
9185 // Let Sema know about the correction.
9186 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9187 SemaRef.diagnoseTypo(
9188 Correction,
9189 SemaRef.PDiag(IsLocalFriend
9190 ? diag::err_no_matching_local_friend_suggest
9191 : diag::err_member_decl_does_not_match_suggest)
9192 << Name << NewDC << IsDefinition);
9193 return Result;
9196 // Pretend the typo correction never occurred
9197 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9198 ExtraArgs.D.getIdentifierLoc());
9199 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9200 Previous.clear();
9201 Previous.setLookupName(Name);
9204 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9205 << Name << NewDC << IsDefinition << NewFD->getLocation();
9207 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9208 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9209 CXXRecordDecl *RD = NewMD->getParent();
9210 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9211 << RD->getName() << RD->getLocation();
9214 bool NewFDisConst = NewMD && NewMD->isConst();
9216 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9217 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9218 NearMatch != NearMatchEnd; ++NearMatch) {
9219 FunctionDecl *FD = NearMatch->first;
9220 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9221 bool FDisConst = MD && MD->isConst();
9222 bool IsMember = MD || !IsLocalFriend;
9224 // FIXME: These notes are poorly worded for the local friend case.
9225 if (unsigned Idx = NearMatch->second) {
9226 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9227 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9228 if (Loc.isInvalid()) Loc = FD->getLocation();
9229 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9230 : diag::note_local_decl_close_param_match)
9231 << Idx << FDParam->getType()
9232 << NewFD->getParamDecl(Idx - 1)->getType();
9233 } else if (FDisConst != NewFDisConst) {
9234 auto DB = SemaRef.Diag(FD->getLocation(),
9235 diag::note_member_def_close_const_match)
9236 << NewFDisConst << FD->getSourceRange().getEnd();
9237 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9238 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9239 " const");
9240 else if (FTI.hasMethodTypeQualifiers() &&
9241 FTI.getConstQualifierLoc().isValid())
9242 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9243 } else {
9244 SemaRef.Diag(FD->getLocation(),
9245 IsMember ? diag::note_member_def_close_match
9246 : diag::note_local_decl_close_match);
9249 return nullptr;
9252 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9253 switch (D.getDeclSpec().getStorageClassSpec()) {
9254 default: llvm_unreachable("Unknown storage class!");
9255 case DeclSpec::SCS_auto:
9256 case DeclSpec::SCS_register:
9257 case DeclSpec::SCS_mutable:
9258 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9259 diag::err_typecheck_sclass_func);
9260 D.getMutableDeclSpec().ClearStorageClassSpecs();
9261 D.setInvalidType();
9262 break;
9263 case DeclSpec::SCS_unspecified: break;
9264 case DeclSpec::SCS_extern:
9265 if (D.getDeclSpec().isExternInLinkageSpec())
9266 return SC_None;
9267 return SC_Extern;
9268 case DeclSpec::SCS_static: {
9269 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9270 // C99 6.7.1p5:
9271 // The declaration of an identifier for a function that has
9272 // block scope shall have no explicit storage-class specifier
9273 // other than extern
9274 // See also (C++ [dcl.stc]p4).
9275 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9276 diag::err_static_block_func);
9277 break;
9278 } else
9279 return SC_Static;
9281 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9284 // No explicit storage class has already been returned
9285 return SC_None;
9288 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9289 DeclContext *DC, QualType &R,
9290 TypeSourceInfo *TInfo,
9291 StorageClass SC,
9292 bool &IsVirtualOkay) {
9293 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9294 DeclarationName Name = NameInfo.getName();
9296 FunctionDecl *NewFD = nullptr;
9297 bool isInline = D.getDeclSpec().isInlineSpecified();
9299 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9300 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9301 (SemaRef.getLangOpts().C23 &&
9302 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9304 if (SemaRef.getLangOpts().C23)
9305 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9306 diag::err_c23_constexpr_not_variable);
9307 else
9308 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9309 diag::err_constexpr_wrong_decl_kind)
9310 << static_cast<int>(ConstexprKind);
9311 ConstexprKind = ConstexprSpecKind::Unspecified;
9312 D.getMutableDeclSpec().ClearConstexprSpec();
9315 if (!SemaRef.getLangOpts().CPlusPlus) {
9316 // Determine whether the function was written with a prototype. This is
9317 // true when:
9318 // - there is a prototype in the declarator, or
9319 // - the type R of the function is some kind of typedef or other non-
9320 // attributed reference to a type name (which eventually refers to a
9321 // function type). Note, we can't always look at the adjusted type to
9322 // check this case because attributes may cause a non-function
9323 // declarator to still have a function type. e.g.,
9324 // typedef void func(int a);
9325 // __attribute__((noreturn)) func other_func; // This has a prototype
9326 bool HasPrototype =
9327 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9328 (D.getDeclSpec().isTypeRep() &&
9329 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9330 ->isFunctionProtoType()) ||
9331 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9332 assert(
9333 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9334 "Strict prototypes are required");
9336 NewFD = FunctionDecl::Create(
9337 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9338 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9339 ConstexprSpecKind::Unspecified,
9340 /*TrailingRequiresClause=*/nullptr);
9341 if (D.isInvalidType())
9342 NewFD->setInvalidDecl();
9344 return NewFD;
9347 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9348 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9350 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9352 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9353 // This is a C++ constructor declaration.
9354 assert(DC->isRecord() &&
9355 "Constructors can only be declared in a member context");
9357 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9358 return CXXConstructorDecl::Create(
9359 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9360 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9361 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9362 InheritedConstructor(), TrailingRequiresClause);
9364 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9365 // This is a C++ destructor declaration.
9366 if (DC->isRecord()) {
9367 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9368 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9369 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9370 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9371 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9372 /*isImplicitlyDeclared=*/false, ConstexprKind,
9373 TrailingRequiresClause);
9374 // User defined destructors start as not selected if the class definition is still
9375 // not done.
9376 if (Record->isBeingDefined())
9377 NewDD->setIneligibleOrNotSelected(true);
9379 // If the destructor needs an implicit exception specification, set it
9380 // now. FIXME: It'd be nice to be able to create the right type to start
9381 // with, but the type needs to reference the destructor declaration.
9382 if (SemaRef.getLangOpts().CPlusPlus11)
9383 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9385 IsVirtualOkay = true;
9386 return NewDD;
9388 } else {
9389 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9390 D.setInvalidType();
9392 // Create a FunctionDecl to satisfy the function definition parsing
9393 // code path.
9394 return FunctionDecl::Create(
9395 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9396 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9397 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9400 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9401 if (!DC->isRecord()) {
9402 SemaRef.Diag(D.getIdentifierLoc(),
9403 diag::err_conv_function_not_member);
9404 return nullptr;
9407 SemaRef.CheckConversionDeclarator(D, R, SC);
9408 if (D.isInvalidType())
9409 return nullptr;
9411 IsVirtualOkay = true;
9412 return CXXConversionDecl::Create(
9413 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9414 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9415 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9416 TrailingRequiresClause);
9418 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9419 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9420 return nullptr;
9421 return CXXDeductionGuideDecl::Create(
9422 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9423 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9424 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9425 } else if (DC->isRecord()) {
9426 // If the name of the function is the same as the name of the record,
9427 // then this must be an invalid constructor that has a return type.
9428 // (The parser checks for a return type and makes the declarator a
9429 // constructor if it has no return type).
9430 if (Name.getAsIdentifierInfo() &&
9431 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9432 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9433 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9434 << SourceRange(D.getIdentifierLoc());
9435 return nullptr;
9438 // This is a C++ method declaration.
9439 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9440 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9441 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9442 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9443 IsVirtualOkay = !Ret->isStatic();
9444 return Ret;
9445 } else {
9446 bool isFriend =
9447 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9448 if (!isFriend && SemaRef.CurContext->isRecord())
9449 return nullptr;
9451 // Determine whether the function was written with a
9452 // prototype. This true when:
9453 // - we're in C++ (where every function has a prototype),
9454 return FunctionDecl::Create(
9455 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9456 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9457 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9461 enum OpenCLParamType {
9462 ValidKernelParam,
9463 PtrPtrKernelParam,
9464 PtrKernelParam,
9465 InvalidAddrSpacePtrKernelParam,
9466 InvalidKernelParam,
9467 RecordKernelParam
9470 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9471 // Size dependent types are just typedefs to normal integer types
9472 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9473 // integers other than by their names.
9474 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9476 // Remove typedefs one by one until we reach a typedef
9477 // for a size dependent type.
9478 QualType DesugaredTy = Ty;
9479 do {
9480 ArrayRef<StringRef> Names(SizeTypeNames);
9481 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9482 if (Names.end() != Match)
9483 return true;
9485 Ty = DesugaredTy;
9486 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9487 } while (DesugaredTy != Ty);
9489 return false;
9492 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9493 if (PT->isDependentType())
9494 return InvalidKernelParam;
9496 if (PT->isPointerOrReferenceType()) {
9497 QualType PointeeType = PT->getPointeeType();
9498 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9499 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9500 PointeeType.getAddressSpace() == LangAS::Default)
9501 return InvalidAddrSpacePtrKernelParam;
9503 if (PointeeType->isPointerType()) {
9504 // This is a pointer to pointer parameter.
9505 // Recursively check inner type.
9506 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9507 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9508 ParamKind == InvalidKernelParam)
9509 return ParamKind;
9511 // OpenCL v3.0 s6.11.a:
9512 // A restriction to pass pointers to pointers only applies to OpenCL C
9513 // v1.2 or below.
9514 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9515 return ValidKernelParam;
9517 return PtrPtrKernelParam;
9520 // C++ for OpenCL v1.0 s2.4:
9521 // Moreover the types used in parameters of the kernel functions must be:
9522 // Standard layout types for pointer parameters. The same applies to
9523 // reference if an implementation supports them in kernel parameters.
9524 if (S.getLangOpts().OpenCLCPlusPlus &&
9525 !S.getOpenCLOptions().isAvailableOption(
9526 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9527 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9528 bool IsStandardLayoutType = true;
9529 if (CXXRec) {
9530 // If template type is not ODR-used its definition is only available
9531 // in the template definition not its instantiation.
9532 // FIXME: This logic doesn't work for types that depend on template
9533 // parameter (PR58590).
9534 if (!CXXRec->hasDefinition())
9535 CXXRec = CXXRec->getTemplateInstantiationPattern();
9536 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9537 IsStandardLayoutType = false;
9539 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9540 !IsStandardLayoutType)
9541 return InvalidKernelParam;
9544 // OpenCL v1.2 s6.9.p:
9545 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9546 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9547 return ValidKernelParam;
9549 return PtrKernelParam;
9552 // OpenCL v1.2 s6.9.k:
9553 // Arguments to kernel functions in a program cannot be declared with the
9554 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9555 // uintptr_t or a struct and/or union that contain fields declared to be one
9556 // of these built-in scalar types.
9557 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9558 return InvalidKernelParam;
9560 if (PT->isImageType())
9561 return PtrKernelParam;
9563 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9564 return InvalidKernelParam;
9566 // OpenCL extension spec v1.2 s9.5:
9567 // This extension adds support for half scalar and vector types as built-in
9568 // types that can be used for arithmetic operations, conversions etc.
9569 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9570 PT->isHalfType())
9571 return InvalidKernelParam;
9573 // Look into an array argument to check if it has a forbidden type.
9574 if (PT->isArrayType()) {
9575 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9576 // Call ourself to check an underlying type of an array. Since the
9577 // getPointeeOrArrayElementType returns an innermost type which is not an
9578 // array, this recursive call only happens once.
9579 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9582 // C++ for OpenCL v1.0 s2.4:
9583 // Moreover the types used in parameters of the kernel functions must be:
9584 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9585 // types) for parameters passed by value;
9586 if (S.getLangOpts().OpenCLCPlusPlus &&
9587 !S.getOpenCLOptions().isAvailableOption(
9588 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9589 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9590 return InvalidKernelParam;
9592 if (PT->isRecordType())
9593 return RecordKernelParam;
9595 return ValidKernelParam;
9598 static void checkIsValidOpenCLKernelParameter(
9599 Sema &S,
9600 Declarator &D,
9601 ParmVarDecl *Param,
9602 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9603 QualType PT = Param->getType();
9605 // Cache the valid types we encounter to avoid rechecking structs that are
9606 // used again
9607 if (ValidTypes.count(PT.getTypePtr()))
9608 return;
9610 switch (getOpenCLKernelParameterType(S, PT)) {
9611 case PtrPtrKernelParam:
9612 // OpenCL v3.0 s6.11.a:
9613 // A kernel function argument cannot be declared as a pointer to a pointer
9614 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9615 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9616 D.setInvalidType();
9617 return;
9619 case InvalidAddrSpacePtrKernelParam:
9620 // OpenCL v1.0 s6.5:
9621 // __kernel function arguments declared to be a pointer of a type can point
9622 // to one of the following address spaces only : __global, __local or
9623 // __constant.
9624 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9625 D.setInvalidType();
9626 return;
9628 // OpenCL v1.2 s6.9.k:
9629 // Arguments to kernel functions in a program cannot be declared with the
9630 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9631 // uintptr_t or a struct and/or union that contain fields declared to be
9632 // one of these built-in scalar types.
9634 case InvalidKernelParam:
9635 // OpenCL v1.2 s6.8 n:
9636 // A kernel function argument cannot be declared
9637 // of event_t type.
9638 // Do not diagnose half type since it is diagnosed as invalid argument
9639 // type for any function elsewhere.
9640 if (!PT->isHalfType()) {
9641 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9643 // Explain what typedefs are involved.
9644 const TypedefType *Typedef = nullptr;
9645 while ((Typedef = PT->getAs<TypedefType>())) {
9646 SourceLocation Loc = Typedef->getDecl()->getLocation();
9647 // SourceLocation may be invalid for a built-in type.
9648 if (Loc.isValid())
9649 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9650 PT = Typedef->desugar();
9654 D.setInvalidType();
9655 return;
9657 case PtrKernelParam:
9658 case ValidKernelParam:
9659 ValidTypes.insert(PT.getTypePtr());
9660 return;
9662 case RecordKernelParam:
9663 break;
9666 // Track nested structs we will inspect
9667 SmallVector<const Decl *, 4> VisitStack;
9669 // Track where we are in the nested structs. Items will migrate from
9670 // VisitStack to HistoryStack as we do the DFS for bad field.
9671 SmallVector<const FieldDecl *, 4> HistoryStack;
9672 HistoryStack.push_back(nullptr);
9674 // At this point we already handled everything except of a RecordType or
9675 // an ArrayType of a RecordType.
9676 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9677 const RecordType *RecTy =
9678 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9679 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9681 VisitStack.push_back(RecTy->getDecl());
9682 assert(VisitStack.back() && "First decl null?");
9684 do {
9685 const Decl *Next = VisitStack.pop_back_val();
9686 if (!Next) {
9687 assert(!HistoryStack.empty());
9688 // Found a marker, we have gone up a level
9689 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9690 ValidTypes.insert(Hist->getType().getTypePtr());
9692 continue;
9695 // Adds everything except the original parameter declaration (which is not a
9696 // field itself) to the history stack.
9697 const RecordDecl *RD;
9698 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9699 HistoryStack.push_back(Field);
9701 QualType FieldTy = Field->getType();
9702 // Other field types (known to be valid or invalid) are handled while we
9703 // walk around RecordDecl::fields().
9704 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9705 "Unexpected type.");
9706 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9708 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9709 } else {
9710 RD = cast<RecordDecl>(Next);
9713 // Add a null marker so we know when we've gone back up a level
9714 VisitStack.push_back(nullptr);
9716 for (const auto *FD : RD->fields()) {
9717 QualType QT = FD->getType();
9719 if (ValidTypes.count(QT.getTypePtr()))
9720 continue;
9722 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9723 if (ParamType == ValidKernelParam)
9724 continue;
9726 if (ParamType == RecordKernelParam) {
9727 VisitStack.push_back(FD);
9728 continue;
9731 // OpenCL v1.2 s6.9.p:
9732 // Arguments to kernel functions that are declared to be a struct or union
9733 // do not allow OpenCL objects to be passed as elements of the struct or
9734 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9735 // of SVM.
9736 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9737 ParamType == InvalidAddrSpacePtrKernelParam) {
9738 S.Diag(Param->getLocation(),
9739 diag::err_record_with_pointers_kernel_param)
9740 << PT->isUnionType()
9741 << PT;
9742 } else {
9743 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9746 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9747 << OrigRecDecl->getDeclName();
9749 // We have an error, now let's go back up through history and show where
9750 // the offending field came from
9751 for (ArrayRef<const FieldDecl *>::const_iterator
9752 I = HistoryStack.begin() + 1,
9753 E = HistoryStack.end();
9754 I != E; ++I) {
9755 const FieldDecl *OuterField = *I;
9756 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9757 << OuterField->getType();
9760 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9761 << QT->isPointerType()
9762 << QT;
9763 D.setInvalidType();
9764 return;
9766 } while (!VisitStack.empty());
9769 /// Find the DeclContext in which a tag is implicitly declared if we see an
9770 /// elaborated type specifier in the specified context, and lookup finds
9771 /// nothing.
9772 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9773 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9774 DC = DC->getParent();
9775 return DC;
9778 /// Find the Scope in which a tag is implicitly declared if we see an
9779 /// elaborated type specifier in the specified context, and lookup finds
9780 /// nothing.
9781 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9782 while (S->isClassScope() ||
9783 (LangOpts.CPlusPlus &&
9784 S->isFunctionPrototypeScope()) ||
9785 ((S->getFlags() & Scope::DeclScope) == 0) ||
9786 (S->getEntity() && S->getEntity()->isTransparentContext()))
9787 S = S->getParent();
9788 return S;
9791 /// Determine whether a declaration matches a known function in namespace std.
9792 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9793 unsigned BuiltinID) {
9794 switch (BuiltinID) {
9795 case Builtin::BI__GetExceptionInfo:
9796 // No type checking whatsoever.
9797 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9799 case Builtin::BIaddressof:
9800 case Builtin::BI__addressof:
9801 case Builtin::BIforward:
9802 case Builtin::BIforward_like:
9803 case Builtin::BImove:
9804 case Builtin::BImove_if_noexcept:
9805 case Builtin::BIas_const: {
9806 // Ensure that we don't treat the algorithm
9807 // OutputIt std::move(InputIt, InputIt, OutputIt)
9808 // as the builtin std::move.
9809 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9810 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9813 default:
9814 return false;
9818 NamedDecl*
9819 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9820 TypeSourceInfo *TInfo, LookupResult &Previous,
9821 MultiTemplateParamsArg TemplateParamListsRef,
9822 bool &AddToScope) {
9823 QualType R = TInfo->getType();
9825 assert(R->isFunctionType());
9826 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9827 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9829 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9830 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9831 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9832 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9833 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9834 TemplateParamLists.back() = Invented;
9835 else
9836 TemplateParamLists.push_back(Invented);
9839 // TODO: consider using NameInfo for diagnostic.
9840 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9841 DeclarationName Name = NameInfo.getName();
9842 StorageClass SC = getFunctionStorageClass(*this, D);
9844 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9845 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9846 diag::err_invalid_thread)
9847 << DeclSpec::getSpecifierName(TSCS);
9849 if (D.isFirstDeclarationOfMember())
9850 adjustMemberFunctionCC(
9851 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9852 D.isCtorOrDtor(), D.getIdentifierLoc());
9854 bool isFriend = false;
9855 FunctionTemplateDecl *FunctionTemplate = nullptr;
9856 bool isMemberSpecialization = false;
9857 bool isFunctionTemplateSpecialization = false;
9859 bool HasExplicitTemplateArgs = false;
9860 TemplateArgumentListInfo TemplateArgs;
9862 bool isVirtualOkay = false;
9864 DeclContext *OriginalDC = DC;
9865 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9867 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9868 isVirtualOkay);
9869 if (!NewFD) return nullptr;
9871 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9872 NewFD->setTopLevelDeclInObjCContainer();
9874 // Set the lexical context. If this is a function-scope declaration, or has a
9875 // C++ scope specifier, or is the object of a friend declaration, the lexical
9876 // context will be different from the semantic context.
9877 NewFD->setLexicalDeclContext(CurContext);
9879 if (IsLocalExternDecl)
9880 NewFD->setLocalExternDecl();
9882 if (getLangOpts().CPlusPlus) {
9883 // The rules for implicit inlines changed in C++20 for methods and friends
9884 // with an in-class definition (when such a definition is not attached to
9885 // the global module). This does not affect declarations that are already
9886 // inline (whether explicitly or implicitly by being declared constexpr,
9887 // consteval, etc).
9888 // FIXME: We need a better way to separate C++ standard and clang modules.
9889 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9890 !NewFD->getOwningModule() ||
9891 NewFD->isFromGlobalModule() ||
9892 NewFD->getOwningModule()->isHeaderLikeModule();
9893 bool isInline = D.getDeclSpec().isInlineSpecified();
9894 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9895 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9896 isFriend = D.getDeclSpec().isFriendSpecified();
9897 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9898 // Pre-C++20 [class.friend]p5
9899 // A function can be defined in a friend declaration of a
9900 // class . . . . Such a function is implicitly inline.
9901 // Post C++20 [class.friend]p7
9902 // Such a function is implicitly an inline function if it is attached
9903 // to the global module.
9904 NewFD->setImplicitlyInline();
9907 // If this is a method defined in an __interface, and is not a constructor
9908 // or an overloaded operator, then set the pure flag (isVirtual will already
9909 // return true).
9910 if (const CXXRecordDecl *Parent =
9911 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9912 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9913 NewFD->setIsPureVirtual(true);
9915 // C++ [class.union]p2
9916 // A union can have member functions, but not virtual functions.
9917 if (isVirtual && Parent->isUnion()) {
9918 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9919 NewFD->setInvalidDecl();
9921 if ((Parent->isClass() || Parent->isStruct()) &&
9922 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9923 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9924 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9925 if (auto *Def = Parent->getDefinition())
9926 Def->setInitMethod(true);
9930 SetNestedNameSpecifier(*this, NewFD, D);
9931 isMemberSpecialization = false;
9932 isFunctionTemplateSpecialization = false;
9933 if (D.isInvalidType())
9934 NewFD->setInvalidDecl();
9936 // Match up the template parameter lists with the scope specifier, then
9937 // determine whether we have a template or a template specialization.
9938 bool Invalid = false;
9939 TemplateIdAnnotation *TemplateId =
9940 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9941 ? D.getName().TemplateId
9942 : nullptr;
9943 TemplateParameterList *TemplateParams =
9944 MatchTemplateParametersToScopeSpecifier(
9945 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9946 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9947 isMemberSpecialization, Invalid);
9948 if (TemplateParams) {
9949 // Check that we can declare a template here.
9950 if (CheckTemplateDeclScope(S, TemplateParams))
9951 NewFD->setInvalidDecl();
9953 if (TemplateParams->size() > 0) {
9954 // This is a function template
9956 // A destructor cannot be a template.
9957 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9958 Diag(NewFD->getLocation(), diag::err_destructor_template);
9959 NewFD->setInvalidDecl();
9960 // Function template with explicit template arguments.
9961 } else if (TemplateId) {
9962 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9963 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9964 NewFD->setInvalidDecl();
9967 // If we're adding a template to a dependent context, we may need to
9968 // rebuilding some of the types used within the template parameter list,
9969 // now that we know what the current instantiation is.
9970 if (DC->isDependentContext()) {
9971 ContextRAII SavedContext(*this, DC);
9972 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9973 Invalid = true;
9976 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9977 NewFD->getLocation(),
9978 Name, TemplateParams,
9979 NewFD);
9980 FunctionTemplate->setLexicalDeclContext(CurContext);
9981 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9983 // For source fidelity, store the other template param lists.
9984 if (TemplateParamLists.size() > 1) {
9985 NewFD->setTemplateParameterListsInfo(Context,
9986 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9987 .drop_back(1));
9989 } else {
9990 // This is a function template specialization.
9991 isFunctionTemplateSpecialization = true;
9992 // For source fidelity, store all the template param lists.
9993 if (TemplateParamLists.size() > 0)
9994 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9996 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9997 if (isFriend) {
9998 // We want to remove the "template<>", found here.
9999 SourceRange RemoveRange = TemplateParams->getSourceRange();
10001 // If we remove the template<> and the name is not a
10002 // template-id, we're actually silently creating a problem:
10003 // the friend declaration will refer to an untemplated decl,
10004 // and clearly the user wants a template specialization. So
10005 // we need to insert '<>' after the name.
10006 SourceLocation InsertLoc;
10007 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10008 InsertLoc = D.getName().getSourceRange().getEnd();
10009 InsertLoc = getLocForEndOfToken(InsertLoc);
10012 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10013 << Name << RemoveRange
10014 << FixItHint::CreateRemoval(RemoveRange)
10015 << FixItHint::CreateInsertion(InsertLoc, "<>");
10016 Invalid = true;
10018 // Recover by faking up an empty template argument list.
10019 HasExplicitTemplateArgs = true;
10020 TemplateArgs.setLAngleLoc(InsertLoc);
10021 TemplateArgs.setRAngleLoc(InsertLoc);
10024 } else {
10025 // Check that we can declare a template here.
10026 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10027 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10028 NewFD->setInvalidDecl();
10030 // All template param lists were matched against the scope specifier:
10031 // this is NOT (an explicit specialization of) a template.
10032 if (TemplateParamLists.size() > 0)
10033 // For source fidelity, store all the template param lists.
10034 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10036 // "friend void foo<>(int);" is an implicit specialization decl.
10037 if (isFriend && TemplateId)
10038 isFunctionTemplateSpecialization = true;
10041 // If this is a function template specialization and the unqualified-id of
10042 // the declarator-id is a template-id, convert the template argument list
10043 // into our AST format and check for unexpanded packs.
10044 if (isFunctionTemplateSpecialization && TemplateId) {
10045 HasExplicitTemplateArgs = true;
10047 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10048 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10049 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10050 TemplateId->NumArgs);
10051 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10053 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10054 // declaration of a function template partial specialization? Should we
10055 // consider the unexpanded pack context to be a partial specialization?
10056 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10057 if (DiagnoseUnexpandedParameterPack(
10058 ArgLoc, isFriend ? UPPC_FriendDeclaration
10059 : UPPC_ExplicitSpecialization))
10060 NewFD->setInvalidDecl();
10064 if (Invalid) {
10065 NewFD->setInvalidDecl();
10066 if (FunctionTemplate)
10067 FunctionTemplate->setInvalidDecl();
10070 // C++ [dcl.fct.spec]p5:
10071 // The virtual specifier shall only be used in declarations of
10072 // nonstatic class member functions that appear within a
10073 // member-specification of a class declaration; see 10.3.
10075 if (isVirtual && !NewFD->isInvalidDecl()) {
10076 if (!isVirtualOkay) {
10077 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10078 diag::err_virtual_non_function);
10079 } else if (!CurContext->isRecord()) {
10080 // 'virtual' was specified outside of the class.
10081 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10082 diag::err_virtual_out_of_class)
10083 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10084 } else if (NewFD->getDescribedFunctionTemplate()) {
10085 // C++ [temp.mem]p3:
10086 // A member function template shall not be virtual.
10087 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10088 diag::err_virtual_member_function_template)
10089 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10090 } else {
10091 // Okay: Add virtual to the method.
10092 NewFD->setVirtualAsWritten(true);
10095 if (getLangOpts().CPlusPlus14 &&
10096 NewFD->getReturnType()->isUndeducedType())
10097 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10100 // C++ [dcl.fct.spec]p3:
10101 // The inline specifier shall not appear on a block scope function
10102 // declaration.
10103 if (isInline && !NewFD->isInvalidDecl()) {
10104 if (CurContext->isFunctionOrMethod()) {
10105 // 'inline' is not allowed on block scope function declaration.
10106 Diag(D.getDeclSpec().getInlineSpecLoc(),
10107 diag::err_inline_declaration_block_scope) << Name
10108 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10112 // C++ [dcl.fct.spec]p6:
10113 // The explicit specifier shall be used only in the declaration of a
10114 // constructor or conversion function within its class definition;
10115 // see 12.3.1 and 12.3.2.
10116 if (hasExplicit && !NewFD->isInvalidDecl() &&
10117 !isa<CXXDeductionGuideDecl>(NewFD)) {
10118 if (!CurContext->isRecord()) {
10119 // 'explicit' was specified outside of the class.
10120 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10121 diag::err_explicit_out_of_class)
10122 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10123 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10124 !isa<CXXConversionDecl>(NewFD)) {
10125 // 'explicit' was specified on a function that wasn't a constructor
10126 // or conversion function.
10127 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10128 diag::err_explicit_non_ctor_or_conv_function)
10129 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10133 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10134 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10135 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10136 // are implicitly inline.
10137 NewFD->setImplicitlyInline();
10139 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10140 // be either constructors or to return a literal type. Therefore,
10141 // destructors cannot be declared constexpr.
10142 if (isa<CXXDestructorDecl>(NewFD) &&
10143 (!getLangOpts().CPlusPlus20 ||
10144 ConstexprKind == ConstexprSpecKind::Consteval)) {
10145 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10146 << static_cast<int>(ConstexprKind);
10147 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10148 ? ConstexprSpecKind::Unspecified
10149 : ConstexprSpecKind::Constexpr);
10151 // C++20 [dcl.constexpr]p2: An allocation function, or a
10152 // deallocation function shall not be declared with the consteval
10153 // specifier.
10154 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10155 (NewFD->getOverloadedOperator() == OO_New ||
10156 NewFD->getOverloadedOperator() == OO_Array_New ||
10157 NewFD->getOverloadedOperator() == OO_Delete ||
10158 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10159 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10160 diag::err_invalid_consteval_decl_kind)
10161 << NewFD;
10162 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10166 // If __module_private__ was specified, mark the function accordingly.
10167 if (D.getDeclSpec().isModulePrivateSpecified()) {
10168 if (isFunctionTemplateSpecialization) {
10169 SourceLocation ModulePrivateLoc
10170 = D.getDeclSpec().getModulePrivateSpecLoc();
10171 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10172 << 0
10173 << FixItHint::CreateRemoval(ModulePrivateLoc);
10174 } else {
10175 NewFD->setModulePrivate();
10176 if (FunctionTemplate)
10177 FunctionTemplate->setModulePrivate();
10181 if (isFriend) {
10182 if (FunctionTemplate) {
10183 FunctionTemplate->setObjectOfFriendDecl();
10184 FunctionTemplate->setAccess(AS_public);
10186 NewFD->setObjectOfFriendDecl();
10187 NewFD->setAccess(AS_public);
10190 // If a function is defined as defaulted or deleted, mark it as such now.
10191 // We'll do the relevant checks on defaulted / deleted functions later.
10192 switch (D.getFunctionDefinitionKind()) {
10193 case FunctionDefinitionKind::Declaration:
10194 case FunctionDefinitionKind::Definition:
10195 break;
10197 case FunctionDefinitionKind::Defaulted:
10198 NewFD->setDefaulted();
10199 break;
10201 case FunctionDefinitionKind::Deleted:
10202 NewFD->setDeletedAsWritten();
10203 break;
10206 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10207 D.isFunctionDefinition()) {
10208 // Pre C++20 [class.mfct]p2:
10209 // A member function may be defined (8.4) in its class definition, in
10210 // which case it is an inline member function (7.1.2)
10211 // Post C++20 [class.mfct]p1:
10212 // If a member function is attached to the global module and is defined
10213 // in its class definition, it is inline.
10214 NewFD->setImplicitlyInline();
10217 if (!isFriend && SC != SC_None) {
10218 // C++ [temp.expl.spec]p2:
10219 // The declaration in an explicit-specialization shall not be an
10220 // export-declaration. An explicit specialization shall not use a
10221 // storage-class-specifier other than thread_local.
10223 // We diagnose friend declarations with storage-class-specifiers
10224 // elsewhere.
10225 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10226 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10227 diag::ext_explicit_specialization_storage_class)
10228 << FixItHint::CreateRemoval(
10229 D.getDeclSpec().getStorageClassSpecLoc());
10232 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10233 assert(isa<CXXMethodDecl>(NewFD) &&
10234 "Out-of-line member function should be a CXXMethodDecl");
10235 // C++ [class.static]p1:
10236 // A data or function member of a class may be declared static
10237 // in a class definition, in which case it is a static member of
10238 // the class.
10240 // Complain about the 'static' specifier if it's on an out-of-line
10241 // member function definition.
10243 // MSVC permits the use of a 'static' storage specifier on an
10244 // out-of-line member function template declaration and class member
10245 // template declaration (MSVC versions before 2015), warn about this.
10246 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10247 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10248 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10249 (getLangOpts().MSVCCompat &&
10250 NewFD->getDescribedFunctionTemplate()))
10251 ? diag::ext_static_out_of_line
10252 : diag::err_static_out_of_line)
10253 << FixItHint::CreateRemoval(
10254 D.getDeclSpec().getStorageClassSpecLoc());
10258 // C++11 [except.spec]p15:
10259 // A deallocation function with no exception-specification is treated
10260 // as if it were specified with noexcept(true).
10261 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10262 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10263 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10264 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10265 NewFD->setType(Context.getFunctionType(
10266 FPT->getReturnType(), FPT->getParamTypes(),
10267 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10269 // C++20 [dcl.inline]/7
10270 // If an inline function or variable that is attached to a named module
10271 // is declared in a definition domain, it shall be defined in that
10272 // domain.
10273 // So, if the current declaration does not have a definition, we must
10274 // check at the end of the TU (or when the PMF starts) to see that we
10275 // have a definition at that point.
10276 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10277 NewFD->isInNamedModule()) {
10278 PendingInlineFuncDecls.insert(NewFD);
10282 // Filter out previous declarations that don't match the scope.
10283 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10284 D.getCXXScopeSpec().isNotEmpty() ||
10285 isMemberSpecialization ||
10286 isFunctionTemplateSpecialization);
10288 // Handle GNU asm-label extension (encoded as an attribute).
10289 if (Expr *E = (Expr*) D.getAsmLabel()) {
10290 // The parser guarantees this is a string.
10291 StringLiteral *SE = cast<StringLiteral>(E);
10292 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10293 /*IsLiteralLabel=*/true,
10294 SE->getStrTokenLoc(0)));
10295 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10296 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10297 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10298 if (I != ExtnameUndeclaredIdentifiers.end()) {
10299 if (isDeclExternC(NewFD)) {
10300 NewFD->addAttr(I->second);
10301 ExtnameUndeclaredIdentifiers.erase(I);
10302 } else
10303 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10304 << /*Variable*/0 << NewFD;
10308 // Copy the parameter declarations from the declarator D to the function
10309 // declaration NewFD, if they are available. First scavenge them into Params.
10310 SmallVector<ParmVarDecl*, 16> Params;
10311 unsigned FTIIdx;
10312 if (D.isFunctionDeclarator(FTIIdx)) {
10313 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10315 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10316 // function that takes no arguments, not a function that takes a
10317 // single void argument.
10318 // We let through "const void" here because Sema::GetTypeForDeclarator
10319 // already checks for that case.
10320 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10321 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10322 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10323 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10324 Param->setDeclContext(NewFD);
10325 Params.push_back(Param);
10327 if (Param->isInvalidDecl())
10328 NewFD->setInvalidDecl();
10332 if (!getLangOpts().CPlusPlus) {
10333 // In C, find all the tag declarations from the prototype and move them
10334 // into the function DeclContext. Remove them from the surrounding tag
10335 // injection context of the function, which is typically but not always
10336 // the TU.
10337 DeclContext *PrototypeTagContext =
10338 getTagInjectionContext(NewFD->getLexicalDeclContext());
10339 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10340 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10342 // We don't want to reparent enumerators. Look at their parent enum
10343 // instead.
10344 if (!TD) {
10345 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10346 TD = cast<EnumDecl>(ECD->getDeclContext());
10348 if (!TD)
10349 continue;
10350 DeclContext *TagDC = TD->getLexicalDeclContext();
10351 if (!TagDC->containsDecl(TD))
10352 continue;
10353 TagDC->removeDecl(TD);
10354 TD->setDeclContext(NewFD);
10355 NewFD->addDecl(TD);
10357 // Preserve the lexical DeclContext if it is not the surrounding tag
10358 // injection context of the FD. In this example, the semantic context of
10359 // E will be f and the lexical context will be S, while both the
10360 // semantic and lexical contexts of S will be f:
10361 // void f(struct S { enum E { a } f; } s);
10362 if (TagDC != PrototypeTagContext)
10363 TD->setLexicalDeclContext(TagDC);
10366 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10367 // When we're declaring a function with a typedef, typeof, etc as in the
10368 // following example, we'll need to synthesize (unnamed)
10369 // parameters for use in the declaration.
10371 // @code
10372 // typedef void fn(int);
10373 // fn f;
10374 // @endcode
10376 // Synthesize a parameter for each argument type.
10377 for (const auto &AI : FT->param_types()) {
10378 ParmVarDecl *Param =
10379 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10380 Param->setScopeInfo(0, Params.size());
10381 Params.push_back(Param);
10383 } else {
10384 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10385 "Should not need args for typedef of non-prototype fn");
10388 // Finally, we know we have the right number of parameters, install them.
10389 NewFD->setParams(Params);
10391 if (D.getDeclSpec().isNoreturnSpecified())
10392 NewFD->addAttr(
10393 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10395 // Functions returning a variably modified type violate C99 6.7.5.2p2
10396 // because all functions have linkage.
10397 if (!NewFD->isInvalidDecl() &&
10398 NewFD->getReturnType()->isVariablyModifiedType()) {
10399 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10400 NewFD->setInvalidDecl();
10403 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10404 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10405 !NewFD->hasAttr<SectionAttr>())
10406 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10407 Context, PragmaClangTextSection.SectionName,
10408 PragmaClangTextSection.PragmaLocation));
10410 // Apply an implicit SectionAttr if #pragma code_seg is active.
10411 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10412 !NewFD->hasAttr<SectionAttr>()) {
10413 NewFD->addAttr(SectionAttr::CreateImplicit(
10414 Context, CodeSegStack.CurrentValue->getString(),
10415 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10416 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10417 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10418 ASTContext::PSF_Read,
10419 NewFD))
10420 NewFD->dropAttr<SectionAttr>();
10423 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10424 // active.
10425 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10426 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10427 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10428 Context, PragmaClangTextSection.PragmaLocation));
10430 // Apply an implicit CodeSegAttr from class declspec or
10431 // apply an implicit SectionAttr from #pragma code_seg if active.
10432 if (!NewFD->hasAttr<CodeSegAttr>()) {
10433 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10434 D.isFunctionDefinition())) {
10435 NewFD->addAttr(SAttr);
10439 // Handle attributes.
10440 ProcessDeclAttributes(S, NewFD, D);
10441 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10442 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10443 !NewTVA->isDefaultVersion() &&
10444 !Context.getTargetInfo().hasFeature("fmv")) {
10445 // Don't add to scope fmv functions declarations if fmv disabled
10446 AddToScope = false;
10447 return NewFD;
10450 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10451 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10452 // type.
10454 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10455 // type declaration will generate a compilation error.
10456 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10457 if (AddressSpace != LangAS::Default) {
10458 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10459 NewFD->setInvalidDecl();
10463 if (!getLangOpts().CPlusPlus) {
10464 // Perform semantic checking on the function declaration.
10465 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10466 CheckMain(NewFD, D.getDeclSpec());
10468 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10469 CheckMSVCRTEntryPoint(NewFD);
10471 if (!NewFD->isInvalidDecl())
10472 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10473 isMemberSpecialization,
10474 D.isFunctionDefinition()));
10475 else if (!Previous.empty())
10476 // Recover gracefully from an invalid redeclaration.
10477 D.setRedeclaration(true);
10478 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10479 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10480 "previous declaration set still overloaded");
10482 // Diagnose no-prototype function declarations with calling conventions that
10483 // don't support variadic calls. Only do this in C and do it after merging
10484 // possibly prototyped redeclarations.
10485 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10486 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10487 CallingConv CC = FT->getExtInfo().getCC();
10488 if (!supportsVariadicCall(CC)) {
10489 // Windows system headers sometimes accidentally use stdcall without
10490 // (void) parameters, so we relax this to a warning.
10491 int DiagID =
10492 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10493 Diag(NewFD->getLocation(), DiagID)
10494 << FunctionType::getNameForCallConv(CC);
10498 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10499 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10500 checkNonTrivialCUnion(NewFD->getReturnType(),
10501 NewFD->getReturnTypeSourceRange().getBegin(),
10502 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10503 } else {
10504 // C++11 [replacement.functions]p3:
10505 // The program's definitions shall not be specified as inline.
10507 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10509 // Suppress the diagnostic if the function is __attribute__((used)), since
10510 // that forces an external definition to be emitted.
10511 if (D.getDeclSpec().isInlineSpecified() &&
10512 NewFD->isReplaceableGlobalAllocationFunction() &&
10513 !NewFD->hasAttr<UsedAttr>())
10514 Diag(D.getDeclSpec().getInlineSpecLoc(),
10515 diag::ext_operator_new_delete_declared_inline)
10516 << NewFD->getDeclName();
10518 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10519 // C++20 [dcl.decl.general]p4:
10520 // The optional requires-clause in an init-declarator or
10521 // member-declarator shall be present only if the declarator declares a
10522 // templated function.
10524 // C++20 [temp.pre]p8:
10525 // An entity is templated if it is
10526 // - a template,
10527 // - an entity defined or created in a templated entity,
10528 // - a member of a templated entity,
10529 // - an enumerator for an enumeration that is a templated entity, or
10530 // - the closure type of a lambda-expression appearing in the
10531 // declaration of a templated entity.
10533 // [Note 6: A local class, a local or block variable, or a friend
10534 // function defined in a templated entity is a templated entity.
10535 // — end note]
10537 // A templated function is a function template or a function that is
10538 // templated. A templated class is a class template or a class that is
10539 // templated. A templated variable is a variable template or a variable
10540 // that is templated.
10541 if (!FunctionTemplate) {
10542 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10543 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10544 // An explicit specialization shall not have a trailing
10545 // requires-clause unless it declares a function template.
10547 // Since a friend function template specialization cannot be
10548 // definition, and since a non-template friend declaration with a
10549 // trailing requires-clause must be a definition, we diagnose
10550 // friend function template specializations with trailing
10551 // requires-clauses on the same path as explicit specializations
10552 // even though they aren't necessarily prohibited by the same
10553 // language rule.
10554 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10555 << isFriend;
10556 } else if (isFriend && NewFD->isTemplated() &&
10557 !D.isFunctionDefinition()) {
10558 // C++ [temp.friend]p9:
10559 // A non-template friend declaration with a requires-clause shall be
10560 // a definition.
10561 Diag(NewFD->getBeginLoc(),
10562 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10563 NewFD->setInvalidDecl();
10564 } else if (!NewFD->isTemplated() ||
10565 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10566 Diag(TRC->getBeginLoc(),
10567 diag::err_constrained_non_templated_function);
10572 // We do not add HD attributes to specializations here because
10573 // they may have different constexpr-ness compared to their
10574 // templates and, after maybeAddHostDeviceAttrs() is applied,
10575 // may end up with different effective targets. Instead, a
10576 // specialization inherits its target attributes from its template
10577 // in the CheckFunctionTemplateSpecialization() call below.
10578 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10579 CUDA().maybeAddHostDeviceAttrs(NewFD, Previous);
10581 // Handle explicit specializations of function templates
10582 // and friend function declarations with an explicit
10583 // template argument list.
10584 if (isFunctionTemplateSpecialization) {
10585 bool isDependentSpecialization = false;
10586 if (isFriend) {
10587 // For friend function specializations, this is a dependent
10588 // specialization if its semantic context is dependent, its
10589 // type is dependent, or if its template-id is dependent.
10590 isDependentSpecialization =
10591 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10592 (HasExplicitTemplateArgs &&
10593 TemplateSpecializationType::
10594 anyInstantiationDependentTemplateArguments(
10595 TemplateArgs.arguments()));
10596 assert((!isDependentSpecialization ||
10597 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10598 "dependent friend function specialization without template "
10599 "args");
10600 } else {
10601 // For class-scope explicit specializations of function templates,
10602 // if the lexical context is dependent, then the specialization
10603 // is dependent.
10604 isDependentSpecialization =
10605 CurContext->isRecord() && CurContext->isDependentContext();
10608 TemplateArgumentListInfo *ExplicitTemplateArgs =
10609 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10610 if (isDependentSpecialization) {
10611 // If it's a dependent specialization, it may not be possible
10612 // to determine the primary template (for explicit specializations)
10613 // or befriended declaration (for friends) until the enclosing
10614 // template is instantiated. In such cases, we store the declarations
10615 // found by name lookup and defer resolution until instantiation.
10616 if (CheckDependentFunctionTemplateSpecialization(
10617 NewFD, ExplicitTemplateArgs, Previous))
10618 NewFD->setInvalidDecl();
10619 } else if (!NewFD->isInvalidDecl()) {
10620 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10621 Previous))
10622 NewFD->setInvalidDecl();
10624 } else if (isMemberSpecialization && !FunctionTemplate) {
10625 if (CheckMemberSpecialization(NewFD, Previous))
10626 NewFD->setInvalidDecl();
10629 // Perform semantic checking on the function declaration.
10630 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10631 CheckMain(NewFD, D.getDeclSpec());
10633 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10634 CheckMSVCRTEntryPoint(NewFD);
10636 if (!NewFD->isInvalidDecl())
10637 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10638 isMemberSpecialization,
10639 D.isFunctionDefinition()));
10640 else if (!Previous.empty())
10641 // Recover gracefully from an invalid redeclaration.
10642 D.setRedeclaration(true);
10644 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10645 !D.isRedeclaration() ||
10646 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10647 "previous declaration set still overloaded");
10649 NamedDecl *PrincipalDecl = (FunctionTemplate
10650 ? cast<NamedDecl>(FunctionTemplate)
10651 : NewFD);
10653 if (isFriend && NewFD->getPreviousDecl()) {
10654 AccessSpecifier Access = AS_public;
10655 if (!NewFD->isInvalidDecl())
10656 Access = NewFD->getPreviousDecl()->getAccess();
10658 NewFD->setAccess(Access);
10659 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10662 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10663 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10664 PrincipalDecl->setNonMemberOperator();
10666 // If we have a function template, check the template parameter
10667 // list. This will check and merge default template arguments.
10668 if (FunctionTemplate) {
10669 FunctionTemplateDecl *PrevTemplate =
10670 FunctionTemplate->getPreviousDecl();
10671 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10672 PrevTemplate ? PrevTemplate->getTemplateParameters()
10673 : nullptr,
10674 D.getDeclSpec().isFriendSpecified()
10675 ? (D.isFunctionDefinition()
10676 ? TPC_FriendFunctionTemplateDefinition
10677 : TPC_FriendFunctionTemplate)
10678 : (D.getCXXScopeSpec().isSet() &&
10679 DC && DC->isRecord() &&
10680 DC->isDependentContext())
10681 ? TPC_ClassTemplateMember
10682 : TPC_FunctionTemplate);
10685 if (NewFD->isInvalidDecl()) {
10686 // Ignore all the rest of this.
10687 } else if (!D.isRedeclaration()) {
10688 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10689 AddToScope };
10690 // Fake up an access specifier if it's supposed to be a class member.
10691 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10692 NewFD->setAccess(AS_public);
10694 // Qualified decls generally require a previous declaration.
10695 if (D.getCXXScopeSpec().isSet()) {
10696 // ...with the major exception of templated-scope or
10697 // dependent-scope friend declarations.
10699 // TODO: we currently also suppress this check in dependent
10700 // contexts because (1) the parameter depth will be off when
10701 // matching friend templates and (2) we might actually be
10702 // selecting a friend based on a dependent factor. But there
10703 // are situations where these conditions don't apply and we
10704 // can actually do this check immediately.
10706 // Unless the scope is dependent, it's always an error if qualified
10707 // redeclaration lookup found nothing at all. Diagnose that now;
10708 // nothing will diagnose that error later.
10709 if (isFriend &&
10710 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10711 (!Previous.empty() && CurContext->isDependentContext()))) {
10712 // ignore these
10713 } else if (NewFD->isCPUDispatchMultiVersion() ||
10714 NewFD->isCPUSpecificMultiVersion()) {
10715 // ignore this, we allow the redeclaration behavior here to create new
10716 // versions of the function.
10717 } else {
10718 // The user tried to provide an out-of-line definition for a
10719 // function that is a member of a class or namespace, but there
10720 // was no such member function declared (C++ [class.mfct]p2,
10721 // C++ [namespace.memdef]p2). For example:
10723 // class X {
10724 // void f() const;
10725 // };
10727 // void X::f() { } // ill-formed
10729 // Complain about this problem, and attempt to suggest close
10730 // matches (e.g., those that differ only in cv-qualifiers and
10731 // whether the parameter types are references).
10733 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10734 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10735 AddToScope = ExtraArgs.AddToScope;
10736 return Result;
10740 // Unqualified local friend declarations are required to resolve
10741 // to something.
10742 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10743 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10744 *this, Previous, NewFD, ExtraArgs, true, S)) {
10745 AddToScope = ExtraArgs.AddToScope;
10746 return Result;
10749 } else if (!D.isFunctionDefinition() &&
10750 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10751 !isFriend && !isFunctionTemplateSpecialization &&
10752 !isMemberSpecialization) {
10753 // An out-of-line member function declaration must also be a
10754 // definition (C++ [class.mfct]p2).
10755 // Note that this is not the case for explicit specializations of
10756 // function templates or member functions of class templates, per
10757 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10758 // extension for compatibility with old SWIG code which likes to
10759 // generate them.
10760 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10761 << D.getCXXScopeSpec().getRange();
10765 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10766 // Any top level function could potentially be specified as an entry.
10767 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10768 HLSL().ActOnTopLevelFunction(NewFD);
10770 if (NewFD->hasAttr<HLSLShaderAttr>())
10771 HLSL().CheckEntryPoint(NewFD);
10774 // If this is the first declaration of a library builtin function, add
10775 // attributes as appropriate.
10776 if (!D.isRedeclaration()) {
10777 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10778 if (unsigned BuiltinID = II->getBuiltinID()) {
10779 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10780 if (!InStdNamespace &&
10781 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10782 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10783 // Validate the type matches unless this builtin is specified as
10784 // matching regardless of its declared type.
10785 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10786 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10787 } else {
10788 ASTContext::GetBuiltinTypeError Error;
10789 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10790 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10792 if (!Error && !BuiltinType.isNull() &&
10793 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10794 NewFD->getType(), BuiltinType))
10795 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10798 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10799 isStdBuiltin(Context, NewFD, BuiltinID)) {
10800 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10806 ProcessPragmaWeak(S, NewFD);
10807 checkAttributesAfterMerging(*this, *NewFD);
10809 AddKnownFunctionAttributes(NewFD);
10811 if (NewFD->hasAttr<OverloadableAttr>() &&
10812 !NewFD->getType()->getAs<FunctionProtoType>()) {
10813 Diag(NewFD->getLocation(),
10814 diag::err_attribute_overloadable_no_prototype)
10815 << NewFD;
10816 NewFD->dropAttr<OverloadableAttr>();
10819 // If there's a #pragma GCC visibility in scope, and this isn't a class
10820 // member, set the visibility of this function.
10821 if (!DC->isRecord() && NewFD->isExternallyVisible())
10822 AddPushedVisibilityAttribute(NewFD);
10824 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10825 // marking the function.
10826 ObjC().AddCFAuditedAttribute(NewFD);
10828 // If this is a function definition, check if we have to apply any
10829 // attributes (i.e. optnone and no_builtin) due to a pragma.
10830 if (D.isFunctionDefinition()) {
10831 AddRangeBasedOptnone(NewFD);
10832 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10833 AddSectionMSAllocText(NewFD);
10834 ModifyFnAttributesMSPragmaOptimize(NewFD);
10837 // If this is the first declaration of an extern C variable, update
10838 // the map of such variables.
10839 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10840 isIncompleteDeclExternC(*this, NewFD))
10841 RegisterLocallyScopedExternCDecl(NewFD, S);
10843 // Set this FunctionDecl's range up to the right paren.
10844 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10846 if (D.isRedeclaration() && !Previous.empty()) {
10847 NamedDecl *Prev = Previous.getRepresentativeDecl();
10848 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10849 isMemberSpecialization ||
10850 isFunctionTemplateSpecialization,
10851 D.isFunctionDefinition());
10854 if (getLangOpts().CUDA) {
10855 IdentifierInfo *II = NewFD->getIdentifier();
10856 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10857 !NewFD->isInvalidDecl() &&
10858 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10859 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10860 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10861 << CUDA().getConfigureFuncName();
10862 Context.setcudaConfigureCallDecl(NewFD);
10865 // Variadic functions, other than a *declaration* of printf, are not allowed
10866 // in device-side CUDA code, unless someone passed
10867 // -fcuda-allow-variadic-functions.
10868 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10869 (NewFD->hasAttr<CUDADeviceAttr>() ||
10870 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10871 !(II && II->isStr("printf") && NewFD->isExternC() &&
10872 !D.isFunctionDefinition())) {
10873 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10877 MarkUnusedFileScopedDecl(NewFD);
10881 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10882 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10883 if (SC == SC_Static) {
10884 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10885 D.setInvalidType();
10888 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10889 if (!NewFD->getReturnType()->isVoidType()) {
10890 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10891 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10892 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10893 : FixItHint());
10894 D.setInvalidType();
10897 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10898 for (auto *Param : NewFD->parameters())
10899 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10901 if (getLangOpts().OpenCLCPlusPlus) {
10902 if (DC->isRecord()) {
10903 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10904 D.setInvalidType();
10906 if (FunctionTemplate) {
10907 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10908 D.setInvalidType();
10913 if (getLangOpts().CPlusPlus) {
10914 // Precalculate whether this is a friend function template with a constraint
10915 // that depends on an enclosing template, per [temp.friend]p9.
10916 if (isFriend && FunctionTemplate &&
10917 FriendConstraintsDependOnEnclosingTemplate(NewFD)) {
10918 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10920 // C++ [temp.friend]p9:
10921 // A friend function template with a constraint that depends on a
10922 // template parameter from an enclosing template shall be a definition.
10923 if (!D.isFunctionDefinition()) {
10924 Diag(NewFD->getBeginLoc(),
10925 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10926 NewFD->setInvalidDecl();
10930 if (FunctionTemplate) {
10931 if (NewFD->isInvalidDecl())
10932 FunctionTemplate->setInvalidDecl();
10933 return FunctionTemplate;
10936 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10937 CompleteMemberSpecialization(NewFD, Previous);
10940 for (const ParmVarDecl *Param : NewFD->parameters()) {
10941 QualType PT = Param->getType();
10943 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10944 // types.
10945 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10946 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10947 QualType ElemTy = PipeTy->getElementType();
10948 if (ElemTy->isPointerOrReferenceType()) {
10949 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
10950 D.setInvalidType();
10954 // WebAssembly tables can't be used as function parameters.
10955 if (Context.getTargetInfo().getTriple().isWasm()) {
10956 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10957 Diag(Param->getTypeSpecStartLoc(),
10958 diag::err_wasm_table_as_function_parameter);
10959 D.setInvalidType();
10964 // Diagnose availability attributes. Availability cannot be used on functions
10965 // that are run during load/unload.
10966 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10967 if (NewFD->hasAttr<ConstructorAttr>()) {
10968 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10969 << 1;
10970 NewFD->dropAttr<AvailabilityAttr>();
10972 if (NewFD->hasAttr<DestructorAttr>()) {
10973 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10974 << 2;
10975 NewFD->dropAttr<AvailabilityAttr>();
10979 // Diagnose no_builtin attribute on function declaration that are not a
10980 // definition.
10981 // FIXME: We should really be doing this in
10982 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10983 // the FunctionDecl and at this point of the code
10984 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10985 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10986 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10987 switch (D.getFunctionDefinitionKind()) {
10988 case FunctionDefinitionKind::Defaulted:
10989 case FunctionDefinitionKind::Deleted:
10990 Diag(NBA->getLocation(),
10991 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10992 << NBA->getSpelling();
10993 break;
10994 case FunctionDefinitionKind::Declaration:
10995 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10996 << NBA->getSpelling();
10997 break;
10998 case FunctionDefinitionKind::Definition:
10999 break;
11002 // Similar to no_builtin logic above, at this point of the code
11003 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11004 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11005 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11006 !NewFD->isInvalidDecl() &&
11007 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11008 ExternalDeclarations.push_back(NewFD);
11010 return NewFD;
11013 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
11014 /// when __declspec(code_seg) "is applied to a class, all member functions of
11015 /// the class and nested classes -- this includes compiler-generated special
11016 /// member functions -- are put in the specified segment."
11017 /// The actual behavior is a little more complicated. The Microsoft compiler
11018 /// won't check outer classes if there is an active value from #pragma code_seg.
11019 /// The CodeSeg is always applied from the direct parent but only from outer
11020 /// classes when the #pragma code_seg stack is empty. See:
11021 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11022 /// available since MS has removed the page.
11023 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11024 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11025 if (!Method)
11026 return nullptr;
11027 const CXXRecordDecl *Parent = Method->getParent();
11028 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11029 Attr *NewAttr = SAttr->clone(S.getASTContext());
11030 NewAttr->setImplicit(true);
11031 return NewAttr;
11034 // The Microsoft compiler won't check outer classes for the CodeSeg
11035 // when the #pragma code_seg stack is active.
11036 if (S.CodeSegStack.CurrentValue)
11037 return nullptr;
11039 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11040 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11041 Attr *NewAttr = SAttr->clone(S.getASTContext());
11042 NewAttr->setImplicit(true);
11043 return NewAttr;
11046 return nullptr;
11049 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11050 bool IsDefinition) {
11051 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11052 return A;
11053 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11054 CodeSegStack.CurrentValue)
11055 return SectionAttr::CreateImplicit(
11056 getASTContext(), CodeSegStack.CurrentValue->getString(),
11057 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11058 return nullptr;
11061 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11062 QualType NewT, QualType OldT) {
11063 if (!NewD->getLexicalDeclContext()->isDependentContext())
11064 return true;
11066 // For dependently-typed local extern declarations and friends, we can't
11067 // perform a correct type check in general until instantiation:
11069 // int f();
11070 // template<typename T> void g() { T f(); }
11072 // (valid if g() is only instantiated with T = int).
11073 if (NewT->isDependentType() &&
11074 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11075 return false;
11077 // Similarly, if the previous declaration was a dependent local extern
11078 // declaration, we don't really know its type yet.
11079 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11080 return false;
11082 return true;
11085 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11086 if (!D->getLexicalDeclContext()->isDependentContext())
11087 return true;
11089 // Don't chain dependent friend function definitions until instantiation, to
11090 // permit cases like
11092 // void func();
11093 // template<typename T> class C1 { friend void func() {} };
11094 // template<typename T> class C2 { friend void func() {} };
11096 // ... which is valid if only one of C1 and C2 is ever instantiated.
11098 // FIXME: This need only apply to function definitions. For now, we proxy
11099 // this by checking for a file-scope function. We do not want this to apply
11100 // to friend declarations nominating member functions, because that gets in
11101 // the way of access checks.
11102 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11103 return false;
11105 auto *VD = dyn_cast<ValueDecl>(D);
11106 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11107 return !VD || !PrevVD ||
11108 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11109 PrevVD->getType());
11112 /// Check the target or target_version attribute of the function for
11113 /// MultiVersion validity.
11115 /// Returns true if there was an error, false otherwise.
11116 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11117 const auto *TA = FD->getAttr<TargetAttr>();
11118 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11120 assert((TA || TVA) && "Expecting target or target_version attribute");
11122 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11123 enum ErrType { Feature = 0, Architecture = 1 };
11125 if (TA) {
11126 ParsedTargetAttr ParseInfo =
11127 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11128 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11129 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11130 << Architecture << ParseInfo.CPU;
11131 return true;
11133 for (const auto &Feat : ParseInfo.Features) {
11134 auto BareFeat = StringRef{Feat}.substr(1);
11135 if (Feat[0] == '-') {
11136 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11137 << Feature << ("no-" + BareFeat).str();
11138 return true;
11141 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11142 !TargetInfo.isValidFeatureName(BareFeat) ||
11143 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11144 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11145 << Feature << BareFeat;
11146 return true;
11151 if (TVA) {
11152 llvm::SmallVector<StringRef, 8> Feats;
11153 ParsedTargetAttr ParseInfo;
11154 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11155 ParseInfo =
11156 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11157 for (auto &Feat : ParseInfo.Features)
11158 Feats.push_back(StringRef{Feat}.substr(1));
11159 } else {
11160 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11161 TVA->getFeatures(Feats);
11163 for (const auto &Feat : Feats) {
11164 if (!TargetInfo.validateCpuSupports(Feat)) {
11165 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11166 << Feature << Feat;
11167 return true;
11171 return false;
11174 // Provide a white-list of attributes that are allowed to be combined with
11175 // multiversion functions.
11176 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11177 MultiVersionKind MVKind) {
11178 // Note: this list/diagnosis must match the list in
11179 // checkMultiversionAttributesAllSame.
11180 switch (Kind) {
11181 default:
11182 return false;
11183 case attr::ArmLocallyStreaming:
11184 return MVKind == MultiVersionKind::TargetVersion ||
11185 MVKind == MultiVersionKind::TargetClones;
11186 case attr::Used:
11187 return MVKind == MultiVersionKind::Target;
11188 case attr::NonNull:
11189 case attr::NoThrow:
11190 return true;
11194 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11195 const FunctionDecl *FD,
11196 const FunctionDecl *CausedFD,
11197 MultiVersionKind MVKind) {
11198 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11199 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11200 << static_cast<unsigned>(MVKind) << A;
11201 if (CausedFD)
11202 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11203 return true;
11206 for (const Attr *A : FD->attrs()) {
11207 switch (A->getKind()) {
11208 case attr::CPUDispatch:
11209 case attr::CPUSpecific:
11210 if (MVKind != MultiVersionKind::CPUDispatch &&
11211 MVKind != MultiVersionKind::CPUSpecific)
11212 return Diagnose(S, A);
11213 break;
11214 case attr::Target:
11215 if (MVKind != MultiVersionKind::Target)
11216 return Diagnose(S, A);
11217 break;
11218 case attr::TargetVersion:
11219 if (MVKind != MultiVersionKind::TargetVersion &&
11220 MVKind != MultiVersionKind::TargetClones)
11221 return Diagnose(S, A);
11222 break;
11223 case attr::TargetClones:
11224 if (MVKind != MultiVersionKind::TargetClones &&
11225 MVKind != MultiVersionKind::TargetVersion)
11226 return Diagnose(S, A);
11227 break;
11228 default:
11229 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11230 return Diagnose(S, A);
11231 break;
11234 return false;
11237 bool Sema::areMultiversionVariantFunctionsCompatible(
11238 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11239 const PartialDiagnostic &NoProtoDiagID,
11240 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11241 const PartialDiagnosticAt &NoSupportDiagIDAt,
11242 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11243 bool ConstexprSupported, bool CLinkageMayDiffer) {
11244 enum DoesntSupport {
11245 FuncTemplates = 0,
11246 VirtFuncs = 1,
11247 DeducedReturn = 2,
11248 Constructors = 3,
11249 Destructors = 4,
11250 DeletedFuncs = 5,
11251 DefaultedFuncs = 6,
11252 ConstexprFuncs = 7,
11253 ConstevalFuncs = 8,
11254 Lambda = 9,
11256 enum Different {
11257 CallingConv = 0,
11258 ReturnType = 1,
11259 ConstexprSpec = 2,
11260 InlineSpec = 3,
11261 Linkage = 4,
11262 LanguageLinkage = 5,
11265 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11266 !OldFD->getType()->getAs<FunctionProtoType>()) {
11267 Diag(OldFD->getLocation(), NoProtoDiagID);
11268 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11269 return true;
11272 if (NoProtoDiagID.getDiagID() != 0 &&
11273 !NewFD->getType()->getAs<FunctionProtoType>())
11274 return Diag(NewFD->getLocation(), NoProtoDiagID);
11276 if (!TemplatesSupported &&
11277 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11278 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11279 << FuncTemplates;
11281 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11282 if (NewCXXFD->isVirtual())
11283 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11284 << VirtFuncs;
11286 if (isa<CXXConstructorDecl>(NewCXXFD))
11287 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11288 << Constructors;
11290 if (isa<CXXDestructorDecl>(NewCXXFD))
11291 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11292 << Destructors;
11295 if (NewFD->isDeleted())
11296 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11297 << DeletedFuncs;
11299 if (NewFD->isDefaulted())
11300 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11301 << DefaultedFuncs;
11303 if (!ConstexprSupported && NewFD->isConstexpr())
11304 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11305 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11307 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11308 const auto *NewType = cast<FunctionType>(NewQType);
11309 QualType NewReturnType = NewType->getReturnType();
11311 if (NewReturnType->isUndeducedType())
11312 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11313 << DeducedReturn;
11315 // Ensure the return type is identical.
11316 if (OldFD) {
11317 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11318 const auto *OldType = cast<FunctionType>(OldQType);
11319 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11320 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11322 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11323 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11325 bool ArmStreamingCCMismatched = false;
11326 if (OldFPT && NewFPT) {
11327 unsigned Diff =
11328 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11329 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11330 // cannot be mixed.
11331 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11332 FunctionType::SME_PStateSMCompatibleMask))
11333 ArmStreamingCCMismatched = true;
11336 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11337 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11339 QualType OldReturnType = OldType->getReturnType();
11341 if (OldReturnType != NewReturnType)
11342 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11344 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11345 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11347 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11348 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11350 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11351 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11353 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11354 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11356 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11357 NewFD->getLocation()))
11358 return true;
11360 return false;
11363 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11364 const FunctionDecl *NewFD,
11365 bool CausesMV,
11366 MultiVersionKind MVKind) {
11367 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11368 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11369 if (OldFD)
11370 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11371 return true;
11374 bool IsCPUSpecificCPUDispatchMVKind =
11375 MVKind == MultiVersionKind::CPUDispatch ||
11376 MVKind == MultiVersionKind::CPUSpecific;
11378 if (CausesMV && OldFD &&
11379 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11380 return true;
11382 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11383 return true;
11385 // Only allow transition to MultiVersion if it hasn't been used.
11386 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11387 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11388 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11389 return true;
11392 return S.areMultiversionVariantFunctionsCompatible(
11393 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11394 PartialDiagnosticAt(NewFD->getLocation(),
11395 S.PDiag(diag::note_multiversioning_caused_here)),
11396 PartialDiagnosticAt(NewFD->getLocation(),
11397 S.PDiag(diag::err_multiversion_doesnt_support)
11398 << static_cast<unsigned>(MVKind)),
11399 PartialDiagnosticAt(NewFD->getLocation(),
11400 S.PDiag(diag::err_multiversion_diff)),
11401 /*TemplatesSupported=*/false,
11402 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11403 /*CLinkageMayDiffer=*/false);
11406 /// Check the validity of a multiversion function declaration that is the
11407 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11409 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11411 /// Returns true if there was an error, false otherwise.
11412 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11413 MultiVersionKind MVKind = FD->getMultiVersionKind();
11414 assert(MVKind != MultiVersionKind::None &&
11415 "Function lacks multiversion attribute");
11416 const auto *TA = FD->getAttr<TargetAttr>();
11417 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11418 // The target attribute only causes MV if this declaration is the default,
11419 // otherwise it is treated as a normal function.
11420 if (TA && !TA->isDefaultVersion())
11421 return false;
11423 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11424 FD->setInvalidDecl();
11425 return true;
11428 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11429 FD->setInvalidDecl();
11430 return true;
11433 FD->setIsMultiVersion();
11434 return false;
11437 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11438 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11439 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11440 return true;
11443 return false;
11446 static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11447 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11448 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11449 return;
11451 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11452 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11454 if (MVKindTo == MultiVersionKind::None &&
11455 (MVKindFrom == MultiVersionKind::TargetVersion ||
11456 MVKindFrom == MultiVersionKind::TargetClones))
11457 To->addAttr(TargetVersionAttr::CreateImplicit(
11458 To->getASTContext(), "default", To->getSourceRange()));
11461 static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11462 FunctionDecl *NewFD,
11463 bool &Redeclaration,
11464 NamedDecl *&OldDecl,
11465 LookupResult &Previous) {
11466 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11468 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11469 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11470 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11471 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11473 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11475 // The definitions should be allowed in any order. If we have discovered
11476 // a new target version and the preceeding was the default, then add the
11477 // corresponding attribute to it.
11478 patchDefaultTargetVersion(NewFD, OldFD);
11480 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11481 // to change, this is a simple redeclaration.
11482 if (NewTA && !NewTA->isDefaultVersion() &&
11483 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11484 return false;
11486 // Otherwise, this decl causes MultiVersioning.
11487 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11488 NewTVA ? MultiVersionKind::TargetVersion
11489 : MultiVersionKind::Target)) {
11490 NewFD->setInvalidDecl();
11491 return true;
11494 if (CheckMultiVersionValue(S, NewFD)) {
11495 NewFD->setInvalidDecl();
11496 return true;
11499 // If this is 'default', permit the forward declaration.
11500 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11501 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11502 Redeclaration = true;
11503 OldDecl = OldFD;
11504 OldFD->setIsMultiVersion();
11505 NewFD->setIsMultiVersion();
11506 return false;
11509 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11510 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11511 NewFD->setInvalidDecl();
11512 return true;
11515 if (NewTA) {
11516 ParsedTargetAttr OldParsed =
11517 S.getASTContext().getTargetInfo().parseTargetAttr(
11518 OldTA->getFeaturesStr());
11519 llvm::sort(OldParsed.Features);
11520 ParsedTargetAttr NewParsed =
11521 S.getASTContext().getTargetInfo().parseTargetAttr(
11522 NewTA->getFeaturesStr());
11523 // Sort order doesn't matter, it just needs to be consistent.
11524 llvm::sort(NewParsed.Features);
11525 if (OldParsed == NewParsed) {
11526 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11527 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11528 NewFD->setInvalidDecl();
11529 return true;
11533 for (const auto *FD : OldFD->redecls()) {
11534 const auto *CurTA = FD->getAttr<TargetAttr>();
11535 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11536 // We allow forward declarations before ANY multiversioning attributes, but
11537 // nothing after the fact.
11538 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11539 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11540 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11541 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11542 << (NewTA ? 0 : 2);
11543 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11544 NewFD->setInvalidDecl();
11545 return true;
11549 OldFD->setIsMultiVersion();
11550 NewFD->setIsMultiVersion();
11551 Redeclaration = false;
11552 OldDecl = nullptr;
11553 Previous.clear();
11554 return false;
11557 static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11558 MultiVersionKind OldKind = Old->getMultiVersionKind();
11559 MultiVersionKind NewKind = New->getMultiVersionKind();
11561 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11562 NewKind == MultiVersionKind::None)
11563 return true;
11565 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11566 switch (OldKind) {
11567 case MultiVersionKind::TargetVersion:
11568 return NewKind == MultiVersionKind::TargetClones;
11569 case MultiVersionKind::TargetClones:
11570 return NewKind == MultiVersionKind::TargetVersion;
11571 default:
11572 return false;
11574 } else {
11575 switch (OldKind) {
11576 case MultiVersionKind::CPUDispatch:
11577 return NewKind == MultiVersionKind::CPUSpecific;
11578 case MultiVersionKind::CPUSpecific:
11579 return NewKind == MultiVersionKind::CPUDispatch;
11580 default:
11581 return false;
11586 /// Check the validity of a new function declaration being added to an existing
11587 /// multiversioned declaration collection.
11588 static bool CheckMultiVersionAdditionalDecl(
11589 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11590 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11591 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11592 LookupResult &Previous) {
11594 // Disallow mixing of multiversioning types.
11595 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11596 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11597 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11598 NewFD->setInvalidDecl();
11599 return true;
11602 // Add the default target_version attribute if it's missing.
11603 patchDefaultTargetVersion(OldFD, NewFD);
11604 patchDefaultTargetVersion(NewFD, OldFD);
11606 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11607 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11608 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11609 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11611 ParsedTargetAttr NewParsed;
11612 if (NewTA) {
11613 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11614 NewTA->getFeaturesStr());
11615 llvm::sort(NewParsed.Features);
11617 llvm::SmallVector<StringRef, 8> NewFeats;
11618 if (NewTVA) {
11619 NewTVA->getFeatures(NewFeats);
11620 llvm::sort(NewFeats);
11623 bool UseMemberUsingDeclRules =
11624 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11626 bool MayNeedOverloadableChecks =
11627 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11629 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11630 // of a previous member of the MultiVersion set.
11631 for (NamedDecl *ND : Previous) {
11632 FunctionDecl *CurFD = ND->getAsFunction();
11633 if (!CurFD || CurFD->isInvalidDecl())
11634 continue;
11635 if (MayNeedOverloadableChecks &&
11636 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11637 continue;
11639 switch (NewMVKind) {
11640 case MultiVersionKind::None:
11641 assert(OldMVKind == MultiVersionKind::TargetClones &&
11642 "Only target_clones can be omitted in subsequent declarations");
11643 break;
11644 case MultiVersionKind::Target: {
11645 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11646 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11647 NewFD->setIsMultiVersion();
11648 Redeclaration = true;
11649 OldDecl = ND;
11650 return false;
11653 ParsedTargetAttr CurParsed =
11654 S.getASTContext().getTargetInfo().parseTargetAttr(
11655 CurTA->getFeaturesStr());
11656 llvm::sort(CurParsed.Features);
11657 if (CurParsed == NewParsed) {
11658 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11659 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11660 NewFD->setInvalidDecl();
11661 return true;
11663 break;
11665 case MultiVersionKind::TargetVersion: {
11666 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11667 if (CurTVA->getName() == NewTVA->getName()) {
11668 NewFD->setIsMultiVersion();
11669 Redeclaration = true;
11670 OldDecl = ND;
11671 return false;
11673 llvm::SmallVector<StringRef, 8> CurFeats;
11674 CurTVA->getFeatures(CurFeats);
11675 llvm::sort(CurFeats);
11677 if (CurFeats == NewFeats) {
11678 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11679 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11680 NewFD->setInvalidDecl();
11681 return true;
11683 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11684 // Default
11685 if (NewFeats.empty())
11686 break;
11688 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11689 llvm::SmallVector<StringRef, 8> CurFeats;
11690 CurClones->getFeatures(CurFeats, I);
11691 llvm::sort(CurFeats);
11693 if (CurFeats == NewFeats) {
11694 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11695 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11696 NewFD->setInvalidDecl();
11697 return true;
11701 break;
11703 case MultiVersionKind::TargetClones: {
11704 assert(NewClones && "MultiVersionKind does not match attribute type");
11705 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11706 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11707 !std::equal(CurClones->featuresStrs_begin(),
11708 CurClones->featuresStrs_end(),
11709 NewClones->featuresStrs_begin())) {
11710 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11711 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11712 NewFD->setInvalidDecl();
11713 return true;
11715 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11716 llvm::SmallVector<StringRef, 8> CurFeats;
11717 CurTVA->getFeatures(CurFeats);
11718 llvm::sort(CurFeats);
11720 // Default
11721 if (CurFeats.empty())
11722 break;
11724 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11725 NewFeats.clear();
11726 NewClones->getFeatures(NewFeats, I);
11727 llvm::sort(NewFeats);
11729 if (CurFeats == NewFeats) {
11730 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11731 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11732 NewFD->setInvalidDecl();
11733 return true;
11736 break;
11738 Redeclaration = true;
11739 OldDecl = CurFD;
11740 NewFD->setIsMultiVersion();
11741 return false;
11743 case MultiVersionKind::CPUSpecific:
11744 case MultiVersionKind::CPUDispatch: {
11745 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11746 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11747 // Handle CPUDispatch/CPUSpecific versions.
11748 // Only 1 CPUDispatch function is allowed, this will make it go through
11749 // the redeclaration errors.
11750 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11751 CurFD->hasAttr<CPUDispatchAttr>()) {
11752 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11753 std::equal(
11754 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11755 NewCPUDisp->cpus_begin(),
11756 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11757 return Cur->getName() == New->getName();
11758 })) {
11759 NewFD->setIsMultiVersion();
11760 Redeclaration = true;
11761 OldDecl = ND;
11762 return false;
11765 // If the declarations don't match, this is an error condition.
11766 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11767 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11768 NewFD->setInvalidDecl();
11769 return true;
11771 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11772 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11773 std::equal(
11774 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11775 NewCPUSpec->cpus_begin(),
11776 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11777 return Cur->getName() == New->getName();
11778 })) {
11779 NewFD->setIsMultiVersion();
11780 Redeclaration = true;
11781 OldDecl = ND;
11782 return false;
11785 // Only 1 version of CPUSpecific is allowed for each CPU.
11786 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11787 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11788 if (CurII == NewII) {
11789 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11790 << NewII;
11791 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11792 NewFD->setInvalidDecl();
11793 return true;
11798 break;
11803 // Else, this is simply a non-redecl case. Checking the 'value' is only
11804 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11805 // handled in the attribute adding step.
11806 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11807 NewFD->setInvalidDecl();
11808 return true;
11811 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11812 !OldFD->isMultiVersion(), NewMVKind)) {
11813 NewFD->setInvalidDecl();
11814 return true;
11817 // Permit forward declarations in the case where these two are compatible.
11818 if (!OldFD->isMultiVersion()) {
11819 OldFD->setIsMultiVersion();
11820 NewFD->setIsMultiVersion();
11821 Redeclaration = true;
11822 OldDecl = OldFD;
11823 return false;
11826 NewFD->setIsMultiVersion();
11827 Redeclaration = false;
11828 OldDecl = nullptr;
11829 Previous.clear();
11830 return false;
11833 /// Check the validity of a mulitversion function declaration.
11834 /// Also sets the multiversion'ness' of the function itself.
11836 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11838 /// Returns true if there was an error, false otherwise.
11839 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11840 bool &Redeclaration, NamedDecl *&OldDecl,
11841 LookupResult &Previous) {
11842 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11844 // Check if FMV is disabled.
11845 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
11846 return false;
11848 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11849 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11850 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11851 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11852 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11853 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11855 // Main isn't allowed to become a multiversion function, however it IS
11856 // permitted to have 'main' be marked with the 'target' optimization hint,
11857 // for 'target_version' only default is allowed.
11858 if (NewFD->isMain()) {
11859 if (MVKind != MultiVersionKind::None &&
11860 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11861 !(MVKind == MultiVersionKind::TargetVersion &&
11862 NewTVA->isDefaultVersion())) {
11863 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11864 NewFD->setInvalidDecl();
11865 return true;
11867 return false;
11870 // Target attribute on AArch64 is not used for multiversioning
11871 if (NewTA && TI.getTriple().isAArch64())
11872 return false;
11874 // Target attribute on RISCV is not used for multiversioning
11875 if (NewTA && TI.getTriple().isRISCV())
11876 return false;
11878 if (!OldDecl || !OldDecl->getAsFunction() ||
11879 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11880 NewFD->getDeclContext()->getRedeclContext())) {
11881 // If there's no previous declaration, AND this isn't attempting to cause
11882 // multiversioning, this isn't an error condition.
11883 if (MVKind == MultiVersionKind::None)
11884 return false;
11885 return CheckMultiVersionFirstFunction(S, NewFD);
11888 FunctionDecl *OldFD = OldDecl->getAsFunction();
11890 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11891 return false;
11893 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11894 // for target_clones and target_version.
11895 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11896 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11897 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11898 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11899 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11900 NewFD->setInvalidDecl();
11901 return true;
11904 if (!OldFD->isMultiVersion()) {
11905 switch (MVKind) {
11906 case MultiVersionKind::Target:
11907 case MultiVersionKind::TargetVersion:
11908 return CheckDeclarationCausesMultiVersioning(
11909 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11910 case MultiVersionKind::TargetClones:
11911 if (OldFD->isUsed(false)) {
11912 NewFD->setInvalidDecl();
11913 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11915 OldFD->setIsMultiVersion();
11916 break;
11918 case MultiVersionKind::CPUDispatch:
11919 case MultiVersionKind::CPUSpecific:
11920 case MultiVersionKind::None:
11921 break;
11925 // At this point, we have a multiversion function decl (in OldFD) AND an
11926 // appropriate attribute in the current function decl. Resolve that these are
11927 // still compatible with previous declarations.
11928 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11929 NewCPUSpec, NewClones, Redeclaration,
11930 OldDecl, Previous);
11933 static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
11934 bool IsPure = NewFD->hasAttr<PureAttr>();
11935 bool IsConst = NewFD->hasAttr<ConstAttr>();
11937 // If there are no pure or const attributes, there's nothing to check.
11938 if (!IsPure && !IsConst)
11939 return;
11941 // If the function is marked both pure and const, we retain the const
11942 // attribute because it makes stronger guarantees than the pure attribute, and
11943 // we drop the pure attribute explicitly to prevent later confusion about
11944 // semantics.
11945 if (IsPure && IsConst) {
11946 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11947 NewFD->dropAttrs<PureAttr>();
11950 // Constructors and destructors are functions which return void, so are
11951 // handled here as well.
11952 if (NewFD->getReturnType()->isVoidType()) {
11953 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11954 << IsConst;
11955 NewFD->dropAttrs<PureAttr, ConstAttr>();
11959 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11960 LookupResult &Previous,
11961 bool IsMemberSpecialization,
11962 bool DeclIsDefn) {
11963 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11964 "Variably modified return types are not handled here");
11966 // Determine whether the type of this function should be merged with
11967 // a previous visible declaration. This never happens for functions in C++,
11968 // and always happens in C if the previous declaration was visible.
11969 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11970 !Previous.isShadowed();
11972 bool Redeclaration = false;
11973 NamedDecl *OldDecl = nullptr;
11974 bool MayNeedOverloadableChecks = false;
11976 inferLifetimeCaptureByAttribute(NewFD);
11977 // Merge or overload the declaration with an existing declaration of
11978 // the same name, if appropriate.
11979 if (!Previous.empty()) {
11980 // Determine whether NewFD is an overload of PrevDecl or
11981 // a declaration that requires merging. If it's an overload,
11982 // there's no more work to do here; we'll just add the new
11983 // function to the scope.
11984 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11985 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11986 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11987 Redeclaration = true;
11988 OldDecl = Candidate;
11990 } else {
11991 MayNeedOverloadableChecks = true;
11992 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11993 /*NewIsUsingDecl*/ false)) {
11994 case Ovl_Match:
11995 Redeclaration = true;
11996 break;
11998 case Ovl_NonFunction:
11999 Redeclaration = true;
12000 break;
12002 case Ovl_Overload:
12003 Redeclaration = false;
12004 break;
12009 // Check for a previous extern "C" declaration with this name.
12010 if (!Redeclaration &&
12011 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
12012 if (!Previous.empty()) {
12013 // This is an extern "C" declaration with the same name as a previous
12014 // declaration, and thus redeclares that entity...
12015 Redeclaration = true;
12016 OldDecl = Previous.getFoundDecl();
12017 MergeTypeWithPrevious = false;
12019 // ... except in the presence of __attribute__((overloadable)).
12020 if (OldDecl->hasAttr<OverloadableAttr>() ||
12021 NewFD->hasAttr<OverloadableAttr>()) {
12022 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12023 MayNeedOverloadableChecks = true;
12024 Redeclaration = false;
12025 OldDecl = nullptr;
12031 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12032 return Redeclaration;
12034 // PPC MMA non-pointer types are not allowed as function return types.
12035 if (Context.getTargetInfo().getTriple().isPPC64() &&
12036 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12037 NewFD->setInvalidDecl();
12040 CheckConstPureAttributesUsage(*this, NewFD);
12042 // C++ [dcl.spec.auto.general]p12:
12043 // Return type deduction for a templated function with a placeholder in its
12044 // declared type occurs when the definition is instantiated even if the
12045 // function body contains a return statement with a non-type-dependent
12046 // operand.
12048 // C++ [temp.dep.expr]p3:
12049 // An id-expression is type-dependent if it is a template-id that is not a
12050 // concept-id and is dependent; or if its terminal name is:
12051 // - [...]
12052 // - associated by name lookup with one or more declarations of member
12053 // functions of a class that is the current instantiation declared with a
12054 // return type that contains a placeholder type,
12055 // - [...]
12057 // If this is a templated function with a placeholder in its return type,
12058 // make the placeholder type dependent since it won't be deduced until the
12059 // definition is instantiated. We do this here because it needs to happen
12060 // for implicitly instantiated member functions/member function templates.
12061 if (getLangOpts().CPlusPlus14 &&
12062 (NewFD->isDependentContext() &&
12063 NewFD->getReturnType()->isUndeducedType())) {
12064 const FunctionProtoType *FPT =
12065 NewFD->getType()->castAs<FunctionProtoType>();
12066 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12067 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12068 FPT->getExtProtoInfo()));
12071 // C++11 [dcl.constexpr]p8:
12072 // A constexpr specifier for a non-static member function that is not
12073 // a constructor declares that member function to be const.
12075 // This needs to be delayed until we know whether this is an out-of-line
12076 // definition of a static member function.
12078 // This rule is not present in C++1y, so we produce a backwards
12079 // compatibility warning whenever it happens in C++11.
12080 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12081 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12082 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12083 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12084 CXXMethodDecl *OldMD = nullptr;
12085 if (OldDecl)
12086 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12087 if (!OldMD || !OldMD->isStatic()) {
12088 const FunctionProtoType *FPT =
12089 MD->getType()->castAs<FunctionProtoType>();
12090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12091 EPI.TypeQuals.addConst();
12092 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12093 FPT->getParamTypes(), EPI));
12095 // Warn that we did this, if we're not performing template instantiation.
12096 // In that case, we'll have warned already when the template was defined.
12097 if (!inTemplateInstantiation()) {
12098 SourceLocation AddConstLoc;
12099 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12100 .IgnoreParens().getAs<FunctionTypeLoc>())
12101 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12103 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12104 << FixItHint::CreateInsertion(AddConstLoc, " const");
12109 if (Redeclaration) {
12110 // NewFD and OldDecl represent declarations that need to be
12111 // merged.
12112 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12113 DeclIsDefn)) {
12114 NewFD->setInvalidDecl();
12115 return Redeclaration;
12118 Previous.clear();
12119 Previous.addDecl(OldDecl);
12121 if (FunctionTemplateDecl *OldTemplateDecl =
12122 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12123 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12124 FunctionTemplateDecl *NewTemplateDecl
12125 = NewFD->getDescribedFunctionTemplate();
12126 assert(NewTemplateDecl && "Template/non-template mismatch");
12128 // The call to MergeFunctionDecl above may have created some state in
12129 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12130 // can add it as a redeclaration.
12131 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12133 NewFD->setPreviousDeclaration(OldFD);
12134 if (NewFD->isCXXClassMember()) {
12135 NewFD->setAccess(OldTemplateDecl->getAccess());
12136 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12139 // If this is an explicit specialization of a member that is a function
12140 // template, mark it as a member specialization.
12141 if (IsMemberSpecialization &&
12142 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12143 NewTemplateDecl->setMemberSpecialization();
12144 assert(OldTemplateDecl->isMemberSpecialization());
12145 // Explicit specializations of a member template do not inherit deleted
12146 // status from the parent member template that they are specializing.
12147 if (OldFD->isDeleted()) {
12148 // FIXME: This assert will not hold in the presence of modules.
12149 assert(OldFD->getCanonicalDecl() == OldFD);
12150 // FIXME: We need an update record for this AST mutation.
12151 OldFD->setDeletedAsWritten(false);
12155 } else {
12156 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12157 auto *OldFD = cast<FunctionDecl>(OldDecl);
12158 // This needs to happen first so that 'inline' propagates.
12159 NewFD->setPreviousDeclaration(OldFD);
12160 if (NewFD->isCXXClassMember())
12161 NewFD->setAccess(OldFD->getAccess());
12164 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12165 !NewFD->getAttr<OverloadableAttr>()) {
12166 assert((Previous.empty() ||
12167 llvm::any_of(Previous,
12168 [](const NamedDecl *ND) {
12169 return ND->hasAttr<OverloadableAttr>();
12170 })) &&
12171 "Non-redecls shouldn't happen without overloadable present");
12173 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12174 const auto *FD = dyn_cast<FunctionDecl>(ND);
12175 return FD && !FD->hasAttr<OverloadableAttr>();
12178 if (OtherUnmarkedIter != Previous.end()) {
12179 Diag(NewFD->getLocation(),
12180 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12181 Diag((*OtherUnmarkedIter)->getLocation(),
12182 diag::note_attribute_overloadable_prev_overload)
12183 << false;
12185 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12189 if (LangOpts.OpenMP)
12190 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12192 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12193 SYCL().CheckSYCLEntryPointFunctionDecl(NewFD);
12195 // Semantic checking for this function declaration (in isolation).
12197 if (getLangOpts().CPlusPlus) {
12198 // C++-specific checks.
12199 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12200 CheckConstructor(Constructor);
12201 } else if (CXXDestructorDecl *Destructor =
12202 dyn_cast<CXXDestructorDecl>(NewFD)) {
12203 // We check here for invalid destructor names.
12204 // If we have a friend destructor declaration that is dependent, we can't
12205 // diagnose right away because cases like this are still valid:
12206 // template <class T> struct A { friend T::X::~Y(); };
12207 // struct B { struct Y { ~Y(); }; using X = Y; };
12208 // template struct A<B>;
12209 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12210 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12211 CXXRecordDecl *Record = Destructor->getParent();
12212 QualType ClassType = Context.getTypeDeclType(Record);
12214 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12215 Context.getCanonicalType(ClassType));
12216 if (NewFD->getDeclName() != Name) {
12217 Diag(NewFD->getLocation(), diag::err_destructor_name);
12218 NewFD->setInvalidDecl();
12219 return Redeclaration;
12222 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12223 if (auto *TD = Guide->getDescribedFunctionTemplate())
12224 CheckDeductionGuideTemplate(TD);
12226 // A deduction guide is not on the list of entities that can be
12227 // explicitly specialized.
12228 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12229 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12230 << /*explicit specialization*/ 1;
12233 // Find any virtual functions that this function overrides.
12234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12235 if (!Method->isFunctionTemplateSpecialization() &&
12236 !Method->getDescribedFunctionTemplate() &&
12237 Method->isCanonicalDecl()) {
12238 AddOverriddenMethods(Method->getParent(), Method);
12240 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12241 // C++2a [class.virtual]p6
12242 // A virtual method shall not have a requires-clause.
12243 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12244 diag::err_constrained_virtual_method);
12246 if (Method->isStatic())
12247 checkThisInStaticMemberFunctionType(Method);
12250 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12251 ActOnConversionDeclarator(Conversion);
12253 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12254 if (NewFD->isOverloadedOperator() &&
12255 CheckOverloadedOperatorDeclaration(NewFD)) {
12256 NewFD->setInvalidDecl();
12257 return Redeclaration;
12260 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12261 if (NewFD->getLiteralIdentifier() &&
12262 CheckLiteralOperatorDeclaration(NewFD)) {
12263 NewFD->setInvalidDecl();
12264 return Redeclaration;
12267 // In C++, check default arguments now that we have merged decls. Unless
12268 // the lexical context is the class, because in this case this is done
12269 // during delayed parsing anyway.
12270 if (!CurContext->isRecord())
12271 CheckCXXDefaultArguments(NewFD);
12273 // If this function is declared as being extern "C", then check to see if
12274 // the function returns a UDT (class, struct, or union type) that is not C
12275 // compatible, and if it does, warn the user.
12276 // But, issue any diagnostic on the first declaration only.
12277 if (Previous.empty() && NewFD->isExternC()) {
12278 QualType R = NewFD->getReturnType();
12279 if (R->isIncompleteType() && !R->isVoidType())
12280 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12281 << NewFD << R;
12282 else if (!R.isPODType(Context) && !R->isVoidType() &&
12283 !R->isObjCObjectPointerType())
12284 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12287 // C++1z [dcl.fct]p6:
12288 // [...] whether the function has a non-throwing exception-specification
12289 // [is] part of the function type
12291 // This results in an ABI break between C++14 and C++17 for functions whose
12292 // declared type includes an exception-specification in a parameter or
12293 // return type. (Exception specifications on the function itself are OK in
12294 // most cases, and exception specifications are not permitted in most other
12295 // contexts where they could make it into a mangling.)
12296 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12297 auto HasNoexcept = [&](QualType T) -> bool {
12298 // Strip off declarator chunks that could be between us and a function
12299 // type. We don't need to look far, exception specifications are very
12300 // restricted prior to C++17.
12301 if (auto *RT = T->getAs<ReferenceType>())
12302 T = RT->getPointeeType();
12303 else if (T->isAnyPointerType())
12304 T = T->getPointeeType();
12305 else if (auto *MPT = T->getAs<MemberPointerType>())
12306 T = MPT->getPointeeType();
12307 if (auto *FPT = T->getAs<FunctionProtoType>())
12308 if (FPT->isNothrow())
12309 return true;
12310 return false;
12313 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12314 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12315 for (QualType T : FPT->param_types())
12316 AnyNoexcept |= HasNoexcept(T);
12317 if (AnyNoexcept)
12318 Diag(NewFD->getLocation(),
12319 diag::warn_cxx17_compat_exception_spec_in_signature)
12320 << NewFD;
12323 if (!Redeclaration && LangOpts.CUDA) {
12324 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12325 for (auto *Parm : NewFD->parameters()) {
12326 if (!Parm->getType()->isDependentType() &&
12327 Parm->hasAttr<CUDAGridConstantAttr>() &&
12328 !(IsKernel && Parm->getType().isConstQualified()))
12329 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12330 diag::err_cuda_grid_constant_not_allowed);
12332 CUDA().checkTargetOverload(NewFD, Previous);
12336 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12337 ARM().CheckSMEFunctionDefAttributes(NewFD);
12339 return Redeclaration;
12342 void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12343 // [basic.start.main]p3
12344 // The main function shall not be declared with a linkage-specification.
12345 if (FD->isExternCContext() ||
12346 (FD->isExternCXXContext() &&
12347 FD->getDeclContext()->getRedeclContext()->isTranslationUnit()))
12348 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12349 << FD->getLanguageLinkage();
12351 // C++11 [basic.start.main]p3:
12352 // A program that [...] declares main to be inline, static or
12353 // constexpr is ill-formed.
12354 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12355 // appear in a declaration of main.
12356 // static main is not an error under C99, but we should warn about it.
12357 // We accept _Noreturn main as an extension.
12358 if (FD->getStorageClass() == SC_Static)
12359 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12360 ? diag::err_static_main : diag::warn_static_main)
12361 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12362 if (FD->isInlineSpecified())
12363 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12364 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12365 if (DS.isNoreturnSpecified()) {
12366 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12367 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12368 Diag(NoreturnLoc, diag::ext_noreturn_main);
12369 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12370 << FixItHint::CreateRemoval(NoreturnRange);
12372 if (FD->isConstexpr()) {
12373 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12374 << FD->isConsteval()
12375 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12376 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12379 if (getLangOpts().OpenCL) {
12380 Diag(FD->getLocation(), diag::err_opencl_no_main)
12381 << FD->hasAttr<OpenCLKernelAttr>();
12382 FD->setInvalidDecl();
12383 return;
12386 // Functions named main in hlsl are default entries, but don't have specific
12387 // signatures they are required to conform to.
12388 if (getLangOpts().HLSL)
12389 return;
12391 QualType T = FD->getType();
12392 assert(T->isFunctionType() && "function decl is not of function type");
12393 const FunctionType* FT = T->castAs<FunctionType>();
12395 // Set default calling convention for main()
12396 if (FT->getCallConv() != CC_C) {
12397 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12398 FD->setType(QualType(FT, 0));
12399 T = Context.getCanonicalType(FD->getType());
12402 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12403 // In C with GNU extensions we allow main() to have non-integer return
12404 // type, but we should warn about the extension, and we disable the
12405 // implicit-return-zero rule.
12407 // GCC in C mode accepts qualified 'int'.
12408 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12409 FD->setHasImplicitReturnZero(true);
12410 else {
12411 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12412 SourceRange RTRange = FD->getReturnTypeSourceRange();
12413 if (RTRange.isValid())
12414 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12415 << FixItHint::CreateReplacement(RTRange, "int");
12417 } else {
12418 // In C and C++, main magically returns 0 if you fall off the end;
12419 // set the flag which tells us that.
12420 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12422 // All the standards say that main() should return 'int'.
12423 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12424 FD->setHasImplicitReturnZero(true);
12425 else {
12426 // Otherwise, this is just a flat-out error.
12427 SourceRange RTRange = FD->getReturnTypeSourceRange();
12428 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12429 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12430 : FixItHint());
12431 FD->setInvalidDecl(true);
12435 // Treat protoless main() as nullary.
12436 if (isa<FunctionNoProtoType>(FT)) return;
12438 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12439 unsigned nparams = FTP->getNumParams();
12440 assert(FD->getNumParams() == nparams);
12442 bool HasExtraParameters = (nparams > 3);
12444 if (FTP->isVariadic()) {
12445 Diag(FD->getLocation(), diag::ext_variadic_main);
12446 // FIXME: if we had information about the location of the ellipsis, we
12447 // could add a FixIt hint to remove it as a parameter.
12450 // Darwin passes an undocumented fourth argument of type char**. If
12451 // other platforms start sprouting these, the logic below will start
12452 // getting shifty.
12453 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12454 HasExtraParameters = false;
12456 if (HasExtraParameters) {
12457 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12458 FD->setInvalidDecl(true);
12459 nparams = 3;
12462 // FIXME: a lot of the following diagnostics would be improved
12463 // if we had some location information about types.
12465 QualType CharPP =
12466 Context.getPointerType(Context.getPointerType(Context.CharTy));
12467 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12469 for (unsigned i = 0; i < nparams; ++i) {
12470 QualType AT = FTP->getParamType(i);
12472 bool mismatch = true;
12474 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12475 mismatch = false;
12476 else if (Expected[i] == CharPP) {
12477 // As an extension, the following forms are okay:
12478 // char const **
12479 // char const * const *
12480 // char * const *
12482 QualifierCollector qs;
12483 const PointerType* PT;
12484 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12485 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12486 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12487 Context.CharTy)) {
12488 qs.removeConst();
12489 mismatch = !qs.empty();
12493 if (mismatch) {
12494 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12495 // TODO: suggest replacing given type with expected type
12496 FD->setInvalidDecl(true);
12500 if (nparams == 1 && !FD->isInvalidDecl()) {
12501 Diag(FD->getLocation(), diag::warn_main_one_arg);
12504 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12505 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12506 FD->setInvalidDecl();
12510 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12512 // Default calling convention for main and wmain is __cdecl
12513 if (FD->getName() == "main" || FD->getName() == "wmain")
12514 return false;
12516 // Default calling convention for MinGW is __cdecl
12517 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12518 if (T.isWindowsGNUEnvironment())
12519 return false;
12521 // Default calling convention for WinMain, wWinMain and DllMain
12522 // is __stdcall on 32 bit Windows
12523 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12524 return true;
12526 return false;
12529 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12530 QualType T = FD->getType();
12531 assert(T->isFunctionType() && "function decl is not of function type");
12532 const FunctionType *FT = T->castAs<FunctionType>();
12534 // Set an implicit return of 'zero' if the function can return some integral,
12535 // enumeration, pointer or nullptr type.
12536 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12537 FT->getReturnType()->isAnyPointerType() ||
12538 FT->getReturnType()->isNullPtrType())
12539 // DllMain is exempt because a return value of zero means it failed.
12540 if (FD->getName() != "DllMain")
12541 FD->setHasImplicitReturnZero(true);
12543 // Explicitly specified calling conventions are applied to MSVC entry points
12544 if (!hasExplicitCallingConv(T)) {
12545 if (isDefaultStdCall(FD, *this)) {
12546 if (FT->getCallConv() != CC_X86StdCall) {
12547 FT = Context.adjustFunctionType(
12548 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12549 FD->setType(QualType(FT, 0));
12551 } else if (FT->getCallConv() != CC_C) {
12552 FT = Context.adjustFunctionType(FT,
12553 FT->getExtInfo().withCallingConv(CC_C));
12554 FD->setType(QualType(FT, 0));
12558 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12559 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12560 FD->setInvalidDecl();
12564 bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12565 // FIXME: Need strict checking. In C89, we need to check for
12566 // any assignment, increment, decrement, function-calls, or
12567 // commas outside of a sizeof. In C99, it's the same list,
12568 // except that the aforementioned are allowed in unevaluated
12569 // expressions. Everything else falls under the
12570 // "may accept other forms of constant expressions" exception.
12572 // Regular C++ code will not end up here (exceptions: language extensions,
12573 // OpenCL C++ etc), so the constant expression rules there don't matter.
12574 if (Init->isValueDependent()) {
12575 assert(Init->containsErrors() &&
12576 "Dependent code should only occur in error-recovery path.");
12577 return true;
12579 const Expr *Culprit;
12580 if (Init->isConstantInitializer(Context, false, &Culprit))
12581 return false;
12582 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12583 return true;
12586 namespace {
12587 // Visits an initialization expression to see if OrigDecl is evaluated in
12588 // its own initialization and throws a warning if it does.
12589 class SelfReferenceChecker
12590 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12591 Sema &S;
12592 Decl *OrigDecl;
12593 bool isRecordType;
12594 bool isPODType;
12595 bool isReferenceType;
12597 bool isInitList;
12598 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12600 public:
12601 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12603 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12604 S(S), OrigDecl(OrigDecl) {
12605 isPODType = false;
12606 isRecordType = false;
12607 isReferenceType = false;
12608 isInitList = false;
12609 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12610 isPODType = VD->getType().isPODType(S.Context);
12611 isRecordType = VD->getType()->isRecordType();
12612 isReferenceType = VD->getType()->isReferenceType();
12616 // For most expressions, just call the visitor. For initializer lists,
12617 // track the index of the field being initialized since fields are
12618 // initialized in order allowing use of previously initialized fields.
12619 void CheckExpr(Expr *E) {
12620 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12621 if (!InitList) {
12622 Visit(E);
12623 return;
12626 // Track and increment the index here.
12627 isInitList = true;
12628 InitFieldIndex.push_back(0);
12629 for (auto *Child : InitList->children()) {
12630 CheckExpr(cast<Expr>(Child));
12631 ++InitFieldIndex.back();
12633 InitFieldIndex.pop_back();
12636 // Returns true if MemberExpr is checked and no further checking is needed.
12637 // Returns false if additional checking is required.
12638 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12639 llvm::SmallVector<FieldDecl*, 4> Fields;
12640 Expr *Base = E;
12641 bool ReferenceField = false;
12643 // Get the field members used.
12644 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12645 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12646 if (!FD)
12647 return false;
12648 Fields.push_back(FD);
12649 if (FD->getType()->isReferenceType())
12650 ReferenceField = true;
12651 Base = ME->getBase()->IgnoreParenImpCasts();
12654 // Keep checking only if the base Decl is the same.
12655 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12656 if (!DRE || DRE->getDecl() != OrigDecl)
12657 return false;
12659 // A reference field can be bound to an unininitialized field.
12660 if (CheckReference && !ReferenceField)
12661 return true;
12663 // Convert FieldDecls to their index number.
12664 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12665 for (const FieldDecl *I : llvm::reverse(Fields))
12666 UsedFieldIndex.push_back(I->getFieldIndex());
12668 // See if a warning is needed by checking the first difference in index
12669 // numbers. If field being used has index less than the field being
12670 // initialized, then the use is safe.
12671 for (auto UsedIter = UsedFieldIndex.begin(),
12672 UsedEnd = UsedFieldIndex.end(),
12673 OrigIter = InitFieldIndex.begin(),
12674 OrigEnd = InitFieldIndex.end();
12675 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12676 if (*UsedIter < *OrigIter)
12677 return true;
12678 if (*UsedIter > *OrigIter)
12679 break;
12682 // TODO: Add a different warning which will print the field names.
12683 HandleDeclRefExpr(DRE);
12684 return true;
12687 // For most expressions, the cast is directly above the DeclRefExpr.
12688 // For conditional operators, the cast can be outside the conditional
12689 // operator if both expressions are DeclRefExpr's.
12690 void HandleValue(Expr *E) {
12691 E = E->IgnoreParens();
12692 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12693 HandleDeclRefExpr(DRE);
12694 return;
12697 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12698 Visit(CO->getCond());
12699 HandleValue(CO->getTrueExpr());
12700 HandleValue(CO->getFalseExpr());
12701 return;
12704 if (BinaryConditionalOperator *BCO =
12705 dyn_cast<BinaryConditionalOperator>(E)) {
12706 Visit(BCO->getCond());
12707 HandleValue(BCO->getFalseExpr());
12708 return;
12711 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12712 if (Expr *SE = OVE->getSourceExpr())
12713 HandleValue(SE);
12714 return;
12717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12718 if (BO->getOpcode() == BO_Comma) {
12719 Visit(BO->getLHS());
12720 HandleValue(BO->getRHS());
12721 return;
12725 if (isa<MemberExpr>(E)) {
12726 if (isInitList) {
12727 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12728 false /*CheckReference*/))
12729 return;
12732 Expr *Base = E->IgnoreParenImpCasts();
12733 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12734 // Check for static member variables and don't warn on them.
12735 if (!isa<FieldDecl>(ME->getMemberDecl()))
12736 return;
12737 Base = ME->getBase()->IgnoreParenImpCasts();
12739 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12740 HandleDeclRefExpr(DRE);
12741 return;
12744 Visit(E);
12747 // Reference types not handled in HandleValue are handled here since all
12748 // uses of references are bad, not just r-value uses.
12749 void VisitDeclRefExpr(DeclRefExpr *E) {
12750 if (isReferenceType)
12751 HandleDeclRefExpr(E);
12754 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12755 if (E->getCastKind() == CK_LValueToRValue) {
12756 HandleValue(E->getSubExpr());
12757 return;
12760 Inherited::VisitImplicitCastExpr(E);
12763 void VisitMemberExpr(MemberExpr *E) {
12764 if (isInitList) {
12765 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12766 return;
12769 // Don't warn on arrays since they can be treated as pointers.
12770 if (E->getType()->canDecayToPointerType()) return;
12772 // Warn when a non-static method call is followed by non-static member
12773 // field accesses, which is followed by a DeclRefExpr.
12774 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12775 bool Warn = (MD && !MD->isStatic());
12776 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12777 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12778 if (!isa<FieldDecl>(ME->getMemberDecl()))
12779 Warn = false;
12780 Base = ME->getBase()->IgnoreParenImpCasts();
12783 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12784 if (Warn)
12785 HandleDeclRefExpr(DRE);
12786 return;
12789 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12790 // Visit that expression.
12791 Visit(Base);
12794 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12795 Expr *Callee = E->getCallee();
12797 if (isa<UnresolvedLookupExpr>(Callee))
12798 return Inherited::VisitCXXOperatorCallExpr(E);
12800 Visit(Callee);
12801 for (auto Arg: E->arguments())
12802 HandleValue(Arg->IgnoreParenImpCasts());
12805 void VisitUnaryOperator(UnaryOperator *E) {
12806 // For POD record types, addresses of its own members are well-defined.
12807 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12808 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12809 if (!isPODType)
12810 HandleValue(E->getSubExpr());
12811 return;
12814 if (E->isIncrementDecrementOp()) {
12815 HandleValue(E->getSubExpr());
12816 return;
12819 Inherited::VisitUnaryOperator(E);
12822 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12824 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12825 if (E->getConstructor()->isCopyConstructor()) {
12826 Expr *ArgExpr = E->getArg(0);
12827 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12828 if (ILE->getNumInits() == 1)
12829 ArgExpr = ILE->getInit(0);
12830 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12831 if (ICE->getCastKind() == CK_NoOp)
12832 ArgExpr = ICE->getSubExpr();
12833 HandleValue(ArgExpr);
12834 return;
12836 Inherited::VisitCXXConstructExpr(E);
12839 void VisitCallExpr(CallExpr *E) {
12840 // Treat std::move as a use.
12841 if (E->isCallToStdMove()) {
12842 HandleValue(E->getArg(0));
12843 return;
12846 Inherited::VisitCallExpr(E);
12849 void VisitBinaryOperator(BinaryOperator *E) {
12850 if (E->isCompoundAssignmentOp()) {
12851 HandleValue(E->getLHS());
12852 Visit(E->getRHS());
12853 return;
12856 Inherited::VisitBinaryOperator(E);
12859 // A custom visitor for BinaryConditionalOperator is needed because the
12860 // regular visitor would check the condition and true expression separately
12861 // but both point to the same place giving duplicate diagnostics.
12862 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12863 Visit(E->getCond());
12864 Visit(E->getFalseExpr());
12867 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12868 Decl* ReferenceDecl = DRE->getDecl();
12869 if (OrigDecl != ReferenceDecl) return;
12870 unsigned diag;
12871 if (isReferenceType) {
12872 diag = diag::warn_uninit_self_reference_in_reference_init;
12873 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12874 diag = diag::warn_static_self_reference_in_init;
12875 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12876 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12877 DRE->getDecl()->getType()->isRecordType()) {
12878 diag = diag::warn_uninit_self_reference_in_init;
12879 } else {
12880 // Local variables will be handled by the CFG analysis.
12881 return;
12884 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12885 S.PDiag(diag)
12886 << DRE->getDecl() << OrigDecl->getLocation()
12887 << DRE->getSourceRange());
12891 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12892 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12893 bool DirectInit) {
12894 // Parameters arguments are occassionially constructed with itself,
12895 // for instance, in recursive functions. Skip them.
12896 if (isa<ParmVarDecl>(OrigDecl))
12897 return;
12899 E = E->IgnoreParens();
12901 // Skip checking T a = a where T is not a record or reference type.
12902 // Doing so is a way to silence uninitialized warnings.
12903 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12904 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12905 if (ICE->getCastKind() == CK_LValueToRValue)
12906 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12907 if (DRE->getDecl() == OrigDecl)
12908 return;
12910 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12912 } // end anonymous namespace
12914 namespace {
12915 // Simple wrapper to add the name of a variable or (if no variable is
12916 // available) a DeclarationName into a diagnostic.
12917 struct VarDeclOrName {
12918 VarDecl *VDecl;
12919 DeclarationName Name;
12921 friend const Sema::SemaDiagnosticBuilder &
12922 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12923 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12926 } // end anonymous namespace
12928 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12929 DeclarationName Name, QualType Type,
12930 TypeSourceInfo *TSI,
12931 SourceRange Range, bool DirectInit,
12932 Expr *Init) {
12933 bool IsInitCapture = !VDecl;
12934 assert((!VDecl || !VDecl->isInitCapture()) &&
12935 "init captures are expected to be deduced prior to initialization");
12937 VarDeclOrName VN{VDecl, Name};
12939 DeducedType *Deduced = Type->getContainedDeducedType();
12940 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12942 // Diagnose auto array declarations in C23, unless it's a supported extension.
12943 if (getLangOpts().C23 && Type->isArrayType() &&
12944 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12945 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12946 << (int)Deduced->getContainedAutoType()->getKeyword()
12947 << /*in array decl*/ 23 << Range;
12948 return QualType();
12951 // C++11 [dcl.spec.auto]p3
12952 if (!Init) {
12953 assert(VDecl && "no init for init capture deduction?");
12955 // Except for class argument deduction, and then for an initializing
12956 // declaration only, i.e. no static at class scope or extern.
12957 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12958 VDecl->hasExternalStorage() ||
12959 VDecl->isStaticDataMember()) {
12960 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12961 << VDecl->getDeclName() << Type;
12962 return QualType();
12966 ArrayRef<Expr*> DeduceInits;
12967 if (Init)
12968 DeduceInits = Init;
12970 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12971 if (DirectInit && PL)
12972 DeduceInits = PL->exprs();
12974 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12975 assert(VDecl && "non-auto type for init capture deduction?");
12976 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12977 InitializationKind Kind = InitializationKind::CreateForInit(
12978 VDecl->getLocation(), DirectInit, Init);
12979 // FIXME: Initialization should not be taking a mutable list of inits.
12980 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12981 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12982 InitsCopy);
12985 if (DirectInit) {
12986 if (auto *IL = dyn_cast<InitListExpr>(Init))
12987 DeduceInits = IL->inits();
12990 // Deduction only works if we have exactly one source expression.
12991 if (DeduceInits.empty()) {
12992 // It isn't possible to write this directly, but it is possible to
12993 // end up in this situation with "auto x(some_pack...);"
12994 Diag(Init->getBeginLoc(), IsInitCapture
12995 ? diag::err_init_capture_no_expression
12996 : diag::err_auto_var_init_no_expression)
12997 << VN << Type << Range;
12998 return QualType();
13001 if (DeduceInits.size() > 1) {
13002 Diag(DeduceInits[1]->getBeginLoc(),
13003 IsInitCapture ? diag::err_init_capture_multiple_expressions
13004 : diag::err_auto_var_init_multiple_expressions)
13005 << VN << Type << Range;
13006 return QualType();
13009 Expr *DeduceInit = DeduceInits[0];
13010 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13011 Diag(Init->getBeginLoc(), IsInitCapture
13012 ? diag::err_init_capture_paren_braces
13013 : diag::err_auto_var_init_paren_braces)
13014 << isa<InitListExpr>(Init) << VN << Type << Range;
13015 return QualType();
13018 // Expressions default to 'id' when we're in a debugger.
13019 bool DefaultedAnyToId = false;
13020 if (getLangOpts().DebuggerCastResultToId &&
13021 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13022 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13023 if (Result.isInvalid()) {
13024 return QualType();
13026 Init = Result.get();
13027 DefaultedAnyToId = true;
13030 // C++ [dcl.decomp]p1:
13031 // If the assignment-expression [...] has array type A and no ref-qualifier
13032 // is present, e has type cv A
13033 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13034 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13035 DeduceInit->getType()->isConstantArrayType())
13036 return Context.getQualifiedType(DeduceInit->getType(),
13037 Type.getQualifiers());
13039 QualType DeducedType;
13040 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13041 TemplateDeductionResult Result =
13042 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13043 if (Result != TemplateDeductionResult::Success &&
13044 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13045 if (!IsInitCapture)
13046 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13047 else if (isa<InitListExpr>(Init))
13048 Diag(Range.getBegin(),
13049 diag::err_init_capture_deduction_failure_from_init_list)
13050 << VN
13051 << (DeduceInit->getType().isNull() ? TSI->getType()
13052 : DeduceInit->getType())
13053 << DeduceInit->getSourceRange();
13054 else
13055 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13056 << VN << TSI->getType()
13057 << (DeduceInit->getType().isNull() ? TSI->getType()
13058 : DeduceInit->getType())
13059 << DeduceInit->getSourceRange();
13062 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13063 // 'id' instead of a specific object type prevents most of our usual
13064 // checks.
13065 // We only want to warn outside of template instantiations, though:
13066 // inside a template, the 'id' could have come from a parameter.
13067 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13068 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13069 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13070 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13073 return DeducedType;
13076 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13077 Expr *Init) {
13078 assert(!Init || !Init->containsErrors());
13079 QualType DeducedType = deduceVarTypeFromInitializer(
13080 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13081 VDecl->getSourceRange(), DirectInit, Init);
13082 if (DeducedType.isNull()) {
13083 VDecl->setInvalidDecl();
13084 return true;
13087 VDecl->setType(DeducedType);
13088 assert(VDecl->isLinkageValid());
13090 // In ARC, infer lifetime.
13091 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13092 VDecl->setInvalidDecl();
13094 if (getLangOpts().OpenCL)
13095 deduceOpenCLAddressSpace(VDecl);
13097 // If this is a redeclaration, check that the type we just deduced matches
13098 // the previously declared type.
13099 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13100 // We never need to merge the type, because we cannot form an incomplete
13101 // array of auto, nor deduce such a type.
13102 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13105 // Check the deduced type is valid for a variable declaration.
13106 CheckVariableDeclarationType(VDecl);
13107 return VDecl->isInvalidDecl();
13110 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13111 SourceLocation Loc) {
13112 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13113 Init = EWC->getSubExpr();
13115 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13116 Init = CE->getSubExpr();
13118 QualType InitType = Init->getType();
13119 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13120 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13121 "shouldn't be called if type doesn't have a non-trivial C struct");
13122 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13123 for (auto *I : ILE->inits()) {
13124 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13125 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13126 continue;
13127 SourceLocation SL = I->getExprLoc();
13128 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13130 return;
13133 if (isa<ImplicitValueInitExpr>(Init)) {
13134 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13135 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
13136 NTCUK_Init);
13137 } else {
13138 // Assume all other explicit initializers involving copying some existing
13139 // object.
13140 // TODO: ignore any explicit initializers where we can guarantee
13141 // copy-elision.
13142 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13143 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13147 namespace {
13149 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13150 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13151 // in the source code or implicitly by the compiler if it is in a union
13152 // defined in a system header and has non-trivial ObjC ownership
13153 // qualifications. We don't want those fields to participate in determining
13154 // whether the containing union is non-trivial.
13155 return FD->hasAttr<UnavailableAttr>();
13158 struct DiagNonTrivalCUnionDefaultInitializeVisitor
13159 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13160 void> {
13161 using Super =
13162 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13163 void>;
13165 DiagNonTrivalCUnionDefaultInitializeVisitor(
13166 QualType OrigTy, SourceLocation OrigLoc,
13167 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13168 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13170 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13171 const FieldDecl *FD, bool InNonTrivialUnion) {
13172 if (const auto *AT = S.Context.getAsArrayType(QT))
13173 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13174 InNonTrivialUnion);
13175 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13178 void visitARCStrong(QualType QT, const FieldDecl *FD,
13179 bool InNonTrivialUnion) {
13180 if (InNonTrivialUnion)
13181 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13182 << 1 << 0 << QT << FD->getName();
13185 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13186 if (InNonTrivialUnion)
13187 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13188 << 1 << 0 << QT << FD->getName();
13191 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13192 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13193 if (RD->isUnion()) {
13194 if (OrigLoc.isValid()) {
13195 bool IsUnion = false;
13196 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13197 IsUnion = OrigRD->isUnion();
13198 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13199 << 0 << OrigTy << IsUnion << UseContext;
13200 // Reset OrigLoc so that this diagnostic is emitted only once.
13201 OrigLoc = SourceLocation();
13203 InNonTrivialUnion = true;
13206 if (InNonTrivialUnion)
13207 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13208 << 0 << 0 << QT.getUnqualifiedType() << "";
13210 for (const FieldDecl *FD : RD->fields())
13211 if (!shouldIgnoreForRecordTriviality(FD))
13212 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13215 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13217 // The non-trivial C union type or the struct/union type that contains a
13218 // non-trivial C union.
13219 QualType OrigTy;
13220 SourceLocation OrigLoc;
13221 Sema::NonTrivialCUnionContext UseContext;
13222 Sema &S;
13225 struct DiagNonTrivalCUnionDestructedTypeVisitor
13226 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13227 using Super =
13228 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13230 DiagNonTrivalCUnionDestructedTypeVisitor(
13231 QualType OrigTy, SourceLocation OrigLoc,
13232 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13233 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13235 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13236 const FieldDecl *FD, bool InNonTrivialUnion) {
13237 if (const auto *AT = S.Context.getAsArrayType(QT))
13238 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13239 InNonTrivialUnion);
13240 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13243 void visitARCStrong(QualType QT, const FieldDecl *FD,
13244 bool InNonTrivialUnion) {
13245 if (InNonTrivialUnion)
13246 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13247 << 1 << 1 << QT << FD->getName();
13250 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13251 if (InNonTrivialUnion)
13252 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13253 << 1 << 1 << QT << FD->getName();
13256 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13257 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13258 if (RD->isUnion()) {
13259 if (OrigLoc.isValid()) {
13260 bool IsUnion = false;
13261 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13262 IsUnion = OrigRD->isUnion();
13263 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13264 << 1 << OrigTy << IsUnion << UseContext;
13265 // Reset OrigLoc so that this diagnostic is emitted only once.
13266 OrigLoc = SourceLocation();
13268 InNonTrivialUnion = true;
13271 if (InNonTrivialUnion)
13272 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13273 << 0 << 1 << QT.getUnqualifiedType() << "";
13275 for (const FieldDecl *FD : RD->fields())
13276 if (!shouldIgnoreForRecordTriviality(FD))
13277 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13280 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13281 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13282 bool InNonTrivialUnion) {}
13284 // The non-trivial C union type or the struct/union type that contains a
13285 // non-trivial C union.
13286 QualType OrigTy;
13287 SourceLocation OrigLoc;
13288 Sema::NonTrivialCUnionContext UseContext;
13289 Sema &S;
13292 struct DiagNonTrivalCUnionCopyVisitor
13293 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13294 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13296 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13297 Sema::NonTrivialCUnionContext UseContext,
13298 Sema &S)
13299 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13301 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13302 const FieldDecl *FD, bool InNonTrivialUnion) {
13303 if (const auto *AT = S.Context.getAsArrayType(QT))
13304 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13305 InNonTrivialUnion);
13306 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13309 void visitARCStrong(QualType QT, const FieldDecl *FD,
13310 bool InNonTrivialUnion) {
13311 if (InNonTrivialUnion)
13312 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13313 << 1 << 2 << QT << FD->getName();
13316 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13317 if (InNonTrivialUnion)
13318 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13319 << 1 << 2 << QT << FD->getName();
13322 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13323 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13324 if (RD->isUnion()) {
13325 if (OrigLoc.isValid()) {
13326 bool IsUnion = false;
13327 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13328 IsUnion = OrigRD->isUnion();
13329 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13330 << 2 << OrigTy << IsUnion << UseContext;
13331 // Reset OrigLoc so that this diagnostic is emitted only once.
13332 OrigLoc = SourceLocation();
13334 InNonTrivialUnion = true;
13337 if (InNonTrivialUnion)
13338 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13339 << 0 << 2 << QT.getUnqualifiedType() << "";
13341 for (const FieldDecl *FD : RD->fields())
13342 if (!shouldIgnoreForRecordTriviality(FD))
13343 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13346 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13347 const FieldDecl *FD, bool InNonTrivialUnion) {}
13348 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13349 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13350 bool InNonTrivialUnion) {}
13352 // The non-trivial C union type or the struct/union type that contains a
13353 // non-trivial C union.
13354 QualType OrigTy;
13355 SourceLocation OrigLoc;
13356 Sema::NonTrivialCUnionContext UseContext;
13357 Sema &S;
13360 } // namespace
13362 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13363 NonTrivialCUnionContext UseContext,
13364 unsigned NonTrivialKind) {
13365 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13366 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13367 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13368 "shouldn't be called if type doesn't have a non-trivial C union");
13370 if ((NonTrivialKind & NTCUK_Init) &&
13371 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13372 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13373 .visit(QT, nullptr, false);
13374 if ((NonTrivialKind & NTCUK_Destruct) &&
13375 QT.hasNonTrivialToPrimitiveDestructCUnion())
13376 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13377 .visit(QT, nullptr, false);
13378 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13379 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13380 .visit(QT, nullptr, false);
13383 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13384 // If there is no declaration, there was an error parsing it. Just ignore
13385 // the initializer.
13386 if (!RealDecl) {
13387 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13388 return;
13391 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13392 if (!Method->isInvalidDecl()) {
13393 // Pure-specifiers are handled in ActOnPureSpecifier.
13394 Diag(Method->getLocation(), diag::err_member_function_initialization)
13395 << Method->getDeclName() << Init->getSourceRange();
13396 Method->setInvalidDecl();
13398 return;
13401 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13402 if (!VDecl) {
13403 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13404 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13405 RealDecl->setInvalidDecl();
13406 return;
13409 if (VDecl->isInvalidDecl()) {
13410 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13411 SmallVector<Expr *> SubExprs;
13412 if (Res.isUsable())
13413 SubExprs.push_back(Res.get());
13414 ExprResult Recovery =
13415 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13416 if (Expr *E = Recovery.get())
13417 VDecl->setInit(E);
13418 return;
13421 // WebAssembly tables can't be used to initialise a variable.
13422 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13423 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13424 VDecl->setInvalidDecl();
13425 return;
13428 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13429 if (VDecl->getType()->isUndeducedType()) {
13430 // Attempt typo correction early so that the type of the init expression can
13431 // be deduced based on the chosen correction if the original init contains a
13432 // TypoExpr.
13433 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13434 if (!Res.isUsable()) {
13435 // There are unresolved typos in Init, just drop them.
13436 // FIXME: improve the recovery strategy to preserve the Init.
13437 RealDecl->setInvalidDecl();
13438 return;
13440 if (Res.get()->containsErrors()) {
13441 // Invalidate the decl as we don't know the type for recovery-expr yet.
13442 RealDecl->setInvalidDecl();
13443 VDecl->setInit(Res.get());
13444 return;
13446 Init = Res.get();
13448 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13449 return;
13452 // dllimport cannot be used on variable definitions.
13453 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13454 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13455 VDecl->setInvalidDecl();
13456 return;
13459 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13460 // the identifier has external or internal linkage, the declaration shall
13461 // have no initializer for the identifier.
13462 // C++14 [dcl.init]p5 is the same restriction for C++.
13463 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13464 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13465 VDecl->setInvalidDecl();
13466 return;
13469 if (!VDecl->getType()->isDependentType()) {
13470 // A definition must end up with a complete type, which means it must be
13471 // complete with the restriction that an array type might be completed by
13472 // the initializer; note that later code assumes this restriction.
13473 QualType BaseDeclType = VDecl->getType();
13474 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13475 BaseDeclType = Array->getElementType();
13476 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13477 diag::err_typecheck_decl_incomplete_type)) {
13478 RealDecl->setInvalidDecl();
13479 return;
13482 // The variable can not have an abstract class type.
13483 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13484 diag::err_abstract_type_in_decl,
13485 AbstractVariableType))
13486 VDecl->setInvalidDecl();
13489 // C++ [module.import/6] external definitions are not permitted in header
13490 // units.
13491 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13492 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13493 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13494 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13495 !VDecl->getInstantiatedFromStaticDataMember()) {
13496 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13497 VDecl->setInvalidDecl();
13500 // If adding the initializer will turn this declaration into a definition,
13501 // and we already have a definition for this variable, diagnose or otherwise
13502 // handle the situation.
13503 if (VarDecl *Def = VDecl->getDefinition())
13504 if (Def != VDecl &&
13505 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13506 !VDecl->isThisDeclarationADemotedDefinition() &&
13507 checkVarDeclRedefinition(Def, VDecl))
13508 return;
13510 if (getLangOpts().CPlusPlus) {
13511 // C++ [class.static.data]p4
13512 // If a static data member is of const integral or const
13513 // enumeration type, its declaration in the class definition can
13514 // specify a constant-initializer which shall be an integral
13515 // constant expression (5.19). In that case, the member can appear
13516 // in integral constant expressions. The member shall still be
13517 // defined in a namespace scope if it is used in the program and the
13518 // namespace scope definition shall not contain an initializer.
13520 // We already performed a redefinition check above, but for static
13521 // data members we also need to check whether there was an in-class
13522 // declaration with an initializer.
13523 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13524 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13525 << VDecl->getDeclName();
13526 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13527 diag::note_previous_initializer)
13528 << 0;
13529 return;
13532 if (VDecl->hasLocalStorage())
13533 setFunctionHasBranchProtectedScope();
13535 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13536 VDecl->setInvalidDecl();
13537 return;
13541 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13542 // a kernel function cannot be initialized."
13543 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13544 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13545 VDecl->setInvalidDecl();
13546 return;
13549 // The LoaderUninitialized attribute acts as a definition (of undef).
13550 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13551 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13552 VDecl->setInvalidDecl();
13553 return;
13556 // Get the decls type and save a reference for later, since
13557 // CheckInitializerTypes may change it.
13558 QualType DclT = VDecl->getType(), SavT = DclT;
13560 // Expressions default to 'id' when we're in a debugger
13561 // and we are assigning it to a variable of Objective-C pointer type.
13562 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13563 Init->getType() == Context.UnknownAnyTy) {
13564 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13565 if (!Result.isUsable()) {
13566 VDecl->setInvalidDecl();
13567 return;
13569 Init = Result.get();
13572 // Perform the initialization.
13573 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13574 bool IsParenListInit = false;
13575 if (!VDecl->isInvalidDecl()) {
13576 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13577 InitializationKind Kind = InitializationKind::CreateForInit(
13578 VDecl->getLocation(), DirectInit, Init);
13580 MultiExprArg Args = Init;
13581 if (CXXDirectInit)
13582 Args = MultiExprArg(CXXDirectInit->getExprs(),
13583 CXXDirectInit->getNumExprs());
13585 // Try to correct any TypoExprs in the initialization arguments.
13586 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13587 ExprResult Res = CorrectDelayedTyposInExpr(
13588 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13589 [this, Entity, Kind](Expr *E) {
13590 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13591 return Init.Failed() ? ExprError() : E;
13593 if (!Res.isUsable()) {
13594 VDecl->setInvalidDecl();
13595 } else if (Res.get() != Args[Idx]) {
13596 Args[Idx] = Res.get();
13599 if (VDecl->isInvalidDecl())
13600 return;
13602 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13603 /*TopLevelOfInitList=*/false,
13604 /*TreatUnavailableAsInvalid=*/false);
13605 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13606 if (!Result.isUsable()) {
13607 // If the provided initializer fails to initialize the var decl,
13608 // we attach a recovery expr for better recovery.
13609 auto RecoveryExpr =
13610 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13611 if (RecoveryExpr.get())
13612 VDecl->setInit(RecoveryExpr.get());
13613 // In general, for error recovery purposes, the initializer doesn't play
13614 // part in the valid bit of the declaration. There are a few exceptions:
13615 // 1) if the var decl has a deduced auto type, and the type cannot be
13616 // deduced by an invalid initializer;
13617 // 2) if the var decl is a decomposition decl with a non-deduced type,
13618 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13619 // Case 1) was already handled elsewhere.
13620 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13621 VDecl->setInvalidDecl();
13622 return;
13625 Init = Result.getAs<Expr>();
13626 IsParenListInit = !InitSeq.steps().empty() &&
13627 InitSeq.step_begin()->Kind ==
13628 InitializationSequence::SK_ParenthesizedListInit;
13629 QualType VDeclType = VDecl->getType();
13630 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13631 !VDeclType->isDependentType() &&
13632 Context.getAsIncompleteArrayType(VDeclType) &&
13633 Context.getAsIncompleteArrayType(Init->getType())) {
13634 // Bail out if it is not possible to deduce array size from the
13635 // initializer.
13636 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13637 << VDeclType;
13638 VDecl->setInvalidDecl();
13639 return;
13643 // Check for self-references within variable initializers.
13644 // Variables declared within a function/method body (except for references)
13645 // are handled by a dataflow analysis.
13646 // This is undefined behavior in C++, but valid in C.
13647 if (getLangOpts().CPlusPlus)
13648 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13649 VDecl->getType()->isReferenceType())
13650 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13652 // If the type changed, it means we had an incomplete type that was
13653 // completed by the initializer. For example:
13654 // int ary[] = { 1, 3, 5 };
13655 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13656 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13657 VDecl->setType(DclT);
13659 if (!VDecl->isInvalidDecl()) {
13660 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13662 if (VDecl->hasAttr<BlocksAttr>())
13663 ObjC().checkRetainCycles(VDecl, Init);
13665 // It is safe to assign a weak reference into a strong variable.
13666 // Although this code can still have problems:
13667 // id x = self.weakProp;
13668 // id y = self.weakProp;
13669 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13670 // paths through the function. This should be revisited if
13671 // -Wrepeated-use-of-weak is made flow-sensitive.
13672 if (FunctionScopeInfo *FSI = getCurFunction())
13673 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13674 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13675 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13676 Init->getBeginLoc()))
13677 FSI->markSafeWeakUse(Init);
13680 // The initialization is usually a full-expression.
13682 // FIXME: If this is a braced initialization of an aggregate, it is not
13683 // an expression, and each individual field initializer is a separate
13684 // full-expression. For instance, in:
13686 // struct Temp { ~Temp(); };
13687 // struct S { S(Temp); };
13688 // struct T { S a, b; } t = { Temp(), Temp() }
13690 // we should destroy the first Temp before constructing the second.
13691 ExprResult Result =
13692 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13693 /*DiscardedValue*/ false, VDecl->isConstexpr());
13694 if (!Result.isUsable()) {
13695 VDecl->setInvalidDecl();
13696 return;
13698 Init = Result.get();
13700 // Attach the initializer to the decl.
13701 VDecl->setInit(Init);
13703 if (VDecl->isLocalVarDecl()) {
13704 // Don't check the initializer if the declaration is malformed.
13705 if (VDecl->isInvalidDecl()) {
13706 // do nothing
13708 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13709 // This is true even in C++ for OpenCL.
13710 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13711 CheckForConstantInitializer(Init);
13713 // Otherwise, C++ does not restrict the initializer.
13714 } else if (getLangOpts().CPlusPlus) {
13715 // do nothing
13717 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13718 // static storage duration shall be constant expressions or string literals.
13719 } else if (VDecl->getStorageClass() == SC_Static) {
13720 CheckForConstantInitializer(Init);
13722 // C89 is stricter than C99 for aggregate initializers.
13723 // C89 6.5.7p3: All the expressions [...] in an initializer list
13724 // for an object that has aggregate or union type shall be
13725 // constant expressions.
13726 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13727 isa<InitListExpr>(Init)) {
13728 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13731 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13732 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13733 if (VDecl->hasLocalStorage())
13734 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13735 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13736 VDecl->getLexicalDeclContext()->isRecord()) {
13737 // This is an in-class initialization for a static data member, e.g.,
13739 // struct S {
13740 // static const int value = 17;
13741 // };
13743 // C++ [class.mem]p4:
13744 // A member-declarator can contain a constant-initializer only
13745 // if it declares a static member (9.4) of const integral or
13746 // const enumeration type, see 9.4.2.
13748 // C++11 [class.static.data]p3:
13749 // If a non-volatile non-inline const static data member is of integral
13750 // or enumeration type, its declaration in the class definition can
13751 // specify a brace-or-equal-initializer in which every initializer-clause
13752 // that is an assignment-expression is a constant expression. A static
13753 // data member of literal type can be declared in the class definition
13754 // with the constexpr specifier; if so, its declaration shall specify a
13755 // brace-or-equal-initializer in which every initializer-clause that is
13756 // an assignment-expression is a constant expression.
13758 // Do nothing on dependent types.
13759 if (DclT->isDependentType()) {
13761 // Allow any 'static constexpr' members, whether or not they are of literal
13762 // type. We separately check that every constexpr variable is of literal
13763 // type.
13764 } else if (VDecl->isConstexpr()) {
13766 // Require constness.
13767 } else if (!DclT.isConstQualified()) {
13768 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13769 << Init->getSourceRange();
13770 VDecl->setInvalidDecl();
13772 // We allow integer constant expressions in all cases.
13773 } else if (DclT->isIntegralOrEnumerationType()) {
13774 // Check whether the expression is a constant expression.
13775 SourceLocation Loc;
13776 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13777 // In C++11, a non-constexpr const static data member with an
13778 // in-class initializer cannot be volatile.
13779 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13780 else if (Init->isValueDependent())
13781 ; // Nothing to check.
13782 else if (Init->isIntegerConstantExpr(Context, &Loc))
13783 ; // Ok, it's an ICE!
13784 else if (Init->getType()->isScopedEnumeralType() &&
13785 Init->isCXX11ConstantExpr(Context))
13786 ; // Ok, it is a scoped-enum constant expression.
13787 else if (Init->isEvaluatable(Context)) {
13788 // If we can constant fold the initializer through heroics, accept it,
13789 // but report this as a use of an extension for -pedantic.
13790 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13791 << Init->getSourceRange();
13792 } else {
13793 // Otherwise, this is some crazy unknown case. Report the issue at the
13794 // location provided by the isIntegerConstantExpr failed check.
13795 Diag(Loc, diag::err_in_class_initializer_non_constant)
13796 << Init->getSourceRange();
13797 VDecl->setInvalidDecl();
13800 // We allow foldable floating-point constants as an extension.
13801 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13802 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13803 // it anyway and provide a fixit to add the 'constexpr'.
13804 if (getLangOpts().CPlusPlus11) {
13805 Diag(VDecl->getLocation(),
13806 diag::ext_in_class_initializer_float_type_cxx11)
13807 << DclT << Init->getSourceRange();
13808 Diag(VDecl->getBeginLoc(),
13809 diag::note_in_class_initializer_float_type_cxx11)
13810 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13811 } else {
13812 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13813 << DclT << Init->getSourceRange();
13815 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13816 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13817 << Init->getSourceRange();
13818 VDecl->setInvalidDecl();
13822 // Suggest adding 'constexpr' in C++11 for literal types.
13823 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13824 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13825 << DclT << Init->getSourceRange()
13826 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13827 VDecl->setConstexpr(true);
13829 } else {
13830 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13831 << DclT << Init->getSourceRange();
13832 VDecl->setInvalidDecl();
13834 } else if (VDecl->isFileVarDecl()) {
13835 // In C, extern is typically used to avoid tentative definitions when
13836 // declaring variables in headers, but adding an initializer makes it a
13837 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13838 // In C++, extern is often used to give implicitly static const variables
13839 // external linkage, so don't warn in that case. If selectany is present,
13840 // this might be header code intended for C and C++ inclusion, so apply the
13841 // C++ rules.
13842 if (VDecl->getStorageClass() == SC_Extern &&
13843 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13844 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13845 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13846 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13847 Diag(VDecl->getLocation(), diag::warn_extern_init);
13849 // In Microsoft C++ mode, a const variable defined in namespace scope has
13850 // external linkage by default if the variable is declared with
13851 // __declspec(dllexport).
13852 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13853 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13854 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13855 VDecl->setStorageClass(SC_Extern);
13857 // C99 6.7.8p4. All file scoped initializers need to be constant.
13858 // Avoid duplicate diagnostics for constexpr variables.
13859 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13860 !VDecl->isConstexpr())
13861 CheckForConstantInitializer(Init);
13864 QualType InitType = Init->getType();
13865 if (!InitType.isNull() &&
13866 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13867 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13868 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13870 // We will represent direct-initialization similarly to copy-initialization:
13871 // int x(1); -as-> int x = 1;
13872 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13874 // Clients that want to distinguish between the two forms, can check for
13875 // direct initializer using VarDecl::getInitStyle().
13876 // A major benefit is that clients that don't particularly care about which
13877 // exactly form was it (like the CodeGen) can handle both cases without
13878 // special case code.
13880 // C++ 8.5p11:
13881 // The form of initialization (using parentheses or '=') is generally
13882 // insignificant, but does matter when the entity being initialized has a
13883 // class type.
13884 if (CXXDirectInit) {
13885 assert(DirectInit && "Call-style initializer must be direct init.");
13886 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13887 : VarDecl::CallInit);
13888 } else if (DirectInit) {
13889 // This must be list-initialization. No other way is direct-initialization.
13890 VDecl->setInitStyle(VarDecl::ListInit);
13893 if (LangOpts.OpenMP &&
13894 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13895 VDecl->isFileVarDecl())
13896 DeclsToCheckForDeferredDiags.insert(VDecl);
13897 CheckCompleteVariableDeclaration(VDecl);
13900 void Sema::ActOnInitializerError(Decl *D) {
13901 // Our main concern here is re-establishing invariants like "a
13902 // variable's type is either dependent or complete".
13903 if (!D || D->isInvalidDecl()) return;
13905 VarDecl *VD = dyn_cast<VarDecl>(D);
13906 if (!VD) return;
13908 // Bindings are not usable if we can't make sense of the initializer.
13909 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13910 for (auto *BD : DD->bindings())
13911 BD->setInvalidDecl();
13913 // Auto types are meaningless if we can't make sense of the initializer.
13914 if (VD->getType()->isUndeducedType()) {
13915 D->setInvalidDecl();
13916 return;
13919 QualType Ty = VD->getType();
13920 if (Ty->isDependentType()) return;
13922 // Require a complete type.
13923 if (RequireCompleteType(VD->getLocation(),
13924 Context.getBaseElementType(Ty),
13925 diag::err_typecheck_decl_incomplete_type)) {
13926 VD->setInvalidDecl();
13927 return;
13930 // Require a non-abstract type.
13931 if (RequireNonAbstractType(VD->getLocation(), Ty,
13932 diag::err_abstract_type_in_decl,
13933 AbstractVariableType)) {
13934 VD->setInvalidDecl();
13935 return;
13938 // Don't bother complaining about constructors or destructors,
13939 // though.
13942 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13943 // If there is no declaration, there was an error parsing it. Just ignore it.
13944 if (!RealDecl)
13945 return;
13947 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13948 QualType Type = Var->getType();
13950 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13951 if (isa<DecompositionDecl>(RealDecl)) {
13952 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13953 Var->setInvalidDecl();
13954 return;
13957 if (Type->isUndeducedType() &&
13958 DeduceVariableDeclarationType(Var, false, nullptr))
13959 return;
13961 // C++11 [class.static.data]p3: A static data member can be declared with
13962 // the constexpr specifier; if so, its declaration shall specify
13963 // a brace-or-equal-initializer.
13964 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13965 // the definition of a variable [...] or the declaration of a static data
13966 // member.
13967 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13968 !Var->isThisDeclarationADemotedDefinition()) {
13969 if (Var->isStaticDataMember()) {
13970 // C++1z removes the relevant rule; the in-class declaration is always
13971 // a definition there.
13972 if (!getLangOpts().CPlusPlus17 &&
13973 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13974 Diag(Var->getLocation(),
13975 diag::err_constexpr_static_mem_var_requires_init)
13976 << Var;
13977 Var->setInvalidDecl();
13978 return;
13980 } else {
13981 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13982 Var->setInvalidDecl();
13983 return;
13987 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13988 // be initialized.
13989 if (!Var->isInvalidDecl() &&
13990 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13991 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13992 bool HasConstExprDefaultConstructor = false;
13993 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13994 for (auto *Ctor : RD->ctors()) {
13995 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13996 Ctor->getMethodQualifiers().getAddressSpace() ==
13997 LangAS::opencl_constant) {
13998 HasConstExprDefaultConstructor = true;
14002 if (!HasConstExprDefaultConstructor) {
14003 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14004 Var->setInvalidDecl();
14005 return;
14009 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14010 if (Var->getStorageClass() == SC_Extern) {
14011 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14012 << Var;
14013 Var->setInvalidDecl();
14014 return;
14016 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14017 diag::err_typecheck_decl_incomplete_type)) {
14018 Var->setInvalidDecl();
14019 return;
14021 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14022 if (!RD->hasTrivialDefaultConstructor()) {
14023 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14024 Var->setInvalidDecl();
14025 return;
14028 // The declaration is uninitialized, no need for further checks.
14029 return;
14032 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14033 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14034 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14035 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14036 NTCUC_DefaultInitializedObject, NTCUK_Init);
14039 switch (DefKind) {
14040 case VarDecl::Definition:
14041 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14042 break;
14044 // We have an out-of-line definition of a static data member
14045 // that has an in-class initializer, so we type-check this like
14046 // a declaration.
14048 [[fallthrough]];
14050 case VarDecl::DeclarationOnly:
14051 // It's only a declaration.
14053 // Block scope. C99 6.7p7: If an identifier for an object is
14054 // declared with no linkage (C99 6.2.2p6), the type for the
14055 // object shall be complete.
14056 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14057 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14058 RequireCompleteType(Var->getLocation(), Type,
14059 diag::err_typecheck_decl_incomplete_type))
14060 Var->setInvalidDecl();
14062 // Make sure that the type is not abstract.
14063 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14064 RequireNonAbstractType(Var->getLocation(), Type,
14065 diag::err_abstract_type_in_decl,
14066 AbstractVariableType))
14067 Var->setInvalidDecl();
14068 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14069 Var->getStorageClass() == SC_PrivateExtern) {
14070 Diag(Var->getLocation(), diag::warn_private_extern);
14071 Diag(Var->getLocation(), diag::note_private_extern);
14074 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14075 !Var->isInvalidDecl())
14076 ExternalDeclarations.push_back(Var);
14078 return;
14080 case VarDecl::TentativeDefinition:
14081 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14082 // object that has file scope without an initializer, and without a
14083 // storage-class specifier or with the storage-class specifier "static",
14084 // constitutes a tentative definition. Note: A tentative definition with
14085 // external linkage is valid (C99 6.2.2p5).
14086 if (!Var->isInvalidDecl()) {
14087 if (const IncompleteArrayType *ArrayT
14088 = Context.getAsIncompleteArrayType(Type)) {
14089 if (RequireCompleteSizedType(
14090 Var->getLocation(), ArrayT->getElementType(),
14091 diag::err_array_incomplete_or_sizeless_type))
14092 Var->setInvalidDecl();
14093 } else if (Var->getStorageClass() == SC_Static) {
14094 // C99 6.9.2p3: If the declaration of an identifier for an object is
14095 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14096 // declared type shall not be an incomplete type.
14097 // NOTE: code such as the following
14098 // static struct s;
14099 // struct s { int a; };
14100 // is accepted by gcc. Hence here we issue a warning instead of
14101 // an error and we do not invalidate the static declaration.
14102 // NOTE: to avoid multiple warnings, only check the first declaration.
14103 if (Var->isFirstDecl())
14104 RequireCompleteType(Var->getLocation(), Type,
14105 diag::ext_typecheck_decl_incomplete_type);
14109 // Record the tentative definition; we're done.
14110 if (!Var->isInvalidDecl())
14111 TentativeDefinitions.push_back(Var);
14112 return;
14115 // Provide a specific diagnostic for uninitialized variable
14116 // definitions with incomplete array type.
14117 if (Type->isIncompleteArrayType()) {
14118 if (Var->isConstexpr())
14119 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14120 << Var;
14121 else
14122 Diag(Var->getLocation(),
14123 diag::err_typecheck_incomplete_array_needs_initializer);
14124 Var->setInvalidDecl();
14125 return;
14128 // Provide a specific diagnostic for uninitialized variable
14129 // definitions with reference type.
14130 if (Type->isReferenceType()) {
14131 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14132 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14133 return;
14136 // Do not attempt to type-check the default initializer for a
14137 // variable with dependent type.
14138 if (Type->isDependentType())
14139 return;
14141 if (Var->isInvalidDecl())
14142 return;
14144 if (!Var->hasAttr<AliasAttr>()) {
14145 if (RequireCompleteType(Var->getLocation(),
14146 Context.getBaseElementType(Type),
14147 diag::err_typecheck_decl_incomplete_type)) {
14148 Var->setInvalidDecl();
14149 return;
14151 } else {
14152 return;
14155 // The variable can not have an abstract class type.
14156 if (RequireNonAbstractType(Var->getLocation(), Type,
14157 diag::err_abstract_type_in_decl,
14158 AbstractVariableType)) {
14159 Var->setInvalidDecl();
14160 return;
14163 // Check for jumps past the implicit initializer. C++0x
14164 // clarifies that this applies to a "variable with automatic
14165 // storage duration", not a "local variable".
14166 // C++11 [stmt.dcl]p3
14167 // A program that jumps from a point where a variable with automatic
14168 // storage duration is not in scope to a point where it is in scope is
14169 // ill-formed unless the variable has scalar type, class type with a
14170 // trivial default constructor and a trivial destructor, a cv-qualified
14171 // version of one of these types, or an array of one of the preceding
14172 // types and is declared without an initializer.
14173 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14174 if (const RecordType *Record
14175 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14176 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14177 // Mark the function (if we're in one) for further checking even if the
14178 // looser rules of C++11 do not require such checks, so that we can
14179 // diagnose incompatibilities with C++98.
14180 if (!CXXRecord->isPOD())
14181 setFunctionHasBranchProtectedScope();
14184 // In OpenCL, we can't initialize objects in the __local address space,
14185 // even implicitly, so don't synthesize an implicit initializer.
14186 if (getLangOpts().OpenCL &&
14187 Var->getType().getAddressSpace() == LangAS::opencl_local)
14188 return;
14189 // C++03 [dcl.init]p9:
14190 // If no initializer is specified for an object, and the
14191 // object is of (possibly cv-qualified) non-POD class type (or
14192 // array thereof), the object shall be default-initialized; if
14193 // the object is of const-qualified type, the underlying class
14194 // type shall have a user-declared default
14195 // constructor. Otherwise, if no initializer is specified for
14196 // a non- static object, the object and its subobjects, if
14197 // any, have an indeterminate initial value); if the object
14198 // or any of its subobjects are of const-qualified type, the
14199 // program is ill-formed.
14200 // C++0x [dcl.init]p11:
14201 // If no initializer is specified for an object, the object is
14202 // default-initialized; [...].
14203 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14204 InitializationKind Kind
14205 = InitializationKind::CreateDefault(Var->getLocation());
14207 InitializationSequence InitSeq(*this, Entity, Kind, {});
14208 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14210 if (Init.get()) {
14211 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14212 // This is important for template substitution.
14213 Var->setInitStyle(VarDecl::CallInit);
14214 } else if (Init.isInvalid()) {
14215 // If default-init fails, attach a recovery-expr initializer to track
14216 // that initialization was attempted and failed.
14217 auto RecoveryExpr =
14218 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14219 if (RecoveryExpr.get())
14220 Var->setInit(RecoveryExpr.get());
14223 CheckCompleteVariableDeclaration(Var);
14227 void Sema::ActOnCXXForRangeDecl(Decl *D) {
14228 // If there is no declaration, there was an error parsing it. Ignore it.
14229 if (!D)
14230 return;
14232 VarDecl *VD = dyn_cast<VarDecl>(D);
14233 if (!VD) {
14234 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14235 D->setInvalidDecl();
14236 return;
14239 VD->setCXXForRangeDecl(true);
14241 // for-range-declaration cannot be given a storage class specifier.
14242 int Error = -1;
14243 switch (VD->getStorageClass()) {
14244 case SC_None:
14245 break;
14246 case SC_Extern:
14247 Error = 0;
14248 break;
14249 case SC_Static:
14250 Error = 1;
14251 break;
14252 case SC_PrivateExtern:
14253 Error = 2;
14254 break;
14255 case SC_Auto:
14256 Error = 3;
14257 break;
14258 case SC_Register:
14259 Error = 4;
14260 break;
14263 // for-range-declaration cannot be given a storage class specifier con't.
14264 switch (VD->getTSCSpec()) {
14265 case TSCS_thread_local:
14266 Error = 6;
14267 break;
14268 case TSCS___thread:
14269 case TSCS__Thread_local:
14270 case TSCS_unspecified:
14271 break;
14274 if (Error != -1) {
14275 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14276 << VD << Error;
14277 D->setInvalidDecl();
14281 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14282 IdentifierInfo *Ident,
14283 ParsedAttributes &Attrs) {
14284 // C++1y [stmt.iter]p1:
14285 // A range-based for statement of the form
14286 // for ( for-range-identifier : for-range-initializer ) statement
14287 // is equivalent to
14288 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14289 DeclSpec DS(Attrs.getPool().getFactory());
14291 const char *PrevSpec;
14292 unsigned DiagID;
14293 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14294 getPrintingPolicy());
14296 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14297 D.SetIdentifier(Ident, IdentLoc);
14298 D.takeAttributes(Attrs);
14300 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14301 IdentLoc);
14302 Decl *Var = ActOnDeclarator(S, D);
14303 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14304 FinalizeDeclaration(Var);
14305 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14306 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14307 : IdentLoc);
14310 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14311 if (var->isInvalidDecl()) return;
14313 CUDA().MaybeAddConstantAttr(var);
14315 if (getLangOpts().OpenCL) {
14316 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14317 // initialiser
14318 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14319 !var->hasInit()) {
14320 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14321 << 1 /*Init*/;
14322 var->setInvalidDecl();
14323 return;
14327 // In Objective-C, don't allow jumps past the implicit initialization of a
14328 // local retaining variable.
14329 if (getLangOpts().ObjC &&
14330 var->hasLocalStorage()) {
14331 switch (var->getType().getObjCLifetime()) {
14332 case Qualifiers::OCL_None:
14333 case Qualifiers::OCL_ExplicitNone:
14334 case Qualifiers::OCL_Autoreleasing:
14335 break;
14337 case Qualifiers::OCL_Weak:
14338 case Qualifiers::OCL_Strong:
14339 setFunctionHasBranchProtectedScope();
14340 break;
14344 if (var->hasLocalStorage() &&
14345 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14346 setFunctionHasBranchProtectedScope();
14348 // Warn about externally-visible variables being defined without a
14349 // prior declaration. We only want to do this for global
14350 // declarations, but we also specifically need to avoid doing it for
14351 // class members because the linkage of an anonymous class can
14352 // change if it's later given a typedef name.
14353 if (var->isThisDeclarationADefinition() &&
14354 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14355 var->isExternallyVisible() && var->hasLinkage() &&
14356 !var->isInline() && !var->getDescribedVarTemplate() &&
14357 var->getStorageClass() != SC_Register &&
14358 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14359 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14360 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14361 var->getLocation())) {
14362 // Find a previous declaration that's not a definition.
14363 VarDecl *prev = var->getPreviousDecl();
14364 while (prev && prev->isThisDeclarationADefinition())
14365 prev = prev->getPreviousDecl();
14367 if (!prev) {
14368 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14369 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14370 << /* variable */ 0;
14374 // Cache the result of checking for constant initialization.
14375 std::optional<bool> CacheHasConstInit;
14376 const Expr *CacheCulprit = nullptr;
14377 auto checkConstInit = [&]() mutable {
14378 if (!CacheHasConstInit)
14379 CacheHasConstInit = var->getInit()->isConstantInitializer(
14380 Context, var->getType()->isReferenceType(), &CacheCulprit);
14381 return *CacheHasConstInit;
14384 if (var->getTLSKind() == VarDecl::TLS_Static) {
14385 if (var->getType().isDestructedType()) {
14386 // GNU C++98 edits for __thread, [basic.start.term]p3:
14387 // The type of an object with thread storage duration shall not
14388 // have a non-trivial destructor.
14389 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14390 if (getLangOpts().CPlusPlus11)
14391 Diag(var->getLocation(), diag::note_use_thread_local);
14392 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14393 if (!checkConstInit()) {
14394 // GNU C++98 edits for __thread, [basic.start.init]p4:
14395 // An object of thread storage duration shall not require dynamic
14396 // initialization.
14397 // FIXME: Need strict checking here.
14398 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14399 << CacheCulprit->getSourceRange();
14400 if (getLangOpts().CPlusPlus11)
14401 Diag(var->getLocation(), diag::note_use_thread_local);
14407 if (!var->getType()->isStructureType() && var->hasInit() &&
14408 isa<InitListExpr>(var->getInit())) {
14409 const auto *ILE = cast<InitListExpr>(var->getInit());
14410 unsigned NumInits = ILE->getNumInits();
14411 if (NumInits > 2)
14412 for (unsigned I = 0; I < NumInits; ++I) {
14413 const auto *Init = ILE->getInit(I);
14414 if (!Init)
14415 break;
14416 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14417 if (!SL)
14418 break;
14420 unsigned NumConcat = SL->getNumConcatenated();
14421 // Diagnose missing comma in string array initialization.
14422 // Do not warn when all the elements in the initializer are concatenated
14423 // together. Do not warn for macros too.
14424 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14425 bool OnlyOneMissingComma = true;
14426 for (unsigned J = I + 1; J < NumInits; ++J) {
14427 const auto *Init = ILE->getInit(J);
14428 if (!Init)
14429 break;
14430 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14431 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14432 OnlyOneMissingComma = false;
14433 break;
14437 if (OnlyOneMissingComma) {
14438 SmallVector<FixItHint, 1> Hints;
14439 for (unsigned i = 0; i < NumConcat - 1; ++i)
14440 Hints.push_back(FixItHint::CreateInsertion(
14441 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14443 Diag(SL->getStrTokenLoc(1),
14444 diag::warn_concatenated_literal_array_init)
14445 << Hints;
14446 Diag(SL->getBeginLoc(),
14447 diag::note_concatenated_string_literal_silence);
14449 // In any case, stop now.
14450 break;
14456 QualType type = var->getType();
14458 if (var->hasAttr<BlocksAttr>())
14459 getCurFunction()->addByrefBlockVar(var);
14461 Expr *Init = var->getInit();
14462 bool GlobalStorage = var->hasGlobalStorage();
14463 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14464 QualType baseType = Context.getBaseElementType(type);
14465 bool HasConstInit = true;
14467 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14468 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14469 << var;
14471 // Check whether the initializer is sufficiently constant.
14472 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14473 !type->isDependentType() && Init && !Init->isValueDependent() &&
14474 (GlobalStorage || var->isConstexpr() ||
14475 var->mightBeUsableInConstantExpressions(Context))) {
14476 // If this variable might have a constant initializer or might be usable in
14477 // constant expressions, check whether or not it actually is now. We can't
14478 // do this lazily, because the result might depend on things that change
14479 // later, such as which constexpr functions happen to be defined.
14480 SmallVector<PartialDiagnosticAt, 8> Notes;
14481 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14482 // Prior to C++11, in contexts where a constant initializer is required,
14483 // the set of valid constant initializers is described by syntactic rules
14484 // in [expr.const]p2-6.
14485 // FIXME: Stricter checking for these rules would be useful for constinit /
14486 // -Wglobal-constructors.
14487 HasConstInit = checkConstInit();
14489 // Compute and cache the constant value, and remember that we have a
14490 // constant initializer.
14491 if (HasConstInit) {
14492 (void)var->checkForConstantInitialization(Notes);
14493 Notes.clear();
14494 } else if (CacheCulprit) {
14495 Notes.emplace_back(CacheCulprit->getExprLoc(),
14496 PDiag(diag::note_invalid_subexpr_in_const_expr));
14497 Notes.back().second << CacheCulprit->getSourceRange();
14499 } else {
14500 // Evaluate the initializer to see if it's a constant initializer.
14501 HasConstInit = var->checkForConstantInitialization(Notes);
14504 if (HasConstInit) {
14505 // FIXME: Consider replacing the initializer with a ConstantExpr.
14506 } else if (var->isConstexpr()) {
14507 SourceLocation DiagLoc = var->getLocation();
14508 // If the note doesn't add any useful information other than a source
14509 // location, fold it into the primary diagnostic.
14510 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14511 diag::note_invalid_subexpr_in_const_expr) {
14512 DiagLoc = Notes[0].first;
14513 Notes.clear();
14515 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14516 << var << Init->getSourceRange();
14517 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14518 Diag(Notes[I].first, Notes[I].second);
14519 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14520 auto *Attr = var->getAttr<ConstInitAttr>();
14521 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14522 << Init->getSourceRange();
14523 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14524 << Attr->getRange() << Attr->isConstinit();
14525 for (auto &it : Notes)
14526 Diag(it.first, it.second);
14527 } else if (IsGlobal &&
14528 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14529 var->getLocation())) {
14530 // Warn about globals which don't have a constant initializer. Don't
14531 // warn about globals with a non-trivial destructor because we already
14532 // warned about them.
14533 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14534 if (!(RD && !RD->hasTrivialDestructor())) {
14535 // checkConstInit() here permits trivial default initialization even in
14536 // C++11 onwards, where such an initializer is not a constant initializer
14537 // but nonetheless doesn't require a global constructor.
14538 if (!checkConstInit())
14539 Diag(var->getLocation(), diag::warn_global_constructor)
14540 << Init->getSourceRange();
14545 // Apply section attributes and pragmas to global variables.
14546 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14547 !inTemplateInstantiation()) {
14548 PragmaStack<StringLiteral *> *Stack = nullptr;
14549 int SectionFlags = ASTContext::PSF_Read;
14550 bool MSVCEnv =
14551 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14552 std::optional<QualType::NonConstantStorageReason> Reason;
14553 if (HasConstInit &&
14554 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14555 Stack = &ConstSegStack;
14556 } else {
14557 SectionFlags |= ASTContext::PSF_Write;
14558 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14560 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14561 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14562 SectionFlags |= ASTContext::PSF_Implicit;
14563 UnifySection(SA->getName(), SectionFlags, var);
14564 } else if (Stack->CurrentValue) {
14565 if (Stack != &ConstSegStack && MSVCEnv &&
14566 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14567 var->getType().isConstQualified()) {
14568 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14569 NonConstNonReferenceType) &&
14570 "This case should've already been handled elsewhere");
14571 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14572 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14573 ? QualType::NonConstantStorageReason::NonTrivialCtor
14574 : *Reason);
14576 SectionFlags |= ASTContext::PSF_Implicit;
14577 auto SectionName = Stack->CurrentValue->getString();
14578 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14579 Stack->CurrentPragmaLocation,
14580 SectionAttr::Declspec_allocate));
14581 if (UnifySection(SectionName, SectionFlags, var))
14582 var->dropAttr<SectionAttr>();
14585 // Apply the init_seg attribute if this has an initializer. If the
14586 // initializer turns out to not be dynamic, we'll end up ignoring this
14587 // attribute.
14588 if (CurInitSeg && var->getInit())
14589 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14590 CurInitSegLoc));
14593 // All the following checks are C++ only.
14594 if (!getLangOpts().CPlusPlus) {
14595 // If this variable must be emitted, add it as an initializer for the
14596 // current module.
14597 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14598 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14599 return;
14602 // Require the destructor.
14603 if (!type->isDependentType())
14604 if (const RecordType *recordType = baseType->getAs<RecordType>())
14605 FinalizeVarWithDestructor(var, recordType);
14607 // If this variable must be emitted, add it as an initializer for the current
14608 // module.
14609 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14610 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14612 // Build the bindings if this is a structured binding declaration.
14613 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14614 CheckCompleteDecompositionDeclaration(DD);
14617 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14618 assert(VD->isStaticLocal());
14620 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14622 // Find outermost function when VD is in lambda function.
14623 while (FD && !getDLLAttr(FD) &&
14624 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14625 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14626 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14629 if (!FD)
14630 return;
14632 // Static locals inherit dll attributes from their function.
14633 if (Attr *A = getDLLAttr(FD)) {
14634 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14635 NewAttr->setInherited(true);
14636 VD->addAttr(NewAttr);
14637 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14638 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14639 NewAttr->setInherited(true);
14640 VD->addAttr(NewAttr);
14642 // Export this function to enforce exporting this static variable even
14643 // if it is not used in this compilation unit.
14644 if (!FD->hasAttr<DLLExportAttr>())
14645 FD->addAttr(NewAttr);
14647 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14648 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14649 NewAttr->setInherited(true);
14650 VD->addAttr(NewAttr);
14654 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14655 assert(VD->getTLSKind());
14657 // Perform TLS alignment check here after attributes attached to the variable
14658 // which may affect the alignment have been processed. Only perform the check
14659 // if the target has a maximum TLS alignment (zero means no constraints).
14660 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14661 // Protect the check so that it's not performed on dependent types and
14662 // dependent alignments (we can't determine the alignment in that case).
14663 if (!VD->hasDependentAlignment()) {
14664 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14665 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14666 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14667 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14668 << (unsigned)MaxAlignChars.getQuantity();
14674 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14675 // Note that we are no longer parsing the initializer for this declaration.
14676 ParsingInitForAutoVars.erase(ThisDecl);
14678 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14679 if (!VD)
14680 return;
14682 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14683 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14684 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14685 if (PragmaClangBSSSection.Valid)
14686 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14687 Context, PragmaClangBSSSection.SectionName,
14688 PragmaClangBSSSection.PragmaLocation));
14689 if (PragmaClangDataSection.Valid)
14690 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14691 Context, PragmaClangDataSection.SectionName,
14692 PragmaClangDataSection.PragmaLocation));
14693 if (PragmaClangRodataSection.Valid)
14694 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14695 Context, PragmaClangRodataSection.SectionName,
14696 PragmaClangRodataSection.PragmaLocation));
14697 if (PragmaClangRelroSection.Valid)
14698 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14699 Context, PragmaClangRelroSection.SectionName,
14700 PragmaClangRelroSection.PragmaLocation));
14703 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14704 for (auto *BD : DD->bindings()) {
14705 FinalizeDeclaration(BD);
14709 CheckInvalidBuiltinCountedByRef(VD->getInit(), InitializerKind);
14711 checkAttributesAfterMerging(*this, *VD);
14713 if (VD->isStaticLocal())
14714 CheckStaticLocalForDllExport(VD);
14716 if (VD->getTLSKind())
14717 CheckThreadLocalForLargeAlignment(VD);
14719 // Perform check for initializers of device-side global variables.
14720 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14721 // 7.5). We must also apply the same checks to all __shared__
14722 // variables whether they are local or not. CUDA also allows
14723 // constant initializers for __constant__ and __device__ variables.
14724 if (getLangOpts().CUDA)
14725 CUDA().checkAllowedInitializer(VD);
14727 // Grab the dllimport or dllexport attribute off of the VarDecl.
14728 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14730 // Imported static data members cannot be defined out-of-line.
14731 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14732 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14733 VD->isThisDeclarationADefinition()) {
14734 // We allow definitions of dllimport class template static data members
14735 // with a warning.
14736 CXXRecordDecl *Context =
14737 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14738 bool IsClassTemplateMember =
14739 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14740 Context->getDescribedClassTemplate();
14742 Diag(VD->getLocation(),
14743 IsClassTemplateMember
14744 ? diag::warn_attribute_dllimport_static_field_definition
14745 : diag::err_attribute_dllimport_static_field_definition);
14746 Diag(IA->getLocation(), diag::note_attribute);
14747 if (!IsClassTemplateMember)
14748 VD->setInvalidDecl();
14752 // dllimport/dllexport variables cannot be thread local, their TLS index
14753 // isn't exported with the variable.
14754 if (DLLAttr && VD->getTLSKind()) {
14755 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14756 if (F && getDLLAttr(F)) {
14757 assert(VD->isStaticLocal());
14758 // But if this is a static local in a dlimport/dllexport function, the
14759 // function will never be inlined, which means the var would never be
14760 // imported, so having it marked import/export is safe.
14761 } else {
14762 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14763 << DLLAttr;
14764 VD->setInvalidDecl();
14768 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14769 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14770 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14771 << Attr;
14772 VD->dropAttr<UsedAttr>();
14775 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14776 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14777 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14778 << Attr;
14779 VD->dropAttr<RetainAttr>();
14783 const DeclContext *DC = VD->getDeclContext();
14784 // If there's a #pragma GCC visibility in scope, and this isn't a class
14785 // member, set the visibility of this variable.
14786 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14787 AddPushedVisibilityAttribute(VD);
14789 // FIXME: Warn on unused var template partial specializations.
14790 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14791 MarkUnusedFileScopedDecl(VD);
14793 // Now we have parsed the initializer and can update the table of magic
14794 // tag values.
14795 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14796 !VD->getType()->isIntegralOrEnumerationType())
14797 return;
14799 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14800 const Expr *MagicValueExpr = VD->getInit();
14801 if (!MagicValueExpr) {
14802 continue;
14804 std::optional<llvm::APSInt> MagicValueInt;
14805 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14806 Diag(I->getRange().getBegin(),
14807 diag::err_type_tag_for_datatype_not_ice)
14808 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14809 continue;
14811 if (MagicValueInt->getActiveBits() > 64) {
14812 Diag(I->getRange().getBegin(),
14813 diag::err_type_tag_for_datatype_too_large)
14814 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14815 continue;
14817 uint64_t MagicValue = MagicValueInt->getZExtValue();
14818 RegisterTypeTagForDatatype(I->getArgumentKind(),
14819 MagicValue,
14820 I->getMatchingCType(),
14821 I->getLayoutCompatible(),
14822 I->getMustBeNull());
14826 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14827 auto *VD = dyn_cast<VarDecl>(DD);
14828 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14831 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14832 ArrayRef<Decl *> Group) {
14833 SmallVector<Decl*, 8> Decls;
14835 if (DS.isTypeSpecOwned())
14836 Decls.push_back(DS.getRepAsDecl());
14838 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14839 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14840 bool DiagnosedMultipleDecomps = false;
14841 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14842 bool DiagnosedNonDeducedAuto = false;
14844 for (Decl *D : Group) {
14845 if (!D)
14846 continue;
14847 // Check if the Decl has been declared in '#pragma omp declare target'
14848 // directive and has static storage duration.
14849 if (auto *VD = dyn_cast<VarDecl>(D);
14850 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14851 VD->hasGlobalStorage())
14852 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
14853 // For declarators, there are some additional syntactic-ish checks we need
14854 // to perform.
14855 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14856 if (!FirstDeclaratorInGroup)
14857 FirstDeclaratorInGroup = DD;
14858 if (!FirstDecompDeclaratorInGroup)
14859 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14860 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14861 !hasDeducedAuto(DD))
14862 FirstNonDeducedAutoInGroup = DD;
14864 if (FirstDeclaratorInGroup != DD) {
14865 // A decomposition declaration cannot be combined with any other
14866 // declaration in the same group.
14867 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14868 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14869 diag::err_decomp_decl_not_alone)
14870 << FirstDeclaratorInGroup->getSourceRange()
14871 << DD->getSourceRange();
14872 DiagnosedMultipleDecomps = true;
14875 // A declarator that uses 'auto' in any way other than to declare a
14876 // variable with a deduced type cannot be combined with any other
14877 // declarator in the same group.
14878 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14879 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14880 diag::err_auto_non_deduced_not_alone)
14881 << FirstNonDeducedAutoInGroup->getType()
14882 ->hasAutoForTrailingReturnType()
14883 << FirstDeclaratorInGroup->getSourceRange()
14884 << DD->getSourceRange();
14885 DiagnosedNonDeducedAuto = true;
14890 Decls.push_back(D);
14893 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14894 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14895 handleTagNumbering(Tag, S);
14896 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14897 getLangOpts().CPlusPlus)
14898 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14902 return BuildDeclaratorGroup(Decls);
14905 Sema::DeclGroupPtrTy
14906 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14907 // C++14 [dcl.spec.auto]p7: (DR1347)
14908 // If the type that replaces the placeholder type is not the same in each
14909 // deduction, the program is ill-formed.
14910 if (Group.size() > 1) {
14911 QualType Deduced;
14912 VarDecl *DeducedDecl = nullptr;
14913 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14914 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14915 if (!D || D->isInvalidDecl())
14916 break;
14917 DeducedType *DT = D->getType()->getContainedDeducedType();
14918 if (!DT || DT->getDeducedType().isNull())
14919 continue;
14920 if (Deduced.isNull()) {
14921 Deduced = DT->getDeducedType();
14922 DeducedDecl = D;
14923 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14924 auto *AT = dyn_cast<AutoType>(DT);
14925 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14926 diag::err_auto_different_deductions)
14927 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14928 << DeducedDecl->getDeclName() << DT->getDeducedType()
14929 << D->getDeclName();
14930 if (DeducedDecl->hasInit())
14931 Dia << DeducedDecl->getInit()->getSourceRange();
14932 if (D->getInit())
14933 Dia << D->getInit()->getSourceRange();
14934 D->setInvalidDecl();
14935 break;
14940 ActOnDocumentableDecls(Group);
14942 return DeclGroupPtrTy::make(
14943 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14946 void Sema::ActOnDocumentableDecl(Decl *D) {
14947 ActOnDocumentableDecls(D);
14950 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14951 // Don't parse the comment if Doxygen diagnostics are ignored.
14952 if (Group.empty() || !Group[0])
14953 return;
14955 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14956 Group[0]->getLocation()) &&
14957 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14958 Group[0]->getLocation()))
14959 return;
14961 if (Group.size() >= 2) {
14962 // This is a decl group. Normally it will contain only declarations
14963 // produced from declarator list. But in case we have any definitions or
14964 // additional declaration references:
14965 // 'typedef struct S {} S;'
14966 // 'typedef struct S *S;'
14967 // 'struct S *pS;'
14968 // FinalizeDeclaratorGroup adds these as separate declarations.
14969 Decl *MaybeTagDecl = Group[0];
14970 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14971 Group = Group.slice(1);
14975 // FIMXE: We assume every Decl in the group is in the same file.
14976 // This is false when preprocessor constructs the group from decls in
14977 // different files (e. g. macros or #include).
14978 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14981 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14982 // Check that there are no default arguments inside the type of this
14983 // parameter.
14984 if (getLangOpts().CPlusPlus)
14985 CheckExtraCXXDefaultArguments(D);
14987 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14988 if (D.getCXXScopeSpec().isSet()) {
14989 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14990 << D.getCXXScopeSpec().getRange();
14993 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14994 // simple identifier except [...irrelevant cases...].
14995 switch (D.getName().getKind()) {
14996 case UnqualifiedIdKind::IK_Identifier:
14997 break;
14999 case UnqualifiedIdKind::IK_OperatorFunctionId:
15000 case UnqualifiedIdKind::IK_ConversionFunctionId:
15001 case UnqualifiedIdKind::IK_LiteralOperatorId:
15002 case UnqualifiedIdKind::IK_ConstructorName:
15003 case UnqualifiedIdKind::IK_DestructorName:
15004 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15005 case UnqualifiedIdKind::IK_DeductionGuideName:
15006 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15007 << GetNameForDeclarator(D).getName();
15008 break;
15010 case UnqualifiedIdKind::IK_TemplateId:
15011 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15012 // GetNameForDeclarator would not produce a useful name in this case.
15013 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15014 break;
15018 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15019 SourceLocation ExplicitThisLoc) {
15020 if (!ExplicitThisLoc.isValid())
15021 return;
15022 assert(S.getLangOpts().CPlusPlus &&
15023 "explicit parameter in non-cplusplus mode");
15024 if (!S.getLangOpts().CPlusPlus23)
15025 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15026 << P->getSourceRange();
15028 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15029 // parameter pack.
15030 if (P->isParameterPack()) {
15031 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15032 << P->getSourceRange();
15033 return;
15035 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15036 if (LambdaScopeInfo *LSI = S.getCurLambda())
15037 LSI->ExplicitObjectParameter = P;
15040 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15041 SourceLocation ExplicitThisLoc) {
15042 const DeclSpec &DS = D.getDeclSpec();
15044 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15045 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15046 // except for the special case of a single unnamed parameter of type void
15047 // with no storage class specifier, no type qualifier, and no following
15048 // ellipsis terminator.
15049 // Clang applies the C2y rules for 'register void' in all C language modes,
15050 // same as GCC, because it's questionable what that could possibly mean.
15052 // C++03 [dcl.stc]p2 also permits 'auto'.
15053 StorageClass SC = SC_None;
15054 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15055 SC = SC_Register;
15056 // In C++11, the 'register' storage class specifier is deprecated.
15057 // In C++17, it is not allowed, but we tolerate it as an extension.
15058 if (getLangOpts().CPlusPlus11) {
15059 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus17
15060 ? diag::ext_register_storage_class
15061 : diag::warn_deprecated_register)
15062 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15063 } else if (!getLangOpts().CPlusPlus &&
15064 DS.getTypeSpecType() == DeclSpec::TST_void &&
15065 D.getNumTypeObjects() == 0) {
15066 Diag(DS.getStorageClassSpecLoc(),
15067 diag::err_invalid_storage_class_in_func_decl)
15068 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15069 D.getMutableDeclSpec().ClearStorageClassSpecs();
15071 } else if (getLangOpts().CPlusPlus &&
15072 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15073 SC = SC_Auto;
15074 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15075 Diag(DS.getStorageClassSpecLoc(),
15076 diag::err_invalid_storage_class_in_func_decl);
15077 D.getMutableDeclSpec().ClearStorageClassSpecs();
15080 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15081 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15082 << DeclSpec::getSpecifierName(TSCS);
15083 if (DS.isInlineSpecified())
15084 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15085 << getLangOpts().CPlusPlus17;
15086 if (DS.hasConstexprSpecifier())
15087 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15088 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15090 DiagnoseFunctionSpecifiers(DS);
15092 CheckFunctionOrTemplateParamDeclarator(S, D);
15094 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15095 QualType parmDeclType = TInfo->getType();
15097 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15098 const IdentifierInfo *II = D.getIdentifier();
15099 if (II) {
15100 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15101 RedeclarationKind::ForVisibleRedeclaration);
15102 LookupName(R, S);
15103 if (!R.empty()) {
15104 NamedDecl *PrevDecl = *R.begin();
15105 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15106 // Maybe we will complain about the shadowed template parameter.
15107 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15108 // Just pretend that we didn't see the previous declaration.
15109 PrevDecl = nullptr;
15111 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15112 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15113 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15114 // Recover by removing the name
15115 II = nullptr;
15116 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15117 D.setInvalidType(true);
15122 // Temporarily put parameter variables in the translation unit, not
15123 // the enclosing context. This prevents them from accidentally
15124 // looking like class members in C++.
15125 ParmVarDecl *New =
15126 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15127 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15129 if (D.isInvalidType())
15130 New->setInvalidDecl();
15132 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15134 assert(S->isFunctionPrototypeScope());
15135 assert(S->getFunctionPrototypeDepth() >= 1);
15136 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15137 S->getNextFunctionPrototypeIndex());
15139 // Add the parameter declaration into this scope.
15140 S->AddDecl(New);
15141 if (II)
15142 IdResolver.AddDecl(New);
15144 ProcessDeclAttributes(S, New, D);
15146 if (D.getDeclSpec().isModulePrivateSpecified())
15147 Diag(New->getLocation(), diag::err_module_private_local)
15148 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15149 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15151 if (New->hasAttr<BlocksAttr>()) {
15152 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15155 if (getLangOpts().OpenCL)
15156 deduceOpenCLAddressSpace(New);
15158 return New;
15161 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15162 SourceLocation Loc,
15163 QualType T) {
15164 /* FIXME: setting StartLoc == Loc.
15165 Would it be worth to modify callers so as to provide proper source
15166 location for the unnamed parameters, embedding the parameter's type? */
15167 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15168 T, Context.getTrivialTypeSourceInfo(T, Loc),
15169 SC_None, nullptr);
15170 Param->setImplicit();
15171 return Param;
15174 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15175 // Don't diagnose unused-parameter errors in template instantiations; we
15176 // will already have done so in the template itself.
15177 if (inTemplateInstantiation())
15178 return;
15180 for (const ParmVarDecl *Parameter : Parameters) {
15181 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15182 !Parameter->hasAttr<UnusedAttr>() &&
15183 !Parameter->getIdentifier()->isPlaceholder()) {
15184 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15185 << Parameter->getDeclName();
15190 void Sema::DiagnoseSizeOfParametersAndReturnValue(
15191 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15192 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15193 return;
15195 // Warn if the return value is pass-by-value and larger than the specified
15196 // threshold.
15197 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15198 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15199 if (Size > LangOpts.NumLargeByValueCopy)
15200 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15203 // Warn if any parameter is pass-by-value and larger than the specified
15204 // threshold.
15205 for (const ParmVarDecl *Parameter : Parameters) {
15206 QualType T = Parameter->getType();
15207 if (T->isDependentType() || !T.isPODType(Context))
15208 continue;
15209 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15210 if (Size > LangOpts.NumLargeByValueCopy)
15211 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15212 << Parameter << Size;
15216 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15217 SourceLocation NameLoc,
15218 const IdentifierInfo *Name, QualType T,
15219 TypeSourceInfo *TSInfo, StorageClass SC) {
15220 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15221 if (getLangOpts().ObjCAutoRefCount &&
15222 T.getObjCLifetime() == Qualifiers::OCL_None &&
15223 T->isObjCLifetimeType()) {
15225 Qualifiers::ObjCLifetime lifetime;
15227 // Special cases for arrays:
15228 // - if it's const, use __unsafe_unretained
15229 // - otherwise, it's an error
15230 if (T->isArrayType()) {
15231 if (!T.isConstQualified()) {
15232 if (DelayedDiagnostics.shouldDelayDiagnostics())
15233 DelayedDiagnostics.add(
15234 sema::DelayedDiagnostic::makeForbiddenType(
15235 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15236 else
15237 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15238 << TSInfo->getTypeLoc().getSourceRange();
15240 lifetime = Qualifiers::OCL_ExplicitNone;
15241 } else {
15242 lifetime = T->getObjCARCImplicitLifetime();
15244 T = Context.getLifetimeQualifiedType(T, lifetime);
15247 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15248 Context.getAdjustedParameterType(T),
15249 TSInfo, SC, nullptr);
15251 // Make a note if we created a new pack in the scope of a lambda, so that
15252 // we know that references to that pack must also be expanded within the
15253 // lambda scope.
15254 if (New->isParameterPack())
15255 if (auto *CSI = getEnclosingLambdaOrBlock())
15256 CSI->LocalPacks.push_back(New);
15258 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15259 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15260 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15261 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15263 // Parameter declarators cannot be interface types. All ObjC objects are
15264 // passed by reference.
15265 if (T->isObjCObjectType()) {
15266 SourceLocation TypeEndLoc =
15267 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15268 Diag(NameLoc,
15269 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15270 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15271 T = Context.getObjCObjectPointerType(T);
15272 New->setType(T);
15275 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15276 // duration shall not be qualified by an address-space qualifier."
15277 // Since all parameters have automatic store duration, they can not have
15278 // an address space.
15279 if (T.getAddressSpace() != LangAS::Default &&
15280 // OpenCL allows function arguments declared to be an array of a type
15281 // to be qualified with an address space.
15282 !(getLangOpts().OpenCL &&
15283 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15284 // WebAssembly allows reference types as parameters. Funcref in particular
15285 // lives in a different address space.
15286 !(T->isFunctionPointerType() &&
15287 T.getAddressSpace() == LangAS::wasm_funcref)) {
15288 Diag(NameLoc, diag::err_arg_with_address_space);
15289 New->setInvalidDecl();
15292 // PPC MMA non-pointer types are not allowed as function argument types.
15293 if (Context.getTargetInfo().getTriple().isPPC64() &&
15294 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15295 New->setInvalidDecl();
15298 return New;
15301 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15302 SourceLocation LocAfterDecls) {
15303 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15305 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15306 // in the declaration list shall have at least one declarator, those
15307 // declarators shall only declare identifiers from the identifier list, and
15308 // every identifier in the identifier list shall be declared.
15310 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15311 // identifiers it names shall be declared in the declaration list."
15313 // This is why we only diagnose in C99 and later. Note, the other conditions
15314 // listed are checked elsewhere.
15315 if (!FTI.hasPrototype) {
15316 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15317 --i;
15318 if (FTI.Params[i].Param == nullptr) {
15319 if (getLangOpts().C99) {
15320 SmallString<256> Code;
15321 llvm::raw_svector_ostream(Code)
15322 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15323 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15324 << FTI.Params[i].Ident
15325 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15328 // Implicitly declare the argument as type 'int' for lack of a better
15329 // type.
15330 AttributeFactory attrs;
15331 DeclSpec DS(attrs);
15332 const char* PrevSpec; // unused
15333 unsigned DiagID; // unused
15334 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15335 DiagID, Context.getPrintingPolicy());
15336 // Use the identifier location for the type source range.
15337 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15338 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15339 Declarator ParamD(DS, ParsedAttributesView::none(),
15340 DeclaratorContext::KNRTypeList);
15341 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15342 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15348 Decl *
15349 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15350 MultiTemplateParamsArg TemplateParameterLists,
15351 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15352 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15353 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15354 Scope *ParentScope = FnBodyScope->getParent();
15356 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15357 // we define a non-templated function definition, we will create a declaration
15358 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15359 // The base function declaration will have the equivalent of an `omp declare
15360 // variant` annotation which specifies the mangled definition as a
15361 // specialization function under the OpenMP context defined as part of the
15362 // `omp begin declare variant`.
15363 SmallVector<FunctionDecl *, 4> Bases;
15364 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15365 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15366 ParentScope, D, TemplateParameterLists, Bases);
15368 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15369 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15370 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15372 if (!Bases.empty())
15373 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl,
15374 Bases);
15376 return Dcl;
15379 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15380 Consumer.HandleInlineFunctionDefinition(D);
15383 static bool FindPossiblePrototype(const FunctionDecl *FD,
15384 const FunctionDecl *&PossiblePrototype) {
15385 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15386 Prev = Prev->getPreviousDecl()) {
15387 // Ignore any declarations that occur in function or method
15388 // scope, because they aren't visible from the header.
15389 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15390 continue;
15392 PossiblePrototype = Prev;
15393 return Prev->getType()->isFunctionProtoType();
15395 return false;
15398 static bool
15399 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15400 const FunctionDecl *&PossiblePrototype) {
15401 // Don't warn about invalid declarations.
15402 if (FD->isInvalidDecl())
15403 return false;
15405 // Or declarations that aren't global.
15406 if (!FD->isGlobal())
15407 return false;
15409 // Don't warn about C++ member functions.
15410 if (isa<CXXMethodDecl>(FD))
15411 return false;
15413 // Don't warn about 'main'.
15414 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15415 if (IdentifierInfo *II = FD->getIdentifier())
15416 if (II->isStr("main") || II->isStr("efi_main"))
15417 return false;
15419 if (FD->isMSVCRTEntryPoint())
15420 return false;
15422 // Don't warn about inline functions.
15423 if (FD->isInlined())
15424 return false;
15426 // Don't warn about function templates.
15427 if (FD->getDescribedFunctionTemplate())
15428 return false;
15430 // Don't warn about function template specializations.
15431 if (FD->isFunctionTemplateSpecialization())
15432 return false;
15434 // Don't warn for OpenCL kernels.
15435 if (FD->hasAttr<OpenCLKernelAttr>())
15436 return false;
15438 // Don't warn on explicitly deleted functions.
15439 if (FD->isDeleted())
15440 return false;
15442 // Don't warn on implicitly local functions (such as having local-typed
15443 // parameters).
15444 if (!FD->isExternallyVisible())
15445 return false;
15447 // If we were able to find a potential prototype, don't warn.
15448 if (FindPossiblePrototype(FD, PossiblePrototype))
15449 return false;
15451 return true;
15454 void
15455 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15456 const FunctionDecl *EffectiveDefinition,
15457 SkipBodyInfo *SkipBody) {
15458 const FunctionDecl *Definition = EffectiveDefinition;
15459 if (!Definition &&
15460 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15461 return;
15463 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15464 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15465 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15466 // A merged copy of the same function, instantiated as a member of
15467 // the same class, is OK.
15468 if (declaresSameEntity(OrigFD, OrigDef) &&
15469 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15470 cast<Decl>(FD->getLexicalDeclContext())))
15471 return;
15476 if (canRedefineFunction(Definition, getLangOpts()))
15477 return;
15479 // Don't emit an error when this is redefinition of a typo-corrected
15480 // definition.
15481 if (TypoCorrectedFunctionDefinitions.count(Definition))
15482 return;
15484 // If we don't have a visible definition of the function, and it's inline or
15485 // a template, skip the new definition.
15486 if (SkipBody && !hasVisibleDefinition(Definition) &&
15487 (Definition->getFormalLinkage() == Linkage::Internal ||
15488 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15489 Definition->getNumTemplateParameterLists())) {
15490 SkipBody->ShouldSkip = true;
15491 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15492 if (auto *TD = Definition->getDescribedFunctionTemplate())
15493 makeMergedDefinitionVisible(TD);
15494 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15495 return;
15498 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15499 Definition->getStorageClass() == SC_Extern)
15500 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15501 << FD << getLangOpts().CPlusPlus;
15502 else
15503 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15505 Diag(Definition->getLocation(), diag::note_previous_definition);
15506 FD->setInvalidDecl();
15509 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15510 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15512 LambdaScopeInfo *LSI = PushLambdaScope();
15513 LSI->CallOperator = CallOperator;
15514 LSI->Lambda = LambdaClass;
15515 LSI->ReturnType = CallOperator->getReturnType();
15516 // When this function is called in situation where the context of the call
15517 // operator is not entered, we set AfterParameterList to false, so that
15518 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15519 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15520 // where we would set the CurContext to the lambda operator before
15521 // substituting into it. In this case the flag needs to be true such that
15522 // tryCaptureVariable can correctly handle potential captures thereof.
15523 LSI->AfterParameterList = CurContext == CallOperator;
15525 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15526 // used at the point of dealing with potential captures.
15528 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15529 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15530 // associated. (Technically, we could recover that list from their
15531 // instantiation patterns, but for now, the GLTemplateParameterList seems
15532 // unnecessary in these cases.)
15533 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15534 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15535 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15537 if (LCD == LCD_None)
15538 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15539 else if (LCD == LCD_ByCopy)
15540 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15541 else if (LCD == LCD_ByRef)
15542 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15543 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15545 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15546 LSI->Mutable = !CallOperator->isConst();
15547 if (CallOperator->isExplicitObjectMemberFunction())
15548 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15550 // Add the captures to the LSI so they can be noted as already
15551 // captured within tryCaptureVar.
15552 auto I = LambdaClass->field_begin();
15553 for (const auto &C : LambdaClass->captures()) {
15554 if (C.capturesVariable()) {
15555 ValueDecl *VD = C.getCapturedVar();
15556 if (VD->isInitCapture())
15557 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15558 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15559 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15560 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15561 /*EllipsisLoc*/C.isPackExpansion()
15562 ? C.getEllipsisLoc() : SourceLocation(),
15563 I->getType(), /*Invalid*/false);
15565 } else if (C.capturesThis()) {
15566 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15567 C.getCaptureKind() == LCK_StarThis);
15568 } else {
15569 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15570 I->getType());
15572 ++I;
15574 return LSI;
15577 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15578 SkipBodyInfo *SkipBody,
15579 FnBodyKind BodyKind) {
15580 if (!D) {
15581 // Parsing the function declaration failed in some way. Push on a fake scope
15582 // anyway so we can try to parse the function body.
15583 PushFunctionScope();
15584 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15585 return D;
15588 FunctionDecl *FD = nullptr;
15590 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15591 FD = FunTmpl->getTemplatedDecl();
15592 else
15593 FD = cast<FunctionDecl>(D);
15595 // Do not push if it is a lambda because one is already pushed when building
15596 // the lambda in ActOnStartOfLambdaDefinition().
15597 if (!isLambdaCallOperator(FD))
15598 // [expr.const]/p14.1
15599 // An expression or conversion is in an immediate function context if it is
15600 // potentially evaluated and either: its innermost enclosing non-block scope
15601 // is a function parameter scope of an immediate function.
15602 PushExpressionEvaluationContext(
15603 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15604 : ExprEvalContexts.back().Context);
15606 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15607 // context is nested in an immediate function context, so smaller contexts
15608 // that appear inside immediate functions (like variable initializers) are
15609 // considered to be inside an immediate function context even though by
15610 // themselves they are not immediate function contexts. But when a new
15611 // function is entered, we need to reset this tracking, since the entered
15612 // function might be not an immediate function.
15613 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15614 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15615 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15617 // Check for defining attributes before the check for redefinition.
15618 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15619 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15620 FD->dropAttr<AliasAttr>();
15621 FD->setInvalidDecl();
15623 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15624 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15625 FD->dropAttr<IFuncAttr>();
15626 FD->setInvalidDecl();
15628 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15629 if (Context.getTargetInfo().getTriple().isAArch64() &&
15630 !Context.getTargetInfo().hasFeature("fmv") &&
15631 !Attr->isDefaultVersion()) {
15632 // If function multi versioning disabled skip parsing function body
15633 // defined with non-default target_version attribute
15634 if (SkipBody)
15635 SkipBody->ShouldSkip = true;
15636 return nullptr;
15640 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15641 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15642 Ctor->isDefaultConstructor() &&
15643 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15644 // If this is an MS ABI dllexport default constructor, instantiate any
15645 // default arguments.
15646 InstantiateDefaultCtorDefaultArgs(Ctor);
15650 // See if this is a redefinition. If 'will have body' (or similar) is already
15651 // set, then these checks were already performed when it was set.
15652 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15653 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15654 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15656 // If we're skipping the body, we're done. Don't enter the scope.
15657 if (SkipBody && SkipBody->ShouldSkip)
15658 return D;
15661 // Mark this function as "will have a body eventually". This lets users to
15662 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15663 // this function.
15664 FD->setWillHaveBody();
15666 // If we are instantiating a generic lambda call operator, push
15667 // a LambdaScopeInfo onto the function stack. But use the information
15668 // that's already been calculated (ActOnLambdaExpr) to prime the current
15669 // LambdaScopeInfo.
15670 // When the template operator is being specialized, the LambdaScopeInfo,
15671 // has to be properly restored so that tryCaptureVariable doesn't try
15672 // and capture any new variables. In addition when calculating potential
15673 // captures during transformation of nested lambdas, it is necessary to
15674 // have the LSI properly restored.
15675 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15676 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15677 // instantiated, explicitly specialized.
15678 if (FD->getTemplateSpecializationInfo()
15679 ->isExplicitInstantiationOrSpecialization()) {
15680 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15681 FD->setInvalidDecl();
15682 PushFunctionScope();
15683 } else {
15684 assert(inTemplateInstantiation() &&
15685 "There should be an active template instantiation on the stack "
15686 "when instantiating a generic lambda!");
15687 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15689 } else {
15690 // Enter a new function scope
15691 PushFunctionScope();
15694 // Builtin functions cannot be defined.
15695 if (unsigned BuiltinID = FD->getBuiltinID()) {
15696 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15697 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15698 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15699 FD->setInvalidDecl();
15703 // The return type of a function definition must be complete (C99 6.9.1p3).
15704 // C++23 [dcl.fct.def.general]/p2
15705 // The type of [...] the return for a function definition
15706 // shall not be a (possibly cv-qualified) class type that is incomplete
15707 // or abstract within the function body unless the function is deleted.
15708 QualType ResultType = FD->getReturnType();
15709 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15710 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15711 (RequireCompleteType(FD->getLocation(), ResultType,
15712 diag::err_func_def_incomplete_result) ||
15713 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15714 diag::err_abstract_type_in_decl,
15715 AbstractReturnType)))
15716 FD->setInvalidDecl();
15718 if (FnBodyScope)
15719 PushDeclContext(FnBodyScope, FD);
15721 // Check the validity of our function parameters
15722 if (BodyKind != FnBodyKind::Delete)
15723 CheckParmsForFunctionDef(FD->parameters(),
15724 /*CheckParameterNames=*/true);
15726 // Add non-parameter declarations already in the function to the current
15727 // scope.
15728 if (FnBodyScope) {
15729 for (Decl *NPD : FD->decls()) {
15730 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15731 if (!NonParmDecl)
15732 continue;
15733 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15734 "parameters should not be in newly created FD yet");
15736 // If the decl has a name, make it accessible in the current scope.
15737 if (NonParmDecl->getDeclName())
15738 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15740 // Similarly, dive into enums and fish their constants out, making them
15741 // accessible in this scope.
15742 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15743 for (auto *EI : ED->enumerators())
15744 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15749 // Introduce our parameters into the function scope
15750 for (auto *Param : FD->parameters()) {
15751 Param->setOwningFunction(FD);
15753 // If this has an identifier, add it to the scope stack.
15754 if (Param->getIdentifier() && FnBodyScope) {
15755 CheckShadow(FnBodyScope, Param);
15757 PushOnScopeChains(Param, FnBodyScope);
15761 // C++ [module.import/6] external definitions are not permitted in header
15762 // units. Deleted and Defaulted functions are implicitly inline (but the
15763 // inline state is not set at this point, so check the BodyKind explicitly).
15764 // FIXME: Consider an alternate location for the test where the inlined()
15765 // state is complete.
15766 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15767 !FD->isInvalidDecl() && !FD->isInlined() &&
15768 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15769 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15770 !FD->isTemplateInstantiation()) {
15771 assert(FD->isThisDeclarationADefinition());
15772 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15773 FD->setInvalidDecl();
15776 // Ensure that the function's exception specification is instantiated.
15777 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15778 ResolveExceptionSpec(D->getLocation(), FPT);
15780 // dllimport cannot be applied to non-inline function definitions.
15781 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15782 !FD->isTemplateInstantiation()) {
15783 assert(!FD->hasAttr<DLLExportAttr>());
15784 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15785 FD->setInvalidDecl();
15786 return D;
15789 // Some function attributes (like OptimizeNoneAttr) need actions before
15790 // parsing body started.
15791 applyFunctionAttributesBeforeParsingBody(D);
15793 // We want to attach documentation to original Decl (which might be
15794 // a function template).
15795 ActOnDocumentableDecl(D);
15796 if (getCurLexicalContext()->isObjCContainer() &&
15797 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15798 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15799 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15801 maybeAddDeclWithEffects(FD);
15803 return D;
15806 void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
15807 if (!FD || FD->isInvalidDecl())
15808 return;
15809 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15810 FD = TD->getTemplatedDecl();
15811 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15812 FPOptionsOverride FPO;
15813 FPO.setDisallowOptimizations();
15814 CurFPFeatures.applyChanges(FPO);
15815 FpPragmaStack.CurrentValue =
15816 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
15820 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15821 ReturnStmt **Returns = Scope->Returns.data();
15823 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15824 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15825 if (!NRVOCandidate->isNRVOVariable())
15826 Returns[I]->setNRVOCandidate(nullptr);
15831 bool Sema::canDelayFunctionBody(const Declarator &D) {
15832 // We can't delay parsing the body of a constexpr function template (yet).
15833 if (D.getDeclSpec().hasConstexprSpecifier())
15834 return false;
15836 // We can't delay parsing the body of a function template with a deduced
15837 // return type (yet).
15838 if (D.getDeclSpec().hasAutoTypeSpec()) {
15839 // If the placeholder introduces a non-deduced trailing return type,
15840 // we can still delay parsing it.
15841 if (D.getNumTypeObjects()) {
15842 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15843 if (Outer.Kind == DeclaratorChunk::Function &&
15844 Outer.Fun.hasTrailingReturnType()) {
15845 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15846 return Ty.isNull() || !Ty->isUndeducedType();
15849 return false;
15852 return true;
15855 bool Sema::canSkipFunctionBody(Decl *D) {
15856 // We cannot skip the body of a function (or function template) which is
15857 // constexpr, since we may need to evaluate its body in order to parse the
15858 // rest of the file.
15859 // We cannot skip the body of a function with an undeduced return type,
15860 // because any callers of that function need to know the type.
15861 if (const FunctionDecl *FD = D->getAsFunction()) {
15862 if (FD->isConstexpr())
15863 return false;
15864 // We can't simply call Type::isUndeducedType here, because inside template
15865 // auto can be deduced to a dependent type, which is not considered
15866 // "undeduced".
15867 if (FD->getReturnType()->getContainedDeducedType())
15868 return false;
15870 return Consumer.shouldSkipFunctionBody(D);
15873 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15874 if (!Decl)
15875 return nullptr;
15876 if (FunctionDecl *FD = Decl->getAsFunction())
15877 FD->setHasSkippedBody();
15878 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15879 MD->setHasSkippedBody();
15880 return Decl;
15883 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15884 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15887 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15888 /// body.
15889 class ExitFunctionBodyRAII {
15890 public:
15891 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15892 ~ExitFunctionBodyRAII() {
15893 if (!IsLambda)
15894 S.PopExpressionEvaluationContext();
15897 private:
15898 Sema &S;
15899 bool IsLambda = false;
15902 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15903 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15905 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15906 if (auto It = EscapeInfo.find(BD); It != EscapeInfo.end())
15907 return It->second;
15909 bool R = false;
15910 const BlockDecl *CurBD = BD;
15912 do {
15913 R = !CurBD->doesNotEscape();
15914 if (R)
15915 break;
15916 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15917 } while (CurBD);
15919 return EscapeInfo[BD] = R;
15922 // If the location where 'self' is implicitly retained is inside a escaping
15923 // block, emit a diagnostic.
15924 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15925 S.ImplicitlyRetainedSelfLocs)
15926 if (IsOrNestedInEscapingBlock(P.second))
15927 S.Diag(P.first, diag::warn_implicitly_retains_self)
15928 << FixItHint::CreateInsertion(P.first, "self->");
15931 static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15932 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15933 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15936 bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
15937 return methodHasName(FD, "get_return_object");
15940 bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
15941 return FD->isStatic() &&
15942 methodHasName(FD, "get_return_object_on_allocation_failure");
15945 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
15946 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
15947 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15948 return;
15949 // Allow some_promise_type::get_return_object().
15950 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
15951 return;
15952 if (!FD->hasAttr<CoroWrapperAttr>())
15953 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15956 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15957 bool IsInstantiation) {
15958 FunctionScopeInfo *FSI = getCurFunction();
15959 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15961 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15962 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15964 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15965 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15967 // If we skip function body, we can't tell if a function is a coroutine.
15968 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15969 if (FSI->isCoroutine())
15970 CheckCompletedCoroutineBody(FD, Body);
15971 else
15972 CheckCoroutineWrapper(FD);
15975 // Diagnose invalid SYCL kernel entry point function declarations
15976 // and build SYCLKernelCallStmts for valid ones.
15977 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
15978 SYCLKernelEntryPointAttr *SKEPAttr =
15979 FD->getAttr<SYCLKernelEntryPointAttr>();
15980 if (FD->isDefaulted()) {
15981 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15982 << /*defaulted function*/ 3;
15983 SKEPAttr->setInvalidAttr();
15984 } else if (FD->isDeleted()) {
15985 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15986 << /*deleted function*/ 2;
15987 SKEPAttr->setInvalidAttr();
15988 } else if (FSI->isCoroutine()) {
15989 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15990 << /*coroutine*/ 7;
15991 SKEPAttr->setInvalidAttr();
15992 } else if (Body && isa<CXXTryStmt>(Body)) {
15993 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
15994 << /*function defined with a function try block*/ 8;
15995 SKEPAttr->setInvalidAttr();
15998 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
15999 StmtResult SR =
16000 SYCL().BuildSYCLKernelCallStmt(FD, cast<CompoundStmt>(Body));
16001 if (SR.isInvalid())
16002 return nullptr;
16003 Body = SR.get();
16008 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16009 // one is already popped when finishing the lambda in BuildLambdaExpr().
16010 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16011 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16012 if (FD) {
16013 // If this is called by Parser::ParseFunctionDefinition() after marking
16014 // the declaration as deleted, and if the deleted-function-body contains
16015 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
16016 // added to store that message; do not overwrite it in that case.
16018 // Since this would always set the body to 'nullptr' in that case anyway,
16019 // which is already done when the function decl is initially created,
16020 // always skipping this irrespective of whether there is a delete message
16021 // should not be a problem.
16022 if (!FD->isDeletedAsWritten())
16023 FD->setBody(Body);
16024 FD->setWillHaveBody(false);
16026 if (getLangOpts().CPlusPlus14) {
16027 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16028 FD->getReturnType()->isUndeducedType()) {
16029 // For a function with a deduced result type to return void,
16030 // the result type as written must be 'auto' or 'decltype(auto)',
16031 // possibly cv-qualified or constrained, but not ref-qualified.
16032 if (!FD->getReturnType()->getAs<AutoType>()) {
16033 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16034 << FD->getReturnType();
16035 FD->setInvalidDecl();
16036 } else {
16037 // Falling off the end of the function is the same as 'return;'.
16038 Expr *Dummy = nullptr;
16039 if (DeduceFunctionTypeFromReturnExpr(
16040 FD, dcl->getLocation(), Dummy,
16041 FD->getReturnType()->getAs<AutoType>()))
16042 FD->setInvalidDecl();
16045 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16046 // In C++11, we don't use 'auto' deduction rules for lambda call
16047 // operators because we don't support return type deduction.
16048 auto *LSI = getCurLambda();
16049 if (LSI->HasImplicitReturnType) {
16050 deduceClosureReturnType(*LSI);
16052 // C++11 [expr.prim.lambda]p4:
16053 // [...] if there are no return statements in the compound-statement
16054 // [the deduced type is] the type void
16055 QualType RetType =
16056 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16058 // Update the return type to the deduced type.
16059 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16060 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16061 Proto->getExtProtoInfo()));
16065 // If the function implicitly returns zero (like 'main') or is naked,
16066 // don't complain about missing return statements.
16067 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16068 WP.disableCheckFallThrough();
16070 // MSVC permits the use of pure specifier (=0) on function definition,
16071 // defined at class scope, warn about this non-standard construct.
16072 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16073 !FD->isOutOfLine())
16074 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16076 if (!FD->isInvalidDecl()) {
16077 // Don't diagnose unused parameters of defaulted, deleted or naked
16078 // functions.
16079 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16080 !FD->hasAttr<NakedAttr>())
16081 DiagnoseUnusedParameters(FD->parameters());
16082 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
16083 FD->getReturnType(), FD);
16085 // If this is a structor, we need a vtable.
16086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16087 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16088 else if (CXXDestructorDecl *Destructor =
16089 dyn_cast<CXXDestructorDecl>(FD))
16090 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16092 // Try to apply the named return value optimization. We have to check
16093 // if we can do this here because lambdas keep return statements around
16094 // to deduce an implicit return type.
16095 if (FD->getReturnType()->isRecordType() &&
16096 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16097 computeNRVO(Body, FSI);
16100 // GNU warning -Wmissing-prototypes:
16101 // Warn if a global function is defined without a previous
16102 // prototype declaration. This warning is issued even if the
16103 // definition itself provides a prototype. The aim is to detect
16104 // global functions that fail to be declared in header files.
16105 const FunctionDecl *PossiblePrototype = nullptr;
16106 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16107 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16109 if (PossiblePrototype) {
16110 // We found a declaration that is not a prototype,
16111 // but that could be a zero-parameter prototype
16112 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16113 TypeLoc TL = TI->getTypeLoc();
16114 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16115 Diag(PossiblePrototype->getLocation(),
16116 diag::note_declaration_not_a_prototype)
16117 << (FD->getNumParams() != 0)
16118 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16119 FTL.getRParenLoc(), "void")
16120 : FixItHint{});
16122 } else {
16123 // Returns true if the token beginning at this Loc is `const`.
16124 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16125 const LangOptions &LangOpts) {
16126 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16127 if (LocInfo.first.isInvalid())
16128 return false;
16130 bool Invalid = false;
16131 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16132 if (Invalid)
16133 return false;
16135 if (LocInfo.second > Buffer.size())
16136 return false;
16138 const char *LexStart = Buffer.data() + LocInfo.second;
16139 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16141 return StartTok.consume_front("const") &&
16142 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16143 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16146 auto findBeginLoc = [&]() {
16147 // If the return type has `const` qualifier, we want to insert
16148 // `static` before `const` (and not before the typename).
16149 if ((FD->getReturnType()->isAnyPointerType() &&
16150 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16151 FD->getReturnType().isConstQualified()) {
16152 // But only do this if we can determine where the `const` is.
16154 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16155 getLangOpts()))
16157 return FD->getBeginLoc();
16159 return FD->getTypeSpecStartLoc();
16161 Diag(FD->getTypeSpecStartLoc(),
16162 diag::note_static_for_internal_linkage)
16163 << /* function */ 1
16164 << (FD->getStorageClass() == SC_None
16165 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16166 : FixItHint{});
16170 // We might not have found a prototype because we didn't wish to warn on
16171 // the lack of a missing prototype. Try again without the checks for
16172 // whether we want to warn on the missing prototype.
16173 if (!PossiblePrototype)
16174 (void)FindPossiblePrototype(FD, PossiblePrototype);
16176 // If the function being defined does not have a prototype, then we may
16177 // need to diagnose it as changing behavior in C23 because we now know
16178 // whether the function accepts arguments or not. This only handles the
16179 // case where the definition has no prototype but does have parameters
16180 // and either there is no previous potential prototype, or the previous
16181 // potential prototype also has no actual prototype. This handles cases
16182 // like:
16183 // void f(); void f(a) int a; {}
16184 // void g(a) int a; {}
16185 // See MergeFunctionDecl() for other cases of the behavior change
16186 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16187 // type without a prototype.
16188 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16189 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16190 !PossiblePrototype->isImplicit()))) {
16191 // The function definition has parameters, so this will change behavior
16192 // in C23. If there is a possible prototype, it comes before the
16193 // function definition.
16194 // FIXME: The declaration may have already been diagnosed as being
16195 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16196 // there's no way to test for the "changes behavior" condition in
16197 // SemaType.cpp when forming the declaration's function type. So, we do
16198 // this awkward dance instead.
16200 // If we have a possible prototype and it declares a function with a
16201 // prototype, we don't want to diagnose it; if we have a possible
16202 // prototype and it has no prototype, it may have already been
16203 // diagnosed in SemaType.cpp as deprecated depending on whether
16204 // -Wstrict-prototypes is enabled. If we already warned about it being
16205 // deprecated, add a note that it also changes behavior. If we didn't
16206 // warn about it being deprecated (because the diagnostic is not
16207 // enabled), warn now that it is deprecated and changes behavior.
16209 // This K&R C function definition definitely changes behavior in C23,
16210 // so diagnose it.
16211 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16212 << /*definition*/ 1 << /* not supported in C23 */ 0;
16214 // If we have a possible prototype for the function which is a user-
16215 // visible declaration, we already tested that it has no prototype.
16216 // This will change behavior in C23. This gets a warning rather than a
16217 // note because it's the same behavior-changing problem as with the
16218 // definition.
16219 if (PossiblePrototype)
16220 Diag(PossiblePrototype->getLocation(),
16221 diag::warn_non_prototype_changes_behavior)
16222 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16223 << /*definition*/ 1;
16226 // Warn on CPUDispatch with an actual body.
16227 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16228 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16229 if (!CmpndBody->body_empty())
16230 Diag(CmpndBody->body_front()->getBeginLoc(),
16231 diag::warn_dispatch_body_ignored);
16233 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16234 const CXXMethodDecl *KeyFunction;
16235 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16236 MD->isVirtual() &&
16237 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16238 MD == KeyFunction->getCanonicalDecl()) {
16239 // Update the key-function state if necessary for this ABI.
16240 if (FD->isInlined() &&
16241 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16242 Context.setNonKeyFunction(MD);
16244 // If the newly-chosen key function is already defined, then we
16245 // need to mark the vtable as used retroactively.
16246 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16247 const FunctionDecl *Definition;
16248 if (KeyFunction && KeyFunction->isDefined(Definition))
16249 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16250 } else {
16251 // We just defined they key function; mark the vtable as used.
16252 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16257 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16258 "Function parsing confused");
16259 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16260 assert(MD == getCurMethodDecl() && "Method parsing confused");
16261 MD->setBody(Body);
16262 if (!MD->isInvalidDecl()) {
16263 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16264 MD->getReturnType(), MD);
16266 if (Body)
16267 computeNRVO(Body, FSI);
16269 if (FSI->ObjCShouldCallSuper) {
16270 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16271 << MD->getSelector().getAsString();
16272 FSI->ObjCShouldCallSuper = false;
16274 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16275 const ObjCMethodDecl *InitMethod = nullptr;
16276 bool isDesignated =
16277 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16278 assert(isDesignated && InitMethod);
16279 (void)isDesignated;
16281 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16282 auto IFace = MD->getClassInterface();
16283 if (!IFace)
16284 return false;
16285 auto SuperD = IFace->getSuperClass();
16286 if (!SuperD)
16287 return false;
16288 return SuperD->getIdentifier() ==
16289 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16291 // Don't issue this warning for unavailable inits or direct subclasses
16292 // of NSObject.
16293 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16294 Diag(MD->getLocation(),
16295 diag::warn_objc_designated_init_missing_super_call);
16296 Diag(InitMethod->getLocation(),
16297 diag::note_objc_designated_init_marked_here);
16299 FSI->ObjCWarnForNoDesignatedInitChain = false;
16301 if (FSI->ObjCWarnForNoInitDelegation) {
16302 // Don't issue this warning for unavailable inits.
16303 if (!MD->isUnavailable())
16304 Diag(MD->getLocation(),
16305 diag::warn_objc_secondary_init_missing_init_call);
16306 FSI->ObjCWarnForNoInitDelegation = false;
16309 diagnoseImplicitlyRetainedSelf(*this);
16310 } else {
16311 // Parsing the function declaration failed in some way. Pop the fake scope
16312 // we pushed on.
16313 PopFunctionScopeInfo(ActivePolicy, dcl);
16314 return nullptr;
16317 if (Body && FSI->HasPotentialAvailabilityViolations)
16318 DiagnoseUnguardedAvailabilityViolations(dcl);
16320 assert(!FSI->ObjCShouldCallSuper &&
16321 "This should only be set for ObjC methods, which should have been "
16322 "handled in the block above.");
16324 // Verify and clean out per-function state.
16325 if (Body && (!FD || !FD->isDefaulted())) {
16326 // C++ constructors that have function-try-blocks can't have return
16327 // statements in the handlers of that block. (C++ [except.handle]p14)
16328 // Verify this.
16329 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16330 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16332 // Verify that gotos and switch cases don't jump into scopes illegally.
16333 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16334 DiagnoseInvalidJumps(Body);
16336 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16337 if (!Destructor->getParent()->isDependentType())
16338 CheckDestructor(Destructor);
16340 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16341 Destructor->getParent());
16344 // If any errors have occurred, clear out any temporaries that may have
16345 // been leftover. This ensures that these temporaries won't be picked up
16346 // for deletion in some later function.
16347 if (hasUncompilableErrorOccurred() ||
16348 hasAnyUnrecoverableErrorsInThisFunction() ||
16349 getDiagnostics().getSuppressAllDiagnostics()) {
16350 DiscardCleanupsInEvaluationContext();
16352 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16353 // Since the body is valid, issue any analysis-based warnings that are
16354 // enabled.
16355 ActivePolicy = &WP;
16358 if (!IsInstantiation && FD &&
16359 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16360 !FD->isInvalidDecl() &&
16361 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16362 FD->setInvalidDecl();
16364 if (FD && FD->hasAttr<NakedAttr>()) {
16365 for (const Stmt *S : Body->children()) {
16366 // Allow local register variables without initializer as they don't
16367 // require prologue.
16368 bool RegisterVariables = false;
16369 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16370 for (const auto *Decl : DS->decls()) {
16371 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16372 RegisterVariables =
16373 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16374 if (!RegisterVariables)
16375 break;
16379 if (RegisterVariables)
16380 continue;
16381 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16382 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16383 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16384 FD->setInvalidDecl();
16385 break;
16390 assert(ExprCleanupObjects.size() ==
16391 ExprEvalContexts.back().NumCleanupObjects &&
16392 "Leftover temporaries in function");
16393 assert(!Cleanup.exprNeedsCleanups() &&
16394 "Unaccounted cleanups in function");
16395 assert(MaybeODRUseExprs.empty() &&
16396 "Leftover expressions for odr-use checking");
16398 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16399 // the declaration context below. Otherwise, we're unable to transform
16400 // 'this' expressions when transforming immediate context functions.
16402 if (FD)
16403 CheckImmediateEscalatingFunctionDefinition(FD, getCurFunction());
16405 if (!IsInstantiation)
16406 PopDeclContext();
16408 PopFunctionScopeInfo(ActivePolicy, dcl);
16409 // If any errors have occurred, clear out any temporaries that may have
16410 // been leftover. This ensures that these temporaries won't be picked up for
16411 // deletion in some later function.
16412 if (hasUncompilableErrorOccurred()) {
16413 DiscardCleanupsInEvaluationContext();
16416 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16417 !LangOpts.OMPTargetTriples.empty())) ||
16418 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16419 auto ES = getEmissionStatus(FD);
16420 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16421 ES == Sema::FunctionEmissionStatus::Unknown)
16422 DeclsToCheckForDeferredDiags.insert(FD);
16425 if (FD && !FD->isDeleted())
16426 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16428 return dcl;
16431 /// When we finish delayed parsing of an attribute, we must attach it to the
16432 /// relevant Decl.
16433 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16434 ParsedAttributes &Attrs) {
16435 // Always attach attributes to the underlying decl.
16436 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16437 D = TD->getTemplatedDecl();
16438 ProcessDeclAttributeList(S, D, Attrs);
16439 ProcessAPINotes(D);
16441 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16442 if (Method->isStatic())
16443 checkThisInStaticMemberFunctionAttributes(Method);
16446 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16447 IdentifierInfo &II, Scope *S) {
16448 // It is not valid to implicitly define a function in C23.
16449 assert(LangOpts.implicitFunctionsAllowed() &&
16450 "Implicit function declarations aren't allowed in this language mode");
16452 // Find the scope in which the identifier is injected and the corresponding
16453 // DeclContext.
16454 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16455 // In that case, we inject the declaration into the translation unit scope
16456 // instead.
16457 Scope *BlockScope = S;
16458 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16459 BlockScope = BlockScope->getParent();
16461 // Loop until we find a DeclContext that is either a function/method or the
16462 // translation unit, which are the only two valid places to implicitly define
16463 // a function. This avoids accidentally defining the function within a tag
16464 // declaration, for example.
16465 Scope *ContextScope = BlockScope;
16466 while (!ContextScope->getEntity() ||
16467 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16468 !ContextScope->getEntity()->isTranslationUnit()))
16469 ContextScope = ContextScope->getParent();
16470 ContextRAII SavedContext(*this, ContextScope->getEntity());
16472 // Before we produce a declaration for an implicitly defined
16473 // function, see whether there was a locally-scoped declaration of
16474 // this name as a function or variable. If so, use that
16475 // (non-visible) declaration, and complain about it.
16476 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16477 if (ExternCPrev) {
16478 // We still need to inject the function into the enclosing block scope so
16479 // that later (non-call) uses can see it.
16480 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16482 // C89 footnote 38:
16483 // If in fact it is not defined as having type "function returning int",
16484 // the behavior is undefined.
16485 if (!isa<FunctionDecl>(ExternCPrev) ||
16486 !Context.typesAreCompatible(
16487 cast<FunctionDecl>(ExternCPrev)->getType(),
16488 Context.getFunctionNoProtoType(Context.IntTy))) {
16489 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16490 << ExternCPrev << !getLangOpts().C99;
16491 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16492 return ExternCPrev;
16496 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16497 unsigned diag_id;
16498 if (II.getName().starts_with("__builtin_"))
16499 diag_id = diag::warn_builtin_unknown;
16500 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16501 else if (getLangOpts().C99)
16502 diag_id = diag::ext_implicit_function_decl_c99;
16503 else
16504 diag_id = diag::warn_implicit_function_decl;
16506 TypoCorrection Corrected;
16507 // Because typo correction is expensive, only do it if the implicit
16508 // function declaration is going to be treated as an error.
16510 // Perform the correction before issuing the main diagnostic, as some
16511 // consumers use typo-correction callbacks to enhance the main diagnostic.
16512 if (S && !ExternCPrev &&
16513 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16514 DeclFilterCCC<FunctionDecl> CCC{};
16515 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16516 S, nullptr, CCC, CTK_NonError);
16519 Diag(Loc, diag_id) << &II;
16520 if (Corrected) {
16521 // If the correction is going to suggest an implicitly defined function,
16522 // skip the correction as not being a particularly good idea.
16523 bool Diagnose = true;
16524 if (const auto *D = Corrected.getCorrectionDecl())
16525 Diagnose = !D->isImplicit();
16526 if (Diagnose)
16527 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16528 /*ErrorRecovery*/ false);
16531 // If we found a prior declaration of this function, don't bother building
16532 // another one. We've already pushed that one into scope, so there's nothing
16533 // more to do.
16534 if (ExternCPrev)
16535 return ExternCPrev;
16537 // Set a Declarator for the implicit definition: int foo();
16538 const char *Dummy;
16539 AttributeFactory attrFactory;
16540 DeclSpec DS(attrFactory);
16541 unsigned DiagID;
16542 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16543 Context.getPrintingPolicy());
16544 (void)Error; // Silence warning.
16545 assert(!Error && "Error setting up implicit decl!");
16546 SourceLocation NoLoc;
16547 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16548 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16549 /*IsAmbiguous=*/false,
16550 /*LParenLoc=*/NoLoc,
16551 /*Params=*/nullptr,
16552 /*NumParams=*/0,
16553 /*EllipsisLoc=*/NoLoc,
16554 /*RParenLoc=*/NoLoc,
16555 /*RefQualifierIsLvalueRef=*/true,
16556 /*RefQualifierLoc=*/NoLoc,
16557 /*MutableLoc=*/NoLoc, EST_None,
16558 /*ESpecRange=*/SourceRange(),
16559 /*Exceptions=*/nullptr,
16560 /*ExceptionRanges=*/nullptr,
16561 /*NumExceptions=*/0,
16562 /*NoexceptExpr=*/nullptr,
16563 /*ExceptionSpecTokens=*/nullptr,
16564 /*DeclsInPrototype=*/{}, Loc, Loc,
16566 std::move(DS.getAttributes()), SourceLocation());
16567 D.SetIdentifier(&II, Loc);
16569 // Insert this function into the enclosing block scope.
16570 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16571 FD->setImplicit();
16573 AddKnownFunctionAttributes(FD);
16575 return FD;
16578 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16579 FunctionDecl *FD) {
16580 if (FD->isInvalidDecl())
16581 return;
16583 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16584 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16585 return;
16587 std::optional<unsigned> AlignmentParam;
16588 bool IsNothrow = false;
16589 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16590 return;
16592 // C++2a [basic.stc.dynamic.allocation]p4:
16593 // An allocation function that has a non-throwing exception specification
16594 // indicates failure by returning a null pointer value. Any other allocation
16595 // function never returns a null pointer value and indicates failure only by
16596 // throwing an exception [...]
16598 // However, -fcheck-new invalidates this possible assumption, so don't add
16599 // NonNull when that is enabled.
16600 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16601 !getLangOpts().CheckNew)
16602 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16604 // C++2a [basic.stc.dynamic.allocation]p2:
16605 // An allocation function attempts to allocate the requested amount of
16606 // storage. [...] If the request succeeds, the value returned by a
16607 // replaceable allocation function is a [...] pointer value p0 different
16608 // from any previously returned value p1 [...]
16610 // However, this particular information is being added in codegen,
16611 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16613 // C++2a [basic.stc.dynamic.allocation]p2:
16614 // An allocation function attempts to allocate the requested amount of
16615 // storage. If it is successful, it returns the address of the start of a
16616 // block of storage whose length in bytes is at least as large as the
16617 // requested size.
16618 if (!FD->hasAttr<AllocSizeAttr>()) {
16619 FD->addAttr(AllocSizeAttr::CreateImplicit(
16620 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16621 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16624 // C++2a [basic.stc.dynamic.allocation]p3:
16625 // For an allocation function [...], the pointer returned on a successful
16626 // call shall represent the address of storage that is aligned as follows:
16627 // (3.1) If the allocation function takes an argument of type
16628 // std​::​align_­val_­t, the storage will have the alignment
16629 // specified by the value of this argument.
16630 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16631 FD->addAttr(AllocAlignAttr::CreateImplicit(
16632 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16635 // FIXME:
16636 // C++2a [basic.stc.dynamic.allocation]p3:
16637 // For an allocation function [...], the pointer returned on a successful
16638 // call shall represent the address of storage that is aligned as follows:
16639 // (3.2) Otherwise, if the allocation function is named operator new[],
16640 // the storage is aligned for any object that does not have
16641 // new-extended alignment ([basic.align]) and is no larger than the
16642 // requested size.
16643 // (3.3) Otherwise, the storage is aligned for any object that does not
16644 // have new-extended alignment and is of the requested size.
16647 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16648 if (FD->isInvalidDecl())
16649 return;
16651 // If this is a built-in function, map its builtin attributes to
16652 // actual attributes.
16653 if (unsigned BuiltinID = FD->getBuiltinID()) {
16654 // Handle printf-formatting attributes.
16655 unsigned FormatIdx;
16656 bool HasVAListArg;
16657 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16658 if (!FD->hasAttr<FormatAttr>()) {
16659 const char *fmt = "printf";
16660 unsigned int NumParams = FD->getNumParams();
16661 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16662 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16663 fmt = "NSString";
16664 FD->addAttr(FormatAttr::CreateImplicit(Context,
16665 &Context.Idents.get(fmt),
16666 FormatIdx+1,
16667 HasVAListArg ? 0 : FormatIdx+2,
16668 FD->getLocation()));
16671 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16672 HasVAListArg)) {
16673 if (!FD->hasAttr<FormatAttr>())
16674 FD->addAttr(FormatAttr::CreateImplicit(Context,
16675 &Context.Idents.get("scanf"),
16676 FormatIdx+1,
16677 HasVAListArg ? 0 : FormatIdx+2,
16678 FD->getLocation()));
16681 // Handle automatically recognized callbacks.
16682 SmallVector<int, 4> Encoding;
16683 if (!FD->hasAttr<CallbackAttr>() &&
16684 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16685 FD->addAttr(CallbackAttr::CreateImplicit(
16686 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16688 // Mark const if we don't care about errno and/or floating point exceptions
16689 // that are the only thing preventing the function from being const. This
16690 // allows IRgen to use LLVM intrinsics for such functions.
16691 bool NoExceptions =
16692 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16693 bool ConstWithoutErrnoAndExceptions =
16694 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16695 bool ConstWithoutExceptions =
16696 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16697 if (!FD->hasAttr<ConstAttr>() &&
16698 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16699 (!ConstWithoutErrnoAndExceptions ||
16700 (!getLangOpts().MathErrno && NoExceptions)) &&
16701 (!ConstWithoutExceptions || NoExceptions))
16702 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16704 // We make "fma" on GNU or Windows const because we know it does not set
16705 // errno in those environments even though it could set errno based on the
16706 // C standard.
16707 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16708 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16709 !FD->hasAttr<ConstAttr>()) {
16710 switch (BuiltinID) {
16711 case Builtin::BI__builtin_fma:
16712 case Builtin::BI__builtin_fmaf:
16713 case Builtin::BI__builtin_fmal:
16714 case Builtin::BIfma:
16715 case Builtin::BIfmaf:
16716 case Builtin::BIfmal:
16717 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16718 break;
16719 default:
16720 break;
16724 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16725 !FD->hasAttr<ReturnsTwiceAttr>())
16726 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16727 FD->getLocation()));
16728 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16729 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16730 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16731 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16732 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16733 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16734 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16735 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16736 // Add the appropriate attribute, depending on the CUDA compilation mode
16737 // and which target the builtin belongs to. For example, during host
16738 // compilation, aux builtins are __device__, while the rest are __host__.
16739 if (getLangOpts().CUDAIsDevice !=
16740 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16741 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16742 else
16743 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16746 // Add known guaranteed alignment for allocation functions.
16747 switch (BuiltinID) {
16748 case Builtin::BImemalign:
16749 case Builtin::BIaligned_alloc:
16750 if (!FD->hasAttr<AllocAlignAttr>())
16751 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16752 FD->getLocation()));
16753 break;
16754 default:
16755 break;
16758 // Add allocsize attribute for allocation functions.
16759 switch (BuiltinID) {
16760 case Builtin::BIcalloc:
16761 FD->addAttr(AllocSizeAttr::CreateImplicit(
16762 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16763 break;
16764 case Builtin::BImemalign:
16765 case Builtin::BIaligned_alloc:
16766 case Builtin::BIrealloc:
16767 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16768 ParamIdx(), FD->getLocation()));
16769 break;
16770 case Builtin::BImalloc:
16771 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16772 ParamIdx(), FD->getLocation()));
16773 break;
16774 default:
16775 break;
16779 LazyProcessLifetimeCaptureByParams(FD);
16780 inferLifetimeBoundAttribute(FD);
16781 inferLifetimeCaptureByAttribute(FD);
16782 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16784 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16785 // throw, add an implicit nothrow attribute to any extern "C" function we come
16786 // across.
16787 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16788 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16789 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16790 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16791 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16794 IdentifierInfo *Name = FD->getIdentifier();
16795 if (!Name)
16796 return;
16797 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16798 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16799 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16800 LinkageSpecLanguageIDs::C)) {
16801 // Okay: this could be a libc/libm/Objective-C function we know
16802 // about.
16803 } else
16804 return;
16806 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16807 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16808 // target-specific builtins, perhaps?
16809 if (!FD->hasAttr<FormatAttr>())
16810 FD->addAttr(FormatAttr::CreateImplicit(Context,
16811 &Context.Idents.get("printf"), 2,
16812 Name->isStr("vasprintf") ? 0 : 3,
16813 FD->getLocation()));
16816 if (Name->isStr("__CFStringMakeConstantString")) {
16817 // We already have a __builtin___CFStringMakeConstantString,
16818 // but builds that use -fno-constant-cfstrings don't go through that.
16819 if (!FD->hasAttr<FormatArgAttr>())
16820 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16821 FD->getLocation()));
16825 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16826 TypeSourceInfo *TInfo) {
16827 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16828 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16830 if (!TInfo) {
16831 assert(D.isInvalidType() && "no declarator info for valid type");
16832 TInfo = Context.getTrivialTypeSourceInfo(T);
16835 // Scope manipulation handled by caller.
16836 TypedefDecl *NewTD =
16837 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16838 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16840 // Bail out immediately if we have an invalid declaration.
16841 if (D.isInvalidType()) {
16842 NewTD->setInvalidDecl();
16843 return NewTD;
16846 if (D.getDeclSpec().isModulePrivateSpecified()) {
16847 if (CurContext->isFunctionOrMethod())
16848 Diag(NewTD->getLocation(), diag::err_module_private_local)
16849 << 2 << NewTD
16850 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16851 << FixItHint::CreateRemoval(
16852 D.getDeclSpec().getModulePrivateSpecLoc());
16853 else
16854 NewTD->setModulePrivate();
16857 // C++ [dcl.typedef]p8:
16858 // If the typedef declaration defines an unnamed class (or
16859 // enum), the first typedef-name declared by the declaration
16860 // to be that class type (or enum type) is used to denote the
16861 // class type (or enum type) for linkage purposes only.
16862 // We need to check whether the type was declared in the declaration.
16863 switch (D.getDeclSpec().getTypeSpecType()) {
16864 case TST_enum:
16865 case TST_struct:
16866 case TST_interface:
16867 case TST_union:
16868 case TST_class: {
16869 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16870 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16871 break;
16874 default:
16875 break;
16878 return NewTD;
16881 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16882 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16883 QualType T = TI->getType();
16885 if (T->isDependentType())
16886 return false;
16888 // This doesn't use 'isIntegralType' despite the error message mentioning
16889 // integral type because isIntegralType would also allow enum types in C.
16890 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16891 if (BT->isInteger())
16892 return false;
16894 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16895 << T << T->isBitIntType();
16898 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16899 QualType EnumUnderlyingTy, bool IsFixed,
16900 const EnumDecl *Prev) {
16901 if (IsScoped != Prev->isScoped()) {
16902 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16903 << Prev->isScoped();
16904 Diag(Prev->getLocation(), diag::note_previous_declaration);
16905 return true;
16908 if (IsFixed && Prev->isFixed()) {
16909 if (!EnumUnderlyingTy->isDependentType() &&
16910 !Prev->getIntegerType()->isDependentType() &&
16911 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16912 Prev->getIntegerType())) {
16913 // TODO: Highlight the underlying type of the redeclaration.
16914 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16915 << EnumUnderlyingTy << Prev->getIntegerType();
16916 Diag(Prev->getLocation(), diag::note_previous_declaration)
16917 << Prev->getIntegerTypeRange();
16918 return true;
16920 } else if (IsFixed != Prev->isFixed()) {
16921 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16922 << Prev->isFixed();
16923 Diag(Prev->getLocation(), diag::note_previous_declaration);
16924 return true;
16927 return false;
16930 /// Get diagnostic %select index for tag kind for
16931 /// redeclaration diagnostic message.
16932 /// WARNING: Indexes apply to particular diagnostics only!
16934 /// \returns diagnostic %select index.
16935 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16936 switch (Tag) {
16937 case TagTypeKind::Struct:
16938 return 0;
16939 case TagTypeKind::Interface:
16940 return 1;
16941 case TagTypeKind::Class:
16942 return 2;
16943 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16947 /// Determine if tag kind is a class-key compatible with
16948 /// class for redeclaration (class, struct, or __interface).
16950 /// \returns true iff the tag kind is compatible.
16951 static bool isClassCompatTagKind(TagTypeKind Tag)
16953 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16954 Tag == TagTypeKind::Interface;
16957 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16958 TagTypeKind TTK) {
16959 if (isa<TypedefDecl>(PrevDecl))
16960 return NTK_Typedef;
16961 else if (isa<TypeAliasDecl>(PrevDecl))
16962 return NTK_TypeAlias;
16963 else if (isa<ClassTemplateDecl>(PrevDecl))
16964 return NTK_Template;
16965 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16966 return NTK_TypeAliasTemplate;
16967 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16968 return NTK_TemplateTemplateArgument;
16969 switch (TTK) {
16970 case TagTypeKind::Struct:
16971 case TagTypeKind::Interface:
16972 case TagTypeKind::Class:
16973 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16974 case TagTypeKind::Union:
16975 return NTK_NonUnion;
16976 case TagTypeKind::Enum:
16977 return NTK_NonEnum;
16979 llvm_unreachable("invalid TTK");
16982 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16983 TagTypeKind NewTag, bool isDefinition,
16984 SourceLocation NewTagLoc,
16985 const IdentifierInfo *Name) {
16986 // C++ [dcl.type.elab]p3:
16987 // The class-key or enum keyword present in the
16988 // elaborated-type-specifier shall agree in kind with the
16989 // declaration to which the name in the elaborated-type-specifier
16990 // refers. This rule also applies to the form of
16991 // elaborated-type-specifier that declares a class-name or
16992 // friend class since it can be construed as referring to the
16993 // definition of the class. Thus, in any
16994 // elaborated-type-specifier, the enum keyword shall be used to
16995 // refer to an enumeration (7.2), the union class-key shall be
16996 // used to refer to a union (clause 9), and either the class or
16997 // struct class-key shall be used to refer to a class (clause 9)
16998 // declared using the class or struct class-key.
16999 TagTypeKind OldTag = Previous->getTagKind();
17000 if (OldTag != NewTag &&
17001 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
17002 return false;
17004 // Tags are compatible, but we might still want to warn on mismatched tags.
17005 // Non-class tags can't be mismatched at this point.
17006 if (!isClassCompatTagKind(NewTag))
17007 return true;
17009 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17010 // by our warning analysis. We don't want to warn about mismatches with (eg)
17011 // declarations in system headers that are designed to be specialized, but if
17012 // a user asks us to warn, we should warn if their code contains mismatched
17013 // declarations.
17014 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17015 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17016 Loc);
17018 if (IsIgnoredLoc(NewTagLoc))
17019 return true;
17021 auto IsIgnored = [&](const TagDecl *Tag) {
17022 return IsIgnoredLoc(Tag->getLocation());
17024 while (IsIgnored(Previous)) {
17025 Previous = Previous->getPreviousDecl();
17026 if (!Previous)
17027 return true;
17028 OldTag = Previous->getTagKind();
17031 bool isTemplate = false;
17032 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17033 isTemplate = Record->getDescribedClassTemplate();
17035 if (inTemplateInstantiation()) {
17036 if (OldTag != NewTag) {
17037 // In a template instantiation, do not offer fix-its for tag mismatches
17038 // since they usually mess up the template instead of fixing the problem.
17039 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17040 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17041 << getRedeclDiagFromTagKind(OldTag);
17042 // FIXME: Note previous location?
17044 return true;
17047 if (isDefinition) {
17048 // On definitions, check all previous tags and issue a fix-it for each
17049 // one that doesn't match the current tag.
17050 if (Previous->getDefinition()) {
17051 // Don't suggest fix-its for redefinitions.
17052 return true;
17055 bool previousMismatch = false;
17056 for (const TagDecl *I : Previous->redecls()) {
17057 if (I->getTagKind() != NewTag) {
17058 // Ignore previous declarations for which the warning was disabled.
17059 if (IsIgnored(I))
17060 continue;
17062 if (!previousMismatch) {
17063 previousMismatch = true;
17064 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17065 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17066 << getRedeclDiagFromTagKind(I->getTagKind());
17068 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17069 << getRedeclDiagFromTagKind(NewTag)
17070 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17071 TypeWithKeyword::getTagTypeKindName(NewTag));
17074 return true;
17077 // Identify the prevailing tag kind: this is the kind of the definition (if
17078 // there is a non-ignored definition), or otherwise the kind of the prior
17079 // (non-ignored) declaration.
17080 const TagDecl *PrevDef = Previous->getDefinition();
17081 if (PrevDef && IsIgnored(PrevDef))
17082 PrevDef = nullptr;
17083 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17084 if (Redecl->getTagKind() != NewTag) {
17085 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17086 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
17087 << getRedeclDiagFromTagKind(OldTag);
17088 Diag(Redecl->getLocation(), diag::note_previous_use);
17090 // If there is a previous definition, suggest a fix-it.
17091 if (PrevDef) {
17092 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17093 << getRedeclDiagFromTagKind(Redecl->getTagKind())
17094 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
17095 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
17099 return true;
17102 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17103 /// from an outer enclosing namespace or file scope inside a friend declaration.
17104 /// This should provide the commented out code in the following snippet:
17105 /// namespace N {
17106 /// struct X;
17107 /// namespace M {
17108 /// struct Y { friend struct /*N::*/ X; };
17109 /// }
17110 /// }
17111 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17112 SourceLocation NameLoc) {
17113 // While the decl is in a namespace, do repeated lookup of that name and see
17114 // if we get the same namespace back. If we do not, continue until
17115 // translation unit scope, at which point we have a fully qualified NNS.
17116 SmallVector<IdentifierInfo *, 4> Namespaces;
17117 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17118 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17119 // This tag should be declared in a namespace, which can only be enclosed by
17120 // other namespaces. Bail if there's an anonymous namespace in the chain.
17121 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17122 if (!Namespace || Namespace->isAnonymousNamespace())
17123 return FixItHint();
17124 IdentifierInfo *II = Namespace->getIdentifier();
17125 Namespaces.push_back(II);
17126 NamedDecl *Lookup = SemaRef.LookupSingleName(
17127 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17128 if (Lookup == Namespace)
17129 break;
17132 // Once we have all the namespaces, reverse them to go outermost first, and
17133 // build an NNS.
17134 SmallString<64> Insertion;
17135 llvm::raw_svector_ostream OS(Insertion);
17136 if (DC->isTranslationUnit())
17137 OS << "::";
17138 std::reverse(Namespaces.begin(), Namespaces.end());
17139 for (auto *II : Namespaces)
17140 OS << II->getName() << "::";
17141 return FixItHint::CreateInsertion(NameLoc, Insertion);
17144 /// Determine whether a tag originally declared in context \p OldDC can
17145 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17146 /// found a declaration in \p OldDC as a previous decl, perhaps through a
17147 /// using-declaration).
17148 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17149 DeclContext *NewDC) {
17150 OldDC = OldDC->getRedeclContext();
17151 NewDC = NewDC->getRedeclContext();
17153 if (OldDC->Equals(NewDC))
17154 return true;
17156 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17157 // encloses the other).
17158 if (S.getLangOpts().MSVCCompat &&
17159 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17160 return true;
17162 return false;
17165 DeclResult
17166 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17167 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17168 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17169 SourceLocation ModulePrivateLoc,
17170 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17171 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17172 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17173 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17174 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17175 // If this is not a definition, it must have a name.
17176 IdentifierInfo *OrigName = Name;
17177 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17178 "Nameless record must be a definition!");
17179 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17181 OwnedDecl = false;
17182 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17183 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17185 // FIXME: Check member specializations more carefully.
17186 bool isMemberSpecialization = false;
17187 bool Invalid = false;
17189 // We only need to do this matching if we have template parameters
17190 // or a scope specifier, which also conveniently avoids this work
17191 // for non-C++ cases.
17192 if (TemplateParameterLists.size() > 0 ||
17193 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17194 TemplateParameterList *TemplateParams =
17195 MatchTemplateParametersToScopeSpecifier(
17196 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17197 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17199 // C++23 [dcl.type.elab] p2:
17200 // If an elaborated-type-specifier is the sole constituent of a
17201 // declaration, the declaration is ill-formed unless it is an explicit
17202 // specialization, an explicit instantiation or it has one of the
17203 // following forms: [...]
17204 // C++23 [dcl.enum] p1:
17205 // If the enum-head-name of an opaque-enum-declaration contains a
17206 // nested-name-specifier, the declaration shall be an explicit
17207 // specialization.
17209 // FIXME: Class template partial specializations can be forward declared
17210 // per CWG2213, but the resolution failed to allow qualified forward
17211 // declarations. This is almost certainly unintentional, so we allow them.
17212 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17213 !isMemberSpecialization)
17214 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17215 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17217 if (TemplateParams) {
17218 if (Kind == TagTypeKind::Enum) {
17219 Diag(KWLoc, diag::err_enum_template);
17220 return true;
17223 if (TemplateParams->size() > 0) {
17224 // This is a declaration or definition of a class template (which may
17225 // be a member of another template).
17227 if (Invalid)
17228 return true;
17230 OwnedDecl = false;
17231 DeclResult Result = CheckClassTemplate(
17232 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17233 AS, ModulePrivateLoc,
17234 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17235 TemplateParameterLists.data(), SkipBody);
17236 return Result.get();
17237 } else {
17238 // The "template<>" header is extraneous.
17239 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17240 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17241 isMemberSpecialization = true;
17245 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17246 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17247 return true;
17250 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17251 // C++23 [dcl.type.elab]p4:
17252 // If an elaborated-type-specifier appears with the friend specifier as
17253 // an entire member-declaration, the member-declaration shall have one
17254 // of the following forms:
17255 // friend class-key nested-name-specifier(opt) identifier ;
17256 // friend class-key simple-template-id ;
17257 // friend class-key nested-name-specifier template(opt)
17258 // simple-template-id ;
17260 // Since enum is not a class-key, so declarations like "friend enum E;"
17261 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17262 // invalid, most implementations accept so we issue a pedantic warning.
17263 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17264 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17265 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17266 Diag(KWLoc, diag::note_enum_friend)
17267 << (ScopedEnum + ScopedEnumUsesClassTag);
17270 // Figure out the underlying type if this a enum declaration. We need to do
17271 // this early, because it's needed to detect if this is an incompatible
17272 // redeclaration.
17273 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17274 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17276 if (Kind == TagTypeKind::Enum) {
17277 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17278 // No underlying type explicitly specified, or we failed to parse the
17279 // type, default to int.
17280 EnumUnderlying = Context.IntTy.getTypePtr();
17281 } else if (UnderlyingType.get()) {
17282 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17283 // integral type; any cv-qualification is ignored.
17284 TypeSourceInfo *TI = nullptr;
17285 GetTypeFromParser(UnderlyingType.get(), &TI);
17286 EnumUnderlying = TI;
17288 if (CheckEnumUnderlyingType(TI))
17289 // Recover by falling back to int.
17290 EnumUnderlying = Context.IntTy.getTypePtr();
17292 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17293 UPPC_FixedUnderlyingType))
17294 EnumUnderlying = Context.IntTy.getTypePtr();
17296 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17297 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17298 // of 'int'. However, if this is an unfixed forward declaration, don't set
17299 // the underlying type unless the user enables -fms-compatibility. This
17300 // makes unfixed forward declared enums incomplete and is more conforming.
17301 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17302 EnumUnderlying = Context.IntTy.getTypePtr();
17306 DeclContext *SearchDC = CurContext;
17307 DeclContext *DC = CurContext;
17308 bool isStdBadAlloc = false;
17309 bool isStdAlignValT = false;
17311 RedeclarationKind Redecl = forRedeclarationInCurContext();
17312 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17313 Redecl = RedeclarationKind::NotForRedeclaration;
17315 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17316 /// implemented asks for structural equivalence checking, the returned decl
17317 /// here is passed back to the parser, allowing the tag body to be parsed.
17318 auto createTagFromNewDecl = [&]() -> TagDecl * {
17319 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17320 // If there is an identifier, use the location of the identifier as the
17321 // location of the decl, otherwise use the location of the struct/union
17322 // keyword.
17323 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17324 TagDecl *New = nullptr;
17326 if (Kind == TagTypeKind::Enum) {
17327 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17328 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17329 // If this is an undefined enum, bail.
17330 if (TUK != TagUseKind::Definition && !Invalid)
17331 return nullptr;
17332 if (EnumUnderlying) {
17333 EnumDecl *ED = cast<EnumDecl>(New);
17334 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17335 ED->setIntegerTypeSourceInfo(TI);
17336 else
17337 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17338 QualType EnumTy = ED->getIntegerType();
17339 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17340 ? Context.getPromotedIntegerType(EnumTy)
17341 : EnumTy);
17343 } else { // struct/union
17344 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17345 nullptr);
17348 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17349 // Add alignment attributes if necessary; these attributes are checked
17350 // when the ASTContext lays out the structure.
17352 // It is important for implementing the correct semantics that this
17353 // happen here (in ActOnTag). The #pragma pack stack is
17354 // maintained as a result of parser callbacks which can occur at
17355 // many points during the parsing of a struct declaration (because
17356 // the #pragma tokens are effectively skipped over during the
17357 // parsing of the struct).
17358 if (TUK == TagUseKind::Definition &&
17359 (!SkipBody || !SkipBody->ShouldSkip)) {
17360 AddAlignmentAttributesForRecord(RD);
17361 AddMsStructLayoutForRecord(RD);
17364 New->setLexicalDeclContext(CurContext);
17365 return New;
17368 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17369 if (Name && SS.isNotEmpty()) {
17370 // We have a nested-name tag ('struct foo::bar').
17372 // Check for invalid 'foo::'.
17373 if (SS.isInvalid()) {
17374 Name = nullptr;
17375 goto CreateNewDecl;
17378 // If this is a friend or a reference to a class in a dependent
17379 // context, don't try to make a decl for it.
17380 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17381 DC = computeDeclContext(SS, false);
17382 if (!DC) {
17383 IsDependent = true;
17384 return true;
17386 } else {
17387 DC = computeDeclContext(SS, true);
17388 if (!DC) {
17389 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17390 << SS.getRange();
17391 return true;
17395 if (RequireCompleteDeclContext(SS, DC))
17396 return true;
17398 SearchDC = DC;
17399 // Look-up name inside 'foo::'.
17400 LookupQualifiedName(Previous, DC);
17402 if (Previous.isAmbiguous())
17403 return true;
17405 if (Previous.empty()) {
17406 // Name lookup did not find anything. However, if the
17407 // nested-name-specifier refers to the current instantiation,
17408 // and that current instantiation has any dependent base
17409 // classes, we might find something at instantiation time: treat
17410 // this as a dependent elaborated-type-specifier.
17411 // But this only makes any sense for reference-like lookups.
17412 if (Previous.wasNotFoundInCurrentInstantiation() &&
17413 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17414 IsDependent = true;
17415 return true;
17418 // A tag 'foo::bar' must already exist.
17419 Diag(NameLoc, diag::err_not_tag_in_scope)
17420 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17421 Name = nullptr;
17422 Invalid = true;
17423 goto CreateNewDecl;
17425 } else if (Name) {
17426 // C++14 [class.mem]p14:
17427 // If T is the name of a class, then each of the following shall have a
17428 // name different from T:
17429 // -- every member of class T that is itself a type
17430 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17431 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17432 return true;
17434 // If this is a named struct, check to see if there was a previous forward
17435 // declaration or definition.
17436 // FIXME: We're looking into outer scopes here, even when we
17437 // shouldn't be. Doing so can result in ambiguities that we
17438 // shouldn't be diagnosing.
17439 LookupName(Previous, S);
17441 // When declaring or defining a tag, ignore ambiguities introduced
17442 // by types using'ed into this scope.
17443 if (Previous.isAmbiguous() &&
17444 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
17445 LookupResult::Filter F = Previous.makeFilter();
17446 while (F.hasNext()) {
17447 NamedDecl *ND = F.next();
17448 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17449 SearchDC->getRedeclContext()))
17450 F.erase();
17452 F.done();
17455 // C++11 [namespace.memdef]p3:
17456 // If the name in a friend declaration is neither qualified nor
17457 // a template-id and the declaration is a function or an
17458 // elaborated-type-specifier, the lookup to determine whether
17459 // the entity has been previously declared shall not consider
17460 // any scopes outside the innermost enclosing namespace.
17462 // MSVC doesn't implement the above rule for types, so a friend tag
17463 // declaration may be a redeclaration of a type declared in an enclosing
17464 // scope. They do implement this rule for friend functions.
17466 // Does it matter that this should be by scope instead of by
17467 // semantic context?
17468 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17469 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17470 LookupResult::Filter F = Previous.makeFilter();
17471 bool FriendSawTagOutsideEnclosingNamespace = false;
17472 while (F.hasNext()) {
17473 NamedDecl *ND = F.next();
17474 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17475 if (DC->isFileContext() &&
17476 !EnclosingNS->Encloses(ND->getDeclContext())) {
17477 if (getLangOpts().MSVCCompat)
17478 FriendSawTagOutsideEnclosingNamespace = true;
17479 else
17480 F.erase();
17483 F.done();
17485 // Diagnose this MSVC extension in the easy case where lookup would have
17486 // unambiguously found something outside the enclosing namespace.
17487 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17488 NamedDecl *ND = Previous.getFoundDecl();
17489 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17490 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17494 // Note: there used to be some attempt at recovery here.
17495 if (Previous.isAmbiguous())
17496 return true;
17498 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17499 // FIXME: This makes sure that we ignore the contexts associated
17500 // with C structs, unions, and enums when looking for a matching
17501 // tag declaration or definition. See the similar lookup tweak
17502 // in Sema::LookupName; is there a better way to deal with this?
17503 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17504 SearchDC = SearchDC->getParent();
17505 } else if (getLangOpts().CPlusPlus) {
17506 // Inside ObjCContainer want to keep it as a lexical decl context but go
17507 // past it (most often to TranslationUnit) to find the semantic decl
17508 // context.
17509 while (isa<ObjCContainerDecl>(SearchDC))
17510 SearchDC = SearchDC->getParent();
17512 } else if (getLangOpts().CPlusPlus) {
17513 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17514 // TagDecl the same way as we skip it for named TagDecl.
17515 while (isa<ObjCContainerDecl>(SearchDC))
17516 SearchDC = SearchDC->getParent();
17519 if (Previous.isSingleResult() &&
17520 Previous.getFoundDecl()->isTemplateParameter()) {
17521 // Maybe we will complain about the shadowed template parameter.
17522 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17523 // Just pretend that we didn't see the previous declaration.
17524 Previous.clear();
17527 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17528 DC->Equals(getStdNamespace())) {
17529 if (Name->isStr("bad_alloc")) {
17530 // This is a declaration of or a reference to "std::bad_alloc".
17531 isStdBadAlloc = true;
17533 // If std::bad_alloc has been implicitly declared (but made invisible to
17534 // name lookup), fill in this implicit declaration as the previous
17535 // declaration, so that the declarations get chained appropriately.
17536 if (Previous.empty() && StdBadAlloc)
17537 Previous.addDecl(getStdBadAlloc());
17538 } else if (Name->isStr("align_val_t")) {
17539 isStdAlignValT = true;
17540 if (Previous.empty() && StdAlignValT)
17541 Previous.addDecl(getStdAlignValT());
17545 // If we didn't find a previous declaration, and this is a reference
17546 // (or friend reference), move to the correct scope. In C++, we
17547 // also need to do a redeclaration lookup there, just in case
17548 // there's a shadow friend decl.
17549 if (Name && Previous.empty() &&
17550 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17551 IsTemplateParamOrArg)) {
17552 if (Invalid) goto CreateNewDecl;
17553 assert(SS.isEmpty());
17555 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17556 // C++ [basic.scope.pdecl]p5:
17557 // -- for an elaborated-type-specifier of the form
17559 // class-key identifier
17561 // if the elaborated-type-specifier is used in the
17562 // decl-specifier-seq or parameter-declaration-clause of a
17563 // function defined in namespace scope, the identifier is
17564 // declared as a class-name in the namespace that contains
17565 // the declaration; otherwise, except as a friend
17566 // declaration, the identifier is declared in the smallest
17567 // non-class, non-function-prototype scope that contains the
17568 // declaration.
17570 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17571 // C structs and unions.
17573 // It is an error in C++ to declare (rather than define) an enum
17574 // type, including via an elaborated type specifier. We'll
17575 // diagnose that later; for now, declare the enum in the same
17576 // scope as we would have picked for any other tag type.
17578 // GNU C also supports this behavior as part of its incomplete
17579 // enum types extension, while GNU C++ does not.
17581 // Find the context where we'll be declaring the tag.
17582 // FIXME: We would like to maintain the current DeclContext as the
17583 // lexical context,
17584 SearchDC = getTagInjectionContext(SearchDC);
17586 // Find the scope where we'll be declaring the tag.
17587 S = getTagInjectionScope(S, getLangOpts());
17588 } else {
17589 assert(TUK == TagUseKind::Friend);
17590 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17592 // C++ [namespace.memdef]p3:
17593 // If a friend declaration in a non-local class first declares a
17594 // class or function, the friend class or function is a member of
17595 // the innermost enclosing namespace.
17596 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17597 : SearchDC->getEnclosingNamespaceContext();
17600 // In C++, we need to do a redeclaration lookup to properly
17601 // diagnose some problems.
17602 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17603 // hidden declaration so that we don't get ambiguity errors when using a
17604 // type declared by an elaborated-type-specifier. In C that is not correct
17605 // and we should instead merge compatible types found by lookup.
17606 if (getLangOpts().CPlusPlus) {
17607 // FIXME: This can perform qualified lookups into function contexts,
17608 // which are meaningless.
17609 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17610 LookupQualifiedName(Previous, SearchDC);
17611 } else {
17612 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17613 LookupName(Previous, S);
17617 // If we have a known previous declaration to use, then use it.
17618 if (Previous.empty() && SkipBody && SkipBody->Previous)
17619 Previous.addDecl(SkipBody->Previous);
17621 if (!Previous.empty()) {
17622 NamedDecl *PrevDecl = Previous.getFoundDecl();
17623 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17625 // It's okay to have a tag decl in the same scope as a typedef
17626 // which hides a tag decl in the same scope. Finding this
17627 // with a redeclaration lookup can only actually happen in C++.
17629 // This is also okay for elaborated-type-specifiers, which is
17630 // technically forbidden by the current standard but which is
17631 // okay according to the likely resolution of an open issue;
17632 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17633 if (getLangOpts().CPlusPlus) {
17634 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17635 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17636 TagDecl *Tag = TT->getDecl();
17637 if (Tag->getDeclName() == Name &&
17638 Tag->getDeclContext()->getRedeclContext()
17639 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17640 PrevDecl = Tag;
17641 Previous.clear();
17642 Previous.addDecl(Tag);
17643 Previous.resolveKind();
17649 // If this is a redeclaration of a using shadow declaration, it must
17650 // declare a tag in the same context. In MSVC mode, we allow a
17651 // redefinition if either context is within the other.
17652 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17653 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17654 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17655 TUK != TagUseKind::Friend &&
17656 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17657 !(OldTag && isAcceptableTagRedeclContext(
17658 *this, OldTag->getDeclContext(), SearchDC))) {
17659 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17660 Diag(Shadow->getTargetDecl()->getLocation(),
17661 diag::note_using_decl_target);
17662 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17663 << 0;
17664 // Recover by ignoring the old declaration.
17665 Previous.clear();
17666 goto CreateNewDecl;
17670 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17671 // If this is a use of a previous tag, or if the tag is already declared
17672 // in the same scope (so that the definition/declaration completes or
17673 // rementions the tag), reuse the decl.
17674 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17675 isDeclInScope(DirectPrevDecl, SearchDC, S,
17676 SS.isNotEmpty() || isMemberSpecialization)) {
17677 // Make sure that this wasn't declared as an enum and now used as a
17678 // struct or something similar.
17679 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17680 TUK == TagUseKind::Definition, KWLoc,
17681 Name)) {
17682 bool SafeToContinue =
17683 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17684 Kind != TagTypeKind::Enum);
17685 if (SafeToContinue)
17686 Diag(KWLoc, diag::err_use_with_wrong_tag)
17687 << Name
17688 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17689 PrevTagDecl->getKindName());
17690 else
17691 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17692 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17694 if (SafeToContinue)
17695 Kind = PrevTagDecl->getTagKind();
17696 else {
17697 // Recover by making this an anonymous redefinition.
17698 Name = nullptr;
17699 Previous.clear();
17700 Invalid = true;
17704 if (Kind == TagTypeKind::Enum &&
17705 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17706 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17707 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17708 return PrevTagDecl;
17710 QualType EnumUnderlyingTy;
17711 if (TypeSourceInfo *TI =
17712 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
17713 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17714 else if (const Type *T =
17715 dyn_cast_if_present<const Type *>(EnumUnderlying))
17716 EnumUnderlyingTy = QualType(T, 0);
17718 // All conflicts with previous declarations are recovered by
17719 // returning the previous declaration, unless this is a definition,
17720 // in which case we want the caller to bail out.
17721 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17722 ScopedEnum, EnumUnderlyingTy,
17723 IsFixed, PrevEnum))
17724 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17727 // C++11 [class.mem]p1:
17728 // A member shall not be declared twice in the member-specification,
17729 // except that a nested class or member class template can be declared
17730 // and then later defined.
17731 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17732 S->isDeclScope(PrevDecl)) {
17733 Diag(NameLoc, diag::ext_member_redeclared);
17734 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17737 if (!Invalid) {
17738 // If this is a use, just return the declaration we found, unless
17739 // we have attributes.
17740 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17741 if (!Attrs.empty()) {
17742 // FIXME: Diagnose these attributes. For now, we create a new
17743 // declaration to hold them.
17744 } else if (TUK == TagUseKind::Reference &&
17745 (PrevTagDecl->getFriendObjectKind() ==
17746 Decl::FOK_Undeclared ||
17747 PrevDecl->getOwningModule() != getCurrentModule()) &&
17748 SS.isEmpty()) {
17749 // This declaration is a reference to an existing entity, but
17750 // has different visibility from that entity: it either makes
17751 // a friend visible or it makes a type visible in a new module.
17752 // In either case, create a new declaration. We only do this if
17753 // the declaration would have meant the same thing if no prior
17754 // declaration were found, that is, if it was found in the same
17755 // scope where we would have injected a declaration.
17756 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17757 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17758 return PrevTagDecl;
17759 // This is in the injected scope, create a new declaration in
17760 // that scope.
17761 S = getTagInjectionScope(S, getLangOpts());
17762 } else {
17763 return PrevTagDecl;
17767 // Diagnose attempts to redefine a tag.
17768 if (TUK == TagUseKind::Definition) {
17769 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17770 // If we're defining a specialization and the previous definition
17771 // is from an implicit instantiation, don't emit an error
17772 // here; we'll catch this in the general case below.
17773 bool IsExplicitSpecializationAfterInstantiation = false;
17774 if (isMemberSpecialization) {
17775 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17776 IsExplicitSpecializationAfterInstantiation =
17777 RD->getTemplateSpecializationKind() !=
17778 TSK_ExplicitSpecialization;
17779 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17780 IsExplicitSpecializationAfterInstantiation =
17781 ED->getTemplateSpecializationKind() !=
17782 TSK_ExplicitSpecialization;
17785 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17786 // not keep more that one definition around (merge them). However,
17787 // ensure the decl passes the structural compatibility check in
17788 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17789 NamedDecl *Hidden = nullptr;
17790 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17791 // There is a definition of this tag, but it is not visible. We
17792 // explicitly make use of C++'s one definition rule here, and
17793 // assume that this definition is identical to the hidden one
17794 // we already have. Make the existing definition visible and
17795 // use it in place of this one.
17796 if (!getLangOpts().CPlusPlus) {
17797 // Postpone making the old definition visible until after we
17798 // complete parsing the new one and do the structural
17799 // comparison.
17800 SkipBody->CheckSameAsPrevious = true;
17801 SkipBody->New = createTagFromNewDecl();
17802 SkipBody->Previous = Def;
17803 return Def;
17804 } else {
17805 SkipBody->ShouldSkip = true;
17806 SkipBody->Previous = Def;
17807 makeMergedDefinitionVisible(Hidden);
17808 // Carry on and handle it like a normal definition. We'll
17809 // skip starting the definition later.
17811 } else if (!IsExplicitSpecializationAfterInstantiation) {
17812 // A redeclaration in function prototype scope in C isn't
17813 // visible elsewhere, so merely issue a warning.
17814 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17815 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17816 else
17817 Diag(NameLoc, diag::err_redefinition) << Name;
17818 notePreviousDefinition(Def,
17819 NameLoc.isValid() ? NameLoc : KWLoc);
17820 // If this is a redefinition, recover by making this
17821 // struct be anonymous, which will make any later
17822 // references get the previous definition.
17823 Name = nullptr;
17824 Previous.clear();
17825 Invalid = true;
17827 } else {
17828 // If the type is currently being defined, complain
17829 // about a nested redefinition.
17830 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17831 if (TD->isBeingDefined()) {
17832 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17833 Diag(PrevTagDecl->getLocation(),
17834 diag::note_previous_definition);
17835 Name = nullptr;
17836 Previous.clear();
17837 Invalid = true;
17841 // Okay, this is definition of a previously declared or referenced
17842 // tag. We're going to create a new Decl for it.
17845 // Okay, we're going to make a redeclaration. If this is some kind
17846 // of reference, make sure we build the redeclaration in the same DC
17847 // as the original, and ignore the current access specifier.
17848 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17849 SearchDC = PrevTagDecl->getDeclContext();
17850 AS = AS_none;
17853 // If we get here we have (another) forward declaration or we
17854 // have a definition. Just create a new decl.
17856 } else {
17857 // If we get here, this is a definition of a new tag type in a nested
17858 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17859 // new decl/type. We set PrevDecl to NULL so that the entities
17860 // have distinct types.
17861 Previous.clear();
17863 // If we get here, we're going to create a new Decl. If PrevDecl
17864 // is non-NULL, it's a definition of the tag declared by
17865 // PrevDecl. If it's NULL, we have a new definition.
17867 // Otherwise, PrevDecl is not a tag, but was found with tag
17868 // lookup. This is only actually possible in C++, where a few
17869 // things like templates still live in the tag namespace.
17870 } else {
17871 // Use a better diagnostic if an elaborated-type-specifier
17872 // found the wrong kind of type on the first
17873 // (non-redeclaration) lookup.
17874 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17875 !Previous.isForRedeclaration()) {
17876 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17877 Diag(NameLoc, diag::err_tag_reference_non_tag)
17878 << PrevDecl << NTK << llvm::to_underlying(Kind);
17879 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17880 Invalid = true;
17882 // Otherwise, only diagnose if the declaration is in scope.
17883 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17884 SS.isNotEmpty() || isMemberSpecialization)) {
17885 // do nothing
17887 // Diagnose implicit declarations introduced by elaborated types.
17888 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17889 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17890 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17891 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17892 Invalid = true;
17894 // Otherwise it's a declaration. Call out a particularly common
17895 // case here.
17896 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17897 unsigned Kind = 0;
17898 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17899 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17900 << Name << Kind << TND->getUnderlyingType();
17901 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17902 Invalid = true;
17904 // Otherwise, diagnose.
17905 } else {
17906 // The tag name clashes with something else in the target scope,
17907 // issue an error and recover by making this tag be anonymous.
17908 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17909 notePreviousDefinition(PrevDecl, NameLoc);
17910 Name = nullptr;
17911 Invalid = true;
17914 // The existing declaration isn't relevant to us; we're in a
17915 // new scope, so clear out the previous declaration.
17916 Previous.clear();
17920 CreateNewDecl:
17922 TagDecl *PrevDecl = nullptr;
17923 if (Previous.isSingleResult())
17924 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17926 // If there is an identifier, use the location of the identifier as the
17927 // location of the decl, otherwise use the location of the struct/union
17928 // keyword.
17929 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17931 // Otherwise, create a new declaration. If there is a previous
17932 // declaration of the same entity, the two will be linked via
17933 // PrevDecl.
17934 TagDecl *New;
17936 if (Kind == TagTypeKind::Enum) {
17937 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17938 // enum X { A, B, C } D; D should chain to X.
17939 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17940 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17941 ScopedEnumUsesClassTag, IsFixed);
17943 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17944 StdAlignValT = cast<EnumDecl>(New);
17946 // If this is an undefined enum, warn.
17947 if (TUK != TagUseKind::Definition && !Invalid) {
17948 TagDecl *Def;
17949 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17950 // C++0x: 7.2p2: opaque-enum-declaration.
17951 // Conflicts are diagnosed above. Do nothing.
17953 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17954 Diag(Loc, diag::ext_forward_ref_enum_def)
17955 << New;
17956 Diag(Def->getLocation(), diag::note_previous_definition);
17957 } else {
17958 unsigned DiagID = diag::ext_forward_ref_enum;
17959 if (getLangOpts().MSVCCompat)
17960 DiagID = diag::ext_ms_forward_ref_enum;
17961 else if (getLangOpts().CPlusPlus)
17962 DiagID = diag::err_forward_ref_enum;
17963 Diag(Loc, DiagID);
17967 if (EnumUnderlying) {
17968 EnumDecl *ED = cast<EnumDecl>(New);
17969 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
17970 ED->setIntegerTypeSourceInfo(TI);
17971 else
17972 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17973 QualType EnumTy = ED->getIntegerType();
17974 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17975 ? Context.getPromotedIntegerType(EnumTy)
17976 : EnumTy);
17977 assert(ED->isComplete() && "enum with type should be complete");
17979 } else {
17980 // struct/union/class
17982 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17983 // struct X { int A; } D; D should chain to X.
17984 if (getLangOpts().CPlusPlus) {
17985 // FIXME: Look for a way to use RecordDecl for simple structs.
17986 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17987 cast_or_null<CXXRecordDecl>(PrevDecl));
17989 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17990 StdBadAlloc = cast<CXXRecordDecl>(New);
17991 } else
17992 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17993 cast_or_null<RecordDecl>(PrevDecl));
17996 // Only C23 and later allow defining new types in 'offsetof()'.
17997 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17998 !getLangOpts().CPlusPlus && !getLangOpts().C23)
17999 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18000 << (OOK == OOK_Macro) << New->getSourceRange();
18002 // C++11 [dcl.type]p3:
18003 // A type-specifier-seq shall not define a class or enumeration [...].
18004 if (!Invalid && getLangOpts().CPlusPlus &&
18005 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18006 TUK == TagUseKind::Definition) {
18007 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18008 << Context.getTagDeclType(New);
18009 Invalid = true;
18012 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18013 DC->getDeclKind() == Decl::Enum) {
18014 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18015 << Context.getTagDeclType(New);
18016 Invalid = true;
18019 // Maybe add qualifier info.
18020 if (SS.isNotEmpty()) {
18021 if (SS.isSet()) {
18022 // If this is either a declaration or a definition, check the
18023 // nested-name-specifier against the current context.
18024 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18025 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18026 /*TemplateId=*/nullptr,
18027 isMemberSpecialization))
18028 Invalid = true;
18030 New->setQualifierInfo(SS.getWithLocInContext(Context));
18031 if (TemplateParameterLists.size() > 0) {
18032 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18035 else
18036 Invalid = true;
18039 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18040 // Add alignment attributes if necessary; these attributes are checked when
18041 // the ASTContext lays out the structure.
18043 // It is important for implementing the correct semantics that this
18044 // happen here (in ActOnTag). The #pragma pack stack is
18045 // maintained as a result of parser callbacks which can occur at
18046 // many points during the parsing of a struct declaration (because
18047 // the #pragma tokens are effectively skipped over during the
18048 // parsing of the struct).
18049 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18050 AddAlignmentAttributesForRecord(RD);
18051 AddMsStructLayoutForRecord(RD);
18055 if (ModulePrivateLoc.isValid()) {
18056 if (isMemberSpecialization)
18057 Diag(New->getLocation(), diag::err_module_private_specialization)
18058 << 2
18059 << FixItHint::CreateRemoval(ModulePrivateLoc);
18060 // __module_private__ does not apply to local classes. However, we only
18061 // diagnose this as an error when the declaration specifiers are
18062 // freestanding. Here, we just ignore the __module_private__.
18063 else if (!SearchDC->isFunctionOrMethod())
18064 New->setModulePrivate();
18067 // If this is a specialization of a member class (of a class template),
18068 // check the specialization.
18069 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18070 Invalid = true;
18072 // If we're declaring or defining a tag in function prototype scope in C,
18073 // note that this type can only be used within the function and add it to
18074 // the list of decls to inject into the function definition scope.
18075 if ((Name || Kind == TagTypeKind::Enum) &&
18076 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18077 if (getLangOpts().CPlusPlus) {
18078 // C++ [dcl.fct]p6:
18079 // Types shall not be defined in return or parameter types.
18080 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18081 Diag(Loc, diag::err_type_defined_in_param_type)
18082 << Name;
18083 Invalid = true;
18085 if (TUK == TagUseKind::Declaration)
18086 Invalid = true;
18087 } else if (!PrevDecl) {
18088 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18092 if (Invalid)
18093 New->setInvalidDecl();
18095 // Set the lexical context. If the tag has a C++ scope specifier, the
18096 // lexical context will be different from the semantic context.
18097 New->setLexicalDeclContext(CurContext);
18099 // Mark this as a friend decl if applicable.
18100 // In Microsoft mode, a friend declaration also acts as a forward
18101 // declaration so we always pass true to setObjectOfFriendDecl to make
18102 // the tag name visible.
18103 if (TUK == TagUseKind::Friend)
18104 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18106 // Set the access specifier.
18107 if (!Invalid && SearchDC->isRecord())
18108 SetMemberAccessSpecifier(New, PrevDecl, AS);
18110 if (PrevDecl)
18111 CheckRedeclarationInModule(New, PrevDecl);
18113 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18114 New->startDefinition();
18116 ProcessDeclAttributeList(S, New, Attrs);
18117 AddPragmaAttributes(S, New);
18119 // If this has an identifier, add it to the scope stack.
18120 if (TUK == TagUseKind::Friend) {
18121 // We might be replacing an existing declaration in the lookup tables;
18122 // if so, borrow its access specifier.
18123 if (PrevDecl)
18124 New->setAccess(PrevDecl->getAccess());
18126 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18127 DC->makeDeclVisibleInContext(New);
18128 if (Name) // can be null along some error paths
18129 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18130 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18131 } else if (Name) {
18132 S = getNonFieldDeclScope(S);
18133 PushOnScopeChains(New, S, true);
18134 } else {
18135 CurContext->addDecl(New);
18138 // If this is the C FILE type, notify the AST context.
18139 if (IdentifierInfo *II = New->getIdentifier())
18140 if (!New->isInvalidDecl() &&
18141 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18142 II->isStr("FILE"))
18143 Context.setFILEDecl(New);
18145 if (PrevDecl)
18146 mergeDeclAttributes(New, PrevDecl);
18148 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18149 inferGslOwnerPointerAttribute(CXXRD);
18150 inferNullableClassAttribute(CXXRD);
18153 // If there's a #pragma GCC visibility in scope, set the visibility of this
18154 // record.
18155 AddPushedVisibilityAttribute(New);
18157 if (isMemberSpecialization && !New->isInvalidDecl())
18158 CompleteMemberSpecialization(New, Previous);
18160 OwnedDecl = true;
18161 // In C++, don't return an invalid declaration. We can't recover well from
18162 // the cases where we make the type anonymous.
18163 if (Invalid && getLangOpts().CPlusPlus) {
18164 if (New->isBeingDefined())
18165 if (auto RD = dyn_cast<RecordDecl>(New))
18166 RD->completeDefinition();
18167 return true;
18168 } else if (SkipBody && SkipBody->ShouldSkip) {
18169 return SkipBody->Previous;
18170 } else {
18171 return New;
18175 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18176 AdjustDeclIfTemplate(TagD);
18177 TagDecl *Tag = cast<TagDecl>(TagD);
18179 // Enter the tag context.
18180 PushDeclContext(S, Tag);
18182 ActOnDocumentableDecl(TagD);
18184 // If there's a #pragma GCC visibility in scope, set the visibility of this
18185 // record.
18186 AddPushedVisibilityAttribute(Tag);
18189 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
18190 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18191 return false;
18193 // Make the previous decl visible.
18194 makeMergedDefinitionVisible(SkipBody.Previous);
18195 return true;
18198 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18199 SourceLocation FinalLoc,
18200 bool IsFinalSpelledSealed,
18201 bool IsAbstract,
18202 SourceLocation LBraceLoc) {
18203 AdjustDeclIfTemplate(TagD);
18204 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18206 FieldCollector->StartClass();
18208 if (!Record->getIdentifier())
18209 return;
18211 if (IsAbstract)
18212 Record->markAbstract();
18214 if (FinalLoc.isValid()) {
18215 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18216 IsFinalSpelledSealed
18217 ? FinalAttr::Keyword_sealed
18218 : FinalAttr::Keyword_final));
18220 // C++ [class]p2:
18221 // [...] The class-name is also inserted into the scope of the
18222 // class itself; this is known as the injected-class-name. For
18223 // purposes of access checking, the injected-class-name is treated
18224 // as if it were a public member name.
18225 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18226 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18227 Record->getLocation(), Record->getIdentifier(),
18228 /*PrevDecl=*/nullptr,
18229 /*DelayTypeCreation=*/true);
18230 Context.getTypeDeclType(InjectedClassName, Record);
18231 InjectedClassName->setImplicit();
18232 InjectedClassName->setAccess(AS_public);
18233 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18234 InjectedClassName->setDescribedClassTemplate(Template);
18235 PushOnScopeChains(InjectedClassName, S);
18236 assert(InjectedClassName->isInjectedClassName() &&
18237 "Broken injected-class-name");
18240 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18241 SourceRange BraceRange) {
18242 AdjustDeclIfTemplate(TagD);
18243 TagDecl *Tag = cast<TagDecl>(TagD);
18244 Tag->setBraceRange(BraceRange);
18246 // Make sure we "complete" the definition even it is invalid.
18247 if (Tag->isBeingDefined()) {
18248 assert(Tag->isInvalidDecl() && "We should already have completed it");
18249 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18250 RD->completeDefinition();
18253 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18254 FieldCollector->FinishClass();
18255 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18256 auto *Def = RD->getDefinition();
18257 assert(Def && "The record is expected to have a completed definition");
18258 unsigned NumInitMethods = 0;
18259 for (auto *Method : Def->methods()) {
18260 if (!Method->getIdentifier())
18261 continue;
18262 if (Method->getName() == "__init")
18263 NumInitMethods++;
18265 if (NumInitMethods > 1 || !Def->hasInitMethod())
18266 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18269 // If we're defining a dynamic class in a module interface unit, we always
18270 // need to produce the vtable for it, even if the vtable is not used in the
18271 // current TU.
18273 // The case where the current class is not dynamic is handled in
18274 // MarkVTableUsed.
18275 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18276 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18279 // Exit this scope of this tag's definition.
18280 PopDeclContext();
18282 if (getCurLexicalContext()->isObjCContainer() &&
18283 Tag->getDeclContext()->isFileContext())
18284 Tag->setTopLevelDeclInObjCContainer();
18286 // Notify the consumer that we've defined a tag.
18287 if (!Tag->isInvalidDecl())
18288 Consumer.HandleTagDeclDefinition(Tag);
18290 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18291 // from XLs and instead matches the XL #pragma pack(1) behavior.
18292 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18293 AlignPackStack.hasValue()) {
18294 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18295 // Only diagnose #pragma align(packed).
18296 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18297 return;
18298 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18299 if (!RD)
18300 return;
18301 // Only warn if there is at least 1 bitfield member.
18302 if (llvm::any_of(RD->fields(),
18303 [](const FieldDecl *FD) { return FD->isBitField(); }))
18304 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18308 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18309 AdjustDeclIfTemplate(TagD);
18310 TagDecl *Tag = cast<TagDecl>(TagD);
18311 Tag->setInvalidDecl();
18313 // Make sure we "complete" the definition even it is invalid.
18314 if (Tag->isBeingDefined()) {
18315 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18316 RD->completeDefinition();
18319 // We're undoing ActOnTagStartDefinition here, not
18320 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18321 // the FieldCollector.
18323 PopDeclContext();
18326 // Note that FieldName may be null for anonymous bitfields.
18327 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18328 const IdentifierInfo *FieldName,
18329 QualType FieldTy, bool IsMsStruct,
18330 Expr *BitWidth) {
18331 assert(BitWidth);
18332 if (BitWidth->containsErrors())
18333 return ExprError();
18335 // C99 6.7.2.1p4 - verify the field type.
18336 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18337 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18338 // Handle incomplete and sizeless types with a specific error.
18339 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18340 diag::err_field_incomplete_or_sizeless))
18341 return ExprError();
18342 if (FieldName)
18343 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18344 << FieldName << FieldTy << BitWidth->getSourceRange();
18345 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18346 << FieldTy << BitWidth->getSourceRange();
18347 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18348 UPPC_BitFieldWidth))
18349 return ExprError();
18351 // If the bit-width is type- or value-dependent, don't try to check
18352 // it now.
18353 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18354 return BitWidth;
18356 llvm::APSInt Value;
18357 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18358 if (ICE.isInvalid())
18359 return ICE;
18360 BitWidth = ICE.get();
18362 // Zero-width bitfield is ok for anonymous field.
18363 if (Value == 0 && FieldName)
18364 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18365 << FieldName << BitWidth->getSourceRange();
18367 if (Value.isSigned() && Value.isNegative()) {
18368 if (FieldName)
18369 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18370 << FieldName << toString(Value, 10);
18371 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18372 << toString(Value, 10);
18375 // The size of the bit-field must not exceed our maximum permitted object
18376 // size.
18377 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18378 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18379 << !FieldName << FieldName << toString(Value, 10);
18382 if (!FieldTy->isDependentType()) {
18383 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18384 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18385 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18387 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18388 // ABI.
18389 bool CStdConstraintViolation =
18390 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18391 bool MSBitfieldViolation =
18392 Value.ugt(TypeStorageSize) &&
18393 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18394 if (CStdConstraintViolation || MSBitfieldViolation) {
18395 unsigned DiagWidth =
18396 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18397 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18398 << (bool)FieldName << FieldName << toString(Value, 10)
18399 << !CStdConstraintViolation << DiagWidth;
18402 // Warn on types where the user might conceivably expect to get all
18403 // specified bits as value bits: that's all integral types other than
18404 // 'bool'.
18405 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18406 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18407 << FieldName << toString(Value, 10)
18408 << (unsigned)TypeWidth;
18412 if (isa<ConstantExpr>(BitWidth))
18413 return BitWidth;
18414 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
18417 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18418 Declarator &D, Expr *BitfieldWidth) {
18419 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18420 D, BitfieldWidth,
18421 /*InitStyle=*/ICIS_NoInit, AS_public);
18422 return Res;
18425 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18426 SourceLocation DeclStart,
18427 Declarator &D, Expr *BitWidth,
18428 InClassInitStyle InitStyle,
18429 AccessSpecifier AS) {
18430 if (D.isDecompositionDeclarator()) {
18431 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18432 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18433 << Decomp.getSourceRange();
18434 return nullptr;
18437 const IdentifierInfo *II = D.getIdentifier();
18438 SourceLocation Loc = DeclStart;
18439 if (II) Loc = D.getIdentifierLoc();
18441 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18442 QualType T = TInfo->getType();
18443 if (getLangOpts().CPlusPlus) {
18444 CheckExtraCXXDefaultArguments(D);
18446 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18447 UPPC_DataMemberType)) {
18448 D.setInvalidType();
18449 T = Context.IntTy;
18450 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18454 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18456 if (D.getDeclSpec().isInlineSpecified())
18457 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18458 << getLangOpts().CPlusPlus17;
18459 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18460 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18461 diag::err_invalid_thread)
18462 << DeclSpec::getSpecifierName(TSCS);
18464 // Check to see if this name was declared as a member previously
18465 NamedDecl *PrevDecl = nullptr;
18466 LookupResult Previous(*this, II, Loc, LookupMemberName,
18467 RedeclarationKind::ForVisibleRedeclaration);
18468 LookupName(Previous, S);
18469 switch (Previous.getResultKind()) {
18470 case LookupResult::Found:
18471 case LookupResult::FoundUnresolvedValue:
18472 PrevDecl = Previous.getAsSingle<NamedDecl>();
18473 break;
18475 case LookupResult::FoundOverloaded:
18476 PrevDecl = Previous.getRepresentativeDecl();
18477 break;
18479 case LookupResult::NotFound:
18480 case LookupResult::NotFoundInCurrentInstantiation:
18481 case LookupResult::Ambiguous:
18482 break;
18484 Previous.suppressDiagnostics();
18486 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18487 // Maybe we will complain about the shadowed template parameter.
18488 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18489 // Just pretend that we didn't see the previous declaration.
18490 PrevDecl = nullptr;
18493 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18494 PrevDecl = nullptr;
18496 bool Mutable
18497 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18498 SourceLocation TSSL = D.getBeginLoc();
18499 FieldDecl *NewFD
18500 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18501 TSSL, AS, PrevDecl, &D);
18503 if (NewFD->isInvalidDecl())
18504 Record->setInvalidDecl();
18506 if (D.getDeclSpec().isModulePrivateSpecified())
18507 NewFD->setModulePrivate();
18509 if (NewFD->isInvalidDecl() && PrevDecl) {
18510 // Don't introduce NewFD into scope; there's already something
18511 // with the same name in the same scope.
18512 } else if (II) {
18513 PushOnScopeChains(NewFD, S);
18514 } else
18515 Record->addDecl(NewFD);
18517 return NewFD;
18520 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18521 TypeSourceInfo *TInfo,
18522 RecordDecl *Record, SourceLocation Loc,
18523 bool Mutable, Expr *BitWidth,
18524 InClassInitStyle InitStyle,
18525 SourceLocation TSSL,
18526 AccessSpecifier AS, NamedDecl *PrevDecl,
18527 Declarator *D) {
18528 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18529 bool InvalidDecl = false;
18530 if (D) InvalidDecl = D->isInvalidType();
18532 // If we receive a broken type, recover by assuming 'int' and
18533 // marking this declaration as invalid.
18534 if (T.isNull() || T->containsErrors()) {
18535 InvalidDecl = true;
18536 T = Context.IntTy;
18539 QualType EltTy = Context.getBaseElementType(T);
18540 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18541 bool isIncomplete =
18542 LangOpts.HLSL // HLSL allows sizeless builtin types
18543 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18544 : RequireCompleteSizedType(Loc, EltTy,
18545 diag::err_field_incomplete_or_sizeless);
18546 if (isIncomplete) {
18547 // Fields of incomplete type force their record to be invalid.
18548 Record->setInvalidDecl();
18549 InvalidDecl = true;
18550 } else {
18551 NamedDecl *Def;
18552 EltTy->isIncompleteType(&Def);
18553 if (Def && Def->isInvalidDecl()) {
18554 Record->setInvalidDecl();
18555 InvalidDecl = true;
18560 // TR 18037 does not allow fields to be declared with address space
18561 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18562 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18563 Diag(Loc, diag::err_field_with_address_space);
18564 Record->setInvalidDecl();
18565 InvalidDecl = true;
18568 if (LangOpts.OpenCL) {
18569 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18570 // used as structure or union field: image, sampler, event or block types.
18571 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18572 T->isBlockPointerType()) {
18573 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18574 Record->setInvalidDecl();
18575 InvalidDecl = true;
18577 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18578 // is enabled.
18579 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18580 "__cl_clang_bitfields", LangOpts)) {
18581 Diag(Loc, diag::err_opencl_bitfields);
18582 InvalidDecl = true;
18586 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18587 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18588 T.hasQualifiers()) {
18589 InvalidDecl = true;
18590 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18593 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18594 // than a variably modified type.
18595 if (!InvalidDecl && T->isVariablyModifiedType()) {
18596 if (!tryToFixVariablyModifiedVarType(
18597 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18598 InvalidDecl = true;
18601 // Fields can not have abstract class types
18602 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18603 diag::err_abstract_type_in_decl,
18604 AbstractFieldType))
18605 InvalidDecl = true;
18607 if (InvalidDecl)
18608 BitWidth = nullptr;
18609 // If this is declared as a bit-field, check the bit-field.
18610 if (BitWidth) {
18611 BitWidth =
18612 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18613 if (!BitWidth) {
18614 InvalidDecl = true;
18615 BitWidth = nullptr;
18619 // Check that 'mutable' is consistent with the type of the declaration.
18620 if (!InvalidDecl && Mutable) {
18621 unsigned DiagID = 0;
18622 if (T->isReferenceType())
18623 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18624 : diag::err_mutable_reference;
18625 else if (T.isConstQualified())
18626 DiagID = diag::err_mutable_const;
18628 if (DiagID) {
18629 SourceLocation ErrLoc = Loc;
18630 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18631 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18632 Diag(ErrLoc, DiagID);
18633 if (DiagID != diag::ext_mutable_reference) {
18634 Mutable = false;
18635 InvalidDecl = true;
18640 // C++11 [class.union]p8 (DR1460):
18641 // At most one variant member of a union may have a
18642 // brace-or-equal-initializer.
18643 if (InitStyle != ICIS_NoInit)
18644 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18646 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18647 BitWidth, Mutable, InitStyle);
18648 if (InvalidDecl)
18649 NewFD->setInvalidDecl();
18651 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18652 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18653 Diag(Loc, diag::err_duplicate_member) << II;
18654 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18655 NewFD->setInvalidDecl();
18658 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18659 if (Record->isUnion()) {
18660 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18661 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18662 if (RDecl->getDefinition()) {
18663 // C++ [class.union]p1: An object of a class with a non-trivial
18664 // constructor, a non-trivial copy constructor, a non-trivial
18665 // destructor, or a non-trivial copy assignment operator
18666 // cannot be a member of a union, nor can an array of such
18667 // objects.
18668 if (CheckNontrivialField(NewFD))
18669 NewFD->setInvalidDecl();
18673 // C++ [class.union]p1: If a union contains a member of reference type,
18674 // the program is ill-formed, except when compiling with MSVC extensions
18675 // enabled.
18676 if (EltTy->isReferenceType()) {
18677 const bool HaveMSExt =
18678 getLangOpts().MicrosoftExt &&
18679 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
18681 Diag(NewFD->getLocation(),
18682 HaveMSExt ? diag::ext_union_member_of_reference_type
18683 : diag::err_union_member_of_reference_type)
18684 << NewFD->getDeclName() << EltTy;
18685 if (!HaveMSExt)
18686 NewFD->setInvalidDecl();
18691 // FIXME: We need to pass in the attributes given an AST
18692 // representation, not a parser representation.
18693 if (D) {
18694 // FIXME: The current scope is almost... but not entirely... correct here.
18695 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18697 if (NewFD->hasAttrs())
18698 CheckAlignasUnderalignment(NewFD);
18701 // In auto-retain/release, infer strong retension for fields of
18702 // retainable type.
18703 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18704 NewFD->setInvalidDecl();
18706 if (T.isObjCGCWeak())
18707 Diag(Loc, diag::warn_attribute_weak_on_field);
18709 // PPC MMA non-pointer types are not allowed as field types.
18710 if (Context.getTargetInfo().getTriple().isPPC64() &&
18711 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18712 NewFD->setInvalidDecl();
18714 NewFD->setAccess(AS);
18715 return NewFD;
18718 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18719 assert(FD);
18720 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18722 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18723 return false;
18725 QualType EltTy = Context.getBaseElementType(FD->getType());
18726 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18727 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18728 if (RDecl->getDefinition()) {
18729 // We check for copy constructors before constructors
18730 // because otherwise we'll never get complaints about
18731 // copy constructors.
18733 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
18734 // We're required to check for any non-trivial constructors. Since the
18735 // implicit default constructor is suppressed if there are any
18736 // user-declared constructors, we just need to check that there is a
18737 // trivial default constructor and a trivial copy constructor. (We don't
18738 // worry about move constructors here, since this is a C++98 check.)
18739 if (RDecl->hasNonTrivialCopyConstructor())
18740 member = CXXSpecialMemberKind::CopyConstructor;
18741 else if (!RDecl->hasTrivialDefaultConstructor())
18742 member = CXXSpecialMemberKind::DefaultConstructor;
18743 else if (RDecl->hasNonTrivialCopyAssignment())
18744 member = CXXSpecialMemberKind::CopyAssignment;
18745 else if (RDecl->hasNonTrivialDestructor())
18746 member = CXXSpecialMemberKind::Destructor;
18748 if (member != CXXSpecialMemberKind::Invalid) {
18749 if (!getLangOpts().CPlusPlus11 &&
18750 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18751 // Objective-C++ ARC: it is an error to have a non-trivial field of
18752 // a union. However, system headers in Objective-C programs
18753 // occasionally have Objective-C lifetime objects within unions,
18754 // and rather than cause the program to fail, we make those
18755 // members unavailable.
18756 SourceLocation Loc = FD->getLocation();
18757 if (getSourceManager().isInSystemHeader(Loc)) {
18758 if (!FD->hasAttr<UnavailableAttr>())
18759 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18760 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18761 return false;
18765 Diag(
18766 FD->getLocation(),
18767 getLangOpts().CPlusPlus11
18768 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18769 : diag::err_illegal_union_or_anon_struct_member)
18770 << FD->getParent()->isUnion() << FD->getDeclName()
18771 << llvm::to_underlying(member);
18772 DiagnoseNontrivial(RDecl, member);
18773 return !getLangOpts().CPlusPlus11;
18778 return false;
18781 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18782 SmallVectorImpl<Decl *> &AllIvarDecls) {
18783 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18784 return;
18786 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18787 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18789 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
18790 return;
18791 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18792 if (!ID) {
18793 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18794 if (!CD->IsClassExtension())
18795 return;
18797 // No need to add this to end of @implementation.
18798 else
18799 return;
18801 // All conditions are met. Add a new bitfield to the tail end of ivars.
18802 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18803 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18804 Expr *BitWidth =
18805 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
18807 Ivar = ObjCIvarDecl::Create(
18808 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
18809 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
18810 ObjCIvarDecl::Private, BitWidth, true);
18811 AllIvarDecls.push_back(Ivar);
18814 /// [class.dtor]p4:
18815 /// At the end of the definition of a class, overload resolution is
18816 /// performed among the prospective destructors declared in that class with
18817 /// an empty argument list to select the destructor for the class, also
18818 /// known as the selected destructor.
18820 /// We do the overload resolution here, then mark the selected constructor in the AST.
18821 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18822 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18823 if (!Record->hasUserDeclaredDestructor()) {
18824 return;
18827 SourceLocation Loc = Record->getLocation();
18828 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18830 for (auto *Decl : Record->decls()) {
18831 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18832 if (DD->isInvalidDecl())
18833 continue;
18834 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18835 OCS);
18836 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18840 if (OCS.empty()) {
18841 return;
18843 OverloadCandidateSet::iterator Best;
18844 unsigned Msg = 0;
18845 OverloadCandidateDisplayKind DisplayKind;
18847 switch (OCS.BestViableFunction(S, Loc, Best)) {
18848 case OR_Success:
18849 case OR_Deleted:
18850 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18851 break;
18853 case OR_Ambiguous:
18854 Msg = diag::err_ambiguous_destructor;
18855 DisplayKind = OCD_AmbiguousCandidates;
18856 break;
18858 case OR_No_Viable_Function:
18859 Msg = diag::err_no_viable_destructor;
18860 DisplayKind = OCD_AllCandidates;
18861 break;
18864 if (Msg) {
18865 // OpenCL have got their own thing going with destructors. It's slightly broken,
18866 // but we allow it.
18867 if (!S.LangOpts.OpenCL) {
18868 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18869 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18870 Record->setInvalidDecl();
18872 // It's a bit hacky: At this point we've raised an error but we want the
18873 // rest of the compiler to continue somehow working. However almost
18874 // everything we'll try to do with the class will depend on there being a
18875 // destructor. So let's pretend the first one is selected and hope for the
18876 // best.
18877 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18881 /// [class.mem.special]p5
18882 /// Two special member functions are of the same kind if:
18883 /// - they are both default constructors,
18884 /// - they are both copy or move constructors with the same first parameter
18885 /// type, or
18886 /// - they are both copy or move assignment operators with the same first
18887 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18888 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18889 CXXMethodDecl *M1,
18890 CXXMethodDecl *M2,
18891 CXXSpecialMemberKind CSM) {
18892 // We don't want to compare templates to non-templates: See
18893 // https://github.com/llvm/llvm-project/issues/59206
18894 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
18895 return bool(M1->getDescribedFunctionTemplate()) ==
18896 bool(M2->getDescribedFunctionTemplate());
18897 // FIXME: better resolve CWG
18898 // https://cplusplus.github.io/CWG/issues/2787.html
18899 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18900 M2->getNonObjectParameter(0)->getType()))
18901 return false;
18902 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18903 M2->getFunctionObjectParameterReferenceType()))
18904 return false;
18906 return true;
18909 /// [class.mem.special]p6:
18910 /// An eligible special member function is a special member function for which:
18911 /// - the function is not deleted,
18912 /// - the associated constraints, if any, are satisfied, and
18913 /// - no special member function of the same kind whose associated constraints
18914 /// [CWG2595], if any, are satisfied is more constrained.
18915 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18916 ArrayRef<CXXMethodDecl *> Methods,
18917 CXXSpecialMemberKind CSM) {
18918 SmallVector<bool, 4> SatisfactionStatus;
18920 for (CXXMethodDecl *Method : Methods) {
18921 const Expr *Constraints = Method->getTrailingRequiresClause();
18922 if (!Constraints)
18923 SatisfactionStatus.push_back(true);
18924 else {
18925 ConstraintSatisfaction Satisfaction;
18926 if (S.CheckFunctionConstraints(Method, Satisfaction))
18927 SatisfactionStatus.push_back(false);
18928 else
18929 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18933 for (size_t i = 0; i < Methods.size(); i++) {
18934 if (!SatisfactionStatus[i])
18935 continue;
18936 CXXMethodDecl *Method = Methods[i];
18937 CXXMethodDecl *OrigMethod = Method;
18938 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18939 OrigMethod = cast<CXXMethodDecl>(MF);
18941 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18942 bool AnotherMethodIsMoreConstrained = false;
18943 for (size_t j = 0; j < Methods.size(); j++) {
18944 if (i == j || !SatisfactionStatus[j])
18945 continue;
18946 CXXMethodDecl *OtherMethod = Methods[j];
18947 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18948 OtherMethod = cast<CXXMethodDecl>(MF);
18950 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18951 CSM))
18952 continue;
18954 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18955 if (!OtherConstraints)
18956 continue;
18957 if (!Constraints) {
18958 AnotherMethodIsMoreConstrained = true;
18959 break;
18961 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18962 {Constraints},
18963 AnotherMethodIsMoreConstrained)) {
18964 // There was an error with the constraints comparison. Exit the loop
18965 // and don't consider this function eligible.
18966 AnotherMethodIsMoreConstrained = true;
18968 if (AnotherMethodIsMoreConstrained)
18969 break;
18971 // FIXME: Do not consider deleted methods as eligible after implementing
18972 // DR1734 and DR1496.
18973 if (!AnotherMethodIsMoreConstrained) {
18974 Method->setIneligibleOrNotSelected(false);
18975 Record->addedEligibleSpecialMemberFunction(Method,
18976 1 << llvm::to_underlying(CSM));
18981 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18982 CXXRecordDecl *Record) {
18983 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18984 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18985 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18986 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18987 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18989 for (auto *Decl : Record->decls()) {
18990 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18991 if (!MD) {
18992 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18993 if (FTD)
18994 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18996 if (!MD)
18997 continue;
18998 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18999 if (CD->isInvalidDecl())
19000 continue;
19001 if (CD->isDefaultConstructor())
19002 DefaultConstructors.push_back(MD);
19003 else if (CD->isCopyConstructor())
19004 CopyConstructors.push_back(MD);
19005 else if (CD->isMoveConstructor())
19006 MoveConstructors.push_back(MD);
19007 } else if (MD->isCopyAssignmentOperator()) {
19008 CopyAssignmentOperators.push_back(MD);
19009 } else if (MD->isMoveAssignmentOperator()) {
19010 MoveAssignmentOperators.push_back(MD);
19014 SetEligibleMethods(S, Record, DefaultConstructors,
19015 CXXSpecialMemberKind::DefaultConstructor);
19016 SetEligibleMethods(S, Record, CopyConstructors,
19017 CXXSpecialMemberKind::CopyConstructor);
19018 SetEligibleMethods(S, Record, MoveConstructors,
19019 CXXSpecialMemberKind::MoveConstructor);
19020 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19021 CXXSpecialMemberKind::CopyAssignment);
19022 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19023 CXXSpecialMemberKind::MoveAssignment);
19026 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19027 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19028 SourceLocation RBrac,
19029 const ParsedAttributesView &Attrs) {
19030 assert(EnclosingDecl && "missing record or interface decl");
19032 // If this is an Objective-C @implementation or category and we have
19033 // new fields here we should reset the layout of the interface since
19034 // it will now change.
19035 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19036 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19037 switch (DC->getKind()) {
19038 default: break;
19039 case Decl::ObjCCategory:
19040 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19041 break;
19042 case Decl::ObjCImplementation:
19043 Context.
19044 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19045 break;
19049 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19050 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19052 // Start counting up the number of named members; make sure to include
19053 // members of anonymous structs and unions in the total.
19054 unsigned NumNamedMembers = 0;
19055 if (Record) {
19056 for (const auto *I : Record->decls()) {
19057 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19058 if (IFD->getDeclName())
19059 ++NumNamedMembers;
19063 // Verify that all the fields are okay.
19064 SmallVector<FieldDecl*, 32> RecFields;
19066 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19067 i != end; ++i) {
19068 FieldDecl *FD = cast<FieldDecl>(*i);
19070 // Get the type for the field.
19071 const Type *FDTy = FD->getType().getTypePtr();
19073 if (!FD->isAnonymousStructOrUnion()) {
19074 // Remember all fields written by the user.
19075 RecFields.push_back(FD);
19078 // If the field is already invalid for some reason, don't emit more
19079 // diagnostics about it.
19080 if (FD->isInvalidDecl()) {
19081 EnclosingDecl->setInvalidDecl();
19082 continue;
19085 // C99 6.7.2.1p2:
19086 // A structure or union shall not contain a member with
19087 // incomplete or function type (hence, a structure shall not
19088 // contain an instance of itself, but may contain a pointer to
19089 // an instance of itself), except that the last member of a
19090 // structure with more than one named member may have incomplete
19091 // array type; such a structure (and any union containing,
19092 // possibly recursively, a member that is such a structure)
19093 // shall not be a member of a structure or an element of an
19094 // array.
19095 bool IsLastField = (i + 1 == Fields.end());
19096 if (FDTy->isFunctionType()) {
19097 // Field declared as a function.
19098 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19099 << FD->getDeclName();
19100 FD->setInvalidDecl();
19101 EnclosingDecl->setInvalidDecl();
19102 continue;
19103 } else if (FDTy->isIncompleteArrayType() &&
19104 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19105 if (Record) {
19106 // Flexible array member.
19107 // Microsoft and g++ is more permissive regarding flexible array.
19108 // It will accept flexible array in union and also
19109 // as the sole element of a struct/class.
19110 unsigned DiagID = 0;
19111 if (!Record->isUnion() && !IsLastField) {
19112 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19113 << FD->getDeclName() << FD->getType()
19114 << llvm::to_underlying(Record->getTagKind());
19115 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19116 FD->setInvalidDecl();
19117 EnclosingDecl->setInvalidDecl();
19118 continue;
19119 } else if (Record->isUnion())
19120 DiagID = getLangOpts().MicrosoftExt
19121 ? diag::ext_flexible_array_union_ms
19122 : diag::ext_flexible_array_union_gnu;
19123 else if (NumNamedMembers < 1)
19124 DiagID = getLangOpts().MicrosoftExt
19125 ? diag::ext_flexible_array_empty_aggregate_ms
19126 : diag::ext_flexible_array_empty_aggregate_gnu;
19128 if (DiagID)
19129 Diag(FD->getLocation(), DiagID)
19130 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19131 // While the layout of types that contain virtual bases is not specified
19132 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19133 // virtual bases after the derived members. This would make a flexible
19134 // array member declared at the end of an object not adjacent to the end
19135 // of the type.
19136 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19137 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19138 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19139 if (!getLangOpts().C99)
19140 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19141 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19143 // If the element type has a non-trivial destructor, we would not
19144 // implicitly destroy the elements, so disallow it for now.
19146 // FIXME: GCC allows this. We should probably either implicitly delete
19147 // the destructor of the containing class, or just allow this.
19148 QualType BaseElem = Context.getBaseElementType(FD->getType());
19149 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19150 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19151 << FD->getDeclName() << FD->getType();
19152 FD->setInvalidDecl();
19153 EnclosingDecl->setInvalidDecl();
19154 continue;
19156 // Okay, we have a legal flexible array member at the end of the struct.
19157 Record->setHasFlexibleArrayMember(true);
19158 } else {
19159 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19160 // unless they are followed by another ivar. That check is done
19161 // elsewhere, after synthesized ivars are known.
19163 } else if (!FDTy->isDependentType() &&
19164 (LangOpts.HLSL // HLSL allows sizeless builtin types
19165 ? RequireCompleteType(FD->getLocation(), FD->getType(),
19166 diag::err_incomplete_type)
19167 : RequireCompleteSizedType(
19168 FD->getLocation(), FD->getType(),
19169 diag::err_field_incomplete_or_sizeless))) {
19170 // Incomplete type
19171 FD->setInvalidDecl();
19172 EnclosingDecl->setInvalidDecl();
19173 continue;
19174 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19175 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19176 // A type which contains a flexible array member is considered to be a
19177 // flexible array member.
19178 Record->setHasFlexibleArrayMember(true);
19179 if (!Record->isUnion()) {
19180 // If this is a struct/class and this is not the last element, reject
19181 // it. Note that GCC supports variable sized arrays in the middle of
19182 // structures.
19183 if (!IsLastField)
19184 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19185 << FD->getDeclName() << FD->getType();
19186 else {
19187 // We support flexible arrays at the end of structs in
19188 // other structs as an extension.
19189 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19190 << FD->getDeclName();
19194 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19195 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19196 diag::err_abstract_type_in_decl,
19197 AbstractIvarType)) {
19198 // Ivars can not have abstract class types
19199 FD->setInvalidDecl();
19201 if (Record && FDTTy->getDecl()->hasObjectMember())
19202 Record->setHasObjectMember(true);
19203 if (Record && FDTTy->getDecl()->hasVolatileMember())
19204 Record->setHasVolatileMember(true);
19205 } else if (FDTy->isObjCObjectType()) {
19206 /// A field cannot be an Objective-c object
19207 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19208 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19209 QualType T = Context.getObjCObjectPointerType(FD->getType());
19210 FD->setType(T);
19211 } else if (Record && Record->isUnion() &&
19212 FD->getType().hasNonTrivialObjCLifetime() &&
19213 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19214 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19215 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19216 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19217 // For backward compatibility, fields of C unions declared in system
19218 // headers that have non-trivial ObjC ownership qualifications are marked
19219 // as unavailable unless the qualifier is explicit and __strong. This can
19220 // break ABI compatibility between programs compiled with ARC and MRR, but
19221 // is a better option than rejecting programs using those unions under
19222 // ARC.
19223 FD->addAttr(UnavailableAttr::CreateImplicit(
19224 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19225 FD->getLocation()));
19226 } else if (getLangOpts().ObjC &&
19227 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19228 !Record->hasObjectMember()) {
19229 if (FD->getType()->isObjCObjectPointerType() ||
19230 FD->getType().isObjCGCStrong())
19231 Record->setHasObjectMember(true);
19232 else if (Context.getAsArrayType(FD->getType())) {
19233 QualType BaseType = Context.getBaseElementType(FD->getType());
19234 if (BaseType->isRecordType() &&
19235 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19236 Record->setHasObjectMember(true);
19237 else if (BaseType->isObjCObjectPointerType() ||
19238 BaseType.isObjCGCStrong())
19239 Record->setHasObjectMember(true);
19243 if (Record && !getLangOpts().CPlusPlus &&
19244 !shouldIgnoreForRecordTriviality(FD)) {
19245 QualType FT = FD->getType();
19246 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19247 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19248 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19249 Record->isUnion())
19250 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19252 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19253 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19254 Record->setNonTrivialToPrimitiveCopy(true);
19255 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19256 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19258 if (FD->hasAttr<ExplicitInitAttr>())
19259 Record->setHasUninitializedExplicitInitFields(true);
19260 if (FT.isDestructedType()) {
19261 Record->setNonTrivialToPrimitiveDestroy(true);
19262 Record->setParamDestroyedInCallee(true);
19263 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19264 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19267 if (const auto *RT = FT->getAs<RecordType>()) {
19268 if (RT->getDecl()->getArgPassingRestrictions() ==
19269 RecordArgPassingKind::CanNeverPassInRegs)
19270 Record->setArgPassingRestrictions(
19271 RecordArgPassingKind::CanNeverPassInRegs);
19272 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19273 Record->setArgPassingRestrictions(
19274 RecordArgPassingKind::CanNeverPassInRegs);
19277 if (Record && FD->getType().isVolatileQualified())
19278 Record->setHasVolatileMember(true);
19279 // Keep track of the number of named members.
19280 if (FD->getIdentifier())
19281 ++NumNamedMembers;
19284 // Okay, we successfully defined 'Record'.
19285 if (Record) {
19286 bool Completed = false;
19287 if (S) {
19288 Scope *Parent = S->getParent();
19289 if (Parent && Parent->isTypeAliasScope() &&
19290 Parent->isTemplateParamScope())
19291 Record->setInvalidDecl();
19294 if (CXXRecord) {
19295 if (!CXXRecord->isInvalidDecl()) {
19296 // Set access bits correctly on the directly-declared conversions.
19297 for (CXXRecordDecl::conversion_iterator
19298 I = CXXRecord->conversion_begin(),
19299 E = CXXRecord->conversion_end(); I != E; ++I)
19300 I.setAccess((*I)->getAccess());
19303 // Add any implicitly-declared members to this class.
19304 AddImplicitlyDeclaredMembersToClass(CXXRecord);
19306 if (!CXXRecord->isDependentType()) {
19307 if (!CXXRecord->isInvalidDecl()) {
19308 // If we have virtual base classes, we may end up finding multiple
19309 // final overriders for a given virtual function. Check for this
19310 // problem now.
19311 if (CXXRecord->getNumVBases()) {
19312 CXXFinalOverriderMap FinalOverriders;
19313 CXXRecord->getFinalOverriders(FinalOverriders);
19315 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19316 MEnd = FinalOverriders.end();
19317 M != MEnd; ++M) {
19318 for (OverridingMethods::iterator SO = M->second.begin(),
19319 SOEnd = M->second.end();
19320 SO != SOEnd; ++SO) {
19321 assert(SO->second.size() > 0 &&
19322 "Virtual function without overriding functions?");
19323 if (SO->second.size() == 1)
19324 continue;
19326 // C++ [class.virtual]p2:
19327 // In a derived class, if a virtual member function of a base
19328 // class subobject has more than one final overrider the
19329 // program is ill-formed.
19330 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19331 << (const NamedDecl *)M->first << Record;
19332 Diag(M->first->getLocation(),
19333 diag::note_overridden_virtual_function);
19334 for (OverridingMethods::overriding_iterator
19335 OM = SO->second.begin(),
19336 OMEnd = SO->second.end();
19337 OM != OMEnd; ++OM)
19338 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19339 << (const NamedDecl *)M->first << OM->Method->getParent();
19341 Record->setInvalidDecl();
19344 CXXRecord->completeDefinition(&FinalOverriders);
19345 Completed = true;
19348 ComputeSelectedDestructor(*this, CXXRecord);
19349 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19353 if (!Completed)
19354 Record->completeDefinition();
19356 // Handle attributes before checking the layout.
19357 ProcessDeclAttributeList(S, Record, Attrs);
19359 // Check to see if a FieldDecl is a pointer to a function.
19360 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19361 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19362 if (!FD) {
19363 // Check whether this is a forward declaration that was inserted by
19364 // Clang. This happens when a non-forward declared / defined type is
19365 // used, e.g.:
19367 // struct foo {
19368 // struct bar *(*f)();
19369 // struct bar *(*g)();
19370 // };
19372 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19373 // incomplete definition.
19374 if (const auto *TD = dyn_cast<TagDecl>(D))
19375 return !TD->isCompleteDefinition();
19376 return false;
19378 QualType FieldType = FD->getType().getDesugaredType(Context);
19379 if (isa<PointerType>(FieldType)) {
19380 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19381 return PointeeType.getDesugaredType(Context)->isFunctionType();
19383 return false;
19386 // Maybe randomize the record's decls. We automatically randomize a record
19387 // of function pointers, unless it has the "no_randomize_layout" attribute.
19388 if (!getLangOpts().CPlusPlus &&
19389 (Record->hasAttr<RandomizeLayoutAttr>() ||
19390 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19391 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19392 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19393 !Record->isRandomized()) {
19394 SmallVector<Decl *, 32> NewDeclOrdering;
19395 if (randstruct::randomizeStructureLayout(Context, Record,
19396 NewDeclOrdering))
19397 Record->reorderDecls(NewDeclOrdering);
19400 // We may have deferred checking for a deleted destructor. Check now.
19401 if (CXXRecord) {
19402 auto *Dtor = CXXRecord->getDestructor();
19403 if (Dtor && Dtor->isImplicit() &&
19404 ShouldDeleteSpecialMember(Dtor, CXXSpecialMemberKind::Destructor)) {
19405 CXXRecord->setImplicitDestructorIsDeleted();
19406 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19410 if (Record->hasAttrs()) {
19411 CheckAlignasUnderalignment(Record);
19413 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19414 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19415 IA->getRange(), IA->getBestCase(),
19416 IA->getInheritanceModel());
19419 // Check if the structure/union declaration is a type that can have zero
19420 // size in C. For C this is a language extension, for C++ it may cause
19421 // compatibility problems.
19422 bool CheckForZeroSize;
19423 if (!getLangOpts().CPlusPlus) {
19424 CheckForZeroSize = true;
19425 } else {
19426 // For C++ filter out types that cannot be referenced in C code.
19427 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19428 CheckForZeroSize =
19429 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19430 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19431 CXXRecord->isCLike();
19433 if (CheckForZeroSize) {
19434 bool ZeroSize = true;
19435 bool IsEmpty = true;
19436 unsigned NonBitFields = 0;
19437 for (RecordDecl::field_iterator I = Record->field_begin(),
19438 E = Record->field_end();
19439 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19440 IsEmpty = false;
19441 if (I->isUnnamedBitField()) {
19442 if (!I->isZeroLengthBitField())
19443 ZeroSize = false;
19444 } else {
19445 ++NonBitFields;
19446 QualType FieldType = I->getType();
19447 if (FieldType->isIncompleteType() ||
19448 !Context.getTypeSizeInChars(FieldType).isZero())
19449 ZeroSize = false;
19453 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19454 // allowed in C++, but warn if its declaration is inside
19455 // extern "C" block.
19456 if (ZeroSize) {
19457 Diag(RecLoc, getLangOpts().CPlusPlus ?
19458 diag::warn_zero_size_struct_union_in_extern_c :
19459 diag::warn_zero_size_struct_union_compat)
19460 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19463 // Structs without named members are extension in C (C99 6.7.2.1p7),
19464 // but are accepted by GCC. In C2y, this became implementation-defined
19465 // (C2y 6.7.3.2p10).
19466 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19467 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19468 : diag::ext_no_named_members_in_struct_union)
19469 << Record->isUnion();
19472 } else {
19473 ObjCIvarDecl **ClsFields =
19474 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19475 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19476 ID->setEndOfDefinitionLoc(RBrac);
19477 // Add ivar's to class's DeclContext.
19478 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19479 ClsFields[i]->setLexicalDeclContext(ID);
19480 ID->addDecl(ClsFields[i]);
19482 // Must enforce the rule that ivars in the base classes may not be
19483 // duplicates.
19484 if (ID->getSuperClass())
19485 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19486 } else if (ObjCImplementationDecl *IMPDecl =
19487 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19488 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19489 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19490 // Ivar declared in @implementation never belongs to the implementation.
19491 // Only it is in implementation's lexical context.
19492 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19493 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19494 RBrac);
19495 IMPDecl->setIvarLBraceLoc(LBrac);
19496 IMPDecl->setIvarRBraceLoc(RBrac);
19497 } else if (ObjCCategoryDecl *CDecl =
19498 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19499 // case of ivars in class extension; all other cases have been
19500 // reported as errors elsewhere.
19501 // FIXME. Class extension does not have a LocEnd field.
19502 // CDecl->setLocEnd(RBrac);
19503 // Add ivar's to class extension's DeclContext.
19504 // Diagnose redeclaration of private ivars.
19505 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19506 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19507 if (IDecl) {
19508 if (const ObjCIvarDecl *ClsIvar =
19509 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19510 Diag(ClsFields[i]->getLocation(),
19511 diag::err_duplicate_ivar_declaration);
19512 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19513 continue;
19515 for (const auto *Ext : IDecl->known_extensions()) {
19516 if (const ObjCIvarDecl *ClsExtIvar
19517 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19518 Diag(ClsFields[i]->getLocation(),
19519 diag::err_duplicate_ivar_declaration);
19520 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19521 continue;
19525 ClsFields[i]->setLexicalDeclContext(CDecl);
19526 CDecl->addDecl(ClsFields[i]);
19528 CDecl->setIvarLBraceLoc(LBrac);
19529 CDecl->setIvarRBraceLoc(RBrac);
19532 ProcessAPINotes(Record);
19535 /// Determine whether the given integral value is representable within
19536 /// the given type T.
19537 static bool isRepresentableIntegerValue(ASTContext &Context,
19538 llvm::APSInt &Value,
19539 QualType T) {
19540 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19541 "Integral type required!");
19542 unsigned BitWidth = Context.getIntWidth(T);
19544 if (Value.isUnsigned() || Value.isNonNegative()) {
19545 if (T->isSignedIntegerOrEnumerationType())
19546 --BitWidth;
19547 return Value.getActiveBits() <= BitWidth;
19549 return Value.getSignificantBits() <= BitWidth;
19552 // Given an integral type, return the next larger integral type
19553 // (or a NULL type of no such type exists).
19554 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19555 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19556 // enum checking below.
19557 assert((T->isIntegralType(Context) ||
19558 T->isEnumeralType()) && "Integral type required!");
19559 const unsigned NumTypes = 4;
19560 QualType SignedIntegralTypes[NumTypes] = {
19561 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19563 QualType UnsignedIntegralTypes[NumTypes] = {
19564 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19565 Context.UnsignedLongLongTy
19568 unsigned BitWidth = Context.getTypeSize(T);
19569 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19570 : UnsignedIntegralTypes;
19571 for (unsigned I = 0; I != NumTypes; ++I)
19572 if (Context.getTypeSize(Types[I]) > BitWidth)
19573 return Types[I];
19575 return QualType();
19578 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19579 EnumConstantDecl *LastEnumConst,
19580 SourceLocation IdLoc,
19581 IdentifierInfo *Id,
19582 Expr *Val) {
19583 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19584 llvm::APSInt EnumVal(IntWidth);
19585 QualType EltTy;
19587 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19588 Val = nullptr;
19590 if (Val)
19591 Val = DefaultLvalueConversion(Val).get();
19593 if (Val) {
19594 if (Enum->isDependentType() || Val->isTypeDependent() ||
19595 Val->containsErrors())
19596 EltTy = Context.DependentTy;
19597 else {
19598 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19599 // underlying type, but do allow it in all other contexts.
19600 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19601 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19602 // constant-expression in the enumerator-definition shall be a converted
19603 // constant expression of the underlying type.
19604 EltTy = Enum->getIntegerType();
19605 ExprResult Converted =
19606 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19607 CCEK_Enumerator);
19608 if (Converted.isInvalid())
19609 Val = nullptr;
19610 else
19611 Val = Converted.get();
19612 } else if (!Val->isValueDependent() &&
19613 !(Val =
19614 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19615 .get())) {
19616 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19617 } else {
19618 if (Enum->isComplete()) {
19619 EltTy = Enum->getIntegerType();
19621 // In Obj-C and Microsoft mode, require the enumeration value to be
19622 // representable in the underlying type of the enumeration. In C++11,
19623 // we perform a non-narrowing conversion as part of converted constant
19624 // expression checking.
19625 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19626 if (Context.getTargetInfo()
19627 .getTriple()
19628 .isWindowsMSVCEnvironment()) {
19629 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19630 } else {
19631 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19635 // Cast to the underlying type.
19636 Val = ImpCastExprToType(Val, EltTy,
19637 EltTy->isBooleanType() ? CK_IntegralToBoolean
19638 : CK_IntegralCast)
19639 .get();
19640 } else if (getLangOpts().CPlusPlus) {
19641 // C++11 [dcl.enum]p5:
19642 // If the underlying type is not fixed, the type of each enumerator
19643 // is the type of its initializing value:
19644 // - If an initializer is specified for an enumerator, the
19645 // initializing value has the same type as the expression.
19646 EltTy = Val->getType();
19647 } else {
19648 // C99 6.7.2.2p2:
19649 // The expression that defines the value of an enumeration constant
19650 // shall be an integer constant expression that has a value
19651 // representable as an int.
19653 // Complain if the value is not representable in an int.
19654 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) {
19655 Diag(IdLoc, getLangOpts().C23
19656 ? diag::warn_c17_compat_enum_value_not_int
19657 : diag::ext_c23_enum_value_not_int)
19658 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
19659 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19660 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19661 // Force the type of the expression to 'int'.
19662 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19664 EltTy = Val->getType();
19670 if (!Val) {
19671 if (Enum->isDependentType())
19672 EltTy = Context.DependentTy;
19673 else if (!LastEnumConst) {
19674 // C++0x [dcl.enum]p5:
19675 // If the underlying type is not fixed, the type of each enumerator
19676 // is the type of its initializing value:
19677 // - If no initializer is specified for the first enumerator, the
19678 // initializing value has an unspecified integral type.
19680 // GCC uses 'int' for its unspecified integral type, as does
19681 // C99 6.7.2.2p3.
19682 if (Enum->isFixed()) {
19683 EltTy = Enum->getIntegerType();
19685 else {
19686 EltTy = Context.IntTy;
19688 } else {
19689 // Assign the last value + 1.
19690 EnumVal = LastEnumConst->getInitVal();
19691 ++EnumVal;
19692 EltTy = LastEnumConst->getType();
19694 // Check for overflow on increment.
19695 if (EnumVal < LastEnumConst->getInitVal()) {
19696 // C++0x [dcl.enum]p5:
19697 // If the underlying type is not fixed, the type of each enumerator
19698 // is the type of its initializing value:
19700 // - Otherwise the type of the initializing value is the same as
19701 // the type of the initializing value of the preceding enumerator
19702 // unless the incremented value is not representable in that type,
19703 // in which case the type is an unspecified integral type
19704 // sufficient to contain the incremented value. If no such type
19705 // exists, the program is ill-formed.
19706 QualType T = getNextLargerIntegralType(Context, EltTy);
19707 if (T.isNull() || Enum->isFixed()) {
19708 // There is no integral type larger enough to represent this
19709 // value. Complain, then allow the value to wrap around.
19710 EnumVal = LastEnumConst->getInitVal();
19711 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19712 ++EnumVal;
19713 if (Enum->isFixed())
19714 // When the underlying type is fixed, this is ill-formed.
19715 Diag(IdLoc, diag::err_enumerator_wrapped)
19716 << toString(EnumVal, 10)
19717 << EltTy;
19718 else
19719 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19720 << toString(EnumVal, 10);
19721 } else {
19722 EltTy = T;
19725 // Retrieve the last enumerator's value, extent that type to the
19726 // type that is supposed to be large enough to represent the incremented
19727 // value, then increment.
19728 EnumVal = LastEnumConst->getInitVal();
19729 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19730 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19731 ++EnumVal;
19733 // If we're not in C++, diagnose the overflow of enumerator values,
19734 // which in C99 means that the enumerator value is not representable in
19735 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
19736 // are representable in some larger integral type and we allow it in
19737 // older language modes as an extension.
19738 // Exclude fixed enumerators since they are diagnosed with an error for
19739 // this case.
19740 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
19741 Diag(IdLoc, getLangOpts().C23
19742 ? diag::warn_c17_compat_enum_value_not_int
19743 : diag::ext_c23_enum_value_not_int)
19744 << 1 << toString(EnumVal, 10) << 1;
19745 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
19746 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19747 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19748 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
19749 : diag::ext_c23_enum_value_not_int)
19750 << 1 << toString(EnumVal, 10) << 1;
19755 if (!EltTy->isDependentType()) {
19756 // Make the enumerator value match the signedness and size of the
19757 // enumerator's type.
19758 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19759 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19762 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19763 Val, EnumVal);
19766 SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19767 SourceLocation IILoc) {
19768 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19769 !getLangOpts().CPlusPlus)
19770 return SkipBodyInfo();
19772 // We have an anonymous enum definition. Look up the first enumerator to
19773 // determine if we should merge the definition with an existing one and
19774 // skip the body.
19775 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19776 forRedeclarationInCurContext());
19777 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19778 if (!PrevECD)
19779 return SkipBodyInfo();
19781 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19782 NamedDecl *Hidden;
19783 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19784 SkipBodyInfo Skip;
19785 Skip.Previous = Hidden;
19786 return Skip;
19789 return SkipBodyInfo();
19792 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19793 SourceLocation IdLoc, IdentifierInfo *Id,
19794 const ParsedAttributesView &Attrs,
19795 SourceLocation EqualLoc, Expr *Val) {
19796 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19797 EnumConstantDecl *LastEnumConst =
19798 cast_or_null<EnumConstantDecl>(lastEnumConst);
19800 // The scope passed in may not be a decl scope. Zip up the scope tree until
19801 // we find one that is.
19802 S = getNonFieldDeclScope(S);
19804 // Verify that there isn't already something declared with this name in this
19805 // scope.
19806 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19807 RedeclarationKind::ForVisibleRedeclaration);
19808 LookupName(R, S);
19809 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19811 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19812 // Maybe we will complain about the shadowed template parameter.
19813 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19814 // Just pretend that we didn't see the previous declaration.
19815 PrevDecl = nullptr;
19818 // C++ [class.mem]p15:
19819 // If T is the name of a class, then each of the following shall have a name
19820 // different from T:
19821 // - every enumerator of every member of class T that is an unscoped
19822 // enumerated type
19823 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19824 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19825 DeclarationNameInfo(Id, IdLoc));
19827 EnumConstantDecl *New =
19828 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19829 if (!New)
19830 return nullptr;
19832 if (PrevDecl) {
19833 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19834 // Check for other kinds of shadowing not already handled.
19835 CheckShadow(New, PrevDecl, R);
19838 // When in C++, we may get a TagDecl with the same name; in this case the
19839 // enum constant will 'hide' the tag.
19840 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19841 "Received TagDecl when not in C++!");
19842 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19843 if (isa<EnumConstantDecl>(PrevDecl))
19844 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19845 else
19846 Diag(IdLoc, diag::err_redefinition) << Id;
19847 notePreviousDefinition(PrevDecl, IdLoc);
19848 return nullptr;
19852 // Process attributes.
19853 ProcessDeclAttributeList(S, New, Attrs);
19854 AddPragmaAttributes(S, New);
19855 ProcessAPINotes(New);
19857 // Register this decl in the current scope stack.
19858 New->setAccess(TheEnumDecl->getAccess());
19859 PushOnScopeChains(New, S);
19861 ActOnDocumentableDecl(New);
19863 return New;
19866 // Returns true when the enum initial expression does not trigger the
19867 // duplicate enum warning. A few common cases are exempted as follows:
19868 // Element2 = Element1
19869 // Element2 = Element1 + 1
19870 // Element2 = Element1 - 1
19871 // Where Element2 and Element1 are from the same enum.
19872 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19873 Expr *InitExpr = ECD->getInitExpr();
19874 if (!InitExpr)
19875 return true;
19876 InitExpr = InitExpr->IgnoreImpCasts();
19878 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19879 if (!BO->isAdditiveOp())
19880 return true;
19881 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19882 if (!IL)
19883 return true;
19884 if (IL->getValue() != 1)
19885 return true;
19887 InitExpr = BO->getLHS();
19890 // This checks if the elements are from the same enum.
19891 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19892 if (!DRE)
19893 return true;
19895 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19896 if (!EnumConstant)
19897 return true;
19899 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19900 Enum)
19901 return true;
19903 return false;
19906 // Emits a warning when an element is implicitly set a value that
19907 // a previous element has already been set to.
19908 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19909 EnumDecl *Enum, QualType EnumType) {
19910 // Avoid anonymous enums
19911 if (!Enum->getIdentifier())
19912 return;
19914 // Only check for small enums.
19915 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19916 return;
19918 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19919 return;
19921 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19922 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19924 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19926 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19927 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19929 // Use int64_t as a key to avoid needing special handling for map keys.
19930 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19931 llvm::APSInt Val = D->getInitVal();
19932 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19935 DuplicatesVector DupVector;
19936 ValueToVectorMap EnumMap;
19938 // Populate the EnumMap with all values represented by enum constants without
19939 // an initializer.
19940 for (auto *Element : Elements) {
19941 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19943 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19944 // this constant. Skip this enum since it may be ill-formed.
19945 if (!ECD) {
19946 return;
19949 // Constants with initializers are handled in the next loop.
19950 if (ECD->getInitExpr())
19951 continue;
19953 // Duplicate values are handled in the next loop.
19954 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19957 if (EnumMap.size() == 0)
19958 return;
19960 // Create vectors for any values that has duplicates.
19961 for (auto *Element : Elements) {
19962 // The last loop returned if any constant was null.
19963 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19964 if (!ValidDuplicateEnum(ECD, Enum))
19965 continue;
19967 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19968 if (Iter == EnumMap.end())
19969 continue;
19971 DeclOrVector& Entry = Iter->second;
19972 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
19973 // Ensure constants are different.
19974 if (D == ECD)
19975 continue;
19977 // Create new vector and push values onto it.
19978 auto Vec = std::make_unique<ECDVector>();
19979 Vec->push_back(D);
19980 Vec->push_back(ECD);
19982 // Update entry to point to the duplicates vector.
19983 Entry = Vec.get();
19985 // Store the vector somewhere we can consult later for quick emission of
19986 // diagnostics.
19987 DupVector.emplace_back(std::move(Vec));
19988 continue;
19991 ECDVector *Vec = cast<ECDVector *>(Entry);
19992 // Make sure constants are not added more than once.
19993 if (*Vec->begin() == ECD)
19994 continue;
19996 Vec->push_back(ECD);
19999 // Emit diagnostics.
20000 for (const auto &Vec : DupVector) {
20001 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20003 // Emit warning for one enum constant.
20004 auto *FirstECD = Vec->front();
20005 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20006 << FirstECD << toString(FirstECD->getInitVal(), 10)
20007 << FirstECD->getSourceRange();
20009 // Emit one note for each of the remaining enum constants with
20010 // the same value.
20011 for (auto *ECD : llvm::drop_begin(*Vec))
20012 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20013 << ECD << toString(ECD->getInitVal(), 10)
20014 << ECD->getSourceRange();
20018 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20019 bool AllowMask) const {
20020 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20021 assert(ED->isCompleteDefinition() && "expected enum definition");
20023 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20024 llvm::APInt &FlagBits = R.first->second;
20026 if (R.second) {
20027 for (auto *E : ED->enumerators()) {
20028 const auto &EVal = E->getInitVal();
20029 // Only single-bit enumerators introduce new flag values.
20030 if (EVal.isPowerOf2())
20031 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20035 // A value is in a flag enum if either its bits are a subset of the enum's
20036 // flag bits (the first condition) or we are allowing masks and the same is
20037 // true of its complement (the second condition). When masks are allowed, we
20038 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20040 // While it's true that any value could be used as a mask, the assumption is
20041 // that a mask will have all of the insignificant bits set. Anything else is
20042 // likely a logic error.
20043 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20044 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20047 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20048 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20049 const ParsedAttributesView &Attrs) {
20050 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20051 QualType EnumType = Context.getTypeDeclType(Enum);
20053 ProcessDeclAttributeList(S, Enum, Attrs);
20054 ProcessAPINotes(Enum);
20056 if (Enum->isDependentType()) {
20057 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20058 EnumConstantDecl *ECD =
20059 cast_or_null<EnumConstantDecl>(Elements[i]);
20060 if (!ECD) continue;
20062 ECD->setType(EnumType);
20065 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20066 return;
20069 // Verify that all the values are okay, compute the size of the values, and
20070 // reverse the list.
20071 unsigned NumNegativeBits = 0;
20072 unsigned NumPositiveBits = 0;
20073 bool MembersRepresentableByInt = true;
20075 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20076 EnumConstantDecl *ECD =
20077 cast_or_null<EnumConstantDecl>(Elements[i]);
20078 if (!ECD) continue; // Already issued a diagnostic.
20080 llvm::APSInt InitVal = ECD->getInitVal();
20082 // Keep track of the size of positive and negative values.
20083 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20084 // If the enumerator is zero that should still be counted as a positive
20085 // bit since we need a bit to store the value zero.
20086 unsigned ActiveBits = InitVal.getActiveBits();
20087 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20088 } else {
20089 NumNegativeBits =
20090 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20092 MembersRepresentableByInt &=
20093 isRepresentableIntegerValue(Context, InitVal, Context.IntTy);
20096 // If we have an empty set of enumerators we still need one bit.
20097 // From [dcl.enum]p8
20098 // If the enumerator-list is empty, the values of the enumeration are as if
20099 // the enumeration had a single enumerator with value 0
20100 if (!NumPositiveBits && !NumNegativeBits)
20101 NumPositiveBits = 1;
20103 // Figure out the type that should be used for this enum.
20104 QualType BestType;
20105 unsigned BestWidth;
20107 // C++0x N3000 [conv.prom]p3:
20108 // An rvalue of an unscoped enumeration type whose underlying
20109 // type is not fixed can be converted to an rvalue of the first
20110 // of the following types that can represent all the values of
20111 // the enumeration: int, unsigned int, long int, unsigned long
20112 // int, long long int, or unsigned long long int.
20113 // C99 6.4.4.3p2:
20114 // An identifier declared as an enumeration constant has type int.
20115 // The C99 rule is modified by C23.
20116 QualType BestPromotionType;
20118 bool Packed = Enum->hasAttr<PackedAttr>();
20119 // -fshort-enums is the equivalent to specifying the packed attribute on all
20120 // enum definitions.
20121 if (LangOpts.ShortEnums)
20122 Packed = true;
20124 // If the enum already has a type because it is fixed or dictated by the
20125 // target, promote that type instead of analyzing the enumerators.
20126 if (Enum->isComplete()) {
20127 BestType = Enum->getIntegerType();
20128 if (Context.isPromotableIntegerType(BestType))
20129 BestPromotionType = Context.getPromotedIntegerType(BestType);
20130 else
20131 BestPromotionType = BestType;
20133 BestWidth = Context.getIntWidth(BestType);
20134 } else {
20135 bool EnumTooLarge = Context.computeBestEnumTypes(
20136 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20137 BestWidth = Context.getIntWidth(BestType);
20138 if (EnumTooLarge)
20139 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20142 // Loop over all of the enumerator constants, changing their types to match
20143 // the type of the enum if needed.
20144 for (auto *D : Elements) {
20145 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20146 if (!ECD) continue; // Already issued a diagnostic.
20148 // C99 says the enumerators have int type, but we allow, as an
20149 // extension, the enumerators to be larger than int size. If each
20150 // enumerator value fits in an int, type it as an int, otherwise type it the
20151 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20152 // that X has type 'int', not 'unsigned'.
20154 // Determine whether the value fits into an int.
20155 llvm::APSInt InitVal = ECD->getInitVal();
20157 // If it fits into an integer type, force it. Otherwise force it to match
20158 // the enum decl type.
20159 QualType NewTy;
20160 unsigned NewWidth;
20161 bool NewSign;
20162 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20163 MembersRepresentableByInt) {
20164 // C23 6.7.3.3.3p15:
20165 // The enumeration member type for an enumerated type without fixed
20166 // underlying type upon completion is:
20167 // - int if all the values of the enumeration are representable as an
20168 // int; or,
20169 // - the enumerated type
20170 NewTy = Context.IntTy;
20171 NewWidth = Context.getTargetInfo().getIntWidth();
20172 NewSign = true;
20173 } else if (ECD->getType() == BestType) {
20174 // Already the right type!
20175 if (getLangOpts().CPlusPlus)
20176 // C++ [dcl.enum]p4: Following the closing brace of an
20177 // enum-specifier, each enumerator has the type of its
20178 // enumeration.
20179 ECD->setType(EnumType);
20180 continue;
20181 } else {
20182 NewTy = BestType;
20183 NewWidth = BestWidth;
20184 NewSign = BestType->isSignedIntegerOrEnumerationType();
20187 // Adjust the APSInt value.
20188 InitVal = InitVal.extOrTrunc(NewWidth);
20189 InitVal.setIsSigned(NewSign);
20190 ECD->setInitVal(Context, InitVal);
20192 // Adjust the Expr initializer and type.
20193 if (ECD->getInitExpr() &&
20194 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20195 ECD->setInitExpr(ImplicitCastExpr::Create(
20196 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20197 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20198 if (getLangOpts().CPlusPlus)
20199 // C++ [dcl.enum]p4: Following the closing brace of an
20200 // enum-specifier, each enumerator has the type of its
20201 // enumeration.
20202 ECD->setType(EnumType);
20203 else
20204 ECD->setType(NewTy);
20207 Enum->completeDefinition(BestType, BestPromotionType,
20208 NumPositiveBits, NumNegativeBits);
20210 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20212 if (Enum->isClosedFlag()) {
20213 for (Decl *D : Elements) {
20214 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20215 if (!ECD) continue; // Already issued a diagnostic.
20217 llvm::APSInt InitVal = ECD->getInitVal();
20218 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20219 !IsValueInFlagEnum(Enum, InitVal, true))
20220 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20221 << ECD << Enum;
20225 // Now that the enum type is defined, ensure it's not been underaligned.
20226 if (Enum->hasAttrs())
20227 CheckAlignasUnderalignment(Enum);
20230 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20231 SourceLocation StartLoc,
20232 SourceLocation EndLoc) {
20233 StringLiteral *AsmString = cast<StringLiteral>(expr);
20235 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20236 AsmString, StartLoc,
20237 EndLoc);
20238 CurContext->addDecl(New);
20239 return New;
20242 TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20243 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20244 CurContext->addDecl(New);
20245 PushDeclContext(S, New);
20246 PushFunctionScope();
20247 PushCompoundScope(false);
20248 return New;
20251 void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20252 D->setStmt(Statement);
20253 PopCompoundScope();
20254 PopFunctionScopeInfo();
20255 PopDeclContext();
20258 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20259 IdentifierInfo* AliasName,
20260 SourceLocation PragmaLoc,
20261 SourceLocation NameLoc,
20262 SourceLocation AliasNameLoc) {
20263 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20264 LookupOrdinaryName);
20265 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20266 AttributeCommonInfo::Form::Pragma());
20267 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20268 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20270 // If a declaration that:
20271 // 1) declares a function or a variable
20272 // 2) has external linkage
20273 // already exists, add a label attribute to it.
20274 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20275 if (isDeclExternC(PrevDecl))
20276 PrevDecl->addAttr(Attr);
20277 else
20278 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20279 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20280 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20281 } else
20282 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20285 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20286 SourceLocation PragmaLoc,
20287 SourceLocation NameLoc) {
20288 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20290 if (PrevDecl) {
20291 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20292 } else {
20293 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20297 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20298 IdentifierInfo* AliasName,
20299 SourceLocation PragmaLoc,
20300 SourceLocation NameLoc,
20301 SourceLocation AliasNameLoc) {
20302 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20303 LookupOrdinaryName);
20304 WeakInfo W = WeakInfo(Name, NameLoc);
20306 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20307 if (!PrevDecl->hasAttr<AliasAttr>())
20308 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20309 DeclApplyPragmaWeak(TUScope, ND, W);
20310 } else {
20311 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20315 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20316 bool Final) {
20317 assert(FD && "Expected non-null FunctionDecl");
20319 // SYCL functions can be template, so we check if they have appropriate
20320 // attribute prior to checking if it is a template.
20321 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20322 return FunctionEmissionStatus::Emitted;
20324 // Templates are emitted when they're instantiated.
20325 if (FD->isDependentContext())
20326 return FunctionEmissionStatus::TemplateDiscarded;
20328 // Check whether this function is an externally visible definition.
20329 auto IsEmittedForExternalSymbol = [this, FD]() {
20330 // We have to check the GVA linkage of the function's *definition* -- if we
20331 // only have a declaration, we don't know whether or not the function will
20332 // be emitted, because (say) the definition could include "inline".
20333 const FunctionDecl *Def = FD->getDefinition();
20335 // We can't compute linkage when we skip function bodies.
20336 return Def && !Def->hasSkippedBody() &&
20337 !isDiscardableGVALinkage(
20338 getASTContext().GetGVALinkageForFunction(Def));
20341 if (LangOpts.OpenMPIsTargetDevice) {
20342 // In OpenMP device mode we will not emit host only functions, or functions
20343 // we don't need due to their linkage.
20344 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20345 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20346 // DevTy may be changed later by
20347 // #pragma omp declare target to(*) device_type(*).
20348 // Therefore DevTy having no value does not imply host. The emission status
20349 // will be checked again at the end of compilation unit with Final = true.
20350 if (DevTy)
20351 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20352 return FunctionEmissionStatus::OMPDiscarded;
20353 // If we have an explicit value for the device type, or we are in a target
20354 // declare context, we need to emit all extern and used symbols.
20355 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20356 if (IsEmittedForExternalSymbol())
20357 return FunctionEmissionStatus::Emitted;
20358 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20359 // we'll omit it.
20360 if (Final)
20361 return FunctionEmissionStatus::OMPDiscarded;
20362 } else if (LangOpts.OpenMP > 45) {
20363 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20364 // function. In 5.0, no_host was introduced which might cause a function to
20365 // be omitted.
20366 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20367 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20368 if (DevTy)
20369 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20370 return FunctionEmissionStatus::OMPDiscarded;
20373 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20374 return FunctionEmissionStatus::Emitted;
20376 if (LangOpts.CUDA) {
20377 // When compiling for device, host functions are never emitted. Similarly,
20378 // when compiling for host, device and global functions are never emitted.
20379 // (Technically, we do emit a host-side stub for global functions, but this
20380 // doesn't count for our purposes here.)
20381 CUDAFunctionTarget T = CUDA().IdentifyTarget(FD);
20382 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20383 return FunctionEmissionStatus::CUDADiscarded;
20384 if (!LangOpts.CUDAIsDevice &&
20385 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
20386 return FunctionEmissionStatus::CUDADiscarded;
20388 if (IsEmittedForExternalSymbol())
20389 return FunctionEmissionStatus::Emitted;
20392 // Otherwise, the function is known-emitted if it's in our set of
20393 // known-emitted functions.
20394 return FunctionEmissionStatus::Unknown;
20397 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20398 // Host-side references to a __global__ function refer to the stub, so the
20399 // function itself is never emitted and therefore should not be marked.
20400 // If we have host fn calls kernel fn calls host+device, the HD function
20401 // does not get instantiated on the host. We model this by omitting at the
20402 // call to the kernel from the callgraph. This ensures that, when compiling
20403 // for host, only HD functions actually called from the host get marked as
20404 // known-emitted.
20405 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20406 CUDA().IdentifyTarget(Callee) == CUDAFunctionTarget::Global;