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.
10//
11//===----------------------------------------------------------------------===//
12
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/SemaOpenACC.h"
54#include "clang/Sema/SemaOpenMP.h"
55#include "clang/Sema/SemaPPC.h"
56#include "clang/Sema/SemaRISCV.h"
57#include "clang/Sema/SemaSYCL.h"
58#include "clang/Sema/SemaSwift.h"
59#include "clang/Sema/SemaWasm.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallString.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/TargetParser/Triple.h"
67#include <algorithm>
68#include <cstring>
69#include <optional>
70#include <unordered_map>
71
72using namespace clang;
73using namespace sema;
74
75Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
76 if (OwnedType) {
77 Decl *Group[2] = { OwnedType, Ptr };
78 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
79 }
80
81 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
82}
83
84namespace {
85
86class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
87 public:
88 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
89 bool AllowTemplates = false,
90 bool AllowNonTemplates = true)
91 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
92 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
93 WantExpressionKeywords = false;
94 WantCXXNamedCasts = false;
95 WantRemainingKeywords = false;
96 }
97
98 bool ValidateCandidate(const TypoCorrection &candidate) override {
99 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
100 if (!AllowInvalidDecl && ND->isInvalidDecl())
101 return false;
102
103 if (getAsTypeTemplateDecl(D: ND))
104 return AllowTemplates;
105
106 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
107 if (!IsType)
108 return false;
109
110 if (AllowNonTemplates)
111 return true;
112
113 // An injected-class-name of a class template (specialization) is valid
114 // as a template or as a non-template.
115 if (AllowTemplates) {
116 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
117 if (!RD || !RD->isInjectedClassName())
118 return false;
119 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
120 return RD->getDescribedClassTemplate() ||
121 isa<ClassTemplateSpecializationDecl>(Val: RD);
122 }
123
124 return false;
125 }
126
127 return !WantClassName && candidate.isKeyword();
128 }
129
130 std::unique_ptr<CorrectionCandidateCallback> clone() override {
131 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
132 }
133
134 private:
135 bool AllowInvalidDecl;
136 bool WantClassName;
137 bool AllowTemplates;
138 bool AllowNonTemplates;
139};
140
141} // end anonymous namespace
142
143QualType Sema::getTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
144 TypeDecl *TD, SourceLocation NameLoc) {
145 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
146 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
147 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
148 FoundRD->isInjectedClassName() &&
149 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
150 Diag(Loc: NameLoc,
151 DiagID: DCK == DiagCtorKind::Typename
152 ? diag::ext_out_of_line_qualified_id_type_names_constructor
153 : diag::err_out_of_line_qualified_id_type_names_constructor)
154 << TD->getIdentifier() << /*Type=*/1
155 << 0 /*if any keyword was present, it was 'typename'*/;
156 }
157
158 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
159 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
160 return Context.getTypeDeclType(Decl: TD);
161}
162
163namespace {
164enum class UnqualifiedTypeNameLookupResult {
165 NotFound,
166 FoundNonType,
167 FoundType
168};
169} // end anonymous namespace
170
171/// Tries to perform unqualified lookup of the type decls in bases for
172/// dependent class.
173/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
174/// type decl, \a FoundType if only type decls are found.
175static UnqualifiedTypeNameLookupResult
176lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
177 SourceLocation NameLoc,
178 const CXXRecordDecl *RD) {
179 if (!RD->hasDefinition())
180 return UnqualifiedTypeNameLookupResult::NotFound;
181 // Look for type decls in base classes.
182 UnqualifiedTypeNameLookupResult FoundTypeDecl =
183 UnqualifiedTypeNameLookupResult::NotFound;
184 for (const auto &Base : RD->bases()) {
185 const CXXRecordDecl *BaseRD = nullptr;
186 if (auto *BaseTT = Base.getType()->getAs<TagType>())
187 BaseRD = BaseTT->getAsCXXRecordDecl();
188 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
189 // Look for type decls in dependent base classes that have known primary
190 // templates.
191 if (!TST || !TST->isDependentType())
192 continue;
193 auto *TD = TST->getTemplateName().getAsTemplateDecl();
194 if (!TD)
195 continue;
196 if (auto *BasePrimaryTemplate =
197 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
198 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
199 BaseRD = BasePrimaryTemplate;
200 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
201 if (const ClassTemplatePartialSpecializationDecl *PS =
202 CTD->findPartialSpecialization(T: Base.getType()))
203 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = PS;
205 }
206 }
207 }
208 if (BaseRD) {
209 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
210 if (!isa<TypeDecl>(Val: ND))
211 return UnqualifiedTypeNameLookupResult::FoundNonType;
212 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
213 }
214 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
215 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
216 case UnqualifiedTypeNameLookupResult::FoundNonType:
217 return UnqualifiedTypeNameLookupResult::FoundNonType;
218 case UnqualifiedTypeNameLookupResult::FoundType:
219 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
220 break;
221 case UnqualifiedTypeNameLookupResult::NotFound:
222 break;
223 }
224 }
225 }
226 }
227
228 return FoundTypeDecl;
229}
230
231static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
232 const IdentifierInfo &II,
233 SourceLocation NameLoc) {
234 // Lookup in the parent class template context, if any.
235 const CXXRecordDecl *RD = nullptr;
236 UnqualifiedTypeNameLookupResult FoundTypeDecl =
237 UnqualifiedTypeNameLookupResult::NotFound;
238 for (DeclContext *DC = S.CurContext;
239 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
240 DC = DC->getParent()) {
241 // Look for type decls in dependent base classes that have known primary
242 // templates.
243 RD = dyn_cast<CXXRecordDecl>(Val: DC);
244 if (RD && RD->getDescribedClassTemplate())
245 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
246 }
247 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
248 return nullptr;
249
250 // We found some types in dependent base classes. Recover as if the user
251 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
252 // allowed. We'll fully resolve the lookup during template instantiation.
253 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
254
255 ASTContext &Context = S.Context;
256 auto *NNS = NestedNameSpecifier::Create(
257 Context, Prefix: nullptr, T: cast<Type>(Val: Context.getRecordType(Decl: RD)));
258 QualType T =
259 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
260
261 CXXScopeSpec SS;
262 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
263
264 TypeLocBuilder Builder;
265 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266 DepTL.setNameLoc(NameLoc);
267 DepTL.setElaboratedKeywordLoc(SourceLocation());
268 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
270}
271
272/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
273static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
274 SourceLocation NameLoc,
275 bool WantNontrivialTypeSourceInfo = true) {
276 switch (T->getTypeClass()) {
277 case Type::DeducedTemplateSpecialization:
278 case Type::Enum:
279 case Type::InjectedClassName:
280 case Type::Record:
281 case Type::Typedef:
282 case Type::UnresolvedUsing:
283 case Type::Using:
284 break;
285 // These can never be qualified so an ElaboratedType node
286 // would carry no additional meaning.
287 case Type::ObjCInterface:
288 case Type::ObjCTypeParam:
289 case Type::TemplateTypeParm:
290 return ParsedType::make(P: T);
291 default:
292 llvm_unreachable("Unexpected Type Class");
293 }
294
295 if (!SS || SS->isEmpty())
296 return ParsedType::make(P: S.Context.getElaboratedType(
297 Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, NamedType: T, OwnedTagDecl: nullptr));
298
299 QualType ElTy = S.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS: *SS, T);
300 if (!WantNontrivialTypeSourceInfo)
301 return ParsedType::make(P: ElTy);
302
303 TypeLocBuilder Builder;
304 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
305 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T: ElTy);
306 ElabTL.setElaboratedKeywordLoc(SourceLocation());
307 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context&: S.Context));
308 return S.CreateParsedType(T: ElTy, TInfo: Builder.getTypeSourceInfo(Context&: S.Context, T: ElTy));
309}
310
311ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
312 Scope *S, CXXScopeSpec *SS, bool isClassName,
313 bool HasTrailingDot, ParsedType ObjectTypePtr,
314 bool IsCtorOrDtorName,
315 bool WantNontrivialTypeSourceInfo,
316 bool IsClassTemplateDeductionContext,
317 ImplicitTypenameContext AllowImplicitTypename,
318 IdentifierInfo **CorrectedII) {
319 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
320 // FIXME: Consider allowing this outside C++1z mode as an extension.
321 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
322 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
323 !HasTrailingDot;
324
325 // Determine where we will perform name lookup.
326 DeclContext *LookupCtx = nullptr;
327 if (ObjectTypePtr) {
328 QualType ObjectType = ObjectTypePtr.get();
329 if (ObjectType->isRecordType())
330 LookupCtx = computeDeclContext(T: ObjectType);
331 } else if (SS && SS->isNotEmpty()) {
332 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
333
334 if (!LookupCtx) {
335 if (isDependentScopeSpecifier(SS: *SS)) {
336 // C++ [temp.res]p3:
337 // A qualified-id that refers to a type and in which the
338 // nested-name-specifier depends on a template-parameter (14.6.2)
339 // shall be prefixed by the keyword typename to indicate that the
340 // qualified-id denotes a type, forming an
341 // elaborated-type-specifier (7.1.5.3).
342 //
343 // We therefore do not perform any name lookup if the result would
344 // refer to a member of an unknown specialization.
345 // In C++2a, in several contexts a 'typename' is not required. Also
346 // allow this as an extension.
347 if (IsImplicitTypename) {
348 if (AllowImplicitTypename == ImplicitTypenameContext::No)
349 return nullptr;
350 SourceLocation QualifiedLoc = SS->getRange().getBegin();
351 auto DB =
352 DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
353 << NestedNameSpecifier::Create(Context, Prefix: SS->getScopeRep(), II: &II);
354 if (!getLangOpts().CPlusPlus20)
355 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
356 }
357
358 // We know from the grammar that this name refers to a type,
359 // so build a dependent node to describe the type.
360 if (WantNontrivialTypeSourceInfo)
361 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
362 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
363 .get();
364
365 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
366 QualType T = CheckTypenameType(
367 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
368 : ElaboratedTypeKeyword::None,
369 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
370 return ParsedType::make(P: T);
371 }
372
373 return nullptr;
374 }
375
376 if (!LookupCtx->isDependentContext() &&
377 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
378 return nullptr;
379 }
380
381 // In the case where we know that the identifier is a class name, we know that
382 // it is a type declaration (struct, class, union or enum) so we can use tag
383 // name lookup.
384 //
385 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
386 // the component name of the type-name or simple-template-id is type-only.
387 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
388 LookupResult Result(*this, &II, NameLoc, Kind);
389 if (LookupCtx) {
390 // Perform "qualified" name lookup into the declaration context we
391 // computed, which is either the type of the base of a member access
392 // expression or the declaration context associated with a prior
393 // nested-name-specifier.
394 LookupQualifiedName(R&: Result, LookupCtx);
395
396 if (ObjectTypePtr && Result.empty()) {
397 // C++ [basic.lookup.classref]p3:
398 // If the unqualified-id is ~type-name, the type-name is looked up
399 // in the context of the entire postfix-expression. If the type T of
400 // the object expression is of a class type C, the type-name is also
401 // looked up in the scope of class C. At least one of the lookups shall
402 // find a name that refers to (possibly cv-qualified) T.
403 LookupName(R&: Result, S);
404 }
405 } else {
406 // Perform unqualified name lookup.
407 LookupName(R&: Result, S);
408
409 // For unqualified lookup in a class template in MSVC mode, look into
410 // dependent base classes where the primary class template is known.
411 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
412 if (ParsedType TypeInBase =
413 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
414 return TypeInBase;
415 }
416 }
417
418 NamedDecl *IIDecl = nullptr;
419 UsingShadowDecl *FoundUsingShadow = nullptr;
420 switch (Result.getResultKind()) {
421 case LookupResultKind::NotFound:
422 if (CorrectedII) {
423 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
424 AllowDeducedTemplate);
425 TypoCorrection Correction =
426 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
427 Mode: CorrectTypoKind::ErrorRecovery);
428 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
429 TemplateTy Template;
430 bool MemberOfUnknownSpecialization;
431 UnqualifiedId TemplateName;
432 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
433 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
434 CXXScopeSpec NewSS, *NewSSPtr = SS;
435 if (SS && NNS) {
436 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
437 NewSSPtr = &NewSS;
438 }
439 if (Correction && (NNS || NewII != &II) &&
440 // Ignore a correction to a template type as the to-be-corrected
441 // identifier is not a template (typo correction for template names
442 // is handled elsewhere).
443 !(getLangOpts().CPlusPlus && NewSSPtr &&
444 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
445 Template, MemberOfUnknownSpecialization))) {
446 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
447 isClassName, HasTrailingDot, ObjectTypePtr,
448 IsCtorOrDtorName,
449 WantNontrivialTypeSourceInfo,
450 IsClassTemplateDeductionContext);
451 if (Ty) {
452 diagnoseTypo(Correction,
453 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
454 << Result.getLookupName() << isClassName);
455 if (SS && NNS)
456 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
457 *CorrectedII = NewII;
458 return Ty;
459 }
460 }
461 }
462 Result.suppressDiagnostics();
463 return nullptr;
464 case LookupResultKind::NotFoundInCurrentInstantiation:
465 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
466 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
467 NNS: SS->getScopeRep(), Name: &II);
468 TypeLocBuilder TLB;
469 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
470 TL.setElaboratedKeywordLoc(SourceLocation());
471 TL.setQualifierLoc(SS->getWithLocInContext(Context));
472 TL.setNameLoc(NameLoc);
473 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
474 }
475 [[fallthrough]];
476 case LookupResultKind::FoundOverloaded:
477 case LookupResultKind::FoundUnresolvedValue:
478 Result.suppressDiagnostics();
479 return nullptr;
480
481 case LookupResultKind::Ambiguous:
482 // Recover from type-hiding ambiguities by hiding the type. We'll
483 // do the lookup again when looking for an object, and we can
484 // diagnose the error then. If we don't do this, then the error
485 // about hiding the type will be immediately followed by an error
486 // that only makes sense if the identifier was treated like a type.
487 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
488 Result.suppressDiagnostics();
489 return nullptr;
490 }
491
492 // Look to see if we have a type anywhere in the list of results.
493 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
494 Res != ResEnd; ++Res) {
495 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
496 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
497 Val: RealRes) ||
498 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
499 if (!IIDecl ||
500 // Make the selection of the recovery decl deterministic.
501 RealRes->getLocation() < IIDecl->getLocation()) {
502 IIDecl = RealRes;
503 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
504 }
505 }
506 }
507
508 if (!IIDecl) {
509 // None of the entities we found is a type, so there is no way
510 // to even assume that the result is a type. In this case, don't
511 // complain about the ambiguity. The parser will either try to
512 // perform this lookup again (e.g., as an object name), which
513 // will produce the ambiguity, or will complain that it expected
514 // a type name.
515 Result.suppressDiagnostics();
516 return nullptr;
517 }
518
519 // We found a type within the ambiguous lookup; diagnose the
520 // ambiguity and then return that type. This might be the right
521 // answer, or it might not be, but it suppresses any attempt to
522 // perform the name lookup again.
523 break;
524
525 case LookupResultKind::Found:
526 IIDecl = Result.getFoundDecl();
527 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
528 break;
529 }
530
531 assert(IIDecl && "Didn't find decl");
532
533 QualType T;
534 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
535 // C++ [class.qual]p2: A lookup that would find the injected-class-name
536 // instead names the constructors of the class, except when naming a class.
537 // This is ill-formed when we're not actually forming a ctor or dtor name.
538 T = getTypeDeclType(LookupCtx,
539 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
540 : DiagCtorKind::None,
541 TD, NameLoc);
542 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
543 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
544 if (!HasTrailingDot)
545 T = Context.getObjCInterfaceType(Decl: IDecl);
546 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
547 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
548 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
549 // Recover with 'int'
550 return ParsedType::make(P: Context.IntTy);
551 } else if (AllowDeducedTemplate) {
552 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
553 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
554 TemplateName Template = Context.getQualifiedTemplateName(
555 NNS: SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
556 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
557 T = Context.getDeducedTemplateSpecializationType(Template, DeducedType: QualType(),
558 IsDependent: false);
559 // Don't wrap in a further UsingType.
560 FoundUsingShadow = nullptr;
561 }
562 }
563
564 if (T.isNull()) {
565 // If it's not plausibly a type, suppress diagnostics.
566 Result.suppressDiagnostics();
567 return nullptr;
568 }
569
570 if (FoundUsingShadow)
571 T = Context.getUsingType(Found: FoundUsingShadow, Underlying: T);
572
573 return buildNamedType(S&: *this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
574}
575
576// Builds a fake NNS for the given decl context.
577static NestedNameSpecifier *
578synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
579 for (;; DC = DC->getLookupParent()) {
580 DC = DC->getPrimaryContext();
581 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
582 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
583 return NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: ND);
584 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
585 return NestedNameSpecifier::Create(Context, Prefix: nullptr,
586 T: RD->getTypeForDecl());
587 if (isa<TranslationUnitDecl>(Val: DC))
588 return NestedNameSpecifier::GlobalSpecifier(Context);
589 }
590 llvm_unreachable("something isn't in TU scope?");
591}
592
593/// Find the parent class with dependent bases of the innermost enclosing method
594/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
595/// up allowing unqualified dependent type names at class-level, which MSVC
596/// correctly rejects.
597static const CXXRecordDecl *
598findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
599 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
600 DC = DC->getPrimaryContext();
601 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
602 if (MD->getParent()->hasAnyDependentBases())
603 return MD->getParent();
604 }
605 return nullptr;
606}
607
608ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
609 SourceLocation NameLoc,
610 bool IsTemplateTypeArg) {
611 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
612
613 NestedNameSpecifier *NNS = nullptr;
614 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
615 // If we weren't able to parse a default template argument, delay lookup
616 // until instantiation time by making a non-dependent DependentTypeName. We
617 // pretend we saw a NestedNameSpecifier referring to the current scope, and
618 // lookup is retried.
619 // FIXME: This hurts our diagnostic quality, since we get errors like "no
620 // type named 'Foo' in 'current_namespace'" when the user didn't write any
621 // name specifiers.
622 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
623 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
624 } else if (const CXXRecordDecl *RD =
625 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
626 // Build a DependentNameType that will perform lookup into RD at
627 // instantiation time.
628 NNS = NestedNameSpecifier::Create(Context, Prefix: nullptr, T: RD->getTypeForDecl());
629
630 // Diagnose that this identifier was undeclared, and retry the lookup during
631 // template instantiation.
632 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
633 << RD;
634 } else {
635 // This is not a situation that we should recover from.
636 return ParsedType();
637 }
638
639 QualType T =
640 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
641
642 // Build type location information. We synthesized the qualifier, so we have
643 // to build a fake NestedNameSpecifierLoc.
644 NestedNameSpecifierLocBuilder NNSLocBuilder;
645 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
646 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
647
648 TypeLocBuilder Builder;
649 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
650 DepTL.setNameLoc(NameLoc);
651 DepTL.setElaboratedKeywordLoc(SourceLocation());
652 DepTL.setQualifierLoc(QualifierLoc);
653 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
654}
655
656DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
657 // Do a tag name lookup in this scope.
658 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
659 LookupName(R, S, AllowBuiltinCreation: false);
660 R.suppressDiagnostics();
661 if (R.getResultKind() == LookupResultKind::Found)
662 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
663 switch (TD->getTagKind()) {
664 case TagTypeKind::Struct:
665 return DeclSpec::TST_struct;
666 case TagTypeKind::Interface:
667 return DeclSpec::TST_interface;
668 case TagTypeKind::Union:
669 return DeclSpec::TST_union;
670 case TagTypeKind::Class:
671 return DeclSpec::TST_class;
672 case TagTypeKind::Enum:
673 return DeclSpec::TST_enum;
674 }
675 }
676
677 return DeclSpec::TST_unspecified;
678}
679
680bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
681 if (CurContext->isRecord()) {
682 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
683 return true;
684
685 const Type *Ty = SS->getScopeRep()->getAsType();
686
687 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: CurContext);
688 for (const auto &Base : RD->bases())
689 if (Ty && Context.hasSameUnqualifiedType(T1: QualType(Ty, 1), T2: Base.getType()))
690 return true;
691 return S->isFunctionPrototypeScope();
692 }
693 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
694}
695
696void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
697 SourceLocation IILoc,
698 Scope *S,
699 CXXScopeSpec *SS,
700 ParsedType &SuggestedType,
701 bool IsTemplateName) {
702 // Don't report typename errors for editor placeholders.
703 if (II->isEditorPlaceholder())
704 return;
705 // We don't have anything to suggest (yet).
706 SuggestedType = nullptr;
707
708 // There may have been a typo in the name of the type. Look up typo
709 // results, in case we have something that we can suggest.
710 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
711 /*AllowTemplates=*/IsTemplateName,
712 /*AllowNonTemplates=*/!IsTemplateName);
713 if (TypoCorrection Corrected =
714 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
715 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
716 // FIXME: Support error recovery for the template-name case.
717 bool CanRecover = !IsTemplateName;
718 if (Corrected.isKeyword()) {
719 // We corrected to a keyword.
720 diagnoseTypo(Correction: Corrected,
721 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
722 : diag::err_unknown_typename_suggest)
723 << II);
724 II = Corrected.getCorrectionAsIdentifierInfo();
725 } else {
726 // We found a similarly-named type or interface; suggest that.
727 if (!SS || !SS->isSet()) {
728 diagnoseTypo(Correction: Corrected,
729 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
730 : diag::err_unknown_typename_suggest)
731 << II, ErrorRecovery: CanRecover);
732 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
733 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
734 bool DroppedSpecifier =
735 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
736 diagnoseTypo(Correction: Corrected,
737 TypoDiag: PDiag(DiagID: IsTemplateName
738 ? diag::err_no_member_template_suggest
739 : diag::err_unknown_nested_typename_suggest)
740 << II << DC << DroppedSpecifier << SS->getRange(),
741 ErrorRecovery: CanRecover);
742 } else {
743 llvm_unreachable("could not have corrected a typo here");
744 }
745
746 if (!CanRecover)
747 return;
748
749 CXXScopeSpec tmpSS;
750 if (Corrected.getCorrectionSpecifier())
751 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
752 R: SourceRange(IILoc));
753 // FIXME: Support class template argument deduction here.
754 SuggestedType =
755 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
756 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
757 /*IsCtorOrDtorName=*/false,
758 /*WantNontrivialTypeSourceInfo=*/true);
759 }
760 return;
761 }
762
763 if (getLangOpts().CPlusPlus && !IsTemplateName) {
764 // See if II is a class template that the user forgot to pass arguments to.
765 UnqualifiedId Name;
766 Name.setIdentifier(Id: II, IdLoc: IILoc);
767 CXXScopeSpec EmptySS;
768 TemplateTy TemplateResult;
769 bool MemberOfUnknownSpecialization;
770 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
771 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
772 MemberOfUnknownSpecialization) == TNK_Type_template) {
773 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
774 return;
775 }
776 }
777
778 // FIXME: Should we move the logic that tries to recover from a missing tag
779 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
780
781 if (!SS || (!SS->isSet() && !SS->isInvalid()))
782 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
783 : diag::err_unknown_typename)
784 << II;
785 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
786 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
787 : diag::err_typename_nested_not_found)
788 << II << DC << SS->getRange();
789 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
790 SuggestedType =
791 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
792 } else if (isDependentScopeSpecifier(SS: *SS)) {
793 unsigned DiagID = diag::err_typename_missing;
794 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
795 DiagID = diag::ext_typename_missing;
796
797 Diag(Loc: SS->getRange().getBegin(), DiagID)
798 << NestedNameSpecifier::Create(Context, Prefix: SS->getScopeRep(), II)
799 << SourceRange(SS->getRange().getBegin(), IILoc)
800 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
801 SuggestedType = ActOnTypenameType(S, TypenameLoc: SourceLocation(),
802 SS: *SS, II: *II, IdLoc: IILoc).get();
803 } else {
804 assert(SS && SS->isInvalid() &&
805 "Invalid scope specifier has already been diagnosed");
806 }
807}
808
809/// Determine whether the given result set contains either a type name
810/// or
811static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
812 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
813 NextToken.is(K: tok::less);
814
815 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
816 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
817 return true;
818
819 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
820 return true;
821 }
822
823 return false;
824}
825
826static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
827 Scope *S, CXXScopeSpec &SS,
828 IdentifierInfo *&Name,
829 SourceLocation NameLoc) {
830 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
831 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
832 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
833 StringRef FixItTagName;
834 switch (Tag->getTagKind()) {
835 case TagTypeKind::Class:
836 FixItTagName = "class ";
837 break;
838
839 case TagTypeKind::Enum:
840 FixItTagName = "enum ";
841 break;
842
843 case TagTypeKind::Struct:
844 FixItTagName = "struct ";
845 break;
846
847 case TagTypeKind::Interface:
848 FixItTagName = "__interface ";
849 break;
850
851 case TagTypeKind::Union:
852 FixItTagName = "union ";
853 break;
854 }
855
856 StringRef TagName = FixItTagName.drop_back();
857 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
858 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
859 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
860
861 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
862 I != IEnd; ++I)
863 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
864 << Name << TagName;
865
866 // Replace lookup results with just the tag decl.
867 Result.clear(Kind: Sema::LookupTagName);
868 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
869 return true;
870 }
871
872 return false;
873}
874
875Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
876 IdentifierInfo *&Name,
877 SourceLocation NameLoc,
878 const Token &NextToken,
879 CorrectionCandidateCallback *CCC) {
880 DeclarationNameInfo NameInfo(Name, NameLoc);
881 ObjCMethodDecl *CurMethod = getCurMethodDecl();
882
883 assert(NextToken.isNot(tok::coloncolon) &&
884 "parse nested name specifiers before calling ClassifyName");
885 if (getLangOpts().CPlusPlus && SS.isSet() &&
886 isCurrentClassName(II: *Name, S, SS: &SS)) {
887 // Per [class.qual]p2, this names the constructors of SS, not the
888 // injected-class-name. We don't have a classification for that.
889 // There's not much point caching this result, since the parser
890 // will reject it later.
891 return NameClassification::Unknown();
892 }
893
894 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
895 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
896 /*AllowBuiltinCreation=*/!CurMethod);
897
898 if (SS.isInvalid())
899 return NameClassification::Error();
900
901 // For unqualified lookup in a class template in MSVC mode, look into
902 // dependent base classes where the primary class template is known.
903 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
904 if (ParsedType TypeInBase =
905 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
906 return TypeInBase;
907 }
908
909 // Perform lookup for Objective-C instance variables (including automatically
910 // synthesized instance variables), if we're in an Objective-C method.
911 // FIXME: This lookup really, really needs to be folded in to the normal
912 // unqualified lookup mechanism.
913 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
914 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
915 if (Ivar.isInvalid())
916 return NameClassification::Error();
917 if (Ivar.isUsable())
918 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
919
920 // We defer builtin creation until after ivar lookup inside ObjC methods.
921 if (Result.empty())
922 LookupBuiltin(R&: Result);
923 }
924
925 bool SecondTry = false;
926 bool IsFilteredTemplateName = false;
927
928Corrected:
929 switch (Result.getResultKind()) {
930 case LookupResultKind::NotFound:
931 // If an unqualified-id is followed by a '(', then we have a function
932 // call.
933 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
934 // In C++, this is an ADL-only call.
935 // FIXME: Reference?
936 if (getLangOpts().CPlusPlus)
937 return NameClassification::UndeclaredNonType();
938
939 // C90 6.3.2.2:
940 // If the expression that precedes the parenthesized argument list in a
941 // function call consists solely of an identifier, and if no
942 // declaration is visible for this identifier, the identifier is
943 // implicitly declared exactly as if, in the innermost block containing
944 // the function call, the declaration
945 //
946 // extern int identifier ();
947 //
948 // appeared.
949 //
950 // We also allow this in C99 as an extension. However, this is not
951 // allowed in all language modes as functions without prototypes may not
952 // be supported.
953 if (getLangOpts().implicitFunctionsAllowed()) {
954 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
955 return NameClassification::NonType(D);
956 }
957 }
958
959 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
960 // In C++20 onwards, this could be an ADL-only call to a function
961 // template, and we're required to assume that this is a template name.
962 //
963 // FIXME: Find a way to still do typo correction in this case.
964 TemplateName Template =
965 Context.getAssumedTemplateName(Name: NameInfo.getName());
966 return NameClassification::UndeclaredTemplate(Name: Template);
967 }
968
969 // In C, we first see whether there is a tag type by the same name, in
970 // which case it's likely that the user just forgot to write "enum",
971 // "struct", or "union".
972 if (!getLangOpts().CPlusPlus && !SecondTry &&
973 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
974 break;
975 }
976
977 // Perform typo correction to determine if there is another name that is
978 // close to this name.
979 if (!SecondTry && CCC) {
980 SecondTry = true;
981 if (TypoCorrection Corrected =
982 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
983 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
984 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
985 unsigned QualifiedDiag = diag::err_no_member_suggest;
986
987 NamedDecl *FirstDecl = Corrected.getFoundDecl();
988 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
989 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
990 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
991 UnqualifiedDiag = diag::err_no_template_suggest;
992 QualifiedDiag = diag::err_no_member_template_suggest;
993 } else if (UnderlyingFirstDecl &&
994 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
995 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
996 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
997 UnqualifiedDiag = diag::err_unknown_typename_suggest;
998 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
999 }
1000
1001 if (SS.isEmpty()) {
1002 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1003 } else {// FIXME: is this even reachable? Test it.
1004 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1005 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1006 Name->getName() == CorrectedStr;
1007 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1008 << Name << computeDeclContext(SS, EnteringContext: false)
1009 << DroppedSpecifier << SS.getRange());
1010 }
1011
1012 // Update the name, so that the caller has the new name.
1013 Name = Corrected.getCorrectionAsIdentifierInfo();
1014
1015 // Typo correction corrected to a keyword.
1016 if (Corrected.isKeyword())
1017 return Name;
1018
1019 // Also update the LookupResult...
1020 // FIXME: This should probably go away at some point
1021 Result.clear();
1022 Result.setLookupName(Corrected.getCorrection());
1023 if (FirstDecl)
1024 Result.addDecl(D: FirstDecl);
1025
1026 // If we found an Objective-C instance variable, let
1027 // LookupInObjCMethod build the appropriate expression to
1028 // reference the ivar.
1029 // FIXME: This is a gross hack.
1030 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1031 DeclResult R =
1032 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1033 if (R.isInvalid())
1034 return NameClassification::Error();
1035 if (R.isUsable())
1036 return NameClassification::NonType(D: Ivar);
1037 }
1038
1039 goto Corrected;
1040 }
1041 }
1042
1043 // We failed to correct; just fall through and let the parser deal with it.
1044 Result.suppressDiagnostics();
1045 return NameClassification::Unknown();
1046
1047 case LookupResultKind::NotFoundInCurrentInstantiation: {
1048 // We performed name lookup into the current instantiation, and there were
1049 // dependent bases, so we treat this result the same way as any other
1050 // dependent nested-name-specifier.
1051
1052 // C++ [temp.res]p2:
1053 // A name used in a template declaration or definition and that is
1054 // dependent on a template-parameter is assumed not to name a type
1055 // unless the applicable name lookup finds a type name or the name is
1056 // qualified by the keyword typename.
1057 //
1058 // FIXME: If the next token is '<', we might want to ask the parser to
1059 // perform some heroics to see if we actually have a
1060 // template-argument-list, which would indicate a missing 'template'
1061 // keyword here.
1062 return NameClassification::DependentNonType();
1063 }
1064
1065 case LookupResultKind::Found:
1066 case LookupResultKind::FoundOverloaded:
1067 case LookupResultKind::FoundUnresolvedValue:
1068 break;
1069
1070 case LookupResultKind::Ambiguous:
1071 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1072 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1073 /*AllowDependent=*/false)) {
1074 // C++ [temp.local]p3:
1075 // A lookup that finds an injected-class-name (10.2) can result in an
1076 // ambiguity in certain cases (for example, if it is found in more than
1077 // one base class). If all of the injected-class-names that are found
1078 // refer to specializations of the same class template, and if the name
1079 // is followed by a template-argument-list, the reference refers to the
1080 // class template itself and not a specialization thereof, and is not
1081 // ambiguous.
1082 //
1083 // This filtering can make an ambiguous result into an unambiguous one,
1084 // so try again after filtering out template names.
1085 FilterAcceptableTemplateNames(R&: Result);
1086 if (!Result.isAmbiguous()) {
1087 IsFilteredTemplateName = true;
1088 break;
1089 }
1090 }
1091
1092 // Diagnose the ambiguity and return an error.
1093 return NameClassification::Error();
1094 }
1095
1096 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1097 (IsFilteredTemplateName ||
1098 hasAnyAcceptableTemplateNames(
1099 R&: Result, /*AllowFunctionTemplates=*/true,
1100 /*AllowDependent=*/false,
1101 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1102 getLangOpts().CPlusPlus20))) {
1103 // C++ [temp.names]p3:
1104 // After name lookup (3.4) finds that a name is a template-name or that
1105 // an operator-function-id or a literal- operator-id refers to a set of
1106 // overloaded functions any member of which is a function template if
1107 // this is followed by a <, the < is always taken as the delimiter of a
1108 // template-argument-list and never as the less-than operator.
1109 // C++2a [temp.names]p2:
1110 // A name is also considered to refer to a template if it is an
1111 // unqualified-id followed by a < and name lookup finds either one
1112 // or more functions or finds nothing.
1113 if (!IsFilteredTemplateName)
1114 FilterAcceptableTemplateNames(R&: Result);
1115
1116 bool IsFunctionTemplate;
1117 bool IsVarTemplate;
1118 TemplateName Template;
1119 if (Result.end() - Result.begin() > 1) {
1120 IsFunctionTemplate = true;
1121 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1122 End: Result.end());
1123 } else if (!Result.empty()) {
1124 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1125 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1126 /*AllowDependent=*/false));
1127 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1128 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1129
1130 UsingShadowDecl *FoundUsingShadow =
1131 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1132 assert(!FoundUsingShadow ||
1133 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1134 Template = Context.getQualifiedTemplateName(
1135 NNS: SS.getScopeRep(),
1136 /*TemplateKeyword=*/false,
1137 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1138 } else {
1139 // All results were non-template functions. This is a function template
1140 // name.
1141 IsFunctionTemplate = true;
1142 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1143 }
1144
1145 if (IsFunctionTemplate) {
1146 // Function templates always go through overload resolution, at which
1147 // point we'll perform the various checks (e.g., accessibility) we need
1148 // to based on which function we selected.
1149 Result.suppressDiagnostics();
1150
1151 return NameClassification::FunctionTemplate(Name: Template);
1152 }
1153
1154 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1155 : NameClassification::TypeTemplate(Name: Template);
1156 }
1157
1158 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1159 QualType T = Context.getTypeDeclType(Decl: Type);
1160 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found))
1161 T = Context.getUsingType(Found: USD, Underlying: T);
1162 return buildNamedType(S&: *this, SS: &SS, T, NameLoc);
1163 };
1164
1165 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1166 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1167 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1168 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1169 return BuildTypeFor(Type, *Result.begin());
1170 }
1171
1172 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1173 if (!Class) {
1174 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1175 if (ObjCCompatibleAliasDecl *Alias =
1176 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1177 Class = Alias->getClassInterface();
1178 }
1179
1180 if (Class) {
1181 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1182
1183 if (NextToken.is(K: tok::period)) {
1184 // Interface. <something> is parsed as a property reference expression.
1185 // Just return "unknown" as a fall-through for now.
1186 Result.suppressDiagnostics();
1187 return NameClassification::Unknown();
1188 }
1189
1190 QualType T = Context.getObjCInterfaceType(Decl: Class);
1191 return ParsedType::make(P: T);
1192 }
1193
1194 if (isa<ConceptDecl>(Val: FirstDecl)) {
1195 // We want to preserve the UsingShadowDecl for concepts.
1196 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1197 return NameClassification::Concept(Name: TemplateName(USD));
1198 return NameClassification::Concept(
1199 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1200 }
1201
1202 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1203 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1204 return NameClassification::Error();
1205 }
1206
1207 // We can have a type template here if we're classifying a template argument.
1208 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1209 !isa<VarTemplateDecl>(Val: FirstDecl))
1210 return NameClassification::TypeTemplate(
1211 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1212
1213 // Check for a tag type hidden by a non-type decl in a few cases where it
1214 // seems likely a type is wanted instead of the non-type that was found.
1215 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1216 if ((NextToken.is(K: tok::identifier) ||
1217 (NextIsOp &&
1218 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1219 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1220 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1221 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1222 return BuildTypeFor(Type, *Result.begin());
1223 }
1224
1225 // If we already know which single declaration is referenced, just annotate
1226 // that declaration directly. Defer resolving even non-overloaded class
1227 // member accesses, as we need to defer certain access checks until we know
1228 // the context.
1229 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1230 if (Result.isSingleResult() && !ADL &&
1231 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1232 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1233
1234 // Otherwise, this is an overload set that we will need to resolve later.
1235 Result.suppressDiagnostics();
1236 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1237 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1238 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1239 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1240}
1241
1242ExprResult
1243Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1244 SourceLocation NameLoc) {
1245 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1246 CXXScopeSpec SS;
1247 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1248 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1249}
1250
1251ExprResult
1252Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1253 IdentifierInfo *Name,
1254 SourceLocation NameLoc,
1255 bool IsAddressOfOperand) {
1256 DeclarationNameInfo NameInfo(Name, NameLoc);
1257 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1258 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1259 /*TemplateArgs=*/nullptr);
1260}
1261
1262ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1263 NamedDecl *Found,
1264 SourceLocation NameLoc,
1265 const Token &NextToken) {
1266 if (getCurMethodDecl() && SS.isEmpty())
1267 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1268 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1269
1270 // Reconstruct the lookup result.
1271 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1272 Result.addDecl(D: Found);
1273 Result.resolveKind();
1274
1275 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1276 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1277}
1278
1279ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1280 // For an implicit class member access, transform the result into a member
1281 // access expression if necessary.
1282 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1283 if ((*ULE->decls_begin())->isCXXClassMember()) {
1284 CXXScopeSpec SS;
1285 SS.Adopt(Other: ULE->getQualifierLoc());
1286
1287 // Reconstruct the lookup result.
1288 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1289 LookupOrdinaryName);
1290 Result.setNamingClass(ULE->getNamingClass());
1291 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1292 Result.addDecl(D: *I, AS: I.getAccess());
1293 Result.resolveKind();
1294 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1295 TemplateArgs: nullptr, S);
1296 }
1297
1298 // Otherwise, this is already in the form we needed, and no further checks
1299 // are necessary.
1300 return ULE;
1301}
1302
1303Sema::TemplateNameKindForDiagnostics
1304Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1305 auto *TD = Name.getAsTemplateDecl();
1306 if (!TD)
1307 return TemplateNameKindForDiagnostics::DependentTemplate;
1308 if (isa<ClassTemplateDecl>(Val: TD))
1309 return TemplateNameKindForDiagnostics::ClassTemplate;
1310 if (isa<FunctionTemplateDecl>(Val: TD))
1311 return TemplateNameKindForDiagnostics::FunctionTemplate;
1312 if (isa<VarTemplateDecl>(Val: TD))
1313 return TemplateNameKindForDiagnostics::VarTemplate;
1314 if (isa<TypeAliasTemplateDecl>(Val: TD))
1315 return TemplateNameKindForDiagnostics::AliasTemplate;
1316 if (isa<TemplateTemplateParmDecl>(Val: TD))
1317 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1318 if (isa<ConceptDecl>(Val: TD))
1319 return TemplateNameKindForDiagnostics::Concept;
1320 return TemplateNameKindForDiagnostics::DependentTemplate;
1321}
1322
1323void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1324 assert(DC->getLexicalParent() == CurContext &&
1325 "The next DeclContext should be lexically contained in the current one.");
1326 CurContext = DC;
1327 S->setEntity(DC);
1328}
1329
1330void Sema::PopDeclContext() {
1331 assert(CurContext && "DeclContext imbalance!");
1332
1333 CurContext = CurContext->getLexicalParent();
1334 assert(CurContext && "Popped translation unit!");
1335}
1336
1337Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1338 Decl *D) {
1339 // Unlike PushDeclContext, the context to which we return is not necessarily
1340 // the containing DC of TD, because the new context will be some pre-existing
1341 // TagDecl definition instead of a fresh one.
1342 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1343 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1344 assert(CurContext && "skipping definition of undefined tag");
1345 // Start lookups from the parent of the current context; we don't want to look
1346 // into the pre-existing complete definition.
1347 S->setEntity(CurContext->getLookupParent());
1348 return Result;
1349}
1350
1351void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1352 CurContext = static_cast<decltype(CurContext)>(Context);
1353}
1354
1355void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1356 // C++0x [basic.lookup.unqual]p13:
1357 // A name used in the definition of a static data member of class
1358 // X (after the qualified-id of the static member) is looked up as
1359 // if the name was used in a member function of X.
1360 // C++0x [basic.lookup.unqual]p14:
1361 // If a variable member of a namespace is defined outside of the
1362 // scope of its namespace then any name used in the definition of
1363 // the variable member (after the declarator-id) is looked up as
1364 // if the definition of the variable member occurred in its
1365 // namespace.
1366 // Both of these imply that we should push a scope whose context
1367 // is the semantic context of the declaration. We can't use
1368 // PushDeclContext here because that context is not necessarily
1369 // lexically contained in the current context. Fortunately,
1370 // the containing scope should have the appropriate information.
1371
1372 assert(!S->getEntity() && "scope already has entity");
1373
1374#ifndef NDEBUG
1375 Scope *Ancestor = S->getParent();
1376 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1377 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1378#endif
1379
1380 CurContext = DC;
1381 S->setEntity(DC);
1382
1383 if (S->getParent()->isTemplateParamScope()) {
1384 // Also set the corresponding entities for all immediately-enclosing
1385 // template parameter scopes.
1386 EnterTemplatedContext(S: S->getParent(), DC);
1387 }
1388}
1389
1390void Sema::ExitDeclaratorContext(Scope *S) {
1391 assert(S->getEntity() == CurContext && "Context imbalance!");
1392
1393 // Switch back to the lexical context. The safety of this is
1394 // enforced by an assert in EnterDeclaratorContext.
1395 Scope *Ancestor = S->getParent();
1396 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1397 CurContext = Ancestor->getEntity();
1398
1399 // We don't need to do anything with the scope, which is going to
1400 // disappear.
1401}
1402
1403void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1404 assert(S->isTemplateParamScope() &&
1405 "expected to be initializing a template parameter scope");
1406
1407 // C++20 [temp.local]p7:
1408 // In the definition of a member of a class template that appears outside
1409 // of the class template definition, the name of a member of the class
1410 // template hides the name of a template-parameter of any enclosing class
1411 // templates (but not a template-parameter of the member if the member is a
1412 // class or function template).
1413 // C++20 [temp.local]p9:
1414 // In the definition of a class template or in the definition of a member
1415 // of such a template that appears outside of the template definition, for
1416 // each non-dependent base class (13.8.2.1), if the name of the base class
1417 // or the name of a member of the base class is the same as the name of a
1418 // template-parameter, the base class name or member name hides the
1419 // template-parameter name (6.4.10).
1420 //
1421 // This means that a template parameter scope should be searched immediately
1422 // after searching the DeclContext for which it is a template parameter
1423 // scope. For example, for
1424 // template<typename T> template<typename U> template<typename V>
1425 // void N::A<T>::B<U>::f(...)
1426 // we search V then B<U> (and base classes) then U then A<T> (and base
1427 // classes) then T then N then ::.
1428 unsigned ScopeDepth = getTemplateDepth(S);
1429 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1430 DeclContext *SearchDCAfterScope = DC;
1431 for (; DC; DC = DC->getLookupParent()) {
1432 if (const TemplateParameterList *TPL =
1433 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1434 unsigned DCDepth = TPL->getDepth() + 1;
1435 if (DCDepth > ScopeDepth)
1436 continue;
1437 if (ScopeDepth == DCDepth)
1438 SearchDCAfterScope = DC = DC->getLookupParent();
1439 break;
1440 }
1441 }
1442 S->setLookupEntity(SearchDCAfterScope);
1443 }
1444}
1445
1446void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1447 // We assume that the caller has already called
1448 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1449 FunctionDecl *FD = D->getAsFunction();
1450 if (!FD)
1451 return;
1452
1453 // Same implementation as PushDeclContext, but enters the context
1454 // from the lexical parent, rather than the top-level class.
1455 assert(CurContext == FD->getLexicalParent() &&
1456 "The next DeclContext should be lexically contained in the current one.");
1457 CurContext = FD;
1458 S->setEntity(CurContext);
1459
1460 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1461 ParmVarDecl *Param = FD->getParamDecl(i: P);
1462 // If the parameter has an identifier, then add it to the scope
1463 if (Param->getIdentifier()) {
1464 S->AddDecl(D: Param);
1465 IdResolver.AddDecl(D: Param);
1466 }
1467 }
1468}
1469
1470void Sema::ActOnExitFunctionContext() {
1471 // Same implementation as PopDeclContext, but returns to the lexical parent,
1472 // rather than the top-level class.
1473 assert(CurContext && "DeclContext imbalance!");
1474 CurContext = CurContext->getLexicalParent();
1475 assert(CurContext && "Popped translation unit!");
1476}
1477
1478/// Determine whether overloading is allowed for a new function
1479/// declaration considering prior declarations of the same name.
1480///
1481/// This routine determines whether overloading is possible, not
1482/// whether a new declaration actually overloads a previous one.
1483/// It will return true in C++ (where overloads are always permitted)
1484/// or, as a C extension, when either the new declaration or a
1485/// previous one is declared with the 'overloadable' attribute.
1486static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1487 ASTContext &Context,
1488 const FunctionDecl *New) {
1489 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1490 return true;
1491
1492 // Multiversion function declarations are not overloads in the
1493 // usual sense of that term, but lookup will report that an
1494 // overload set was found if more than one multiversion function
1495 // declaration is present for the same name. It is therefore
1496 // inadequate to assume that some prior declaration(s) had
1497 // the overloadable attribute; checking is required. Since one
1498 // declaration is permitted to omit the attribute, it is necessary
1499 // to check at least two; hence the 'any_of' check below. Note that
1500 // the overloadable attribute is implicitly added to declarations
1501 // that were required to have it but did not.
1502 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1503 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1504 return ND->hasAttr<OverloadableAttr>();
1505 });
1506 } else if (Previous.getResultKind() == LookupResultKind::Found)
1507 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1508
1509 return false;
1510}
1511
1512void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1513 // Move up the scope chain until we find the nearest enclosing
1514 // non-transparent context. The declaration will be introduced into this
1515 // scope.
1516 while (S->getEntity() && S->getEntity()->isTransparentContext())
1517 S = S->getParent();
1518
1519 // Add scoped declarations into their context, so that they can be
1520 // found later. Declarations without a context won't be inserted
1521 // into any context.
1522 if (AddToContext)
1523 CurContext->addDecl(D);
1524
1525 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1526 // are function-local declarations.
1527 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1528 return;
1529
1530 // Template instantiations should also not be pushed into scope.
1531 if (isa<FunctionDecl>(Val: D) &&
1532 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1533 return;
1534
1535 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1536 S->AddDecl(D);
1537 return;
1538 }
1539 // If this replaces anything in the current scope,
1540 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1541 IEnd = IdResolver.end();
1542 for (; I != IEnd; ++I) {
1543 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1544 S->RemoveDecl(D: *I);
1545 IdResolver.RemoveDecl(D: *I);
1546
1547 // Should only need to replace one decl.
1548 break;
1549 }
1550 }
1551
1552 S->AddDecl(D);
1553
1554 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1555 // Implicitly-generated labels may end up getting generated in an order that
1556 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1557 // the label at the appropriate place in the identifier chain.
1558 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1559 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1560 if (IDC == CurContext) {
1561 if (!S->isDeclScope(D: *I))
1562 continue;
1563 } else if (IDC->Encloses(DC: CurContext))
1564 break;
1565 }
1566
1567 IdResolver.InsertDeclAfter(Pos: I, D);
1568 } else {
1569 IdResolver.AddDecl(D);
1570 }
1571 warnOnReservedIdentifier(D);
1572}
1573
1574bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1575 bool AllowInlineNamespace) const {
1576 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1577}
1578
1579Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1580 DeclContext *TargetDC = DC->getPrimaryContext();
1581 do {
1582 if (DeclContext *ScopeDC = S->getEntity())
1583 if (ScopeDC->getPrimaryContext() == TargetDC)
1584 return S;
1585 } while ((S = S->getParent()));
1586
1587 return nullptr;
1588}
1589
1590static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1591 DeclContext*,
1592 ASTContext&);
1593
1594void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1595 bool ConsiderLinkage,
1596 bool AllowInlineNamespace) {
1597 LookupResult::Filter F = R.makeFilter();
1598 while (F.hasNext()) {
1599 NamedDecl *D = F.next();
1600
1601 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1602 continue;
1603
1604 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1605 continue;
1606
1607 F.erase();
1608 }
1609
1610 F.done();
1611}
1612
1613bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1614 // [module.interface]p7:
1615 // A declaration is attached to a module as follows:
1616 // - If the declaration is a non-dependent friend declaration that nominates a
1617 // function with a declarator-id that is a qualified-id or template-id or that
1618 // nominates a class other than with an elaborated-type-specifier with neither
1619 // a nested-name-specifier nor a simple-template-id, it is attached to the
1620 // module to which the friend is attached ([basic.link]).
1621 if (New->getFriendObjectKind() &&
1622 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1623 New->setLocalOwningModule(Old->getOwningModule());
1624 makeMergedDefinitionVisible(ND: New);
1625 return false;
1626 }
1627
1628 Module *NewM = New->getOwningModule();
1629 Module *OldM = Old->getOwningModule();
1630
1631 if (NewM && NewM->isPrivateModule())
1632 NewM = NewM->Parent;
1633 if (OldM && OldM->isPrivateModule())
1634 OldM = OldM->Parent;
1635
1636 if (NewM == OldM)
1637 return false;
1638
1639 if (NewM && OldM) {
1640 // A module implementation unit has visibility of the decls in its
1641 // implicitly imported interface.
1642 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1643 return false;
1644
1645 // Partitions are part of the module, but a partition could import another
1646 // module, so verify that the PMIs agree.
1647 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1648 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1649 return false;
1650 }
1651
1652 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1653 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1654 if (NewIsModuleInterface || OldIsModuleInterface) {
1655 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1656 // if a declaration of D [...] appears in the purview of a module, all
1657 // other such declarations shall appear in the purview of the same module
1658 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1659 << New
1660 << NewIsModuleInterface
1661 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1662 << OldIsModuleInterface
1663 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1664 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1665 New->setInvalidDecl();
1666 return true;
1667 }
1668
1669 return false;
1670}
1671
1672bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1673 // [module.interface]p1:
1674 // An export-declaration shall inhabit a namespace scope.
1675 //
1676 // So it is meaningless to talk about redeclaration which is not at namespace
1677 // scope.
1678 if (!New->getLexicalDeclContext()
1679 ->getNonTransparentContext()
1680 ->isFileContext() ||
1681 !Old->getLexicalDeclContext()
1682 ->getNonTransparentContext()
1683 ->isFileContext())
1684 return false;
1685
1686 bool IsNewExported = New->isInExportDeclContext();
1687 bool IsOldExported = Old->isInExportDeclContext();
1688
1689 // It should be irrevelant if both of them are not exported.
1690 if (!IsNewExported && !IsOldExported)
1691 return false;
1692
1693 if (IsOldExported)
1694 return false;
1695
1696 // If the Old declaration are not attached to named modules
1697 // and the New declaration are attached to global module.
1698 // It should be fine to allow the export since it doesn't change
1699 // the linkage of declarations. See
1700 // https://github.com/llvm/llvm-project/issues/98583 for details.
1701 if (!Old->isInNamedModule() && New->getOwningModule() &&
1702 New->getOwningModule()->isImplicitGlobalModule())
1703 return false;
1704
1705 assert(IsNewExported);
1706
1707 auto Lk = Old->getFormalLinkage();
1708 int S = 0;
1709 if (Lk == Linkage::Internal)
1710 S = 1;
1711 else if (Lk == Linkage::Module)
1712 S = 2;
1713 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1714 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1715 return true;
1716}
1717
1718bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1719 if (CheckRedeclarationModuleOwnership(New, Old))
1720 return true;
1721
1722 if (CheckRedeclarationExported(New, Old))
1723 return true;
1724
1725 return false;
1726}
1727
1728bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1729 const NamedDecl *Old) const {
1730 assert(getASTContext().isSameEntity(New, Old) &&
1731 "New and Old are not the same definition, we should diagnostic it "
1732 "immediately instead of checking it.");
1733 assert(const_cast<Sema *>(this)->isReachable(New) &&
1734 const_cast<Sema *>(this)->isReachable(Old) &&
1735 "We shouldn't see unreachable definitions here.");
1736
1737 Module *NewM = New->getOwningModule();
1738 Module *OldM = Old->getOwningModule();
1739
1740 // We only checks for named modules here. The header like modules is skipped.
1741 // FIXME: This is not right if we import the header like modules in the module
1742 // purview.
1743 //
1744 // For example, assuming "header.h" provides definition for `D`.
1745 // ```C++
1746 // //--- M.cppm
1747 // export module M;
1748 // import "header.h"; // or #include "header.h" but import it by clang modules
1749 // actually.
1750 //
1751 // //--- Use.cpp
1752 // import M;
1753 // import "header.h"; // or uses clang modules.
1754 // ```
1755 //
1756 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1757 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1758 // reject it. But the current implementation couldn't detect the case since we
1759 // don't record the information about the importee modules.
1760 //
1761 // But this might not be painful in practice. Since the design of C++20 Named
1762 // Modules suggests us to use headers in global module fragment instead of
1763 // module purview.
1764 if (NewM && NewM->isHeaderLikeModule())
1765 NewM = nullptr;
1766 if (OldM && OldM->isHeaderLikeModule())
1767 OldM = nullptr;
1768
1769 if (!NewM && !OldM)
1770 return true;
1771
1772 // [basic.def.odr]p14.3
1773 // Each such definition shall not be attached to a named module
1774 // ([module.unit]).
1775 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1776 return true;
1777
1778 // Then New and Old lives in the same TU if their share one same module unit.
1779 if (NewM)
1780 NewM = NewM->getTopLevelModule();
1781 if (OldM)
1782 OldM = OldM->getTopLevelModule();
1783 return OldM == NewM;
1784}
1785
1786static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1787 if (D->getDeclContext()->isFileContext())
1788 return false;
1789
1790 return isa<UsingShadowDecl>(Val: D) ||
1791 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1792 isa<UnresolvedUsingValueDecl>(Val: D);
1793}
1794
1795/// Removes using shadow declarations not at class scope from the lookup
1796/// results.
1797static void RemoveUsingDecls(LookupResult &R) {
1798 LookupResult::Filter F = R.makeFilter();
1799 while (F.hasNext())
1800 if (isUsingDeclNotAtClassScope(D: F.next()))
1801 F.erase();
1802
1803 F.done();
1804}
1805
1806/// Check for this common pattern:
1807/// @code
1808/// class S {
1809/// S(const S&); // DO NOT IMPLEMENT
1810/// void operator=(const S&); // DO NOT IMPLEMENT
1811/// };
1812/// @endcode
1813static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1814 // FIXME: Should check for private access too but access is set after we get
1815 // the decl here.
1816 if (D->doesThisDeclarationHaveABody())
1817 return false;
1818
1819 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1820 return CD->isCopyConstructor();
1821 return D->isCopyAssignmentOperator();
1822}
1823
1824bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1825 const DeclContext *DC = D->getDeclContext();
1826 while (!DC->isTranslationUnit()) {
1827 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1828 if (!RD->hasNameForLinkage())
1829 return true;
1830 }
1831 DC = DC->getParent();
1832 }
1833
1834 return !D->isExternallyVisible();
1835}
1836
1837// FIXME: This needs to be refactored; some other isInMainFile users want
1838// these semantics.
1839static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1840 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1841 return false;
1842 return S.SourceMgr.isInMainFile(Loc);
1843}
1844
1845bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1846 assert(D);
1847
1848 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1849 return false;
1850
1851 // Ignore all entities declared within templates, and out-of-line definitions
1852 // of members of class templates.
1853 if (D->getDeclContext()->isDependentContext() ||
1854 D->getLexicalDeclContext()->isDependentContext())
1855 return false;
1856
1857 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1858 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1859 return false;
1860 // A non-out-of-line declaration of a member specialization was implicitly
1861 // instantiated; it's the out-of-line declaration that we're interested in.
1862 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1863 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1864 return false;
1865
1866 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1867 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1868 return false;
1869 } else {
1870 // 'static inline' functions are defined in headers; don't warn.
1871 if (FD->isInlined() && !isMainFileLoc(S: *this, Loc: FD->getLocation()))
1872 return false;
1873 }
1874
1875 if (FD->doesThisDeclarationHaveABody() &&
1876 Context.DeclMustBeEmitted(D: FD))
1877 return false;
1878 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1879 // Constants and utility variables are defined in headers with internal
1880 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1881 // like "inline".)
1882 if (!isMainFileLoc(S: *this, Loc: VD->getLocation()))
1883 return false;
1884
1885 if (Context.DeclMustBeEmitted(D: VD))
1886 return false;
1887
1888 if (VD->isStaticDataMember() &&
1889 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1890 return false;
1891 if (VD->isStaticDataMember() &&
1892 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1893 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1894 return false;
1895
1896 if (VD->isInline() && !isMainFileLoc(S: *this, Loc: VD->getLocation()))
1897 return false;
1898 } else {
1899 return false;
1900 }
1901
1902 // Only warn for unused decls internal to the translation unit.
1903 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1904 // for inline functions defined in the main source file, for instance.
1905 return mightHaveNonExternalLinkage(D);
1906}
1907
1908void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1909 if (!D)
1910 return;
1911
1912 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1913 const FunctionDecl *First = FD->getFirstDecl();
1914 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1915 return; // First should already be in the vector.
1916 }
1917
1918 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1919 const VarDecl *First = VD->getFirstDecl();
1920 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1921 return; // First should already be in the vector.
1922 }
1923
1924 if (ShouldWarnIfUnusedFileScopedDecl(D))
1925 UnusedFileScopedDecls.push_back(LocalValue: D);
1926}
1927
1928static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1929 const NamedDecl *D) {
1930 if (D->isInvalidDecl())
1931 return false;
1932
1933 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
1934 // For a decomposition declaration, warn if none of the bindings are
1935 // referenced, instead of if the variable itself is referenced (which
1936 // it is, by the bindings' expressions).
1937 bool IsAllIgnored = true;
1938 for (const auto *BD : DD->bindings()) {
1939 if (BD->isReferenced())
1940 return false;
1941 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
1942 BD->hasAttr<UnusedAttr>());
1943 }
1944 if (IsAllIgnored)
1945 return false;
1946 } else if (!D->getDeclName()) {
1947 return false;
1948 } else if (D->isReferenced() || D->isUsed()) {
1949 return false;
1950 }
1951
1952 if (D->isPlaceholderVar(LangOpts))
1953 return false;
1954
1955 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1956 D->hasAttr<CleanupAttr>())
1957 return false;
1958
1959 if (isa<LabelDecl>(Val: D))
1960 return true;
1961
1962 // Except for labels, we only care about unused decls that are local to
1963 // functions.
1964 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1965 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
1966 // For dependent types, the diagnostic is deferred.
1967 WithinFunction =
1968 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1969 if (!WithinFunction)
1970 return false;
1971
1972 if (isa<TypedefNameDecl>(Val: D))
1973 return true;
1974
1975 // White-list anything that isn't a local variable.
1976 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
1977 return false;
1978
1979 // Types of valid local variables should be complete, so this should succeed.
1980 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1981
1982 const Expr *Init = VD->getInit();
1983 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
1984 Init = Cleanups->getSubExpr();
1985
1986 const auto *Ty = VD->getType().getTypePtr();
1987
1988 // Only look at the outermost level of typedef.
1989 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1990 // Allow anything marked with __attribute__((unused)).
1991 if (TT->getDecl()->hasAttr<UnusedAttr>())
1992 return false;
1993 }
1994
1995 // Warn for reference variables whose initializtion performs lifetime
1996 // extension.
1997 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
1998 MTE && MTE->getExtendingDecl()) {
1999 Ty = VD->getType().getNonReferenceType().getTypePtr();
2000 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2001 }
2002
2003 // If we failed to complete the type for some reason, or if the type is
2004 // dependent, don't diagnose the variable.
2005 if (Ty->isIncompleteType() || Ty->isDependentType())
2006 return false;
2007
2008 // Look at the element type to ensure that the warning behaviour is
2009 // consistent for both scalars and arrays.
2010 Ty = Ty->getBaseElementTypeUnsafe();
2011
2012 if (const TagType *TT = Ty->getAs<TagType>()) {
2013 const TagDecl *Tag = TT->getDecl();
2014 if (Tag->hasAttr<UnusedAttr>())
2015 return false;
2016
2017 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2018 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2019 return false;
2020
2021 if (Init) {
2022 const auto *Construct =
2023 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2024 if (Construct && !Construct->isElidable()) {
2025 const CXXConstructorDecl *CD = Construct->getConstructor();
2026 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2027 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2028 return false;
2029 }
2030
2031 // Suppress the warning if we don't know how this is constructed, and
2032 // it could possibly be non-trivial constructor.
2033 if (Init->isTypeDependent()) {
2034 for (const CXXConstructorDecl *Ctor : RD->ctors())
2035 if (!Ctor->isTrivial())
2036 return false;
2037 }
2038
2039 // Suppress the warning if the constructor is unresolved because
2040 // its arguments are dependent.
2041 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2042 return false;
2043 }
2044 }
2045 }
2046
2047 // TODO: __attribute__((unused)) templates?
2048 }
2049
2050 return true;
2051}
2052
2053static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2054 FixItHint &Hint) {
2055 if (isa<LabelDecl>(Val: D)) {
2056 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2057 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2058 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2059 if (AfterColon.isInvalid())
2060 return;
2061 Hint = FixItHint::CreateRemoval(
2062 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2063 }
2064}
2065
2066void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2067 DiagnoseUnusedNestedTypedefs(
2068 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2069}
2070
2071void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2072 DiagReceiverTy DiagReceiver) {
2073 if (D->getTypeForDecl()->isDependentType())
2074 return;
2075
2076 for (auto *TmpD : D->decls()) {
2077 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2078 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2079 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2080 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2081 }
2082}
2083
2084void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2085 DiagnoseUnusedDecl(
2086 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2087}
2088
2089void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2090 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2091 return;
2092
2093 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2094 // typedefs can be referenced later on, so the diagnostics are emitted
2095 // at end-of-translation-unit.
2096 UnusedLocalTypedefNameCandidates.insert(X: TD);
2097 return;
2098 }
2099
2100 FixItHint Hint;
2101 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2102
2103 unsigned DiagID;
2104 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2105 DiagID = diag::warn_unused_exception_param;
2106 else if (isa<LabelDecl>(Val: D))
2107 DiagID = diag::warn_unused_label;
2108 else
2109 DiagID = diag::warn_unused_variable;
2110
2111 SourceLocation DiagLoc = D->getLocation();
2112 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2113}
2114
2115void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2116 DiagReceiverTy DiagReceiver) {
2117 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2118 // it's not really unused.
2119 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2120 return;
2121
2122 // In C++, `_` variables behave as if they were maybe_unused
2123 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2124 return;
2125
2126 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2127
2128 if (Ty->isReferenceType() || Ty->isDependentType())
2129 return;
2130
2131 if (const TagType *TT = Ty->getAs<TagType>()) {
2132 const TagDecl *Tag = TT->getDecl();
2133 if (Tag->hasAttr<UnusedAttr>())
2134 return;
2135 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2136 // mimic gcc's behavior.
2137 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2138 RD && !RD->hasAttr<WarnUnusedAttr>())
2139 return;
2140 }
2141
2142 // Don't warn about __block Objective-C pointer variables, as they might
2143 // be assigned in the block but not used elsewhere for the purpose of lifetime
2144 // extension.
2145 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2146 return;
2147
2148 // Don't warn about Objective-C pointer variables with precise lifetime
2149 // semantics; they can be used to ensure ARC releases the object at a known
2150 // time, which may mean assignment but no other references.
2151 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2152 return;
2153
2154 auto iter = RefsMinusAssignments.find(Val: VD);
2155 if (iter == RefsMinusAssignments.end())
2156 return;
2157
2158 assert(iter->getSecond() >= 0 &&
2159 "Found a negative number of references to a VarDecl");
2160 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2161 // Assume the given VarDecl is "used" if its ref count stored in
2162 // `RefMinusAssignments` is positive, with one exception.
2163 //
2164 // For a C++ variable whose decl (with initializer) entirely consist the
2165 // condition expression of a if/while/for construct,
2166 // Clang creates a DeclRefExpr for the condition expression rather than a
2167 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2168 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2169 // used in the body of the if/while/for construct.
2170 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2171 if (!UnusedCXXCondDecl)
2172 return;
2173 }
2174
2175 unsigned DiagID = isa<ParmVarDecl>(Val: VD) ? diag::warn_unused_but_set_parameter
2176 : diag::warn_unused_but_set_variable;
2177 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2178}
2179
2180static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2181 Sema::DiagReceiverTy DiagReceiver) {
2182 // Verify that we have no forward references left. If so, there was a goto
2183 // or address of a label taken, but no definition of it. Label fwd
2184 // definitions are indicated with a null substmt which is also not a resolved
2185 // MS inline assembly label name.
2186 bool Diagnose = false;
2187 if (L->isMSAsmLabel())
2188 Diagnose = !L->isResolvedMSAsmLabel();
2189 else
2190 Diagnose = L->getStmt() == nullptr;
2191 if (Diagnose)
2192 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2193 << L);
2194}
2195
2196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2197 S->applyNRVO();
2198
2199 if (S->decl_empty()) return;
2200 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2201 "Scope shouldn't contain decls!");
2202
2203 /// We visit the decls in non-deterministic order, but we want diagnostics
2204 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2205 /// and sort the diagnostics before emitting them, after we visited all decls.
2206 struct LocAndDiag {
2207 SourceLocation Loc;
2208 std::optional<SourceLocation> PreviousDeclLoc;
2209 PartialDiagnostic PD;
2210 };
2211 SmallVector<LocAndDiag, 16> DeclDiags;
2212 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2213 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2214 };
2215 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2216 SourceLocation PreviousDeclLoc,
2217 PartialDiagnostic PD) {
2218 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2219 };
2220
2221 for (auto *TmpD : S->decls()) {
2222 assert(TmpD && "This decl didn't get pushed??");
2223
2224 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2225 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2226
2227 // Diagnose unused variables in this scope.
2228 if (!S->hasUnrecoverableErrorOccurred()) {
2229 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2230 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2231 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2232 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2233 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2234 RefsMinusAssignments.erase(Val: VD);
2235 }
2236 }
2237
2238 if (!D->getDeclName()) continue;
2239
2240 // If this was a forward reference to a label, verify it was defined.
2241 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2242 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2243
2244 // Partial translation units that are created in incremental processing must
2245 // not clean up the IdResolver because PTUs should take into account the
2246 // declarations that came from previous PTUs.
2247 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2248 getLangOpts().CPlusPlus)
2249 IdResolver.RemoveDecl(D);
2250
2251 // Warn on it if we are shadowing a declaration.
2252 auto ShadowI = ShadowingDecls.find(Val: D);
2253 if (ShadowI != ShadowingDecls.end()) {
2254 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2255 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2256 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2257 << D << FD << FD->getParent());
2258 }
2259 ShadowingDecls.erase(I: ShadowI);
2260 }
2261 }
2262
2263 llvm::sort(C&: DeclDiags,
2264 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2265 // The particular order for diagnostics is not important, as long
2266 // as the order is deterministic. Using the raw location is going
2267 // to generally be in source order unless there are macro
2268 // expansions involved.
2269 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2270 });
2271 for (const LocAndDiag &D : DeclDiags) {
2272 Diag(Loc: D.Loc, PD: D.PD);
2273 if (D.PreviousDeclLoc)
2274 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2275 }
2276}
2277
2278Scope *Sema::getNonFieldDeclScope(Scope *S) {
2279 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2280 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2281 (S->isClassScope() && !getLangOpts().CPlusPlus))
2282 S = S->getParent();
2283 return S;
2284}
2285
2286static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2287 ASTContext::GetBuiltinTypeError Error) {
2288 switch (Error) {
2289 case ASTContext::GE_None:
2290 return "";
2291 case ASTContext::GE_Missing_type:
2292 return BuiltinInfo.getHeaderName(ID);
2293 case ASTContext::GE_Missing_stdio:
2294 return "stdio.h";
2295 case ASTContext::GE_Missing_setjmp:
2296 return "setjmp.h";
2297 case ASTContext::GE_Missing_ucontext:
2298 return "ucontext.h";
2299 }
2300 llvm_unreachable("unhandled error kind");
2301}
2302
2303FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2304 unsigned ID, SourceLocation Loc) {
2305 DeclContext *Parent = Context.getTranslationUnitDecl();
2306
2307 if (getLangOpts().CPlusPlus) {
2308 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2309 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2310 CLinkageDecl->setImplicit();
2311 Parent->addDecl(D: CLinkageDecl);
2312 Parent = CLinkageDecl;
2313 }
2314
2315 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2316 if (Context.BuiltinInfo.isImmediate(ID)) {
2317 assert(getLangOpts().CPlusPlus20 &&
2318 "consteval builtins should only be available in C++20 mode");
2319 ConstexprKind = ConstexprSpecKind::Consteval;
2320 }
2321
2322 FunctionDecl *New = FunctionDecl::Create(
2323 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2324 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2325 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2326 New->setImplicit();
2327 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2328
2329 // Create Decl objects for each parameter, adding them to the
2330 // FunctionDecl.
2331 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2332 SmallVector<ParmVarDecl *, 16> Params;
2333 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2334 ParmVarDecl *parm = ParmVarDecl::Create(
2335 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2336 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2337 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2338 Params.push_back(Elt: parm);
2339 }
2340 New->setParams(Params);
2341 }
2342
2343 AddKnownFunctionAttributes(FD: New);
2344 return New;
2345}
2346
2347NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2348 Scope *S, bool ForRedeclaration,
2349 SourceLocation Loc) {
2350 LookupNecessaryTypesForBuiltin(S, ID);
2351
2352 ASTContext::GetBuiltinTypeError Error;
2353 QualType R = Context.GetBuiltinType(ID, Error);
2354 if (Error) {
2355 if (!ForRedeclaration)
2356 return nullptr;
2357
2358 // If we have a builtin without an associated type we should not emit a
2359 // warning when we were not able to find a type for it.
2360 if (Error == ASTContext::GE_Missing_type ||
2361 Context.BuiltinInfo.allowTypeMismatch(ID))
2362 return nullptr;
2363
2364 // If we could not find a type for setjmp it is because the jmp_buf type was
2365 // not defined prior to the setjmp declaration.
2366 if (Error == ASTContext::GE_Missing_setjmp) {
2367 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2368 << Context.BuiltinInfo.getName(ID);
2369 return nullptr;
2370 }
2371
2372 // Generally, we emit a warning that the declaration requires the
2373 // appropriate header.
2374 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2375 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2376 << Context.BuiltinInfo.getName(ID);
2377 return nullptr;
2378 }
2379
2380 if (!ForRedeclaration &&
2381 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2382 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2383 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2384 : diag::ext_implicit_lib_function_decl)
2385 << Context.BuiltinInfo.getName(ID) << R;
2386 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2387 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2388 << Header << Context.BuiltinInfo.getName(ID);
2389 }
2390
2391 if (R.isNull())
2392 return nullptr;
2393
2394 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2395 RegisterLocallyScopedExternCDecl(ND: New, S);
2396
2397 // TUScope is the translation-unit scope to insert this function into.
2398 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2399 // relate Scopes to DeclContexts, and probably eliminate CurContext
2400 // entirely, but we're not there yet.
2401 DeclContext *SavedContext = CurContext;
2402 CurContext = New->getDeclContext();
2403 PushOnScopeChains(D: New, S: TUScope);
2404 CurContext = SavedContext;
2405 return New;
2406}
2407
2408/// Typedef declarations don't have linkage, but they still denote the same
2409/// entity if their types are the same.
2410/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2411/// isSameEntity.
2412static void
2413filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2414 LookupResult &Previous) {
2415 // This is only interesting when modules are enabled.
2416 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2417 return;
2418
2419 // Empty sets are uninteresting.
2420 if (Previous.empty())
2421 return;
2422
2423 LookupResult::Filter Filter = Previous.makeFilter();
2424 while (Filter.hasNext()) {
2425 NamedDecl *Old = Filter.next();
2426
2427 // Non-hidden declarations are never ignored.
2428 if (S.isVisible(D: Old))
2429 continue;
2430
2431 // Declarations of the same entity are not ignored, even if they have
2432 // different linkages.
2433 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2434 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2435 T2: Decl->getUnderlyingType()))
2436 continue;
2437
2438 // If both declarations give a tag declaration a typedef name for linkage
2439 // purposes, then they declare the same entity.
2440 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2441 Decl->getAnonDeclWithTypedefName())
2442 continue;
2443 }
2444
2445 Filter.erase();
2446 }
2447
2448 Filter.done();
2449}
2450
2451bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2452 QualType OldType;
2453 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2454 OldType = OldTypedef->getUnderlyingType();
2455 else
2456 OldType = Context.getTypeDeclType(Decl: Old);
2457 QualType NewType = New->getUnderlyingType();
2458
2459 if (NewType->isVariablyModifiedType()) {
2460 // Must not redefine a typedef with a variably-modified type.
2461 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2462 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2463 << Kind << NewType;
2464 if (Old->getLocation().isValid())
2465 notePreviousDefinition(Old, New: New->getLocation());
2466 New->setInvalidDecl();
2467 return true;
2468 }
2469
2470 if (OldType != NewType &&
2471 !OldType->isDependentType() &&
2472 !NewType->isDependentType() &&
2473 !Context.hasSameType(T1: OldType, T2: NewType)) {
2474 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2475 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2476 << Kind << NewType << OldType;
2477 if (Old->getLocation().isValid())
2478 notePreviousDefinition(Old, New: New->getLocation());
2479 New->setInvalidDecl();
2480 return true;
2481 }
2482 return false;
2483}
2484
2485void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2486 LookupResult &OldDecls) {
2487 // If the new decl is known invalid already, don't bother doing any
2488 // merging checks.
2489 if (New->isInvalidDecl()) return;
2490
2491 // Allow multiple definitions for ObjC built-in typedefs.
2492 // FIXME: Verify the underlying types are equivalent!
2493 if (getLangOpts().ObjC) {
2494 const IdentifierInfo *TypeID = New->getIdentifier();
2495 switch (TypeID->getLength()) {
2496 default: break;
2497 case 2:
2498 {
2499 if (!TypeID->isStr(Str: "id"))
2500 break;
2501 QualType T = New->getUnderlyingType();
2502 if (!T->isPointerType())
2503 break;
2504 if (!T->isVoidPointerType()) {
2505 QualType PT = T->castAs<PointerType>()->getPointeeType();
2506 if (!PT->isStructureType())
2507 break;
2508 }
2509 Context.setObjCIdRedefinitionType(T);
2510 // Install the built-in type for 'id', ignoring the current definition.
2511 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2512 return;
2513 }
2514 case 5:
2515 if (!TypeID->isStr(Str: "Class"))
2516 break;
2517 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2518 // Install the built-in type for 'Class', ignoring the current definition.
2519 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2520 return;
2521 case 3:
2522 if (!TypeID->isStr(Str: "SEL"))
2523 break;
2524 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2525 // Install the built-in type for 'SEL', ignoring the current definition.
2526 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2527 return;
2528 }
2529 // Fall through - the typedef name was not a builtin type.
2530 }
2531
2532 // Verify the old decl was also a type.
2533 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2534 if (!Old) {
2535 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2536 << New->getDeclName();
2537
2538 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2539 if (OldD->getLocation().isValid())
2540 notePreviousDefinition(Old: OldD, New: New->getLocation());
2541
2542 return New->setInvalidDecl();
2543 }
2544
2545 // If the old declaration is invalid, just give up here.
2546 if (Old->isInvalidDecl())
2547 return New->setInvalidDecl();
2548
2549 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2550 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2551 auto *NewTag = New->getAnonDeclWithTypedefName();
2552 NamedDecl *Hidden = nullptr;
2553 if (OldTag && NewTag &&
2554 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2555 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2556 // There is a definition of this tag, but it is not visible. Use it
2557 // instead of our tag.
2558 New->setTypeForDecl(OldTD->getTypeForDecl());
2559 if (OldTD->isModed())
2560 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2561 modedTy: OldTD->getUnderlyingType());
2562 else
2563 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2564
2565 // Make the old tag definition visible.
2566 makeMergedDefinitionVisible(ND: Hidden);
2567
2568 CleanupMergedEnum(S, New: NewTag);
2569 }
2570 }
2571
2572 // If the typedef types are not identical, reject them in all languages and
2573 // with any extensions enabled.
2574 if (isIncompatibleTypedef(Old, New))
2575 return;
2576
2577 // The types match. Link up the redeclaration chain and merge attributes if
2578 // the old declaration was a typedef.
2579 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2580 New->setPreviousDecl(Typedef);
2581 mergeDeclAttributes(New, Old);
2582 }
2583
2584 if (getLangOpts().MicrosoftExt)
2585 return;
2586
2587 if (getLangOpts().CPlusPlus) {
2588 // C++ [dcl.typedef]p2:
2589 // In a given non-class scope, a typedef specifier can be used to
2590 // redefine the name of any type declared in that scope to refer
2591 // to the type to which it already refers.
2592 if (!isa<CXXRecordDecl>(Val: CurContext))
2593 return;
2594
2595 // C++0x [dcl.typedef]p4:
2596 // In a given class scope, a typedef specifier can be used to redefine
2597 // any class-name declared in that scope that is not also a typedef-name
2598 // to refer to the type to which it already refers.
2599 //
2600 // This wording came in via DR424, which was a correction to the
2601 // wording in DR56, which accidentally banned code like:
2602 //
2603 // struct S {
2604 // typedef struct A { } A;
2605 // };
2606 //
2607 // in the C++03 standard. We implement the C++0x semantics, which
2608 // allow the above but disallow
2609 //
2610 // struct S {
2611 // typedef int I;
2612 // typedef int I;
2613 // };
2614 //
2615 // since that was the intent of DR56.
2616 if (!isa<TypedefNameDecl>(Val: Old))
2617 return;
2618
2619 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2620 << New->getDeclName();
2621 notePreviousDefinition(Old, New: New->getLocation());
2622 return New->setInvalidDecl();
2623 }
2624
2625 // Modules always permit redefinition of typedefs, as does C11.
2626 if (getLangOpts().Modules || getLangOpts().C11)
2627 return;
2628
2629 // If we have a redefinition of a typedef in C, emit a warning. This warning
2630 // is normally mapped to an error, but can be controlled with
2631 // -Wtypedef-redefinition. If either the original or the redefinition is
2632 // in a system header, don't emit this for compatibility with GCC.
2633 if (getDiagnostics().getSuppressSystemWarnings() &&
2634 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2635 (Old->isImplicit() ||
2636 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2637 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2638 return;
2639
2640 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2641 << New->getDeclName();
2642 notePreviousDefinition(Old, New: New->getLocation());
2643}
2644
2645void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2646 // If this was an unscoped enumeration, yank all of its enumerators
2647 // out of the scope.
2648 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2649 Scope *EnumScope = getNonFieldDeclScope(S);
2650 for (auto *ECD : ED->enumerators()) {
2651 assert(EnumScope->isDeclScope(ECD));
2652 EnumScope->RemoveDecl(D: ECD);
2653 IdResolver.RemoveDecl(D: ECD);
2654 }
2655 }
2656}
2657
2658/// DeclhasAttr - returns true if decl Declaration already has the target
2659/// attribute.
2660static bool DeclHasAttr(const Decl *D, const Attr *A) {
2661 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2662 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2663 for (const auto *i : D->attrs())
2664 if (i->getKind() == A->getKind()) {
2665 if (Ann) {
2666 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2667 return true;
2668 continue;
2669 }
2670 // FIXME: Don't hardcode this check
2671 if (OA && isa<OwnershipAttr>(Val: i))
2672 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2673 return true;
2674 }
2675
2676 return false;
2677}
2678
2679static bool isAttributeTargetADefinition(Decl *D) {
2680 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2681 return VD->isThisDeclarationADefinition();
2682 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2683 return TD->isCompleteDefinition() || TD->isBeingDefined();
2684 return true;
2685}
2686
2687/// Merge alignment attributes from \p Old to \p New, taking into account the
2688/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2689///
2690/// \return \c true if any attributes were added to \p New.
2691static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2692 // Look for alignas attributes on Old, and pick out whichever attribute
2693 // specifies the strictest alignment requirement.
2694 AlignedAttr *OldAlignasAttr = nullptr;
2695 AlignedAttr *OldStrictestAlignAttr = nullptr;
2696 unsigned OldAlign = 0;
2697 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2698 // FIXME: We have no way of representing inherited dependent alignments
2699 // in a case like:
2700 // template<int A, int B> struct alignas(A) X;
2701 // template<int A, int B> struct alignas(B) X {};
2702 // For now, we just ignore any alignas attributes which are not on the
2703 // definition in such a case.
2704 if (I->isAlignmentDependent())
2705 return false;
2706
2707 if (I->isAlignas())
2708 OldAlignasAttr = I;
2709
2710 unsigned Align = I->getAlignment(Ctx&: S.Context);
2711 if (Align > OldAlign) {
2712 OldAlign = Align;
2713 OldStrictestAlignAttr = I;
2714 }
2715 }
2716
2717 // Look for alignas attributes on New.
2718 AlignedAttr *NewAlignasAttr = nullptr;
2719 unsigned NewAlign = 0;
2720 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2721 if (I->isAlignmentDependent())
2722 return false;
2723
2724 if (I->isAlignas())
2725 NewAlignasAttr = I;
2726
2727 unsigned Align = I->getAlignment(Ctx&: S.Context);
2728 if (Align > NewAlign)
2729 NewAlign = Align;
2730 }
2731
2732 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2733 // Both declarations have 'alignas' attributes. We require them to match.
2734 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2735 // fall short. (If two declarations both have alignas, they must both match
2736 // every definition, and so must match each other if there is a definition.)
2737
2738 // If either declaration only contains 'alignas(0)' specifiers, then it
2739 // specifies the natural alignment for the type.
2740 if (OldAlign == 0 || NewAlign == 0) {
2741 QualType Ty;
2742 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2743 Ty = VD->getType();
2744 else
2745 Ty = S.Context.getTagDeclType(Decl: cast<TagDecl>(Val: New));
2746
2747 if (OldAlign == 0)
2748 OldAlign = S.Context.getTypeAlign(T: Ty);
2749 if (NewAlign == 0)
2750 NewAlign = S.Context.getTypeAlign(T: Ty);
2751 }
2752
2753 if (OldAlign != NewAlign) {
2754 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2755 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2756 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2757 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2758 }
2759 }
2760
2761 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2762 // C++11 [dcl.align]p6:
2763 // if any declaration of an entity has an alignment-specifier,
2764 // every defining declaration of that entity shall specify an
2765 // equivalent alignment.
2766 // C11 6.7.5/7:
2767 // If the definition of an object does not have an alignment
2768 // specifier, any other declaration of that object shall also
2769 // have no alignment specifier.
2770 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2771 << OldAlignasAttr;
2772 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2773 << OldAlignasAttr;
2774 }
2775
2776 bool AnyAdded = false;
2777
2778 // Ensure we have an attribute representing the strictest alignment.
2779 if (OldAlign > NewAlign) {
2780 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2781 Clone->setInherited(true);
2782 New->addAttr(A: Clone);
2783 AnyAdded = true;
2784 }
2785
2786 // Ensure we have an alignas attribute if the old declaration had one.
2787 if (OldAlignasAttr && !NewAlignasAttr &&
2788 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2789 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2790 Clone->setInherited(true);
2791 New->addAttr(A: Clone);
2792 AnyAdded = true;
2793 }
2794
2795 return AnyAdded;
2796}
2797
2798#define WANT_DECL_MERGE_LOGIC
2799#include "clang/Sema/AttrParsedAttrImpl.inc"
2800#undef WANT_DECL_MERGE_LOGIC
2801
2802static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2803 const InheritableAttr *Attr,
2804 AvailabilityMergeKind AMK) {
2805 // Diagnose any mutual exclusions between the attribute that we want to add
2806 // and attributes that already exist on the declaration.
2807 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2808 return false;
2809
2810 // This function copies an attribute Attr from a previous declaration to the
2811 // new declaration D if the new declaration doesn't itself have that attribute
2812 // yet or if that attribute allows duplicates.
2813 // If you're adding a new attribute that requires logic different from
2814 // "use explicit attribute on decl if present, else use attribute from
2815 // previous decl", for example if the attribute needs to be consistent
2816 // between redeclarations, you need to call a custom merge function here.
2817 InheritableAttr *NewAttr = nullptr;
2818 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr))
2819 NewAttr = S.mergeAvailabilityAttr(
2820 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2821 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2822 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2823 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment());
2824 else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2825 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2826 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2827 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2828 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2829 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2830 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2831 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2832 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2833 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2834 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2835 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2836 FirstArg: FA->getFirstArg());
2837 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2838 NewAttr = S.mergeFormatMatchesAttr(
2839 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2840 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2841 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2842 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2843 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2844 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2845 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2846 Model: IA->getInheritanceModel());
2847 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2848 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2849 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2850 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2851 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2852 isa<CUDAGlobalAttr>(Val: Attr))) {
2853 // CUDA target attributes are part of function signature for
2854 // overloading purposes and must not be merged.
2855 return false;
2856 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2857 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2858 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2859 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2860 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2861 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2862 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2863 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2864 else if (isa<AlignedAttr>(Val: Attr))
2865 // AlignedAttrs are handled separately, because we need to handle all
2866 // such attributes on a declaration at the same time.
2867 NewAttr = nullptr;
2868 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2869 (AMK == AvailabilityMergeKind::Override ||
2870 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2871 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2872 NewAttr = nullptr;
2873 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2874 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2875 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2876 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2877 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2878 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2879 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2880 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2881 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2882 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2883 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2884 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2885 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2886 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2887 Z: NT->getZ());
2888 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
2889 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
2890 Preferred: WS->getPreferred(),
2891 SpelledArgsCount: WS->getSpelledArgsCount());
2892 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
2893 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
2894 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
2895 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
2896 else if (isa<SuppressAttr>(Val: Attr))
2897 // Do nothing. Each redeclaration should be suppressed separately.
2898 NewAttr = nullptr;
2899 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
2900 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
2901 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
2902 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
2903
2904 if (NewAttr) {
2905 NewAttr->setInherited(true);
2906 D->addAttr(A: NewAttr);
2907 if (isa<MSInheritanceAttr>(Val: NewAttr))
2908 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
2909 return true;
2910 }
2911
2912 return false;
2913}
2914
2915static const NamedDecl *getDefinition(const Decl *D) {
2916 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2917 return TD->getDefinition();
2918 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2919 const VarDecl *Def = VD->getDefinition();
2920 if (Def)
2921 return Def;
2922 return VD->getActingDefinition();
2923 }
2924 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2925 const FunctionDecl *Def = nullptr;
2926 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
2927 return Def;
2928 }
2929 return nullptr;
2930}
2931
2932static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2933 for (const auto *Attribute : D->attrs())
2934 if (Attribute->getKind() == Kind)
2935 return true;
2936 return false;
2937}
2938
2939/// checkNewAttributesAfterDef - If we already have a definition, check that
2940/// there are no new attributes in this declaration.
2941static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2942 if (!New->hasAttrs())
2943 return;
2944
2945 const NamedDecl *Def = getDefinition(D: Old);
2946 if (!Def || Def == New)
2947 return;
2948
2949 AttrVec &NewAttributes = New->getAttrs();
2950 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2951 Attr *NewAttribute = NewAttributes[I];
2952
2953 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
2954 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
2955 SkipBodyInfo SkipBody;
2956 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
2957
2958 // If we're skipping this definition, drop the "alias" attribute.
2959 if (SkipBody.ShouldSkip) {
2960 NewAttributes.erase(CI: NewAttributes.begin() + I);
2961 --E;
2962 continue;
2963 }
2964 } else {
2965 VarDecl *VD = cast<VarDecl>(Val: New);
2966 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
2967 VarDecl::TentativeDefinition
2968 ? diag::err_alias_after_tentative
2969 : diag::err_redefinition;
2970 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
2971 if (Diag == diag::err_redefinition)
2972 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
2973 else
2974 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2975 VD->setInvalidDecl();
2976 }
2977 ++I;
2978 continue;
2979 }
2980
2981 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
2982 // Tentative definitions are only interesting for the alias check above.
2983 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2984 ++I;
2985 continue;
2986 }
2987 }
2988
2989 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
2990 ++I;
2991 continue; // regular attr merging will take care of validating this.
2992 }
2993
2994 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
2995 // C's _Noreturn is allowed to be added to a function after it is defined.
2996 ++I;
2997 continue;
2998 } else if (isa<UuidAttr>(Val: NewAttribute)) {
2999 // msvc will allow a subsequent definition to add an uuid to a class
3000 ++I;
3001 continue;
3002 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3003 Val: NewAttribute) &&
3004 NewAttribute->isStandardAttributeSyntax()) {
3005 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3006 // deprecated attribute can later be re-declared with the attribute and
3007 // vice-versa.
3008 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3009 // maybe_unused attribute can later be redeclared with the attribute and
3010 // vice versa.
3011 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3012 // nodiscard attribute can later be redeclared with the attribute and
3013 // vice-versa.
3014 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3015 ++I;
3016 continue;
3017 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3018 if (AA->isAlignas()) {
3019 // C++11 [dcl.align]p6:
3020 // if any declaration of an entity has an alignment-specifier,
3021 // every defining declaration of that entity shall specify an
3022 // equivalent alignment.
3023 // C11 6.7.5/7:
3024 // If the definition of an object does not have an alignment
3025 // specifier, any other declaration of that object shall also
3026 // have no alignment specifier.
3027 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3028 << AA;
3029 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3030 << AA;
3031 NewAttributes.erase(CI: NewAttributes.begin() + I);
3032 --E;
3033 continue;
3034 }
3035 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3036 // If there is a C definition followed by a redeclaration with this
3037 // attribute then there are two different definitions. In C++, prefer the
3038 // standard diagnostics.
3039 if (!S.getLangOpts().CPlusPlus) {
3040 S.Diag(Loc: NewAttribute->getLocation(),
3041 DiagID: diag::err_loader_uninitialized_redeclaration);
3042 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3043 NewAttributes.erase(CI: NewAttributes.begin() + I);
3044 --E;
3045 continue;
3046 }
3047 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3048 cast<VarDecl>(Val: New)->isInline() &&
3049 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3050 // Don't warn about applying selectany to implicitly inline variables.
3051 // Older compilers and language modes would require the use of selectany
3052 // to make such variables inline, and it would have no effect if we
3053 // honored it.
3054 ++I;
3055 continue;
3056 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3057 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3058 // declarations after definitions.
3059 ++I;
3060 continue;
3061 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3062 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3063 // error since the definition will have already been created without
3064 // the semantic effects of the attribute having been applied.
3065 S.Diag(Loc: NewAttribute->getLocation(),
3066 DiagID: diag::err_sycl_entry_point_after_definition);
3067 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3068 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3069 ++I;
3070 continue;
3071 }
3072
3073 S.Diag(Loc: NewAttribute->getLocation(),
3074 DiagID: diag::warn_attribute_precede_definition);
3075 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3076 NewAttributes.erase(CI: NewAttributes.begin() + I);
3077 --E;
3078 }
3079}
3080
3081static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3082 const ConstInitAttr *CIAttr,
3083 bool AttrBeforeInit) {
3084 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3085
3086 // Figure out a good way to write this specifier on the old declaration.
3087 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3088 // enough of the attribute list spelling information to extract that without
3089 // heroics.
3090 std::string SuitableSpelling;
3091 if (S.getLangOpts().CPlusPlus20)
3092 SuitableSpelling = std::string(
3093 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3094 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3095 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3096 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3097 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3098 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3099 tok::r_square, tok::r_square}));
3100 if (SuitableSpelling.empty())
3101 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3102 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3103 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3104 tok::r_paren, tok::r_paren}));
3105 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3106 SuitableSpelling = "constinit";
3107 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3108 SuitableSpelling = "[[clang::require_constant_initialization]]";
3109 if (SuitableSpelling.empty())
3110 SuitableSpelling = "__attribute__((require_constant_initialization))";
3111 SuitableSpelling += " ";
3112
3113 if (AttrBeforeInit) {
3114 // extern constinit int a;
3115 // int a = 0; // error (missing 'constinit'), accepted as extension
3116 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3117 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3118 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3119 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3120 } else {
3121 // int a = 0;
3122 // constinit extern int a; // error (missing 'constinit')
3123 S.Diag(Loc: CIAttr->getLocation(),
3124 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3125 : diag::warn_require_const_init_added_too_late)
3126 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3127 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3128 << CIAttr->isConstinit()
3129 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3130 }
3131}
3132
3133void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3134 AvailabilityMergeKind AMK) {
3135 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3136 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3137 NewAttr->setInherited(true);
3138 New->addAttr(A: NewAttr);
3139 }
3140 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3141 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3142 NewAttr->setInherited(true);
3143 New->addAttr(A: NewAttr);
3144 }
3145
3146 if (!Old->hasAttrs() && !New->hasAttrs())
3147 return;
3148
3149 // [dcl.constinit]p1:
3150 // If the [constinit] specifier is applied to any declaration of a
3151 // variable, it shall be applied to the initializing declaration.
3152 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3153 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3154 if (bool(OldConstInit) != bool(NewConstInit)) {
3155 const auto *OldVD = cast<VarDecl>(Val: Old);
3156 auto *NewVD = cast<VarDecl>(Val: New);
3157
3158 // Find the initializing declaration. Note that we might not have linked
3159 // the new declaration into the redeclaration chain yet.
3160 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3161 if (!InitDecl &&
3162 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3163 InitDecl = NewVD;
3164
3165 if (InitDecl == NewVD) {
3166 // This is the initializing declaration. If it would inherit 'constinit',
3167 // that's ill-formed. (Note that we do not apply this to the attribute
3168 // form).
3169 if (OldConstInit && OldConstInit->isConstinit())
3170 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3171 /*AttrBeforeInit=*/true);
3172 } else if (NewConstInit) {
3173 // This is the first time we've been told that this declaration should
3174 // have a constant initializer. If we already saw the initializing
3175 // declaration, this is too late.
3176 if (InitDecl && InitDecl != NewVD) {
3177 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3178 /*AttrBeforeInit=*/false);
3179 NewVD->dropAttr<ConstInitAttr>();
3180 }
3181 }
3182 }
3183
3184 // Attributes declared post-definition are currently ignored.
3185 checkNewAttributesAfterDef(S&: *this, New, Old);
3186
3187 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3188 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3189 if (!OldA->isEquivalent(Other: NewA)) {
3190 // This redeclaration changes __asm__ label.
3191 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3192 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3193 }
3194 } else if (Old->isUsed()) {
3195 // This redeclaration adds an __asm__ label to a declaration that has
3196 // already been ODR-used.
3197 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3198 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3199 }
3200 }
3201
3202 // Re-declaration cannot add abi_tag's.
3203 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3204 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3205 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3206 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3207 Diag(Loc: NewAbiTagAttr->getLocation(),
3208 DiagID: diag::err_new_abi_tag_on_redeclaration)
3209 << NewTag;
3210 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3211 }
3212 }
3213 } else {
3214 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3215 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3216 }
3217 }
3218
3219 // This redeclaration adds a section attribute.
3220 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3221 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3222 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3223 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3224 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3225 }
3226 }
3227 }
3228
3229 // Redeclaration adds code-seg attribute.
3230 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3231 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3232 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3233 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3234 << 0 /*codeseg*/;
3235 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3236 }
3237
3238 if (!Old->hasAttrs())
3239 return;
3240
3241 bool foundAny = New->hasAttrs();
3242
3243 // Ensure that any moving of objects within the allocated map is done before
3244 // we process them.
3245 if (!foundAny) New->setAttrs(AttrVec());
3246
3247 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3248 // Ignore deprecated/unavailable/availability attributes if requested.
3249 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3250 if (isa<DeprecatedAttr>(Val: I) ||
3251 isa<UnavailableAttr>(Val: I) ||
3252 isa<AvailabilityAttr>(Val: I)) {
3253 switch (AMK) {
3254 case AvailabilityMergeKind::None:
3255 continue;
3256
3257 case AvailabilityMergeKind::Redeclaration:
3258 case AvailabilityMergeKind::Override:
3259 case AvailabilityMergeKind::ProtocolImplementation:
3260 case AvailabilityMergeKind::OptionalProtocolImplementation:
3261 LocalAMK = AMK;
3262 break;
3263 }
3264 }
3265
3266 // Already handled.
3267 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3268 continue;
3269
3270 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3271 foundAny = true;
3272 }
3273
3274 if (mergeAlignedAttrs(S&: *this, New, Old))
3275 foundAny = true;
3276
3277 if (!foundAny) New->dropAttrs();
3278}
3279
3280// Returns the number of added attributes.
3281template <class T>
3282static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3283 Sema &S) {
3284 unsigned found = 0;
3285 for (const auto *I : From->specific_attrs<T>()) {
3286 if (!DeclHasAttr(To, I)) {
3287 T *newAttr = cast<T>(I->clone(S.Context));
3288 newAttr->setInherited(true);
3289 To->addAttr(A: newAttr);
3290 ++found;
3291 }
3292 }
3293 return found;
3294}
3295
3296template <class F>
3297static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3298 F &&propagator) {
3299 if (!From->hasAttrs()) {
3300 return;
3301 }
3302
3303 bool foundAny = To->hasAttrs();
3304
3305 // Ensure that any moving of objects within the allocated map is
3306 // done before we process them.
3307 if (!foundAny)
3308 To->setAttrs(AttrVec());
3309
3310 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3311
3312 if (!foundAny)
3313 To->dropAttrs();
3314}
3315
3316/// mergeParamDeclAttributes - Copy attributes from the old parameter
3317/// to the new one.
3318static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3319 const ParmVarDecl *oldDecl,
3320 Sema &S) {
3321 // C++11 [dcl.attr.depend]p2:
3322 // The first declaration of a function shall specify the
3323 // carries_dependency attribute for its declarator-id if any declaration
3324 // of the function specifies the carries_dependency attribute.
3325 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3326 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3327 S.Diag(Loc: CDA->getLocation(),
3328 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3329 // Find the first declaration of the parameter.
3330 // FIXME: Should we build redeclaration chains for function parameters?
3331 const FunctionDecl *FirstFD =
3332 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3333 const ParmVarDecl *FirstVD =
3334 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3335 S.Diag(Loc: FirstVD->getLocation(),
3336 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3337 }
3338
3339 propagateAttributes(
3340 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3341 unsigned found = 0;
3342 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3343 // Propagate the lifetimebound attribute from parameters to the
3344 // most recent declaration. Note that this doesn't include the implicit
3345 // 'this' parameter, as the attribute is applied to the function type in
3346 // that case.
3347 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3348 return found;
3349 });
3350}
3351
3352static bool EquivalentArrayTypes(QualType Old, QualType New,
3353 const ASTContext &Ctx) {
3354
3355 auto NoSizeInfo = [&Ctx](QualType Ty) {
3356 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3357 return true;
3358 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3359 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3360 return false;
3361 };
3362
3363 // `type[]` is equivalent to `type *` and `type[*]`.
3364 if (NoSizeInfo(Old) && NoSizeInfo(New))
3365 return true;
3366
3367 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3368 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3369 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3370 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3371 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3372 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3373 return false;
3374 return true;
3375 }
3376
3377 // Only compare size, ignore Size modifiers and CVR.
3378 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3379 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3380 Ctx.getAsConstantArrayType(T: New)->getSize();
3381 }
3382
3383 // Don't try to compare dependent sized array
3384 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3385 return true;
3386 }
3387
3388 return Old == New;
3389}
3390
3391static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3392 const ParmVarDecl *OldParam,
3393 Sema &S) {
3394 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3395 if (auto Newnullability = NewParam->getType()->getNullability()) {
3396 if (*Oldnullability != *Newnullability) {
3397 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3398 << DiagNullabilityKind(
3399 *Newnullability,
3400 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3401 != 0))
3402 << DiagNullabilityKind(
3403 *Oldnullability,
3404 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3405 != 0));
3406 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3407 }
3408 } else {
3409 QualType NewT = NewParam->getType();
3410 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3411 NewParam->setType(NewT);
3412 }
3413 }
3414 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3415 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3416 if (OldParamDT && NewParamDT &&
3417 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3418 QualType OldParamOT = OldParamDT->getOriginalType();
3419 QualType NewParamOT = NewParamDT->getOriginalType();
3420 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3421 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3422 << NewParam << NewParamOT;
3423 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3424 << OldParamOT;
3425 }
3426 }
3427}
3428
3429namespace {
3430
3431/// Used in MergeFunctionDecl to keep track of function parameters in
3432/// C.
3433struct GNUCompatibleParamWarning {
3434 ParmVarDecl *OldParm;
3435 ParmVarDecl *NewParm;
3436 QualType PromotedType;
3437};
3438
3439} // end anonymous namespace
3440
3441// Determine whether the previous declaration was a definition, implicit
3442// declaration, or a declaration.
3443template <typename T>
3444static std::pair<diag::kind, SourceLocation>
3445getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3446 diag::kind PrevDiag;
3447 SourceLocation OldLocation = Old->getLocation();
3448 if (Old->isThisDeclarationADefinition())
3449 PrevDiag = diag::note_previous_definition;
3450 else if (Old->isImplicit()) {
3451 PrevDiag = diag::note_previous_implicit_declaration;
3452 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3453 if (FD->getBuiltinID())
3454 PrevDiag = diag::note_previous_builtin_declaration;
3455 }
3456 if (OldLocation.isInvalid())
3457 OldLocation = New->getLocation();
3458 } else
3459 PrevDiag = diag::note_previous_declaration;
3460 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3461}
3462
3463/// canRedefineFunction - checks if a function can be redefined. Currently,
3464/// only extern inline functions can be redefined, and even then only in
3465/// GNU89 mode.
3466static bool canRedefineFunction(const FunctionDecl *FD,
3467 const LangOptions& LangOpts) {
3468 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3469 !LangOpts.CPlusPlus &&
3470 FD->isInlineSpecified() &&
3471 FD->getStorageClass() == SC_Extern);
3472}
3473
3474const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3475 const AttributedType *AT = T->getAs<AttributedType>();
3476 while (AT && !AT->isCallingConv())
3477 AT = AT->getModifiedType()->getAs<AttributedType>();
3478 return AT;
3479}
3480
3481template <typename T>
3482static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3483 const DeclContext *DC = Old->getDeclContext();
3484 if (DC->isRecord())
3485 return false;
3486
3487 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3488 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3489 return true;
3490 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3491 return true;
3492 return false;
3493}
3494
3495template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3496static bool isExternC(VarTemplateDecl *) { return false; }
3497static bool isExternC(FunctionTemplateDecl *) { return false; }
3498
3499/// Check whether a redeclaration of an entity introduced by a
3500/// using-declaration is valid, given that we know it's not an overload
3501/// (nor a hidden tag declaration).
3502template<typename ExpectedDecl>
3503static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3504 ExpectedDecl *New) {
3505 // C++11 [basic.scope.declarative]p4:
3506 // Given a set of declarations in a single declarative region, each of
3507 // which specifies the same unqualified name,
3508 // -- they shall all refer to the same entity, or all refer to functions
3509 // and function templates; or
3510 // -- exactly one declaration shall declare a class name or enumeration
3511 // name that is not a typedef name and the other declarations shall all
3512 // refer to the same variable or enumerator, or all refer to functions
3513 // and function templates; in this case the class name or enumeration
3514 // name is hidden (3.3.10).
3515
3516 // C++11 [namespace.udecl]p14:
3517 // If a function declaration in namespace scope or block scope has the
3518 // same name and the same parameter-type-list as a function introduced
3519 // by a using-declaration, and the declarations do not declare the same
3520 // function, the program is ill-formed.
3521
3522 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3523 if (Old &&
3524 !Old->getDeclContext()->getRedeclContext()->Equals(
3525 New->getDeclContext()->getRedeclContext()) &&
3526 !(isExternC(Old) && isExternC(New)))
3527 Old = nullptr;
3528
3529 if (!Old) {
3530 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3531 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3532 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3533 return true;
3534 }
3535 return false;
3536}
3537
3538static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3539 const FunctionDecl *B) {
3540 assert(A->getNumParams() == B->getNumParams());
3541
3542 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3543 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3544 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3545 if (AttrA == AttrB)
3546 return true;
3547 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3548 AttrA->isDynamic() == AttrB->isDynamic();
3549 };
3550
3551 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3552}
3553
3554/// If necessary, adjust the semantic declaration context for a qualified
3555/// declaration to name the correct inline namespace within the qualifier.
3556static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3557 DeclaratorDecl *OldD) {
3558 // The only case where we need to update the DeclContext is when
3559 // redeclaration lookup for a qualified name finds a declaration
3560 // in an inline namespace within the context named by the qualifier:
3561 //
3562 // inline namespace N { int f(); }
3563 // int ::f(); // Sema DC needs adjusting from :: to N::.
3564 //
3565 // For unqualified declarations, the semantic context *can* change
3566 // along the redeclaration chain (for local extern declarations,
3567 // extern "C" declarations, and friend declarations in particular).
3568 if (!NewD->getQualifier())
3569 return;
3570
3571 // NewD is probably already in the right context.
3572 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3573 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3574 if (NamedDC->Equals(DC: SemaDC))
3575 return;
3576
3577 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3578 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3579 "unexpected context for redeclaration");
3580
3581 auto *LexDC = NewD->getLexicalDeclContext();
3582 auto FixSemaDC = [=](NamedDecl *D) {
3583 if (!D)
3584 return;
3585 D->setDeclContext(SemaDC);
3586 D->setLexicalDeclContext(LexDC);
3587 };
3588
3589 FixSemaDC(NewD);
3590 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3591 FixSemaDC(FD->getDescribedFunctionTemplate());
3592 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3593 FixSemaDC(VD->getDescribedVarTemplate());
3594}
3595
3596bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3597 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3598 // Verify the old decl was also a function.
3599 FunctionDecl *Old = OldD->getAsFunction();
3600 if (!Old) {
3601 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3602 if (New->getFriendObjectKind()) {
3603 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3604 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3605 DiagID: diag::note_using_decl_target);
3606 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3607 << 0;
3608 return true;
3609 }
3610
3611 // Check whether the two declarations might declare the same function or
3612 // function template.
3613 if (FunctionTemplateDecl *NewTemplate =
3614 New->getDescribedFunctionTemplate()) {
3615 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3616 New: NewTemplate))
3617 return true;
3618 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3619 ->getAsFunction();
3620 } else {
3621 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3622 return true;
3623 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3624 }
3625 } else {
3626 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3627 << New->getDeclName();
3628 notePreviousDefinition(Old: OldD, New: New->getLocation());
3629 return true;
3630 }
3631 }
3632
3633 // If the old declaration was found in an inline namespace and the new
3634 // declaration was qualified, update the DeclContext to match.
3635 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3636
3637 // If the old declaration is invalid, just give up here.
3638 if (Old->isInvalidDecl())
3639 return true;
3640
3641 // Disallow redeclaration of some builtins.
3642 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3643 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3644 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3645 << Old << Old->getType();
3646 return true;
3647 }
3648
3649 diag::kind PrevDiag;
3650 SourceLocation OldLocation;
3651 std::tie(args&: PrevDiag, args&: OldLocation) =
3652 getNoteDiagForInvalidRedeclaration(Old, New);
3653
3654 // Don't complain about this if we're in GNU89 mode and the old function
3655 // is an extern inline function.
3656 // Don't complain about specializations. They are not supposed to have
3657 // storage classes.
3658 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3659 New->getStorageClass() == SC_Static &&
3660 Old->hasExternalFormalLinkage() &&
3661 !New->getTemplateSpecializationInfo() &&
3662 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3663 if (getLangOpts().MicrosoftExt) {
3664 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3665 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3666 } else {
3667 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3668 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3669 return true;
3670 }
3671 }
3672
3673 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3674 if (!Old->hasAttr<InternalLinkageAttr>()) {
3675 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3676 << ILA;
3677 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3678 New->dropAttr<InternalLinkageAttr>();
3679 }
3680
3681 if (auto *EA = New->getAttr<ErrorAttr>()) {
3682 if (!Old->hasAttr<ErrorAttr>()) {
3683 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3684 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3685 New->dropAttr<ErrorAttr>();
3686 }
3687 }
3688
3689 if (CheckRedeclarationInModule(New, Old))
3690 return true;
3691
3692 if (!getLangOpts().CPlusPlus) {
3693 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3694 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3695 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3696 << New << OldOvl;
3697
3698 // Try our best to find a decl that actually has the overloadable
3699 // attribute for the note. In most cases (e.g. programs with only one
3700 // broken declaration/definition), this won't matter.
3701 //
3702 // FIXME: We could do this if we juggled some extra state in
3703 // OverloadableAttr, rather than just removing it.
3704 const Decl *DiagOld = Old;
3705 if (OldOvl) {
3706 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3707 const auto *A = D->getAttr<OverloadableAttr>();
3708 return A && !A->isImplicit();
3709 });
3710 // If we've implicitly added *all* of the overloadable attrs to this
3711 // chain, emitting a "previous redecl" note is pointless.
3712 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3713 }
3714
3715 if (DiagOld)
3716 Diag(Loc: DiagOld->getLocation(),
3717 DiagID: diag::note_attribute_overloadable_prev_overload)
3718 << OldOvl;
3719
3720 if (OldOvl)
3721 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3722 else
3723 New->dropAttr<OverloadableAttr>();
3724 }
3725 }
3726
3727 // It is not permitted to redeclare an SME function with different SME
3728 // attributes.
3729 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3730 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3731 << New->getType() << Old->getType();
3732 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3733 return true;
3734 }
3735
3736 // If a function is first declared with a calling convention, but is later
3737 // declared or defined without one, all following decls assume the calling
3738 // convention of the first.
3739 //
3740 // It's OK if a function is first declared without a calling convention,
3741 // but is later declared or defined with the default calling convention.
3742 //
3743 // To test if either decl has an explicit calling convention, we look for
3744 // AttributedType sugar nodes on the type as written. If they are missing or
3745 // were canonicalized away, we assume the calling convention was implicit.
3746 //
3747 // Note also that we DO NOT return at this point, because we still have
3748 // other tests to run.
3749 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3750 QualType NewQType = Context.getCanonicalType(T: New->getType());
3751 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3752 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3753 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3754 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3755 bool RequiresAdjustment = false;
3756
3757 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3758 FunctionDecl *First = Old->getFirstDecl();
3759 const FunctionType *FT =
3760 First->getType().getCanonicalType()->castAs<FunctionType>();
3761 FunctionType::ExtInfo FI = FT->getExtInfo();
3762 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3763 if (!NewCCExplicit) {
3764 // Inherit the CC from the previous declaration if it was specified
3765 // there but not here.
3766 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3767 RequiresAdjustment = true;
3768 } else if (Old->getBuiltinID()) {
3769 // Builtin attribute isn't propagated to the new one yet at this point,
3770 // so we check if the old one is a builtin.
3771
3772 // Calling Conventions on a Builtin aren't really useful and setting a
3773 // default calling convention and cdecl'ing some builtin redeclarations is
3774 // common, so warn and ignore the calling convention on the redeclaration.
3775 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3776 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3777 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3778 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3779 RequiresAdjustment = true;
3780 } else {
3781 // Calling conventions aren't compatible, so complain.
3782 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3783 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3784 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3785 << !FirstCCExplicit
3786 << (!FirstCCExplicit ? "" :
3787 FunctionType::getNameForCallConv(CC: FI.getCC()));
3788
3789 // Put the note on the first decl, since it is the one that matters.
3790 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3791 return true;
3792 }
3793 }
3794
3795 // FIXME: diagnose the other way around?
3796 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3797 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3798 RequiresAdjustment = true;
3799 }
3800
3801 // Merge regparm attribute.
3802 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3803 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3804 if (NewTypeInfo.getHasRegParm()) {
3805 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3806 << NewType->getRegParmType()
3807 << OldType->getRegParmType();
3808 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3809 return true;
3810 }
3811
3812 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3813 RequiresAdjustment = true;
3814 }
3815
3816 // Merge ns_returns_retained attribute.
3817 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3818 if (NewTypeInfo.getProducesResult()) {
3819 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3820 << "'ns_returns_retained'";
3821 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3822 return true;
3823 }
3824
3825 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3826 RequiresAdjustment = true;
3827 }
3828
3829 if (OldTypeInfo.getNoCallerSavedRegs() !=
3830 NewTypeInfo.getNoCallerSavedRegs()) {
3831 if (NewTypeInfo.getNoCallerSavedRegs()) {
3832 AnyX86NoCallerSavedRegistersAttr *Attr =
3833 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3834 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3835 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3836 return true;
3837 }
3838
3839 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3840 RequiresAdjustment = true;
3841 }
3842
3843 if (RequiresAdjustment) {
3844 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3845 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3846 New->setType(QualType(AdjustedType, 0));
3847 NewQType = Context.getCanonicalType(T: New->getType());
3848 }
3849
3850 // If this redeclaration makes the function inline, we may need to add it to
3851 // UndefinedButUsed.
3852 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3853 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
3854 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3855 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
3856 y: SourceLocation()));
3857
3858 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3859 // about it.
3860 if (New->hasAttr<GNUInlineAttr>() &&
3861 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3862 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
3863 }
3864
3865 // If pass_object_size params don't match up perfectly, this isn't a valid
3866 // redeclaration.
3867 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3868 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3869 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
3870 << New->getDeclName();
3871 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3872 return true;
3873 }
3874
3875 QualType OldQTypeForComparison = OldQType;
3876 if (Context.hasAnyFunctionEffects()) {
3877 const auto OldFX = Old->getFunctionEffects();
3878 const auto NewFX = New->getFunctionEffects();
3879 if (OldFX != NewFX) {
3880 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3881 for (const auto &Diff : Diffs) {
3882 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
3883 Diag(Loc: New->getLocation(),
3884 DiagID: diag::warn_mismatched_func_effect_redeclaration)
3885 << Diff.effectName();
3886 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3887 }
3888 }
3889 // Following a warning, we could skip merging effects from the previous
3890 // declaration, but that would trigger an additional "conflicting types"
3891 // error.
3892 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3893 FunctionEffectSet::Conflicts MergeErrs;
3894 FunctionEffectSet MergedFX =
3895 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
3896 if (!MergeErrs.empty())
3897 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
3898 OldLoc: Old->getLocation());
3899
3900 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3901 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3902 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
3903 Args: NewFPT->getParamTypes(), EPI);
3904
3905 New->setType(ModQT);
3906 NewQType = New->getType();
3907
3908 // Revise OldQTForComparison to include the merged effects,
3909 // so as not to fail due to differences later.
3910 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3911 EPI = OldFPT->getExtProtoInfo();
3912 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3913 OldQTypeForComparison = Context.getFunctionType(
3914 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
3915 }
3916 if (OldFX.empty()) {
3917 // A redeclaration may add the attribute to a previously seen function
3918 // body which needs to be verified.
3919 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
3920 }
3921 }
3922 }
3923 }
3924
3925 if (getLangOpts().CPlusPlus) {
3926 OldQType = Context.getCanonicalType(T: Old->getType());
3927 NewQType = Context.getCanonicalType(T: New->getType());
3928
3929 // Go back to the type source info to compare the declared return types,
3930 // per C++1y [dcl.type.auto]p13:
3931 // Redeclarations or specializations of a function or function template
3932 // with a declared return type that uses a placeholder type shall also
3933 // use that placeholder, not a deduced type.
3934 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3935 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3936 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
3937 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
3938 OldT: OldDeclaredReturnType)) {
3939 QualType ResQT;
3940 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3941 OldDeclaredReturnType->isObjCObjectPointerType())
3942 // FIXME: This does the wrong thing for a deduced return type.
3943 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3944 if (ResQT.isNull()) {
3945 if (New->isCXXClassMember() && New->isOutOfLine())
3946 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
3947 << New << New->getReturnTypeSourceRange();
3948 else if (Old->isExternC() && New->isExternC() &&
3949 !Old->hasAttr<OverloadableAttr>() &&
3950 !New->hasAttr<OverloadableAttr>())
3951 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
3952 else
3953 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
3954 << New->getReturnTypeSourceRange();
3955 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
3956 << Old->getReturnTypeSourceRange();
3957 return true;
3958 }
3959 else
3960 NewQType = ResQT;
3961 }
3962
3963 QualType OldReturnType = OldType->getReturnType();
3964 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
3965 if (OldReturnType != NewReturnType) {
3966 // If this function has a deduced return type and has already been
3967 // defined, copy the deduced value from the old declaration.
3968 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3969 if (OldAT && OldAT->isDeduced()) {
3970 QualType DT = OldAT->getDeducedType();
3971 if (DT.isNull()) {
3972 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
3973 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
3974 } else {
3975 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
3976 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
3977 }
3978 }
3979 }
3980
3981 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
3982 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
3983 if (OldMethod && NewMethod) {
3984 // Preserve triviality.
3985 NewMethod->setTrivial(OldMethod->isTrivial());
3986
3987 // MSVC allows explicit template specialization at class scope:
3988 // 2 CXXMethodDecls referring to the same function will be injected.
3989 // We don't want a redeclaration error.
3990 bool IsClassScopeExplicitSpecialization =
3991 OldMethod->isFunctionTemplateSpecialization() &&
3992 NewMethod->isFunctionTemplateSpecialization();
3993 bool isFriend = NewMethod->getFriendObjectKind();
3994
3995 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3996 !IsClassScopeExplicitSpecialization) {
3997 // -- Member function declarations with the same name and the
3998 // same parameter types cannot be overloaded if any of them
3999 // is a static member function declaration.
4000 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4001 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4002 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4003 return true;
4004 }
4005
4006 // C++ [class.mem]p1:
4007 // [...] A member shall not be declared twice in the
4008 // member-specification, except that a nested class or member
4009 // class template can be declared and then later defined.
4010 if (!inTemplateInstantiation()) {
4011 unsigned NewDiag;
4012 if (isa<CXXConstructorDecl>(Val: OldMethod))
4013 NewDiag = diag::err_constructor_redeclared;
4014 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4015 NewDiag = diag::err_destructor_redeclared;
4016 else if (isa<CXXConversionDecl>(Val: NewMethod))
4017 NewDiag = diag::err_conv_function_redeclared;
4018 else
4019 NewDiag = diag::err_member_redeclared;
4020
4021 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4022 } else {
4023 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4024 << New << New->getType();
4025 }
4026 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4027 return true;
4028
4029 // Complain if this is an explicit declaration of a special
4030 // member that was initially declared implicitly.
4031 //
4032 // As an exception, it's okay to befriend such methods in order
4033 // to permit the implicit constructor/destructor/operator calls.
4034 } else if (OldMethod->isImplicit()) {
4035 if (isFriend) {
4036 NewMethod->setImplicit();
4037 } else {
4038 Diag(Loc: NewMethod->getLocation(),
4039 DiagID: diag::err_definition_of_implicitly_declared_member)
4040 << New << getSpecialMember(MD: OldMethod);
4041 return true;
4042 }
4043 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4044 Diag(Loc: NewMethod->getLocation(),
4045 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4046 << getSpecialMember(MD: OldMethod);
4047 return true;
4048 }
4049 }
4050
4051 // C++1z [over.load]p2
4052 // Certain function declarations cannot be overloaded:
4053 // -- Function declarations that differ only in the return type,
4054 // the exception specification, or both cannot be overloaded.
4055
4056 // Check the exception specifications match. This may recompute the type of
4057 // both Old and New if it resolved exception specifications, so grab the
4058 // types again after this. Because this updates the type, we do this before
4059 // any of the other checks below, which may update the "de facto" NewQType
4060 // but do not necessarily update the type of New.
4061 if (CheckEquivalentExceptionSpec(Old, New))
4062 return true;
4063
4064 // C++11 [dcl.attr.noreturn]p1:
4065 // The first declaration of a function shall specify the noreturn
4066 // attribute if any declaration of that function specifies the noreturn
4067 // attribute.
4068 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4069 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4070 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4071 << NRA;
4072 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4073 }
4074
4075 // C++11 [dcl.attr.depend]p2:
4076 // The first declaration of a function shall specify the
4077 // carries_dependency attribute for its declarator-id if any declaration
4078 // of the function specifies the carries_dependency attribute.
4079 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4080 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4081 Diag(Loc: CDA->getLocation(),
4082 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4083 Diag(Loc: Old->getFirstDecl()->getLocation(),
4084 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4085 }
4086
4087 // (C++98 8.3.5p3):
4088 // All declarations for a function shall agree exactly in both the
4089 // return type and the parameter-type-list.
4090 // We also want to respect all the extended bits except noreturn.
4091
4092 // noreturn should now match unless the old type info didn't have it.
4093 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4094 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4095 const FunctionType *OldTypeForComparison
4096 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4097 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4098 assert(OldQTypeForComparison.isCanonical());
4099 }
4100
4101 if (haveIncompatibleLanguageLinkages(Old, New)) {
4102 // As a special case, retain the language linkage from previous
4103 // declarations of a friend function as an extension.
4104 //
4105 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4106 // and is useful because there's otherwise no way to specify language
4107 // linkage within class scope.
4108 //
4109 // Check cautiously as the friend object kind isn't yet complete.
4110 if (New->getFriendObjectKind() != Decl::FOK_None) {
4111 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4112 Diag(Loc: OldLocation, DiagID: PrevDiag);
4113 } else {
4114 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4115 Diag(Loc: OldLocation, DiagID: PrevDiag);
4116 return true;
4117 }
4118 }
4119
4120 // HLSL check parameters for matching ABI specifications.
4121 if (getLangOpts().HLSL) {
4122 if (HLSL().CheckCompatibleParameterABI(New, Old))
4123 return true;
4124
4125 // If no errors are generated when checking parameter ABIs we can check if
4126 // the two declarations have the same type ignoring the ABIs and if so,
4127 // the declarations can be merged. This case for merging is only valid in
4128 // HLSL because there are no valid cases of merging mismatched parameter
4129 // ABIs except the HLSL implicit in and explicit in.
4130 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4131 U: NewQType))
4132 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4133 // Fall through for conflicting redeclarations and redefinitions.
4134 }
4135
4136 // If the function types are compatible, merge the declarations. Ignore the
4137 // exception specifier because it was already checked above in
4138 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4139 // about incompatible types under -fms-compatibility.
4140 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4141 U: NewQType))
4142 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4143
4144 // If the types are imprecise (due to dependent constructs in friends or
4145 // local extern declarations), it's OK if they differ. We'll check again
4146 // during instantiation.
4147 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4148 return false;
4149
4150 // Fall through for conflicting redeclarations and redefinitions.
4151 }
4152
4153 // C: Function types need to be compatible, not identical. This handles
4154 // duplicate function decls like "void f(int); void f(enum X);" properly.
4155 if (!getLangOpts().CPlusPlus) {
4156 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4157 // type is specified by a function definition that contains a (possibly
4158 // empty) identifier list, both shall agree in the number of parameters
4159 // and the type of each parameter shall be compatible with the type that
4160 // results from the application of default argument promotions to the
4161 // type of the corresponding identifier. ...
4162 // This cannot be handled by ASTContext::typesAreCompatible() because that
4163 // doesn't know whether the function type is for a definition or not when
4164 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4165 // we need to cover here is that the number of arguments agree as the
4166 // default argument promotion rules were already checked by
4167 // ASTContext::typesAreCompatible().
4168 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4169 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4170 if (Old->hasInheritedPrototype())
4171 Old = Old->getCanonicalDecl();
4172 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4173 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4174 return true;
4175 }
4176
4177 // If we are merging two functions where only one of them has a prototype,
4178 // we may have enough information to decide to issue a diagnostic that the
4179 // function without a prototype will change behavior in C23. This handles
4180 // cases like:
4181 // void i(); void i(int j);
4182 // void i(int j); void i();
4183 // void i(); void i(int j) {}
4184 // See ActOnFinishFunctionBody() for other cases of the behavior change
4185 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4186 // type without a prototype.
4187 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4188 !New->isImplicit() && !Old->isImplicit()) {
4189 const FunctionDecl *WithProto, *WithoutProto;
4190 if (New->hasWrittenPrototype()) {
4191 WithProto = New;
4192 WithoutProto = Old;
4193 } else {
4194 WithProto = Old;
4195 WithoutProto = New;
4196 }
4197
4198 if (WithProto->getNumParams() != 0) {
4199 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4200 // The one without the prototype will be changing behavior in C23, so
4201 // warn about that one so long as it's a user-visible declaration.
4202 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4203 if (WithoutProto == New)
4204 IsWithoutProtoADef = NewDeclIsDefn;
4205 else
4206 IsWithProtoADef = NewDeclIsDefn;
4207 Diag(Loc: WithoutProto->getLocation(),
4208 DiagID: diag::warn_non_prototype_changes_behavior)
4209 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4210 << (WithoutProto == Old) << IsWithProtoADef;
4211
4212 // The reason the one without the prototype will be changing behavior
4213 // is because of the one with the prototype, so note that so long as
4214 // it's a user-visible declaration. There is one exception to this:
4215 // when the new declaration is a definition without a prototype, the
4216 // old declaration with a prototype is not the cause of the issue,
4217 // and that does not need to be noted because the one with a
4218 // prototype will not change behavior in C23.
4219 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4220 !IsWithoutProtoADef)
4221 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4222 }
4223 }
4224 }
4225
4226 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4227 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4228 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4229 const FunctionProtoType *OldProto = nullptr;
4230 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4231 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4232 // The old declaration provided a function prototype, but the
4233 // new declaration does not. Merge in the prototype.
4234 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4235 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4236 Args: OldProto->getParamTypes(),
4237 EPI: OldProto->getExtProtoInfo());
4238 New->setType(NewQType);
4239 New->setHasInheritedPrototype();
4240
4241 // Synthesize parameters with the same types.
4242 SmallVector<ParmVarDecl *, 16> Params;
4243 for (const auto &ParamType : OldProto->param_types()) {
4244 ParmVarDecl *Param = ParmVarDecl::Create(
4245 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4246 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4247 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4248 Param->setImplicit();
4249 Params.push_back(Elt: Param);
4250 }
4251
4252 New->setParams(Params);
4253 }
4254
4255 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4256 }
4257 }
4258
4259 // Check if the function types are compatible when pointer size address
4260 // spaces are ignored.
4261 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4262 return false;
4263
4264 // GNU C permits a K&R definition to follow a prototype declaration
4265 // if the declared types of the parameters in the K&R definition
4266 // match the types in the prototype declaration, even when the
4267 // promoted types of the parameters from the K&R definition differ
4268 // from the types in the prototype. GCC then keeps the types from
4269 // the prototype.
4270 //
4271 // If a variadic prototype is followed by a non-variadic K&R definition,
4272 // the K&R definition becomes variadic. This is sort of an edge case, but
4273 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4274 // C99 6.9.1p8.
4275 if (!getLangOpts().CPlusPlus &&
4276 Old->hasPrototype() && !New->hasPrototype() &&
4277 New->getType()->getAs<FunctionProtoType>() &&
4278 Old->getNumParams() == New->getNumParams()) {
4279 SmallVector<QualType, 16> ArgTypes;
4280 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4281 const FunctionProtoType *OldProto
4282 = Old->getType()->getAs<FunctionProtoType>();
4283 const FunctionProtoType *NewProto
4284 = New->getType()->getAs<FunctionProtoType>();
4285
4286 // Determine whether this is the GNU C extension.
4287 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4288 NewProto->getReturnType());
4289 bool LooseCompatible = !MergedReturn.isNull();
4290 for (unsigned Idx = 0, End = Old->getNumParams();
4291 LooseCompatible && Idx != End; ++Idx) {
4292 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4293 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4294 if (Context.typesAreCompatible(T1: OldParm->getType(),
4295 T2: NewProto->getParamType(i: Idx))) {
4296 ArgTypes.push_back(Elt: NewParm->getType());
4297 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4298 T2: NewParm->getType(),
4299 /*CompareUnqualified=*/true)) {
4300 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4301 .PromotedType: NewProto->getParamType(i: Idx) };
4302 Warnings.push_back(Elt: Warn);
4303 ArgTypes.push_back(Elt: NewParm->getType());
4304 } else
4305 LooseCompatible = false;
4306 }
4307
4308 if (LooseCompatible) {
4309 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4310 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4311 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4312 << Warnings[Warn].PromotedType
4313 << Warnings[Warn].OldParm->getType();
4314 if (Warnings[Warn].OldParm->getLocation().isValid())
4315 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4316 DiagID: diag::note_previous_declaration);
4317 }
4318
4319 if (MergeTypeWithOld)
4320 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4321 EPI: OldProto->getExtProtoInfo()));
4322 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4323 }
4324
4325 // Fall through to diagnose conflicting types.
4326 }
4327
4328 // A function that has already been declared has been redeclared or
4329 // defined with a different type; show an appropriate diagnostic.
4330
4331 // If the previous declaration was an implicitly-generated builtin
4332 // declaration, then at the very least we should use a specialized note.
4333 unsigned BuiltinID;
4334 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4335 // If it's actually a library-defined builtin function like 'malloc'
4336 // or 'printf', just warn about the incompatible redeclaration.
4337 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4338 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4339 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4340 << Old << Old->getType();
4341 return false;
4342 }
4343
4344 PrevDiag = diag::note_previous_builtin_declaration;
4345 }
4346
4347 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4348 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4349 return true;
4350}
4351
4352bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4353 Scope *S, bool MergeTypeWithOld) {
4354 // Merge the attributes
4355 mergeDeclAttributes(New, Old);
4356
4357 // Merge "pure" flag.
4358 if (Old->isPureVirtual())
4359 New->setIsPureVirtual();
4360
4361 // Merge "used" flag.
4362 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4363 New->setIsUsed();
4364
4365 // Merge attributes from the parameters. These can mismatch with K&R
4366 // declarations.
4367 if (New->getNumParams() == Old->getNumParams())
4368 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4369 ParmVarDecl *NewParam = New->getParamDecl(i);
4370 ParmVarDecl *OldParam = Old->getParamDecl(i);
4371 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4372 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4373 }
4374
4375 if (getLangOpts().CPlusPlus)
4376 return MergeCXXFunctionDecl(New, Old, S);
4377
4378 // Merge the function types so the we get the composite types for the return
4379 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4380 // was visible.
4381 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4382 if (!Merged.isNull() && MergeTypeWithOld)
4383 New->setType(Merged);
4384
4385 return false;
4386}
4387
4388void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4389 ObjCMethodDecl *oldMethod) {
4390 // Merge the attributes, including deprecated/unavailable
4391 AvailabilityMergeKind MergeKind =
4392 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4393 ? (oldMethod->isOptional()
4394 ? AvailabilityMergeKind::OptionalProtocolImplementation
4395 : AvailabilityMergeKind::ProtocolImplementation)
4396 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4397 ? AvailabilityMergeKind::Redeclaration
4398 : AvailabilityMergeKind::Override;
4399
4400 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4401
4402 // Merge attributes from the parameters.
4403 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4404 oe = oldMethod->param_end();
4405 for (ObjCMethodDecl::param_iterator
4406 ni = newMethod->param_begin(), ne = newMethod->param_end();
4407 ni != ne && oi != oe; ++ni, ++oi)
4408 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4409
4410 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4411}
4412
4413static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4414 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4415
4416 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4417 ? diag::err_redefinition_different_type
4418 : diag::err_redeclaration_different_type)
4419 << New->getDeclName() << New->getType() << Old->getType();
4420
4421 diag::kind PrevDiag;
4422 SourceLocation OldLocation;
4423 std::tie(args&: PrevDiag, args&: OldLocation)
4424 = getNoteDiagForInvalidRedeclaration(Old, New);
4425 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4426 New->setInvalidDecl();
4427}
4428
4429void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4430 bool MergeTypeWithOld) {
4431 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4432 return;
4433
4434 QualType MergedT;
4435 if (getLangOpts().CPlusPlus) {
4436 if (New->getType()->isUndeducedType()) {
4437 // We don't know what the new type is until the initializer is attached.
4438 return;
4439 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4440 // These could still be something that needs exception specs checked.
4441 return MergeVarDeclExceptionSpecs(New, Old);
4442 }
4443 // C++ [basic.link]p10:
4444 // [...] the types specified by all declarations referring to a given
4445 // object or function shall be identical, except that declarations for an
4446 // array object can specify array types that differ by the presence or
4447 // absence of a major array bound (8.3.4).
4448 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4449 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4450 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4451
4452 // We are merging a variable declaration New into Old. If it has an array
4453 // bound, and that bound differs from Old's bound, we should diagnose the
4454 // mismatch.
4455 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4456 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4457 PrevVD = PrevVD->getPreviousDecl()) {
4458 QualType PrevVDTy = PrevVD->getType();
4459 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4460 continue;
4461
4462 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4463 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4464 }
4465 }
4466
4467 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4468 if (Context.hasSameType(T1: OldArray->getElementType(),
4469 T2: NewArray->getElementType()))
4470 MergedT = New->getType();
4471 }
4472 // FIXME: Check visibility. New is hidden but has a complete type. If New
4473 // has no array bound, it should not inherit one from Old, if Old is not
4474 // visible.
4475 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4476 if (Context.hasSameType(T1: OldArray->getElementType(),
4477 T2: NewArray->getElementType()))
4478 MergedT = Old->getType();
4479 }
4480 }
4481 else if (New->getType()->isObjCObjectPointerType() &&
4482 Old->getType()->isObjCObjectPointerType()) {
4483 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4484 Old->getType());
4485 }
4486 } else {
4487 // C 6.2.7p2:
4488 // All declarations that refer to the same object or function shall have
4489 // compatible type.
4490 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4491 }
4492 if (MergedT.isNull()) {
4493 // It's OK if we couldn't merge types if either type is dependent, for a
4494 // block-scope variable. In other cases (static data members of class
4495 // templates, variable templates, ...), we require the types to be
4496 // equivalent.
4497 // FIXME: The C++ standard doesn't say anything about this.
4498 if ((New->getType()->isDependentType() ||
4499 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4500 // If the old type was dependent, we can't merge with it, so the new type
4501 // becomes dependent for now. We'll reproduce the original type when we
4502 // instantiate the TypeSourceInfo for the variable.
4503 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4504 New->setType(Context.DependentTy);
4505 return;
4506 }
4507 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4508 }
4509
4510 // Don't actually update the type on the new declaration if the old
4511 // declaration was an extern declaration in a different scope.
4512 if (MergeTypeWithOld)
4513 New->setType(MergedT);
4514}
4515
4516static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4517 LookupResult &Previous) {
4518 // C11 6.2.7p4:
4519 // For an identifier with internal or external linkage declared
4520 // in a scope in which a prior declaration of that identifier is
4521 // visible, if the prior declaration specifies internal or
4522 // external linkage, the type of the identifier at the later
4523 // declaration becomes the composite type.
4524 //
4525 // If the variable isn't visible, we do not merge with its type.
4526 if (Previous.isShadowed())
4527 return false;
4528
4529 if (S.getLangOpts().CPlusPlus) {
4530 // C++11 [dcl.array]p3:
4531 // If there is a preceding declaration of the entity in the same
4532 // scope in which the bound was specified, an omitted array bound
4533 // is taken to be the same as in that earlier declaration.
4534 return NewVD->isPreviousDeclInSameBlockScope() ||
4535 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4536 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4537 } else {
4538 // If the old declaration was function-local, don't merge with its
4539 // type unless we're in the same function.
4540 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4541 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4542 }
4543}
4544
4545void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4546 // If the new decl is already invalid, don't do any other checking.
4547 if (New->isInvalidDecl())
4548 return;
4549
4550 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4551 return;
4552
4553 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4554
4555 // Verify the old decl was also a variable or variable template.
4556 VarDecl *Old = nullptr;
4557 VarTemplateDecl *OldTemplate = nullptr;
4558 if (Previous.isSingleResult()) {
4559 if (NewTemplate) {
4560 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4561 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4562
4563 if (auto *Shadow =
4564 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4565 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4566 return New->setInvalidDecl();
4567 } else {
4568 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4569
4570 if (auto *Shadow =
4571 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4572 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4573 return New->setInvalidDecl();
4574 }
4575 }
4576 if (!Old) {
4577 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4578 << New->getDeclName();
4579 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4580 New: New->getLocation());
4581 return New->setInvalidDecl();
4582 }
4583
4584 // If the old declaration was found in an inline namespace and the new
4585 // declaration was qualified, update the DeclContext to match.
4586 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4587
4588 // Ensure the template parameters are compatible.
4589 if (NewTemplate &&
4590 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4591 Old: OldTemplate->getTemplateParameters(),
4592 /*Complain=*/true, Kind: TPL_TemplateMatch))
4593 return New->setInvalidDecl();
4594
4595 // C++ [class.mem]p1:
4596 // A member shall not be declared twice in the member-specification [...]
4597 //
4598 // Here, we need only consider static data members.
4599 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4600 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4601 << New->getIdentifier();
4602 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4603 New->setInvalidDecl();
4604 }
4605
4606 mergeDeclAttributes(New, Old);
4607 // Warn if an already-defined variable is made a weak_import in a subsequent
4608 // declaration
4609 if (New->hasAttr<WeakImportAttr>())
4610 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4611 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4612 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4613 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4614 // Remove weak_import attribute on new declaration.
4615 New->dropAttr<WeakImportAttr>();
4616 break;
4617 }
4618 }
4619
4620 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4621 if (!Old->hasAttr<InternalLinkageAttr>()) {
4622 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4623 << ILA;
4624 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4625 New->dropAttr<InternalLinkageAttr>();
4626 }
4627
4628 // Merge the types.
4629 VarDecl *MostRecent = Old->getMostRecentDecl();
4630 if (MostRecent != Old) {
4631 MergeVarDeclTypes(New, Old: MostRecent,
4632 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4633 if (New->isInvalidDecl())
4634 return;
4635 }
4636
4637 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4638 if (New->isInvalidDecl())
4639 return;
4640
4641 diag::kind PrevDiag;
4642 SourceLocation OldLocation;
4643 std::tie(args&: PrevDiag, args&: OldLocation) =
4644 getNoteDiagForInvalidRedeclaration(Old, New);
4645
4646 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4647 if (New->getStorageClass() == SC_Static &&
4648 !New->isStaticDataMember() &&
4649 Old->hasExternalFormalLinkage()) {
4650 if (getLangOpts().MicrosoftExt) {
4651 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4652 << New->getDeclName();
4653 Diag(Loc: OldLocation, DiagID: PrevDiag);
4654 } else {
4655 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4656 << New->getDeclName();
4657 Diag(Loc: OldLocation, DiagID: PrevDiag);
4658 return New->setInvalidDecl();
4659 }
4660 }
4661 // C99 6.2.2p4:
4662 // For an identifier declared with the storage-class specifier
4663 // extern in a scope in which a prior declaration of that
4664 // identifier is visible,23) if the prior declaration specifies
4665 // internal or external linkage, the linkage of the identifier at
4666 // the later declaration is the same as the linkage specified at
4667 // the prior declaration. If no prior declaration is visible, or
4668 // if the prior declaration specifies no linkage, then the
4669 // identifier has external linkage.
4670 if (New->hasExternalStorage() && Old->hasLinkage())
4671 /* Okay */;
4672 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4673 !New->isStaticDataMember() &&
4674 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4675 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4676 Diag(Loc: OldLocation, DiagID: PrevDiag);
4677 return New->setInvalidDecl();
4678 }
4679
4680 // Check if extern is followed by non-extern and vice-versa.
4681 if (New->hasExternalStorage() &&
4682 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4683 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4684 Diag(Loc: OldLocation, DiagID: PrevDiag);
4685 return New->setInvalidDecl();
4686 }
4687 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4688 !New->hasExternalStorage()) {
4689 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4690 Diag(Loc: OldLocation, DiagID: PrevDiag);
4691 return New->setInvalidDecl();
4692 }
4693
4694 if (CheckRedeclarationInModule(New, Old))
4695 return;
4696
4697 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4698
4699 // FIXME: The test for external storage here seems wrong? We still
4700 // need to check for mismatches.
4701 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4702 // Don't complain about out-of-line definitions of static members.
4703 !(Old->getLexicalDeclContext()->isRecord() &&
4704 !New->getLexicalDeclContext()->isRecord())) {
4705 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4706 Diag(Loc: OldLocation, DiagID: PrevDiag);
4707 return New->setInvalidDecl();
4708 }
4709
4710 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4711 if (VarDecl *Def = Old->getDefinition()) {
4712 // C++1z [dcl.fcn.spec]p4:
4713 // If the definition of a variable appears in a translation unit before
4714 // its first declaration as inline, the program is ill-formed.
4715 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4716 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4717 }
4718 }
4719
4720 // If this redeclaration makes the variable inline, we may need to add it to
4721 // UndefinedButUsed.
4722 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4723 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4724 !Old->isInAnotherModuleUnit())
4725 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4726 y: SourceLocation()));
4727
4728 if (New->getTLSKind() != Old->getTLSKind()) {
4729 if (!Old->getTLSKind()) {
4730 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4731 Diag(Loc: OldLocation, DiagID: PrevDiag);
4732 } else if (!New->getTLSKind()) {
4733 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4734 Diag(Loc: OldLocation, DiagID: PrevDiag);
4735 } else {
4736 // Do not allow redeclaration to change the variable between requiring
4737 // static and dynamic initialization.
4738 // FIXME: GCC allows this, but uses the TLS keyword on the first
4739 // declaration to determine the kind. Do we need to be compatible here?
4740 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4741 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4742 Diag(Loc: OldLocation, DiagID: PrevDiag);
4743 }
4744 }
4745
4746 // C++ doesn't have tentative definitions, so go right ahead and check here.
4747 if (getLangOpts().CPlusPlus) {
4748 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4749 Old->getCanonicalDecl()->isConstexpr()) {
4750 // This definition won't be a definition any more once it's been merged.
4751 Diag(Loc: New->getLocation(),
4752 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4753 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4754 VarDecl *Def = Old->getDefinition();
4755 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4756 return;
4757 }
4758 } else {
4759 // C++ may not have a tentative definition rule, but it has a different
4760 // rule about what constitutes a definition in the first place. See
4761 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4762 // contains the extern specifier and doesn't have an initializer, it's fine
4763 // in C++.
4764 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4765 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4766 << New;
4767 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4768 }
4769 }
4770
4771 if (haveIncompatibleLanguageLinkages(Old, New)) {
4772 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4773 Diag(Loc: OldLocation, DiagID: PrevDiag);
4774 New->setInvalidDecl();
4775 return;
4776 }
4777
4778 // Merge "used" flag.
4779 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4780 New->setIsUsed();
4781
4782 // Keep a chain of previous declarations.
4783 New->setPreviousDecl(Old);
4784 if (NewTemplate)
4785 NewTemplate->setPreviousDecl(OldTemplate);
4786
4787 // Inherit access appropriately.
4788 New->setAccess(Old->getAccess());
4789 if (NewTemplate)
4790 NewTemplate->setAccess(New->getAccess());
4791
4792 if (Old->isInline())
4793 New->setImplicitlyInline();
4794}
4795
4796void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4797 SourceManager &SrcMgr = getSourceManager();
4798 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4799 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4800 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4801 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4802 auto &HSI = PP.getHeaderSearchInfo();
4803 StringRef HdrFilename =
4804 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4805
4806 auto noteFromModuleOrInclude = [&](Module *Mod,
4807 SourceLocation IncLoc) -> bool {
4808 // Redefinition errors with modules are common with non modular mapped
4809 // headers, example: a non-modular header H in module A that also gets
4810 // included directly in a TU. Pointing twice to the same header/definition
4811 // is confusing, try to get better diagnostics when modules is on.
4812 if (IncLoc.isValid()) {
4813 if (Mod) {
4814 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4815 << HdrFilename.str() << Mod->getFullModuleName();
4816 if (!Mod->DefinitionLoc.isInvalid())
4817 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4818 << Mod->getFullModuleName();
4819 } else {
4820 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4821 << HdrFilename.str();
4822 }
4823 return true;
4824 }
4825
4826 return false;
4827 };
4828
4829 // Is it the same file and same offset? Provide more information on why
4830 // this leads to a redefinition error.
4831 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4832 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4833 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4834 bool EmittedDiag =
4835 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4836 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4837
4838 // If the header has no guards, emit a note suggesting one.
4839 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
4840 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
4841
4842 if (EmittedDiag)
4843 return;
4844 }
4845
4846 // Redefinition coming from different files or couldn't do better above.
4847 if (Old->getLocation().isValid())
4848 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
4849}
4850
4851bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4852 if (!hasVisibleDefinition(D: Old) &&
4853 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4854 isa<VarTemplateSpecializationDecl>(Val: New) ||
4855 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4856 New->getDeclContext()->isDependentContext() ||
4857 New->hasAttr<SelectAnyAttr>())) {
4858 // The previous definition is hidden, and multiple definitions are
4859 // permitted (in separate TUs). Demote this to a declaration.
4860 New->demoteThisDefinitionToDeclaration();
4861
4862 // Make the canonical definition visible.
4863 if (auto *OldTD = Old->getDescribedVarTemplate())
4864 makeMergedDefinitionVisible(ND: OldTD);
4865 makeMergedDefinitionVisible(ND: Old);
4866 return false;
4867 } else {
4868 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
4869 notePreviousDefinition(Old, New: New->getLocation());
4870 New->setInvalidDecl();
4871 return true;
4872 }
4873}
4874
4875Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4876 DeclSpec &DS,
4877 const ParsedAttributesView &DeclAttrs,
4878 RecordDecl *&AnonRecord) {
4879 return ParsedFreeStandingDeclSpec(
4880 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
4881}
4882
4883// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4884// disambiguate entities defined in different scopes.
4885// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4886// compatibility.
4887// We will pick our mangling number depending on which version of MSVC is being
4888// targeted.
4889static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4890 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
4891 ? S->getMSCurManglingNumber()
4892 : S->getMSLastManglingNumber();
4893}
4894
4895void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4896 if (!Context.getLangOpts().CPlusPlus)
4897 return;
4898
4899 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
4900 // If this tag is the direct child of a class, number it if
4901 // it is anonymous.
4902 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4903 return;
4904 MangleNumberingContext &MCtx =
4905 Context.getManglingNumberContext(DC: Tag->getParent());
4906 Context.setManglingNumber(
4907 ND: Tag, Number: MCtx.getManglingNumber(
4908 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4909 return;
4910 }
4911
4912 // If this tag isn't a direct child of a class, number it if it is local.
4913 MangleNumberingContext *MCtx;
4914 Decl *ManglingContextDecl;
4915 std::tie(args&: MCtx, args&: ManglingContextDecl) =
4916 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
4917 if (MCtx) {
4918 Context.setManglingNumber(
4919 ND: Tag, Number: MCtx->getManglingNumber(
4920 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
4921 }
4922}
4923
4924namespace {
4925struct NonCLikeKind {
4926 enum {
4927 None,
4928 BaseClass,
4929 DefaultMemberInit,
4930 Lambda,
4931 Friend,
4932 OtherMember,
4933 Invalid,
4934 } Kind = None;
4935 SourceRange Range;
4936
4937 explicit operator bool() { return Kind != None; }
4938};
4939}
4940
4941/// Determine whether a class is C-like, according to the rules of C++
4942/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4943static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4944 if (RD->isInvalidDecl())
4945 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
4946
4947 // C++ [dcl.typedef]p9: [P1766R1]
4948 // An unnamed class with a typedef name for linkage purposes shall not
4949 //
4950 // -- have any base classes
4951 if (RD->getNumBases())
4952 return {.Kind: NonCLikeKind::BaseClass,
4953 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
4954 RD->bases_end()[-1].getEndLoc())};
4955 bool Invalid = false;
4956 for (Decl *D : RD->decls()) {
4957 // Don't complain about things we already diagnosed.
4958 if (D->isInvalidDecl()) {
4959 Invalid = true;
4960 continue;
4961 }
4962
4963 // -- have any [...] default member initializers
4964 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
4965 if (FD->hasInClassInitializer()) {
4966 auto *Init = FD->getInClassInitializer();
4967 return {.Kind: NonCLikeKind::DefaultMemberInit,
4968 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
4969 }
4970 continue;
4971 }
4972
4973 // FIXME: We don't allow friend declarations. This violates the wording of
4974 // P1766, but not the intent.
4975 if (isa<FriendDecl>(Val: D))
4976 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
4977
4978 // -- declare any members other than non-static data members, member
4979 // enumerations, or member classes,
4980 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
4981 isa<EnumDecl>(Val: D))
4982 continue;
4983 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
4984 if (!MemberRD) {
4985 if (D->isImplicit())
4986 continue;
4987 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
4988 }
4989
4990 // -- contain a lambda-expression,
4991 if (MemberRD->isLambda())
4992 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
4993
4994 // and all member classes shall also satisfy these requirements
4995 // (recursively).
4996 if (MemberRD->isThisDeclarationADefinition()) {
4997 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
4998 return Kind;
4999 }
5000 }
5001
5002 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5003}
5004
5005void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5006 TypedefNameDecl *NewTD) {
5007 if (TagFromDeclSpec->isInvalidDecl())
5008 return;
5009
5010 // Do nothing if the tag already has a name for linkage purposes.
5011 if (TagFromDeclSpec->hasNameForLinkage())
5012 return;
5013
5014 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5015 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5016
5017 // The type must match the tag exactly; no qualifiers allowed.
5018 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5019 T2: Context.getTagDeclType(Decl: TagFromDeclSpec))) {
5020 if (getLangOpts().CPlusPlus)
5021 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5022 return;
5023 }
5024
5025 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5026 // An unnamed class with a typedef name for linkage purposes shall [be
5027 // C-like].
5028 //
5029 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5030 // shouldn't happen, but there are constructs that the language rule doesn't
5031 // disallow for which we can't reasonably avoid computing linkage early.
5032 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5033 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5034 : NonCLikeKind();
5035 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5036 if (NonCLike || ChangesLinkage) {
5037 if (NonCLike.Kind == NonCLikeKind::Invalid)
5038 return;
5039
5040 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5041 if (ChangesLinkage) {
5042 // If the linkage changes, we can't accept this as an extension.
5043 if (NonCLike.Kind == NonCLikeKind::None)
5044 DiagID = diag::err_typedef_changes_linkage;
5045 else
5046 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5047 }
5048
5049 SourceLocation FixitLoc =
5050 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5051 llvm::SmallString<40> TextToInsert;
5052 TextToInsert += ' ';
5053 TextToInsert += NewTD->getIdentifier()->getName();
5054
5055 Diag(Loc: FixitLoc, DiagID)
5056 << isa<TypeAliasDecl>(Val: NewTD)
5057 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5058 if (NonCLike.Kind != NonCLikeKind::None) {
5059 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5060 << NonCLike.Kind - 1 << NonCLike.Range;
5061 }
5062 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5063 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5064
5065 if (ChangesLinkage)
5066 return;
5067 }
5068
5069 // Otherwise, set this as the anon-decl typedef for the tag.
5070 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5071
5072 // Now that we have a name for the tag, process API notes again.
5073 ProcessAPINotes(D: TagFromDeclSpec);
5074}
5075
5076static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5077 DeclSpec::TST T = DS.getTypeSpecType();
5078 switch (T) {
5079 case DeclSpec::TST_class:
5080 return 0;
5081 case DeclSpec::TST_struct:
5082 return 1;
5083 case DeclSpec::TST_interface:
5084 return 2;
5085 case DeclSpec::TST_union:
5086 return 3;
5087 case DeclSpec::TST_enum:
5088 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5089 if (ED->isScopedUsingClassTag())
5090 return 5;
5091 if (ED->isScoped())
5092 return 6;
5093 }
5094 return 4;
5095 default:
5096 llvm_unreachable("unexpected type specifier");
5097 }
5098}
5099
5100Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5101 DeclSpec &DS,
5102 const ParsedAttributesView &DeclAttrs,
5103 MultiTemplateParamsArg TemplateParams,
5104 bool IsExplicitInstantiation,
5105 RecordDecl *&AnonRecord,
5106 SourceLocation EllipsisLoc) {
5107 Decl *TagD = nullptr;
5108 TagDecl *Tag = nullptr;
5109 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5110 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5111 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5112 DS.getTypeSpecType() == DeclSpec::TST_union ||
5113 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5114 TagD = DS.getRepAsDecl();
5115
5116 if (!TagD) // We probably had an error
5117 return nullptr;
5118
5119 // Note that the above type specs guarantee that the
5120 // type rep is a Decl, whereas in many of the others
5121 // it's a Type.
5122 if (isa<TagDecl>(Val: TagD))
5123 Tag = cast<TagDecl>(Val: TagD);
5124 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5125 Tag = CTD->getTemplatedDecl();
5126 }
5127
5128 if (Tag) {
5129 handleTagNumbering(Tag, TagScope: S);
5130 Tag->setFreeStanding();
5131 if (Tag->isInvalidDecl())
5132 return Tag;
5133 }
5134
5135 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5136 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5137 // or incomplete types shall not be restrict-qualified."
5138 if (TypeQuals & DeclSpec::TQ_restrict)
5139 Diag(Loc: DS.getRestrictSpecLoc(),
5140 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5141 << DS.getSourceRange();
5142 }
5143
5144 if (DS.isInlineSpecified())
5145 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5146 << getLangOpts().CPlusPlus17;
5147
5148 if (DS.hasConstexprSpecifier()) {
5149 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5150 // and definitions of functions and variables.
5151 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5152 // the declaration of a function or function template
5153 if (Tag)
5154 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5155 << GetDiagnosticTypeSpecifierID(DS)
5156 << static_cast<int>(DS.getConstexprSpecifier());
5157 else if (getLangOpts().C23)
5158 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5159 else
5160 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5161 << static_cast<int>(DS.getConstexprSpecifier());
5162 // Don't emit warnings after this error.
5163 return TagD;
5164 }
5165
5166 DiagnoseFunctionSpecifiers(DS);
5167
5168 if (DS.isFriendSpecified()) {
5169 // If we're dealing with a decl but not a TagDecl, assume that
5170 // whatever routines created it handled the friendship aspect.
5171 if (TagD && !Tag)
5172 return nullptr;
5173 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5174 }
5175
5176 assert(EllipsisLoc.isInvalid() &&
5177 "Friend ellipsis but not friend-specified?");
5178
5179 // Track whether this decl-specifier declares anything.
5180 bool DeclaresAnything = true;
5181
5182 // Handle anonymous struct definitions.
5183 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5184 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5185 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5186 if (getLangOpts().CPlusPlus ||
5187 Record->getDeclContext()->isRecord()) {
5188 // If CurContext is a DeclContext that can contain statements,
5189 // RecursiveASTVisitor won't visit the decls that
5190 // BuildAnonymousStructOrUnion() will put into CurContext.
5191 // Also store them here so that they can be part of the
5192 // DeclStmt that gets created in this case.
5193 // FIXME: Also return the IndirectFieldDecls created by
5194 // BuildAnonymousStructOr union, for the same reason?
5195 if (CurContext->isFunctionOrMethod())
5196 AnonRecord = Record;
5197 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5198 Policy: Context.getPrintingPolicy());
5199 }
5200
5201 DeclaresAnything = false;
5202 }
5203 }
5204
5205 // C11 6.7.2.1p2:
5206 // A struct-declaration that does not declare an anonymous structure or
5207 // anonymous union shall contain a struct-declarator-list.
5208 //
5209 // This rule also existed in C89 and C99; the grammar for struct-declaration
5210 // did not permit a struct-declaration without a struct-declarator-list.
5211 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5212 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5213 // Check for Microsoft C extension: anonymous struct/union member.
5214 // Handle 2 kinds of anonymous struct/union:
5215 // struct STRUCT;
5216 // union UNION;
5217 // and
5218 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5219 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5220 if ((Tag && Tag->getDeclName()) ||
5221 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5222 RecordDecl *Record = nullptr;
5223 if (Tag)
5224 Record = dyn_cast<RecordDecl>(Val: Tag);
5225 else if (const RecordType *RT =
5226 DS.getRepAsType().get()->getAsStructureType())
5227 Record = RT->getDecl();
5228 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5229 Record = UT->getDecl();
5230
5231 if (Record && getLangOpts().MicrosoftExt) {
5232 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5233 << Record->isUnion() << DS.getSourceRange();
5234 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5235 }
5236
5237 DeclaresAnything = false;
5238 }
5239 }
5240
5241 // Skip all the checks below if we have a type error.
5242 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5243 (TagD && TagD->isInvalidDecl()))
5244 return TagD;
5245
5246 if (getLangOpts().CPlusPlus &&
5247 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5248 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5249 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5250 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5251 DeclaresAnything = false;
5252
5253 if (!DS.isMissingDeclaratorOk()) {
5254 // Customize diagnostic for a typedef missing a name.
5255 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5256 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5257 << DS.getSourceRange();
5258 else
5259 DeclaresAnything = false;
5260 }
5261
5262 if (DS.isModulePrivateSpecified() &&
5263 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5264 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5265 << Tag->getTagKind()
5266 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5267
5268 ActOnDocumentableDecl(D: TagD);
5269
5270 // C 6.7/2:
5271 // A declaration [...] shall declare at least a declarator [...], a tag,
5272 // or the members of an enumeration.
5273 // C++ [dcl.dcl]p3:
5274 // [If there are no declarators], and except for the declaration of an
5275 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5276 // names into the program, or shall redeclare a name introduced by a
5277 // previous declaration.
5278 if (!DeclaresAnything) {
5279 // In C, we allow this as a (popular) extension / bug. Don't bother
5280 // producing further diagnostics for redundant qualifiers after this.
5281 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5282 ? diag::err_no_declarators
5283 : diag::ext_no_declarators)
5284 << DS.getSourceRange();
5285 return TagD;
5286 }
5287
5288 // C++ [dcl.stc]p1:
5289 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5290 // init-declarator-list of the declaration shall not be empty.
5291 // C++ [dcl.fct.spec]p1:
5292 // If a cv-qualifier appears in a decl-specifier-seq, the
5293 // init-declarator-list of the declaration shall not be empty.
5294 //
5295 // Spurious qualifiers here appear to be valid in C.
5296 unsigned DiagID = diag::warn_standalone_specifier;
5297 if (getLangOpts().CPlusPlus)
5298 DiagID = diag::ext_standalone_specifier;
5299
5300 // Note that a linkage-specification sets a storage class, but
5301 // 'extern "C" struct foo;' is actually valid and not theoretically
5302 // useless.
5303 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5304 if (SCS == DeclSpec::SCS_mutable)
5305 // Since mutable is not a viable storage class specifier in C, there is
5306 // no reason to treat it as an extension. Instead, diagnose as an error.
5307 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5308 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5309 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5310 << DeclSpec::getSpecifierName(S: SCS);
5311 }
5312
5313 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5314 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5315 << DeclSpec::getSpecifierName(S: TSCS);
5316 if (DS.getTypeQualifiers()) {
5317 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5318 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5319 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5320 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5321 // Restrict is covered above.
5322 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5323 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5324 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5325 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5326 }
5327
5328 // Warn about ignored type attributes, for example:
5329 // __attribute__((aligned)) struct A;
5330 // Attributes should be placed after tag to apply to type declaration.
5331 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5332 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5333 if (TypeSpecType == DeclSpec::TST_class ||
5334 TypeSpecType == DeclSpec::TST_struct ||
5335 TypeSpecType == DeclSpec::TST_interface ||
5336 TypeSpecType == DeclSpec::TST_union ||
5337 TypeSpecType == DeclSpec::TST_enum) {
5338
5339 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5340 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5341 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5342 DiagnosticId = diag::warn_attribute_ignored;
5343 else if (AL.isRegularKeywordAttribute())
5344 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5345 else
5346 DiagnosticId = diag::warn_declspec_attribute_ignored;
5347 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5348 << AL << GetDiagnosticTypeSpecifierID(DS);
5349 };
5350
5351 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5352 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5353 }
5354 }
5355
5356 return TagD;
5357}
5358
5359/// We are trying to inject an anonymous member into the given scope;
5360/// check if there's an existing declaration that can't be overloaded.
5361///
5362/// \return true if this is a forbidden redeclaration
5363static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5364 DeclContext *Owner,
5365 DeclarationName Name,
5366 SourceLocation NameLoc, bool IsUnion,
5367 StorageClass SC) {
5368 LookupResult R(SemaRef, Name, NameLoc,
5369 Owner->isRecord() ? Sema::LookupMemberName
5370 : Sema::LookupOrdinaryName,
5371 RedeclarationKind::ForVisibleRedeclaration);
5372 if (!SemaRef.LookupName(R, S)) return false;
5373
5374 // Pick a representative declaration.
5375 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5376 assert(PrevDecl && "Expected a non-null Decl");
5377
5378 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5379 return false;
5380
5381 if (SC == StorageClass::SC_None &&
5382 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5383 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5384 if (!Owner->isRecord())
5385 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5386 return false;
5387 }
5388
5389 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5390 << IsUnion << Name;
5391 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5392
5393 return true;
5394}
5395
5396void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5397 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5398 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5399}
5400
5401void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5402 if (!getLangOpts().CPlusPlus)
5403 return;
5404
5405 // This function can be parsed before we have validated the
5406 // structure as an anonymous struct
5407 if (Record->isAnonymousStructOrUnion())
5408 return;
5409
5410 const NamedDecl *First = 0;
5411 for (const Decl *D : Record->decls()) {
5412 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5413 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5414 continue;
5415 if (!First)
5416 First = ND;
5417 else
5418 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5419 }
5420}
5421
5422/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5423/// anonymous struct or union AnonRecord into the owning context Owner
5424/// and scope S. This routine will be invoked just after we realize
5425/// that an unnamed union or struct is actually an anonymous union or
5426/// struct, e.g.,
5427///
5428/// @code
5429/// union {
5430/// int i;
5431/// float f;
5432/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5433/// // f into the surrounding scope.x
5434/// @endcode
5435///
5436/// This routine is recursive, injecting the names of nested anonymous
5437/// structs/unions into the owning context and scope as well.
5438static bool
5439InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5440 RecordDecl *AnonRecord, AccessSpecifier AS,
5441 StorageClass SC,
5442 SmallVectorImpl<NamedDecl *> &Chaining) {
5443 bool Invalid = false;
5444
5445 // Look every FieldDecl and IndirectFieldDecl with a name.
5446 for (auto *D : AnonRecord->decls()) {
5447 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5448 cast<NamedDecl>(Val: D)->getDeclName()) {
5449 ValueDecl *VD = cast<ValueDecl>(Val: D);
5450 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, Name: VD->getDeclName(),
5451 NameLoc: VD->getLocation(), IsUnion: AnonRecord->isUnion(),
5452 SC)) {
5453 // C++ [class.union]p2:
5454 // The names of the members of an anonymous union shall be
5455 // distinct from the names of any other entity in the
5456 // scope in which the anonymous union is declared.
5457 Invalid = true;
5458 } else {
5459 // C++ [class.union]p2:
5460 // For the purpose of name lookup, after the anonymous union
5461 // definition, the members of the anonymous union are
5462 // considered to have been defined in the scope in which the
5463 // anonymous union is declared.
5464 unsigned OldChainingSize = Chaining.size();
5465 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5466 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5467 else
5468 Chaining.push_back(Elt: VD);
5469
5470 assert(Chaining.size() >= 2);
5471 NamedDecl **NamedChain =
5472 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5473 for (unsigned i = 0; i < Chaining.size(); i++)
5474 NamedChain[i] = Chaining[i];
5475
5476 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5477 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5478 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5479
5480 for (const auto *Attr : VD->attrs())
5481 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5482
5483 IndirectField->setAccess(AS);
5484 IndirectField->setImplicit();
5485 SemaRef.PushOnScopeChains(D: IndirectField, S);
5486
5487 // That includes picking up the appropriate access specifier.
5488 if (AS != AS_none) IndirectField->setAccess(AS);
5489
5490 Chaining.resize(N: OldChainingSize);
5491 }
5492 }
5493 }
5494
5495 return Invalid;
5496}
5497
5498/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5499/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5500/// illegal input values are mapped to SC_None.
5501static StorageClass
5502StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5503 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5504 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5505 "Parser allowed 'typedef' as storage class VarDecl.");
5506 switch (StorageClassSpec) {
5507 case DeclSpec::SCS_unspecified: return SC_None;
5508 case DeclSpec::SCS_extern:
5509 if (DS.isExternInLinkageSpec())
5510 return SC_None;
5511 return SC_Extern;
5512 case DeclSpec::SCS_static: return SC_Static;
5513 case DeclSpec::SCS_auto: return SC_Auto;
5514 case DeclSpec::SCS_register: return SC_Register;
5515 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5516 // Illegal SCSs map to None: error reporting is up to the caller.
5517 case DeclSpec::SCS_mutable: // Fall through.
5518 case DeclSpec::SCS_typedef: return SC_None;
5519 }
5520 llvm_unreachable("unknown storage class specifier");
5521}
5522
5523static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5524 assert(Record->hasInClassInitializer());
5525
5526 for (const auto *I : Record->decls()) {
5527 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5528 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5529 FD = IFD->getAnonField();
5530 if (FD && FD->hasInClassInitializer())
5531 return FD->getLocation();
5532 }
5533
5534 llvm_unreachable("couldn't find in-class initializer");
5535}
5536
5537static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5538 SourceLocation DefaultInitLoc) {
5539 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5540 return;
5541
5542 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5543 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5544}
5545
5546static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5547 CXXRecordDecl *AnonUnion) {
5548 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5549 return;
5550
5551 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5552}
5553
5554Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5555 AccessSpecifier AS,
5556 RecordDecl *Record,
5557 const PrintingPolicy &Policy) {
5558 DeclContext *Owner = Record->getDeclContext();
5559
5560 // Diagnose whether this anonymous struct/union is an extension.
5561 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5562 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5563 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5564 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5565 else if (!Record->isUnion() && !getLangOpts().C11)
5566 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5567
5568 // C and C++ require different kinds of checks for anonymous
5569 // structs/unions.
5570 bool Invalid = false;
5571 if (getLangOpts().CPlusPlus) {
5572 const char *PrevSpec = nullptr;
5573 if (Record->isUnion()) {
5574 // C++ [class.union]p6:
5575 // C++17 [class.union.anon]p2:
5576 // Anonymous unions declared in a named namespace or in the
5577 // global namespace shall be declared static.
5578 unsigned DiagID;
5579 DeclContext *OwnerScope = Owner->getRedeclContext();
5580 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5581 (OwnerScope->isTranslationUnit() ||
5582 (OwnerScope->isNamespace() &&
5583 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5584 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5585 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5586
5587 // Recover by adding 'static'.
5588 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5589 PrevSpec, DiagID, Policy);
5590 }
5591 // C++ [class.union]p6:
5592 // A storage class is not allowed in a declaration of an
5593 // anonymous union in a class scope.
5594 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5595 isa<RecordDecl>(Val: Owner)) {
5596 Diag(Loc: DS.getStorageClassSpecLoc(),
5597 DiagID: diag::err_anonymous_union_with_storage_spec)
5598 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5599
5600 // Recover by removing the storage specifier.
5601 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5602 Loc: SourceLocation(),
5603 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5604 }
5605 }
5606
5607 // Ignore const/volatile/restrict qualifiers.
5608 if (DS.getTypeQualifiers()) {
5609 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5610 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5611 << Record->isUnion() << "const"
5612 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5613 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5614 Diag(Loc: DS.getVolatileSpecLoc(),
5615 DiagID: diag::ext_anonymous_struct_union_qualified)
5616 << Record->isUnion() << "volatile"
5617 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5618 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5619 Diag(Loc: DS.getRestrictSpecLoc(),
5620 DiagID: diag::ext_anonymous_struct_union_qualified)
5621 << Record->isUnion() << "restrict"
5622 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5623 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5624 Diag(Loc: DS.getAtomicSpecLoc(),
5625 DiagID: diag::ext_anonymous_struct_union_qualified)
5626 << Record->isUnion() << "_Atomic"
5627 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5628 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5629 Diag(Loc: DS.getUnalignedSpecLoc(),
5630 DiagID: diag::ext_anonymous_struct_union_qualified)
5631 << Record->isUnion() << "__unaligned"
5632 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5633
5634 DS.ClearTypeQualifiers();
5635 }
5636
5637 // C++ [class.union]p2:
5638 // The member-specification of an anonymous union shall only
5639 // define non-static data members. [Note: nested types and
5640 // functions cannot be declared within an anonymous union. ]
5641 for (auto *Mem : Record->decls()) {
5642 // Ignore invalid declarations; we already diagnosed them.
5643 if (Mem->isInvalidDecl())
5644 continue;
5645
5646 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5647 // C++ [class.union]p3:
5648 // An anonymous union shall not have private or protected
5649 // members (clause 11).
5650 assert(FD->getAccess() != AS_none);
5651 if (FD->getAccess() != AS_public) {
5652 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5653 << Record->isUnion() << (FD->getAccess() == AS_protected);
5654 Invalid = true;
5655 }
5656
5657 // C++ [class.union]p1
5658 // An object of a class with a non-trivial constructor, a non-trivial
5659 // copy constructor, a non-trivial destructor, or a non-trivial copy
5660 // assignment operator cannot be a member of a union, nor can an
5661 // array of such objects.
5662 if (CheckNontrivialField(FD))
5663 Invalid = true;
5664 } else if (Mem->isImplicit()) {
5665 // Any implicit members are fine.
5666 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5667 // This is a type that showed up in an
5668 // elaborated-type-specifier inside the anonymous struct or
5669 // union, but which actually declares a type outside of the
5670 // anonymous struct or union. It's okay.
5671 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5672 if (!MemRecord->isAnonymousStructOrUnion() &&
5673 MemRecord->getDeclName()) {
5674 // Visual C++ allows type definition in anonymous struct or union.
5675 if (getLangOpts().MicrosoftExt)
5676 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5677 << Record->isUnion();
5678 else {
5679 // This is a nested type declaration.
5680 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5681 << Record->isUnion();
5682 Invalid = true;
5683 }
5684 } else {
5685 // This is an anonymous type definition within another anonymous type.
5686 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5687 // not part of standard C++.
5688 Diag(Loc: MemRecord->getLocation(),
5689 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5690 << Record->isUnion();
5691 }
5692 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5693 // Any access specifier is fine.
5694 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5695 // In C++1z, static_assert declarations are also fine.
5696 } else {
5697 // We have something that isn't a non-static data
5698 // member. Complain about it.
5699 unsigned DK = diag::err_anonymous_record_bad_member;
5700 if (isa<TypeDecl>(Val: Mem))
5701 DK = diag::err_anonymous_record_with_type;
5702 else if (isa<FunctionDecl>(Val: Mem))
5703 DK = diag::err_anonymous_record_with_function;
5704 else if (isa<VarDecl>(Val: Mem))
5705 DK = diag::err_anonymous_record_with_static;
5706
5707 // Visual C++ allows type definition in anonymous struct or union.
5708 if (getLangOpts().MicrosoftExt &&
5709 DK == diag::err_anonymous_record_with_type)
5710 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5711 << Record->isUnion();
5712 else {
5713 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5714 Invalid = true;
5715 }
5716 }
5717 }
5718
5719 // C++11 [class.union]p8 (DR1460):
5720 // At most one variant member of a union may have a
5721 // brace-or-equal-initializer.
5722 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5723 Owner->isRecord())
5724 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5725 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5726 }
5727
5728 if (!Record->isUnion() && !Owner->isRecord()) {
5729 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5730 << getLangOpts().CPlusPlus;
5731 Invalid = true;
5732 }
5733
5734 // C++ [dcl.dcl]p3:
5735 // [If there are no declarators], and except for the declaration of an
5736 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5737 // names into the program
5738 // C++ [class.mem]p2:
5739 // each such member-declaration shall either declare at least one member
5740 // name of the class or declare at least one unnamed bit-field
5741 //
5742 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5743 if (getLangOpts().CPlusPlus && Record->field_empty())
5744 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5745
5746 // Mock up a declarator.
5747 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5748 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5749 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5750 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5751
5752 // Create a declaration for this anonymous struct/union.
5753 NamedDecl *Anon = nullptr;
5754 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5755 Anon = FieldDecl::Create(
5756 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5757 /*IdentifierInfo=*/Id: nullptr, T: Context.getTypeDeclType(Decl: Record), TInfo,
5758 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5759 /*InitStyle=*/ICIS_NoInit);
5760 Anon->setAccess(AS);
5761 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5762
5763 if (getLangOpts().CPlusPlus)
5764 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5765 } else {
5766 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5767 if (SCSpec == DeclSpec::SCS_mutable) {
5768 // mutable can only appear on non-static class members, so it's always
5769 // an error here
5770 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5771 Invalid = true;
5772 SC = SC_None;
5773 }
5774
5775 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5776 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5777 T: Context.getTypeDeclType(Decl: Record), TInfo, S: SC);
5778 if (Invalid)
5779 Anon->setInvalidDecl();
5780
5781 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5782
5783 // Default-initialize the implicit variable. This initialization will be
5784 // trivial in almost all cases, except if a union member has an in-class
5785 // initializer:
5786 // union { int n = 0; };
5787 ActOnUninitializedDecl(dcl: Anon);
5788 }
5789 Anon->setImplicit();
5790
5791 // Mark this as an anonymous struct/union type.
5792 Record->setAnonymousStructOrUnion(true);
5793
5794 // Add the anonymous struct/union object to the current
5795 // context. We'll be referencing this object when we refer to one of
5796 // its members.
5797 Owner->addDecl(D: Anon);
5798
5799 // Inject the members of the anonymous struct/union into the owning
5800 // context and into the identifier resolver chain for name lookup
5801 // purposes.
5802 SmallVector<NamedDecl*, 2> Chain;
5803 Chain.push_back(Elt: Anon);
5804
5805 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5806 Chaining&: Chain))
5807 Invalid = true;
5808
5809 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5810 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5811 MangleNumberingContext *MCtx;
5812 Decl *ManglingContextDecl;
5813 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5814 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5815 if (MCtx) {
5816 Context.setManglingNumber(
5817 ND: NewVD, Number: MCtx->getManglingNumber(
5818 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5819 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5820 }
5821 }
5822 }
5823
5824 if (Invalid)
5825 Anon->setInvalidDecl();
5826
5827 return Anon;
5828}
5829
5830Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5831 RecordDecl *Record) {
5832 assert(Record && "expected a record!");
5833
5834 // Mock up a declarator.
5835 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5837 assert(TInfo && "couldn't build declarator info for anonymous struct");
5838
5839 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5840 QualType RecTy = Context.getTypeDeclType(Decl: Record);
5841
5842 // Create a declaration for this anonymous struct.
5843 NamedDecl *Anon =
5844 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
5845 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
5846 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5847 /*InitStyle=*/ICIS_NoInit);
5848 Anon->setImplicit();
5849
5850 // Add the anonymous struct object to the current context.
5851 CurContext->addDecl(D: Anon);
5852
5853 // Inject the members of the anonymous struct into the current
5854 // context and into the identifier resolver chain for name lookup
5855 // purposes.
5856 SmallVector<NamedDecl*, 2> Chain;
5857 Chain.push_back(Elt: Anon);
5858
5859 RecordDecl *RecordDef = Record->getDefinition();
5860 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
5861 DiagID: diag::err_field_incomplete_or_sizeless) ||
5862 InjectAnonymousStructOrUnionMembers(
5863 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
5864 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
5865 Anon->setInvalidDecl();
5866 ParentDecl->setInvalidDecl();
5867 }
5868
5869 return Anon;
5870}
5871
5872DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5873 return GetNameFromUnqualifiedId(Name: D.getName());
5874}
5875
5876DeclarationNameInfo
5877Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5878 DeclarationNameInfo NameInfo;
5879 NameInfo.setLoc(Name.StartLocation);
5880
5881 switch (Name.getKind()) {
5882
5883 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5884 case UnqualifiedIdKind::IK_Identifier:
5885 NameInfo.setName(Name.Identifier);
5886 return NameInfo;
5887
5888 case UnqualifiedIdKind::IK_DeductionGuideName: {
5889 // C++ [temp.deduct.guide]p3:
5890 // The simple-template-id shall name a class template specialization.
5891 // The template-name shall be the same identifier as the template-name
5892 // of the simple-template-id.
5893 // These together intend to imply that the template-name shall name a
5894 // class template.
5895 // FIXME: template<typename T> struct X {};
5896 // template<typename T> using Y = X<T>;
5897 // Y(int) -> Y<int>;
5898 // satisfies these rules but does not name a class template.
5899 TemplateName TN = Name.TemplateName.get().get();
5900 auto *Template = TN.getAsTemplateDecl();
5901 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
5902 Diag(Loc: Name.StartLocation,
5903 DiagID: diag::err_deduction_guide_name_not_class_template)
5904 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
5905 if (Template)
5906 NoteTemplateLocation(Decl: *Template);
5907 return DeclarationNameInfo();
5908 }
5909
5910 NameInfo.setName(
5911 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
5912 return NameInfo;
5913 }
5914
5915 case UnqualifiedIdKind::IK_OperatorFunctionId:
5916 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5917 Op: Name.OperatorFunctionId.Operator));
5918 NameInfo.setCXXOperatorNameRange(SourceRange(
5919 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5920 return NameInfo;
5921
5922 case UnqualifiedIdKind::IK_LiteralOperatorId:
5923 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5924 II: Name.Identifier));
5925 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5926 return NameInfo;
5927
5928 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5929 TypeSourceInfo *TInfo;
5930 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
5931 if (Ty.isNull())
5932 return DeclarationNameInfo();
5933 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5934 Ty: Context.getCanonicalType(T: Ty)));
5935 NameInfo.setNamedTypeInfo(TInfo);
5936 return NameInfo;
5937 }
5938
5939 case UnqualifiedIdKind::IK_ConstructorName: {
5940 TypeSourceInfo *TInfo;
5941 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
5942 if (Ty.isNull())
5943 return DeclarationNameInfo();
5944 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5945 Ty: Context.getCanonicalType(T: Ty)));
5946 NameInfo.setNamedTypeInfo(TInfo);
5947 return NameInfo;
5948 }
5949
5950 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5951 // In well-formed code, we can only have a constructor
5952 // template-id that refers to the current context, so go there
5953 // to find the actual type being constructed.
5954 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
5955 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5956 return DeclarationNameInfo();
5957
5958 // Determine the type of the class being constructed.
5959 QualType CurClassType = Context.getTypeDeclType(Decl: CurClass);
5960
5961 // FIXME: Check two things: that the template-id names the same type as
5962 // CurClassType, and that the template-id does not occur when the name
5963 // was qualified.
5964
5965 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5966 Ty: Context.getCanonicalType(T: CurClassType)));
5967 // FIXME: should we retrieve TypeSourceInfo?
5968 NameInfo.setNamedTypeInfo(nullptr);
5969 return NameInfo;
5970 }
5971
5972 case UnqualifiedIdKind::IK_DestructorName: {
5973 TypeSourceInfo *TInfo;
5974 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
5975 if (Ty.isNull())
5976 return DeclarationNameInfo();
5977 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5978 Ty: Context.getCanonicalType(T: Ty)));
5979 NameInfo.setNamedTypeInfo(TInfo);
5980 return NameInfo;
5981 }
5982
5983 case UnqualifiedIdKind::IK_TemplateId: {
5984 TemplateName TName = Name.TemplateId->Template.get();
5985 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5986 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
5987 }
5988
5989 } // switch (Name.getKind())
5990
5991 llvm_unreachable("Unknown name kind");
5992}
5993
5994static QualType getCoreType(QualType Ty) {
5995 do {
5996 if (Ty->isPointerOrReferenceType())
5997 Ty = Ty->getPointeeType();
5998 else if (Ty->isArrayType())
5999 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6000 else
6001 return Ty.withoutLocalFastQualifiers();
6002 } while (true);
6003}
6004
6005/// hasSimilarParameters - Determine whether the C++ functions Declaration
6006/// and Definition have "nearly" matching parameters. This heuristic is
6007/// used to improve diagnostics in the case where an out-of-line function
6008/// definition doesn't match any declaration within the class or namespace.
6009/// Also sets Params to the list of indices to the parameters that differ
6010/// between the declaration and the definition. If hasSimilarParameters
6011/// returns true and Params is empty, then all of the parameters match.
6012static bool hasSimilarParameters(ASTContext &Context,
6013 FunctionDecl *Declaration,
6014 FunctionDecl *Definition,
6015 SmallVectorImpl<unsigned> &Params) {
6016 Params.clear();
6017 if (Declaration->param_size() != Definition->param_size())
6018 return false;
6019 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6020 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6021 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6022
6023 // The parameter types are identical
6024 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6025 continue;
6026
6027 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6028 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6029 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6030 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6031
6032 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6033 (DeclTyName && DeclTyName == DefTyName))
6034 Params.push_back(Elt: Idx);
6035 else // The two parameters aren't even close
6036 return false;
6037 }
6038
6039 return true;
6040}
6041
6042/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6043/// declarator needs to be rebuilt in the current instantiation.
6044/// Any bits of declarator which appear before the name are valid for
6045/// consideration here. That's specifically the type in the decl spec
6046/// and the base type in any member-pointer chunks.
6047static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6048 DeclarationName Name) {
6049 // The types we specifically need to rebuild are:
6050 // - typenames, typeofs, and decltypes
6051 // - types which will become injected class names
6052 // Of course, we also need to rebuild any type referencing such a
6053 // type. It's safest to just say "dependent", but we call out a
6054 // few cases here.
6055
6056 DeclSpec &DS = D.getMutableDeclSpec();
6057 switch (DS.getTypeSpecType()) {
6058 case DeclSpec::TST_typename:
6059 case DeclSpec::TST_typeofType:
6060 case DeclSpec::TST_typeof_unqualType:
6061#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6062#include "clang/Basic/TransformTypeTraits.def"
6063 case DeclSpec::TST_atomic: {
6064 // Grab the type from the parser.
6065 TypeSourceInfo *TSI = nullptr;
6066 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6067 if (T.isNull() || !T->isInstantiationDependentType()) break;
6068
6069 // Make sure there's a type source info. This isn't really much
6070 // of a waste; most dependent types should have type source info
6071 // attached already.
6072 if (!TSI)
6073 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6074
6075 // Rebuild the type in the current instantiation.
6076 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6077 if (!TSI) return true;
6078
6079 // Store the new type back in the decl spec.
6080 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6081 DS.UpdateTypeRep(Rep: LocType);
6082 break;
6083 }
6084
6085 case DeclSpec::TST_decltype:
6086 case DeclSpec::TST_typeof_unqualExpr:
6087 case DeclSpec::TST_typeofExpr: {
6088 Expr *E = DS.getRepAsExpr();
6089 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6090 if (Result.isInvalid()) return true;
6091 DS.UpdateExprRep(Rep: Result.get());
6092 break;
6093 }
6094
6095 default:
6096 // Nothing to do for these decl specs.
6097 break;
6098 }
6099
6100 // It doesn't matter what order we do this in.
6101 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6102 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6103
6104 // The only type information in the declarator which can come
6105 // before the declaration name is the base type of a member
6106 // pointer.
6107 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6108 continue;
6109
6110 // Rebuild the scope specifier in-place.
6111 CXXScopeSpec &SS = Chunk.Mem.Scope();
6112 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6113 return true;
6114 }
6115
6116 return false;
6117}
6118
6119/// Returns true if the declaration is declared in a system header or from a
6120/// system macro.
6121static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6122 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6123 SM.isInSystemMacro(loc: D->getLocation());
6124}
6125
6126void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6127 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6128 // of system decl.
6129 if (D->getPreviousDecl() || D->isImplicit())
6130 return;
6131 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6132 if (Status != ReservedIdentifierStatus::NotReserved &&
6133 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6134 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6135 << D << static_cast<int>(Status);
6136 }
6137}
6138
6139Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6140 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6141
6142 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6143 // declaration only if the `bind_to_declaration` extension is set.
6144 SmallVector<FunctionDecl *, 4> Bases;
6145 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6146 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6147 TP: llvm::omp::TraitProperty::
6148 implementation_extension_bind_to_declaration))
6149 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6150 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6151
6152 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6153
6154 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6155 Dcl && Dcl->getDeclContext()->isFileContext())
6156 Dcl->setTopLevelDeclInObjCContainer();
6157
6158 if (!Bases.empty())
6159 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6160 Bases);
6161
6162 return Dcl;
6163}
6164
6165bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6166 DeclarationNameInfo NameInfo) {
6167 DeclarationName Name = NameInfo.getName();
6168
6169 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6170 while (Record && Record->isAnonymousStructOrUnion())
6171 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6172 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6173 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6174 return true;
6175 }
6176
6177 return false;
6178}
6179
6180bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6181 DeclarationName Name,
6182 SourceLocation Loc,
6183 TemplateIdAnnotation *TemplateId,
6184 bool IsMemberSpecialization) {
6185 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6186 "without nested-name-specifier");
6187 DeclContext *Cur = CurContext;
6188 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6189 Cur = Cur->getParent();
6190
6191 // If the user provided a superfluous scope specifier that refers back to the
6192 // class in which the entity is already declared, diagnose and ignore it.
6193 //
6194 // class X {
6195 // void X::f();
6196 // };
6197 //
6198 // Note, it was once ill-formed to give redundant qualification in all
6199 // contexts, but that rule was removed by DR482.
6200 if (Cur->Equals(DC)) {
6201 if (Cur->isRecord()) {
6202 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6203 : diag::err_member_extra_qualification)
6204 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6205 SS.clear();
6206 } else {
6207 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6208 }
6209 return false;
6210 }
6211
6212 // Check whether the qualifying scope encloses the scope of the original
6213 // declaration. For a template-id, we perform the checks in
6214 // CheckTemplateSpecializationScope.
6215 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6216 if (Cur->isRecord())
6217 Diag(Loc, DiagID: diag::err_member_qualification)
6218 << Name << SS.getRange();
6219 else if (isa<TranslationUnitDecl>(Val: DC))
6220 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6221 << Name << SS.getRange();
6222 else if (isa<FunctionDecl>(Val: Cur))
6223 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6224 << Name << SS.getRange();
6225 else if (isa<BlockDecl>(Val: Cur))
6226 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6227 << Name << SS.getRange();
6228 else if (isa<ExportDecl>(Val: Cur)) {
6229 if (!isa<NamespaceDecl>(Val: DC))
6230 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6231 << Name << SS.getRange();
6232 else
6233 // The cases that DC is not NamespaceDecl should be handled in
6234 // CheckRedeclarationExported.
6235 return false;
6236 } else
6237 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6238 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6239
6240 return true;
6241 }
6242
6243 if (Cur->isRecord()) {
6244 // Cannot qualify members within a class.
6245 Diag(Loc, DiagID: diag::err_member_qualification)
6246 << Name << SS.getRange();
6247 SS.clear();
6248
6249 // C++ constructors and destructors with incorrect scopes can break
6250 // our AST invariants by having the wrong underlying types. If
6251 // that's the case, then drop this declaration entirely.
6252 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6253 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6254 !Context.hasSameType(T1: Name.getCXXNameType(),
6255 T2: Context.getTypeDeclType(Decl: cast<CXXRecordDecl>(Val: Cur))))
6256 return true;
6257
6258 return false;
6259 }
6260
6261 // C++23 [temp.names]p5:
6262 // The keyword template shall not appear immediately after a declarative
6263 // nested-name-specifier.
6264 //
6265 // First check the template-id (if any), and then check each component of the
6266 // nested-name-specifier in reverse order.
6267 //
6268 // FIXME: nested-name-specifiers in friend declarations are declarative,
6269 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6270 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6271 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6272 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6273
6274 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6275 do {
6276 if (TypeLoc TL = SpecLoc.getTypeLoc()) {
6277 if (SourceLocation TemplateKeywordLoc = TL.getTemplateKeywordLoc();
6278 TemplateKeywordLoc.isValid())
6279 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6280 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6281 }
6282
6283 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6284 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6285 // C++23 [expr.prim.id.qual]p3:
6286 // [...] If a nested-name-specifier N is declarative and has a
6287 // simple-template-id with a template argument list A that involves a
6288 // template parameter, let T be the template nominated by N without A.
6289 // T shall be a class template.
6290 if (TST->isDependentType() && TST->isTypeAlias())
6291 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6292 << SpecLoc.getLocalSourceRange();
6293 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6294 // C++23 [expr.prim.id.qual]p2:
6295 // [...] A declarative nested-name-specifier shall not have a
6296 // computed-type-specifier.
6297 //
6298 // CWG2858 changed this from 'decltype-specifier' to
6299 // 'computed-type-specifier'.
6300 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6301 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6302 }
6303 }
6304 } while ((SpecLoc = SpecLoc.getPrefix()));
6305
6306 return false;
6307}
6308
6309NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6310 MultiTemplateParamsArg TemplateParamLists) {
6311 // TODO: consider using NameInfo for diagnostic.
6312 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6313 DeclarationName Name = NameInfo.getName();
6314
6315 // All of these full declarators require an identifier. If it doesn't have
6316 // one, the ParsedFreeStandingDeclSpec action should be used.
6317 if (D.isDecompositionDeclarator()) {
6318 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6319 } else if (!Name) {
6320 if (!D.isInvalidType()) // Reject this if we think it is valid.
6321 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6322 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6323 return nullptr;
6324 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6325 return nullptr;
6326
6327 DeclContext *DC = CurContext;
6328 if (D.getCXXScopeSpec().isInvalid())
6329 D.setInvalidType();
6330 else if (D.getCXXScopeSpec().isSet()) {
6331 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6332 UPPC: UPPC_DeclarationQualifier))
6333 return nullptr;
6334
6335 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6336 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6337 if (!DC || isa<EnumDecl>(Val: DC)) {
6338 // If we could not compute the declaration context, it's because the
6339 // declaration context is dependent but does not refer to a class,
6340 // class template, or class template partial specialization. Complain
6341 // and return early, to avoid the coming semantic disaster.
6342 Diag(Loc: D.getIdentifierLoc(),
6343 DiagID: diag::err_template_qualified_declarator_no_match)
6344 << D.getCXXScopeSpec().getScopeRep()
6345 << D.getCXXScopeSpec().getRange();
6346 return nullptr;
6347 }
6348 bool IsDependentContext = DC->isDependentContext();
6349
6350 if (!IsDependentContext &&
6351 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6352 return nullptr;
6353
6354 // If a class is incomplete, do not parse entities inside it.
6355 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6356 Diag(Loc: D.getIdentifierLoc(),
6357 DiagID: diag::err_member_def_undefined_record)
6358 << Name << DC << D.getCXXScopeSpec().getRange();
6359 return nullptr;
6360 }
6361 if (!D.getDeclSpec().isFriendSpecified()) {
6362 TemplateIdAnnotation *TemplateId =
6363 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6364 ? D.getName().TemplateId
6365 : nullptr;
6366 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6367 Loc: D.getIdentifierLoc(), TemplateId,
6368 /*IsMemberSpecialization=*/false)) {
6369 if (DC->isRecord())
6370 return nullptr;
6371
6372 D.setInvalidType();
6373 }
6374 }
6375
6376 // Check whether we need to rebuild the type of the given
6377 // declaration in the current instantiation.
6378 if (EnteringContext && IsDependentContext &&
6379 TemplateParamLists.size() != 0) {
6380 ContextRAII SavedContext(*this, DC);
6381 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6382 D.setInvalidType();
6383 }
6384 }
6385
6386 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6387 QualType R = TInfo->getType();
6388
6389 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6390 UPPC: UPPC_DeclarationType))
6391 D.setInvalidType();
6392
6393 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6394 forRedeclarationInCurContext());
6395
6396 // See if this is a redefinition of a variable in the same scope.
6397 if (!D.getCXXScopeSpec().isSet()) {
6398 bool IsLinkageLookup = false;
6399 bool CreateBuiltins = false;
6400
6401 // If the declaration we're planning to build will be a function
6402 // or object with linkage, then look for another declaration with
6403 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6404 //
6405 // If the declaration we're planning to build will be declared with
6406 // external linkage in the translation unit, create any builtin with
6407 // the same name.
6408 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6409 /* Do nothing*/;
6410 else if (CurContext->isFunctionOrMethod() &&
6411 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6412 R->isFunctionType())) {
6413 IsLinkageLookup = true;
6414 CreateBuiltins =
6415 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6416 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6417 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6418 CreateBuiltins = true;
6419
6420 if (IsLinkageLookup) {
6421 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6422 Previous.setRedeclarationKind(
6423 RedeclarationKind::ForExternalRedeclaration);
6424 }
6425
6426 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6427 } else { // Something like "int foo::x;"
6428 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6429
6430 // C++ [dcl.meaning]p1:
6431 // When the declarator-id is qualified, the declaration shall refer to a
6432 // previously declared member of the class or namespace to which the
6433 // qualifier refers (or, in the case of a namespace, of an element of the
6434 // inline namespace set of that namespace (7.3.1)) or to a specialization
6435 // thereof; [...]
6436 //
6437 // Note that we already checked the context above, and that we do not have
6438 // enough information to make sure that Previous contains the declaration
6439 // we want to match. For example, given:
6440 //
6441 // class X {
6442 // void f();
6443 // void f(float);
6444 // };
6445 //
6446 // void X::f(int) { } // ill-formed
6447 //
6448 // In this case, Previous will point to the overload set
6449 // containing the two f's declared in X, but neither of them
6450 // matches.
6451
6452 RemoveUsingDecls(R&: Previous);
6453 }
6454
6455 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6456 TPD && TPD->isTemplateParameter()) {
6457 // Older versions of clang allowed the names of function/variable templates
6458 // to shadow the names of their template parameters. For the compatibility
6459 // purposes we detect such cases and issue a default-to-error warning that
6460 // can be disabled with -Wno-strict-primary-template-shadow.
6461 if (!D.isInvalidType()) {
6462 bool AllowForCompatibility = false;
6463 if (Scope *DeclParent = S->getDeclParent();
6464 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6465 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6466 TemplateParamParent->isDeclScope(D: TPD);
6467 }
6468 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6469 SupportedForCompatibility: AllowForCompatibility);
6470 }
6471
6472 // Just pretend that we didn't see the previous declaration.
6473 Previous.clear();
6474 }
6475
6476 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6477 // Forget that the previous declaration is the injected-class-name.
6478 Previous.clear();
6479
6480 // In C++, the previous declaration we find might be a tag type
6481 // (class or enum). In this case, the new declaration will hide the
6482 // tag type. Note that this applies to functions, function templates, and
6483 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6484 if (Previous.isSingleTagDecl() &&
6485 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6486 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6487 Previous.clear();
6488
6489 // Check that there are no default arguments other than in the parameters
6490 // of a function declaration (C++ only).
6491 if (getLangOpts().CPlusPlus)
6492 CheckExtraCXXDefaultArguments(D);
6493
6494 /// Get the innermost enclosing declaration scope.
6495 S = S->getDeclParent();
6496
6497 NamedDecl *New;
6498
6499 bool AddToScope = true;
6500 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6501 if (TemplateParamLists.size()) {
6502 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6503 return nullptr;
6504 }
6505
6506 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6507 } else if (R->isFunctionType()) {
6508 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6509 TemplateParamLists,
6510 AddToScope);
6511 } else {
6512 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6513 AddToScope);
6514 }
6515
6516 if (!New)
6517 return nullptr;
6518
6519 warnOnCTypeHiddenInCPlusPlus(D: New);
6520
6521 // If this has an identifier and is not a function template specialization,
6522 // add it to the scope stack.
6523 if (New->getDeclName() && AddToScope)
6524 PushOnScopeChains(D: New, S);
6525
6526 if (OpenMP().isInOpenMPDeclareTargetContext())
6527 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6528
6529 return New;
6530}
6531
6532/// Helper method to turn variable array types into constant array
6533/// types in certain situations which would otherwise be errors (for
6534/// GCC compatibility).
6535static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6536 ASTContext &Context,
6537 bool &SizeIsNegative,
6538 llvm::APSInt &Oversized) {
6539 // This method tries to turn a variable array into a constant
6540 // array even when the size isn't an ICE. This is necessary
6541 // for compatibility with code that depends on gcc's buggy
6542 // constant expression folding, like struct {char x[(int)(char*)2];}
6543 SizeIsNegative = false;
6544 Oversized = 0;
6545
6546 if (T->isDependentType())
6547 return QualType();
6548
6549 QualifierCollector Qs;
6550 const Type *Ty = Qs.strip(type: T);
6551
6552 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6553 QualType Pointee = PTy->getPointeeType();
6554 QualType FixedType =
6555 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6556 Oversized);
6557 if (FixedType.isNull()) return FixedType;
6558 FixedType = Context.getPointerType(T: FixedType);
6559 return Qs.apply(Context, QT: FixedType);
6560 }
6561 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6562 QualType Inner = PTy->getInnerType();
6563 QualType FixedType =
6564 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6565 Oversized);
6566 if (FixedType.isNull()) return FixedType;
6567 FixedType = Context.getParenType(NamedType: FixedType);
6568 return Qs.apply(Context, QT: FixedType);
6569 }
6570
6571 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6572 if (!VLATy)
6573 return QualType();
6574
6575 QualType ElemTy = VLATy->getElementType();
6576 if (ElemTy->isVariablyModifiedType()) {
6577 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6578 SizeIsNegative, Oversized);
6579 if (ElemTy.isNull())
6580 return QualType();
6581 }
6582
6583 Expr::EvalResult Result;
6584 if (!VLATy->getSizeExpr() ||
6585 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6586 return QualType();
6587
6588 llvm::APSInt Res = Result.Val.getInt();
6589
6590 // Check whether the array size is negative.
6591 if (Res.isSigned() && Res.isNegative()) {
6592 SizeIsNegative = true;
6593 return QualType();
6594 }
6595
6596 // Check whether the array is too large to be addressed.
6597 unsigned ActiveSizeBits =
6598 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6599 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6600 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6601 : Res.getActiveBits();
6602 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6603 Oversized = Res;
6604 return QualType();
6605 }
6606
6607 QualType FoldedArrayType = Context.getConstantArrayType(
6608 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6609 return Qs.apply(Context, QT: FoldedArrayType);
6610}
6611
6612static void
6613FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6614 SrcTL = SrcTL.getUnqualifiedLoc();
6615 DstTL = DstTL.getUnqualifiedLoc();
6616 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6617 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6618 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6619 DstTL: DstPTL.getPointeeLoc());
6620 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6621 return;
6622 }
6623 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6624 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6625 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6626 DstTL: DstPTL.getInnerLoc());
6627 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6628 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6629 return;
6630 }
6631 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6632 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6633 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6634 TypeLoc DstElemTL = DstATL.getElementLoc();
6635 if (VariableArrayTypeLoc SrcElemATL =
6636 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6637 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6638 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6639 } else {
6640 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6641 }
6642 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6643 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6644 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6645}
6646
6647/// Helper method to turn variable array types into constant array
6648/// types in certain situations which would otherwise be errors (for
6649/// GCC compatibility).
6650static TypeSourceInfo*
6651TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6652 ASTContext &Context,
6653 bool &SizeIsNegative,
6654 llvm::APSInt &Oversized) {
6655 QualType FixedTy
6656 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6657 SizeIsNegative, Oversized);
6658 if (FixedTy.isNull())
6659 return nullptr;
6660 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6661 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6662 DstTL: FixedTInfo->getTypeLoc());
6663 return FixedTInfo;
6664}
6665
6666bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6667 QualType &T, SourceLocation Loc,
6668 unsigned FailedFoldDiagID) {
6669 bool SizeIsNegative;
6670 llvm::APSInt Oversized;
6671 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6672 TInfo, Context, SizeIsNegative, Oversized);
6673 if (FixedTInfo) {
6674 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6675 TInfo = FixedTInfo;
6676 T = FixedTInfo->getType();
6677 return true;
6678 }
6679
6680 if (SizeIsNegative)
6681 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6682 else if (Oversized.getBoolValue())
6683 Diag(Loc, DiagID: diag::err_array_too_large) << toString(I: Oversized, Radix: 10);
6684 else if (FailedFoldDiagID)
6685 Diag(Loc, DiagID: FailedFoldDiagID);
6686 return false;
6687}
6688
6689void
6690Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6691 if (!getLangOpts().CPlusPlus &&
6692 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6693 // Don't need to track declarations in the TU in C.
6694 return;
6695
6696 // Note that we have a locally-scoped external with this name.
6697 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6698}
6699
6700NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6701 // FIXME: We can have multiple results via __attribute__((overloadable)).
6702 auto Result = Context.getExternCContextDecl()->lookup(Name);
6703 return Result.empty() ? nullptr : *Result.begin();
6704}
6705
6706void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6707 // FIXME: We should probably indicate the identifier in question to avoid
6708 // confusion for constructs like "virtual int a(), b;"
6709 if (DS.isVirtualSpecified())
6710 Diag(Loc: DS.getVirtualSpecLoc(),
6711 DiagID: diag::err_virtual_non_function);
6712
6713 if (DS.hasExplicitSpecifier())
6714 Diag(Loc: DS.getExplicitSpecLoc(),
6715 DiagID: diag::err_explicit_non_function);
6716
6717 if (DS.isNoreturnSpecified())
6718 Diag(Loc: DS.getNoreturnSpecLoc(),
6719 DiagID: diag::err_noreturn_non_function);
6720}
6721
6722NamedDecl*
6723Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6724 TypeSourceInfo *TInfo, LookupResult &Previous) {
6725 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6726 if (D.getCXXScopeSpec().isSet()) {
6727 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6728 << D.getCXXScopeSpec().getRange();
6729 D.setInvalidType();
6730 // Pretend we didn't see the scope specifier.
6731 DC = CurContext;
6732 Previous.clear();
6733 }
6734
6735 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6736
6737 if (D.getDeclSpec().isInlineSpecified())
6738 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6739 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6740 ? diag::warn_ms_inline_non_function
6741 : diag::err_inline_non_function)
6742 << getLangOpts().CPlusPlus17;
6743 if (D.getDeclSpec().hasConstexprSpecifier())
6744 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6745 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6746
6747 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6748 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6749 Diag(Loc: D.getName().StartLocation,
6750 DiagID: diag::err_deduction_guide_invalid_specifier)
6751 << "typedef";
6752 else
6753 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6754 << D.getName().getSourceRange();
6755 return nullptr;
6756 }
6757
6758 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6759 if (!NewTD) return nullptr;
6760
6761 // Handle attributes prior to checking for duplicates in MergeVarDecl
6762 ProcessDeclAttributes(S, D: NewTD, PD: D);
6763
6764 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6765
6766 bool Redeclaration = D.isRedeclaration();
6767 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6768 D.setRedeclaration(Redeclaration);
6769 return ND;
6770}
6771
6772void
6773Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6774 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6775 // then it shall have block scope.
6776 // Note that variably modified types must be fixed before merging the decl so
6777 // that redeclarations will match.
6778 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6779 QualType T = TInfo->getType();
6780 if (T->isVariablyModifiedType()) {
6781 setFunctionHasBranchProtectedScope();
6782
6783 if (S->getFnParent() == nullptr) {
6784 bool SizeIsNegative;
6785 llvm::APSInt Oversized;
6786 TypeSourceInfo *FixedTInfo =
6787 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6788 SizeIsNegative,
6789 Oversized);
6790 if (FixedTInfo) {
6791 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6792 NewTD->setTypeSourceInfo(FixedTInfo);
6793 } else {
6794 if (SizeIsNegative)
6795 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6796 else if (T->isVariableArrayType())
6797 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6798 else if (Oversized.getBoolValue())
6799 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6800 << toString(I: Oversized, Radix: 10);
6801 else
6802 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6803 NewTD->setInvalidDecl();
6804 }
6805 }
6806 }
6807}
6808
6809NamedDecl*
6810Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6811 LookupResult &Previous, bool &Redeclaration) {
6812
6813 // Find the shadowed declaration before filtering for scope.
6814 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6815
6816 // Merge the decl with the existing one if appropriate. If the decl is
6817 // in an outer scope, it isn't the same thing.
6818 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6819 /*AllowInlineNamespace*/false);
6820 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6821 if (!Previous.empty()) {
6822 Redeclaration = true;
6823 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6824 } else {
6825 inferGslPointerAttribute(TD: NewTD);
6826 }
6827
6828 if (ShadowedDecl && !Redeclaration)
6829 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
6830
6831 // If this is the C FILE type, notify the AST context.
6832 if (IdentifierInfo *II = NewTD->getIdentifier())
6833 if (!NewTD->isInvalidDecl() &&
6834 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6835 switch (II->getNotableIdentifierID()) {
6836 case tok::NotableIdentifierKind::FILE:
6837 Context.setFILEDecl(NewTD);
6838 break;
6839 case tok::NotableIdentifierKind::jmp_buf:
6840 Context.setjmp_bufDecl(NewTD);
6841 break;
6842 case tok::NotableIdentifierKind::sigjmp_buf:
6843 Context.setsigjmp_bufDecl(NewTD);
6844 break;
6845 case tok::NotableIdentifierKind::ucontext_t:
6846 Context.setucontext_tDecl(NewTD);
6847 break;
6848 case tok::NotableIdentifierKind::float_t:
6849 case tok::NotableIdentifierKind::double_t:
6850 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
6851 break;
6852 default:
6853 break;
6854 }
6855 }
6856
6857 return NewTD;
6858}
6859
6860/// Determines whether the given declaration is an out-of-scope
6861/// previous declaration.
6862///
6863/// This routine should be invoked when name lookup has found a
6864/// previous declaration (PrevDecl) that is not in the scope where a
6865/// new declaration by the same name is being introduced. If the new
6866/// declaration occurs in a local scope, previous declarations with
6867/// linkage may still be considered previous declarations (C99
6868/// 6.2.2p4-5, C++ [basic.link]p6).
6869///
6870/// \param PrevDecl the previous declaration found by name
6871/// lookup
6872///
6873/// \param DC the context in which the new declaration is being
6874/// declared.
6875///
6876/// \returns true if PrevDecl is an out-of-scope previous declaration
6877/// for a new delcaration with the same name.
6878static bool
6879isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6880 ASTContext &Context) {
6881 if (!PrevDecl)
6882 return false;
6883
6884 if (!PrevDecl->hasLinkage())
6885 return false;
6886
6887 if (Context.getLangOpts().CPlusPlus) {
6888 // C++ [basic.link]p6:
6889 // If there is a visible declaration of an entity with linkage
6890 // having the same name and type, ignoring entities declared
6891 // outside the innermost enclosing namespace scope, the block
6892 // scope declaration declares that same entity and receives the
6893 // linkage of the previous declaration.
6894 DeclContext *OuterContext = DC->getRedeclContext();
6895 if (!OuterContext->isFunctionOrMethod())
6896 // This rule only applies to block-scope declarations.
6897 return false;
6898
6899 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6900 if (PrevOuterContext->isRecord())
6901 // We found a member function: ignore it.
6902 return false;
6903
6904 // Find the innermost enclosing namespace for the new and
6905 // previous declarations.
6906 OuterContext = OuterContext->getEnclosingNamespaceContext();
6907 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6908
6909 // The previous declaration is in a different namespace, so it
6910 // isn't the same function.
6911 if (!OuterContext->Equals(DC: PrevOuterContext))
6912 return false;
6913 }
6914
6915 return true;
6916}
6917
6918static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6919 CXXScopeSpec &SS = D.getCXXScopeSpec();
6920 if (!SS.isSet()) return;
6921 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
6922}
6923
6924void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6925 if (Decl->getType().hasAddressSpace())
6926 return;
6927 if (Decl->getType()->isDependentType())
6928 return;
6929 if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) {
6930 QualType Type = Var->getType();
6931 if (Type->isSamplerT() || Type->isVoidType())
6932 return;
6933 LangAS ImplAS = LangAS::opencl_private;
6934 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6935 // __opencl_c_program_scope_global_variables feature, the address space
6936 // for a variable at program scope or a static or extern variable inside
6937 // a function are inferred to be __global.
6938 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
6939 Var->hasGlobalStorage())
6940 ImplAS = LangAS::opencl_global;
6941 // If the original type from a decayed type is an array type and that array
6942 // type has no address space yet, deduce it now.
6943 if (auto DT = dyn_cast<DecayedType>(Val&: Type)) {
6944 auto OrigTy = DT->getOriginalType();
6945 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6946 // Add the address space to the original array type and then propagate
6947 // that to the element type through `getAsArrayType`.
6948 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
6949 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
6950 // Re-generate the decayed type.
6951 Type = Context.getDecayedType(T: OrigTy);
6952 }
6953 }
6954 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6955 // Apply any qualifiers (including address space) from the array type to
6956 // the element type. This implements C99 6.7.3p8: "If the specification of
6957 // an array type includes any type qualifiers, the element type is so
6958 // qualified, not the array type."
6959 if (Type->isArrayType())
6960 Type = QualType(Context.getAsArrayType(T: Type), 0);
6961 Decl->setType(Type);
6962 }
6963}
6964
6965static void checkWeakAttr(Sema &S, NamedDecl &ND) {
6966 // 'weak' only applies to declarations with external linkage.
6967 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6968 if (!ND.isExternallyVisible()) {
6969 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
6970 ND.dropAttr<WeakAttr>();
6971 }
6972 }
6973}
6974
6975static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6976 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6977 if (ND.isExternallyVisible()) {
6978 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
6979 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6980 }
6981 }
6982}
6983
6984static void checkAliasAttr(Sema &S, NamedDecl &ND) {
6985 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
6986 if (VD->hasInit()) {
6987 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6988 assert(VD->isThisDeclarationADefinition() &&
6989 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6990 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
6991 VD->dropAttr<AliasAttr>();
6992 }
6993 }
6994 }
6995}
6996
6997static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
6998 // 'selectany' only applies to externally visible variable declarations.
6999 // It does not apply to functions.
7000 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7001 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7002 S.Diag(Loc: Attr->getLocation(),
7003 DiagID: diag::err_attribute_selectany_non_extern_data);
7004 ND.dropAttr<SelectAnyAttr>();
7005 }
7006 }
7007}
7008
7009static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7010 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7011 if (!ND.isExternallyVisible())
7012 S.Diag(Loc: Attr->getLocation(),
7013 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7014 }
7015}
7016
7017static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7018 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7019 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7020 bool IsAnonymousNS = false;
7021 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7022 if (VD) {
7023 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7024 while (NS && !IsAnonymousNS) {
7025 IsAnonymousNS = NS->isAnonymousNamespace();
7026 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7027 }
7028 }
7029 // dll attributes require external linkage. Static locals may have external
7030 // linkage but still cannot be explicitly imported or exported.
7031 // In Microsoft mode, a variable defined in anonymous namespace must have
7032 // external linkage in order to be exported.
7033 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7034 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7035 (!AnonNSInMicrosoftMode &&
7036 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7037 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7038 << &ND << Attr;
7039 ND.setInvalidDecl();
7040 }
7041 }
7042}
7043
7044static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7045 // Check the attributes on the function type and function params, if any.
7046 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7047 FD = FD->getMostRecentDecl();
7048 // Don't declare this variable in the second operand of the for-statement;
7049 // GCC miscompiles that by ending its lifetime before evaluating the
7050 // third operand. See gcc.gnu.org/PR86769.
7051 AttributedTypeLoc ATL;
7052 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7053 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7054 TL = ATL.getModifiedLoc()) {
7055 // The [[lifetimebound]] attribute can be applied to the implicit object
7056 // parameter of a non-static member function (other than a ctor or dtor)
7057 // by applying it to the function type.
7058 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7059 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7060 int NoImplicitObjectError = -1;
7061 if (!MD)
7062 NoImplicitObjectError = 0;
7063 else if (MD->isStatic())
7064 NoImplicitObjectError = 1;
7065 else if (MD->isExplicitObjectMemberFunction())
7066 NoImplicitObjectError = 2;
7067 if (NoImplicitObjectError != -1) {
7068 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7069 << NoImplicitObjectError << A->getRange();
7070 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7071 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7072 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7073 } else if (MD->getReturnType()->isVoidType()) {
7074 S.Diag(
7075 Loc: MD->getLocation(),
7076 DiagID: diag::
7077 err_lifetimebound_implicit_object_parameter_void_return_type);
7078 }
7079 }
7080 }
7081
7082 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7083 const ParmVarDecl *P = FD->getParamDecl(i: I);
7084
7085 // The [[lifetimebound]] attribute can be applied to a function parameter
7086 // only if the function returns a value.
7087 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7088 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7089 S.Diag(Loc: A->getLocation(),
7090 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7091 }
7092 }
7093 }
7094 }
7095}
7096
7097static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7098 // Ensure that an auto decl is deduced otherwise the checks below might cache
7099 // the wrong linkage.
7100 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7101
7102 checkWeakAttr(S, ND);
7103 checkWeakRefAttr(S, ND);
7104 checkAliasAttr(S, ND);
7105 checkSelectAnyAttr(S, ND);
7106 checkHybridPatchableAttr(S, ND);
7107 checkInheritableAttr(S, ND);
7108 checkLifetimeBoundAttr(S, ND);
7109}
7110
7111static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7112 NamedDecl *NewDecl,
7113 bool IsSpecialization,
7114 bool IsDefinition) {
7115 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7116 return;
7117
7118 bool IsTemplate = false;
7119 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7120 OldDecl = OldTD->getTemplatedDecl();
7121 IsTemplate = true;
7122 if (!IsSpecialization)
7123 IsDefinition = false;
7124 }
7125 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7126 NewDecl = NewTD->getTemplatedDecl();
7127 IsTemplate = true;
7128 }
7129
7130 if (!OldDecl || !NewDecl)
7131 return;
7132
7133 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7134 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7135 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7136 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7137
7138 // dllimport and dllexport are inheritable attributes so we have to exclude
7139 // inherited attribute instances.
7140 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7141 (NewExportAttr && !NewExportAttr->isInherited());
7142
7143 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7144 // the only exception being explicit specializations.
7145 // Implicitly generated declarations are also excluded for now because there
7146 // is no other way to switch these to use dllimport or dllexport.
7147 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7148
7149 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7150 // Allow with a warning for free functions and global variables.
7151 bool JustWarn = false;
7152 if (!OldDecl->isCXXClassMember()) {
7153 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7154 if (VD && !VD->getDescribedVarTemplate())
7155 JustWarn = true;
7156 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7157 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7158 JustWarn = true;
7159 }
7160
7161 // We cannot change a declaration that's been used because IR has already
7162 // been emitted. Dllimported functions will still work though (modulo
7163 // address equality) as they can use the thunk.
7164 if (OldDecl->isUsed())
7165 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7166 JustWarn = false;
7167
7168 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7169 : diag::err_attribute_dll_redeclaration;
7170 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7171 << NewDecl
7172 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7173 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7174 if (!JustWarn) {
7175 NewDecl->setInvalidDecl();
7176 return;
7177 }
7178 }
7179
7180 // A redeclaration is not allowed to drop a dllimport attribute, the only
7181 // exceptions being inline function definitions (except for function
7182 // templates), local extern declarations, qualified friend declarations or
7183 // special MSVC extension: in the last case, the declaration is treated as if
7184 // it were marked dllexport.
7185 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7186 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7187 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7188 // Ignore static data because out-of-line definitions are diagnosed
7189 // separately.
7190 IsStaticDataMember = VD->isStaticDataMember();
7191 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7192 VarDecl::DeclarationOnly;
7193 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7194 IsInline = FD->isInlined();
7195 IsQualifiedFriend = FD->getQualifier() &&
7196 FD->getFriendObjectKind() == Decl::FOK_Declared;
7197 }
7198
7199 if (OldImportAttr && !HasNewAttr &&
7200 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7201 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7202 if (IsMicrosoftABI && IsDefinition) {
7203 if (IsSpecialization) {
7204 S.Diag(
7205 Loc: NewDecl->getLocation(),
7206 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7207 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7208 NewDecl->dropAttr<DLLImportAttr>();
7209 } else {
7210 S.Diag(Loc: NewDecl->getLocation(),
7211 DiagID: diag::warn_redeclaration_without_import_attribute)
7212 << NewDecl;
7213 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7214 NewDecl->dropAttr<DLLImportAttr>();
7215 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7216 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7217 }
7218 } else if (IsMicrosoftABI && IsSpecialization) {
7219 assert(!IsDefinition);
7220 // MSVC allows this. Keep the inherited attribute.
7221 } else {
7222 S.Diag(Loc: NewDecl->getLocation(),
7223 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7224 << NewDecl << OldImportAttr;
7225 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7226 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7227 OldDecl->dropAttr<DLLImportAttr>();
7228 NewDecl->dropAttr<DLLImportAttr>();
7229 }
7230 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7231 // In MinGW, seeing a function declared inline drops the dllimport
7232 // attribute.
7233 OldDecl->dropAttr<DLLImportAttr>();
7234 NewDecl->dropAttr<DLLImportAttr>();
7235 S.Diag(Loc: NewDecl->getLocation(),
7236 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7237 << NewDecl << OldImportAttr;
7238 }
7239
7240 // A specialization of a class template member function is processed here
7241 // since it's a redeclaration. If the parent class is dllexport, the
7242 // specialization inherits that attribute. This doesn't happen automatically
7243 // since the parent class isn't instantiated until later.
7244 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7245 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7246 !NewImportAttr && !NewExportAttr) {
7247 if (const DLLExportAttr *ParentExportAttr =
7248 MD->getParent()->getAttr<DLLExportAttr>()) {
7249 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7250 NewAttr->setInherited(true);
7251 NewDecl->addAttr(A: NewAttr);
7252 }
7253 }
7254 }
7255}
7256
7257/// Given that we are within the definition of the given function,
7258/// will that definition behave like C99's 'inline', where the
7259/// definition is discarded except for optimization purposes?
7260static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7261 // Try to avoid calling GetGVALinkageForFunction.
7262
7263 // All cases of this require the 'inline' keyword.
7264 if (!FD->isInlined()) return false;
7265
7266 // This is only possible in C++ with the gnu_inline attribute.
7267 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7268 return false;
7269
7270 // Okay, go ahead and call the relatively-more-expensive function.
7271 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7272}
7273
7274/// Determine whether a variable is extern "C" prior to attaching
7275/// an initializer. We can't just call isExternC() here, because that
7276/// will also compute and cache whether the declaration is externally
7277/// visible, which might change when we attach the initializer.
7278///
7279/// This can only be used if the declaration is known to not be a
7280/// redeclaration of an internal linkage declaration.
7281///
7282/// For instance:
7283///
7284/// auto x = []{};
7285///
7286/// Attaching the initializer here makes this declaration not externally
7287/// visible, because its type has internal linkage.
7288///
7289/// FIXME: This is a hack.
7290template<typename T>
7291static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7292 if (S.getLangOpts().CPlusPlus) {
7293 // In C++, the overloadable attribute negates the effects of extern "C".
7294 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7295 return false;
7296
7297 // So do CUDA's host/device attributes.
7298 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7299 D->template hasAttr<CUDAHostAttr>()))
7300 return false;
7301 }
7302 return D->isExternC();
7303}
7304
7305static bool shouldConsiderLinkage(const VarDecl *VD) {
7306 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7307 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7308 isa<OMPDeclareMapperDecl>(Val: DC))
7309 return VD->hasExternalStorage();
7310 if (DC->isFileContext())
7311 return true;
7312 if (DC->isRecord())
7313 return false;
7314 if (DC->getDeclKind() == Decl::HLSLBuffer)
7315 return false;
7316
7317 if (isa<RequiresExprBodyDecl>(Val: DC))
7318 return false;
7319 llvm_unreachable("Unexpected context");
7320}
7321
7322static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7323 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7324 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7325 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7326 return true;
7327 if (DC->isRecord())
7328 return false;
7329 llvm_unreachable("Unexpected context");
7330}
7331
7332static bool hasParsedAttr(Scope *S, const Declarator &PD,
7333 ParsedAttr::Kind Kind) {
7334 // Check decl attributes on the DeclSpec.
7335 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7336 return true;
7337
7338 // Walk the declarator structure, checking decl attributes that were in a type
7339 // position to the decl itself.
7340 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7341 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7342 return true;
7343 }
7344
7345 // Finally, check attributes on the decl itself.
7346 return PD.getAttributes().hasAttribute(K: Kind) ||
7347 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7348}
7349
7350bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7351 if (!DC->isFunctionOrMethod())
7352 return false;
7353
7354 // If this is a local extern function or variable declared within a function
7355 // template, don't add it into the enclosing namespace scope until it is
7356 // instantiated; it might have a dependent type right now.
7357 if (DC->isDependentContext())
7358 return true;
7359
7360 // C++11 [basic.link]p7:
7361 // When a block scope declaration of an entity with linkage is not found to
7362 // refer to some other declaration, then that entity is a member of the
7363 // innermost enclosing namespace.
7364 //
7365 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7366 // semantically-enclosing namespace, not a lexically-enclosing one.
7367 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7368 DC = DC->getParent();
7369 return true;
7370}
7371
7372/// Returns true if given declaration has external C language linkage.
7373static bool isDeclExternC(const Decl *D) {
7374 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7375 return FD->isExternC();
7376 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7377 return VD->isExternC();
7378
7379 llvm_unreachable("Unknown type of decl!");
7380}
7381
7382/// Returns true if there hasn't been any invalid type diagnosed.
7383static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7384 DeclContext *DC = NewVD->getDeclContext();
7385 QualType R = NewVD->getType();
7386
7387 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7388 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7389 // argument.
7390 if (R->isImageType() || R->isPipeType()) {
7391 Se.Diag(Loc: NewVD->getLocation(),
7392 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7393 << R;
7394 NewVD->setInvalidDecl();
7395 return false;
7396 }
7397
7398 // OpenCL v1.2 s6.9.r:
7399 // The event type cannot be used to declare a program scope variable.
7400 // OpenCL v2.0 s6.9.q:
7401 // The clk_event_t and reserve_id_t types cannot be declared in program
7402 // scope.
7403 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7404 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7405 Se.Diag(Loc: NewVD->getLocation(),
7406 DiagID: diag::err_invalid_type_for_program_scope_var)
7407 << R;
7408 NewVD->setInvalidDecl();
7409 return false;
7410 }
7411 }
7412
7413 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7414 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7415 LO: Se.getLangOpts())) {
7416 QualType NR = R.getCanonicalType();
7417 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7418 NR->isReferenceType()) {
7419 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7420 NR->isFunctionReferenceType()) {
7421 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7422 << NR->isReferenceType();
7423 NewVD->setInvalidDecl();
7424 return false;
7425 }
7426 NR = NR->getPointeeType();
7427 }
7428 }
7429
7430 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7431 LO: Se.getLangOpts())) {
7432 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7433 // half array type (unless the cl_khr_fp16 extension is enabled).
7434 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7435 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7436 NewVD->setInvalidDecl();
7437 return false;
7438 }
7439 }
7440
7441 // OpenCL v1.2 s6.9.r:
7442 // The event type cannot be used with the __local, __constant and __global
7443 // address space qualifiers.
7444 if (R->isEventT()) {
7445 if (R.getAddressSpace() != LangAS::opencl_private) {
7446 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7447 NewVD->setInvalidDecl();
7448 return false;
7449 }
7450 }
7451
7452 if (R->isSamplerT()) {
7453 // OpenCL v1.2 s6.9.b p4:
7454 // The sampler type cannot be used with the __local and __global address
7455 // space qualifiers.
7456 if (R.getAddressSpace() == LangAS::opencl_local ||
7457 R.getAddressSpace() == LangAS::opencl_global) {
7458 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7459 NewVD->setInvalidDecl();
7460 }
7461
7462 // OpenCL v1.2 s6.12.14.1:
7463 // A global sampler must be declared with either the constant address
7464 // space qualifier or with the const qualifier.
7465 if (DC->isTranslationUnit() &&
7466 !(R.getAddressSpace() == LangAS::opencl_constant ||
7467 R.isConstQualified())) {
7468 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7469 NewVD->setInvalidDecl();
7470 }
7471 if (NewVD->isInvalidDecl())
7472 return false;
7473 }
7474
7475 return true;
7476}
7477
7478template <typename AttrTy>
7479static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7480 const TypedefNameDecl *TND = TT->getDecl();
7481 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7482 AttrTy *Clone = Attribute->clone(S.Context);
7483 Clone->setInherited(true);
7484 D->addAttr(A: Clone);
7485 }
7486}
7487
7488// This function emits warning and a corresponding note based on the
7489// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7490// declarations of an annotated type must be const qualified.
7491static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7492 QualType VarType = VD->getType().getCanonicalType();
7493
7494 // Ignore local declarations (for now) and those with const qualification.
7495 // TODO: Local variables should not be allowed if their type declaration has
7496 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7497 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7498 return;
7499
7500 if (VarType->isArrayType()) {
7501 // Retrieve element type for array declarations.
7502 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7503 }
7504
7505 const RecordDecl *RD = VarType->getAsRecordDecl();
7506
7507 // Check if the record declaration is present and if it has any attributes.
7508 if (RD == nullptr)
7509 return;
7510
7511 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7512 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7513 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7514 return;
7515 }
7516}
7517
7518// Checks if VD is declared at global scope or with C language linkage.
7519static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7520 return Name.getAsIdentifierInfo() &&
7521 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7522 !VD->getDescribedVarTemplate() &&
7523 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7524 VD->isExternC());
7525}
7526
7527NamedDecl *Sema::ActOnVariableDeclarator(
7528 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7529 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7530 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7531 QualType R = TInfo->getType();
7532 DeclarationName Name = GetNameForDeclarator(D).getName();
7533
7534 IdentifierInfo *II = Name.getAsIdentifierInfo();
7535 bool IsPlaceholderVariable = false;
7536
7537 if (D.isDecompositionDeclarator()) {
7538 // Take the name of the first declarator as our name for diagnostic
7539 // purposes.
7540 auto &Decomp = D.getDecompositionDeclarator();
7541 if (!Decomp.bindings().empty()) {
7542 II = Decomp.bindings()[0].Name;
7543 Name = II;
7544 }
7545 } else if (!II) {
7546 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7547 return nullptr;
7548 }
7549
7550
7551 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7552 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7553 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7554 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7555
7556 IsPlaceholderVariable = true;
7557
7558 if (!Previous.empty()) {
7559 NamedDecl *PrevDecl = *Previous.begin();
7560 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7561 DC: DC->getRedeclContext());
7562 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7563 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7564 if (IsPlaceholderVariable)
7565 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7566 }
7567 }
7568 }
7569
7570 // dllimport globals without explicit storage class are treated as extern. We
7571 // have to change the storage class this early to get the right DeclContext.
7572 if (SC == SC_None && !DC->isRecord() &&
7573 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7574 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7575 SC = SC_Extern;
7576
7577 DeclContext *OriginalDC = DC;
7578 bool IsLocalExternDecl = SC == SC_Extern &&
7579 adjustContextForLocalExternDecl(DC);
7580
7581 if (SCSpec == DeclSpec::SCS_mutable) {
7582 // mutable can only appear on non-static class members, so it's always
7583 // an error here
7584 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7585 D.setInvalidType();
7586 SC = SC_None;
7587 }
7588
7589 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7590 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7591 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7592 // In C++11, the 'register' storage class specifier is deprecated.
7593 // Suppress the warning in system macros, it's used in macros in some
7594 // popular C system headers, such as in glibc's htonl() macro.
7595 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7596 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7597 : diag::warn_deprecated_register)
7598 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7599 }
7600
7601 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7602
7603 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7604 // C99 6.9p2: The storage-class specifiers auto and register shall not
7605 // appear in the declaration specifiers in an external declaration.
7606 // Global Register+Asm is a GNU extension we support.
7607 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7608 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7609 D.setInvalidType();
7610 }
7611 }
7612
7613 // If this variable has a VLA type and an initializer, try to
7614 // fold to a constant-sized type. This is otherwise invalid.
7615 if (D.hasInitializer() && R->isVariableArrayType())
7616 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7617 /*DiagID=*/FailedFoldDiagID: 0);
7618
7619 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7620 const AutoType *AT = TL.getTypePtr();
7621 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7622 }
7623
7624 bool IsMemberSpecialization = false;
7625 bool IsVariableTemplateSpecialization = false;
7626 bool IsPartialSpecialization = false;
7627 bool IsVariableTemplate = false;
7628 VarDecl *NewVD = nullptr;
7629 VarTemplateDecl *NewTemplate = nullptr;
7630 TemplateParameterList *TemplateParams = nullptr;
7631 if (!getLangOpts().CPlusPlus) {
7632 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7633 Id: II, T: R, TInfo, S: SC);
7634
7635 if (R->getContainedDeducedType())
7636 ParsingInitForAutoVars.insert(Ptr: NewVD);
7637
7638 if (D.isInvalidType())
7639 NewVD->setInvalidDecl();
7640
7641 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7642 NewVD->hasLocalStorage())
7643 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7644 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7645 } else {
7646 bool Invalid = false;
7647 // Match up the template parameter lists with the scope specifier, then
7648 // determine whether we have a template or a template specialization.
7649 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7650 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7651 SS: D.getCXXScopeSpec(),
7652 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7653 ? D.getName().TemplateId
7654 : nullptr,
7655 ParamLists: TemplateParamLists,
7656 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7657
7658 if (TemplateParams) {
7659 if (DC->isDependentContext()) {
7660 ContextRAII SavedContext(*this, DC);
7661 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7662 Invalid = true;
7663 }
7664
7665 if (!TemplateParams->size() &&
7666 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7667 // There is an extraneous 'template<>' for this variable. Complain
7668 // about it, but allow the declaration of the variable.
7669 Diag(Loc: TemplateParams->getTemplateLoc(),
7670 DiagID: diag::err_template_variable_noparams)
7671 << II
7672 << SourceRange(TemplateParams->getTemplateLoc(),
7673 TemplateParams->getRAngleLoc());
7674 TemplateParams = nullptr;
7675 } else {
7676 // Check that we can declare a template here.
7677 if (CheckTemplateDeclScope(S, TemplateParams))
7678 return nullptr;
7679
7680 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7681 // This is an explicit specialization or a partial specialization.
7682 IsVariableTemplateSpecialization = true;
7683 IsPartialSpecialization = TemplateParams->size() > 0;
7684 } else { // if (TemplateParams->size() > 0)
7685 // This is a template declaration.
7686 IsVariableTemplate = true;
7687
7688 // Only C++1y supports variable templates (N3651).
7689 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7690 }
7691 }
7692 } else {
7693 // Check that we can declare a member specialization here.
7694 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7695 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7696 return nullptr;
7697 assert((Invalid ||
7698 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7699 "should have a 'template<>' for this decl");
7700 }
7701
7702 bool IsExplicitSpecialization =
7703 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7704
7705 // C++ [temp.expl.spec]p2:
7706 // The declaration in an explicit-specialization shall not be an
7707 // export-declaration. An explicit specialization shall not use a
7708 // storage-class-specifier other than thread_local.
7709 //
7710 // We use the storage-class-specifier from DeclSpec because we may have
7711 // added implicit 'extern' for declarations with __declspec(dllimport)!
7712 if (SCSpec != DeclSpec::SCS_unspecified &&
7713 (IsExplicitSpecialization || IsMemberSpecialization)) {
7714 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7715 DiagID: diag::ext_explicit_specialization_storage_class)
7716 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7717 }
7718
7719 if (CurContext->isRecord()) {
7720 if (SC == SC_Static) {
7721 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7722 // Walk up the enclosing DeclContexts to check for any that are
7723 // incompatible with static data members.
7724 const DeclContext *FunctionOrMethod = nullptr;
7725 const CXXRecordDecl *AnonStruct = nullptr;
7726 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7727 if (Ctxt->isFunctionOrMethod()) {
7728 FunctionOrMethod = Ctxt;
7729 break;
7730 }
7731 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7732 if (ParentDecl && !ParentDecl->getDeclName()) {
7733 AnonStruct = ParentDecl;
7734 break;
7735 }
7736 }
7737 if (FunctionOrMethod) {
7738 // C++ [class.static.data]p5: A local class shall not have static
7739 // data members.
7740 Diag(Loc: D.getIdentifierLoc(),
7741 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7742 << Name << RD->getDeclName() << RD->getTagKind();
7743 } else if (AnonStruct) {
7744 // C++ [class.static.data]p4: Unnamed classes and classes contained
7745 // directly or indirectly within unnamed classes shall not contain
7746 // static data members.
7747 Diag(Loc: D.getIdentifierLoc(),
7748 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7749 << Name << AnonStruct->getTagKind();
7750 Invalid = true;
7751 } else if (RD->isUnion()) {
7752 // C++98 [class.union]p1: If a union contains a static data member,
7753 // the program is ill-formed. C++11 drops this restriction.
7754 DiagCompat(Loc: D.getIdentifierLoc(),
7755 CompatDiagId: diag_compat::static_data_member_in_union)
7756 << Name;
7757 }
7758 }
7759 } else if (IsVariableTemplate || IsPartialSpecialization) {
7760 // There is no such thing as a member field template.
7761 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7762 << II << TemplateParams->getSourceRange();
7763 // Recover by pretending this is a static data member template.
7764 SC = SC_Static;
7765 }
7766 } else if (DC->isRecord()) {
7767 // This is an out-of-line definition of a static data member.
7768 switch (SC) {
7769 case SC_None:
7770 break;
7771 case SC_Static:
7772 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7773 DiagID: diag::err_static_out_of_line)
7774 << FixItHint::CreateRemoval(
7775 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7776 break;
7777 case SC_Auto:
7778 case SC_Register:
7779 case SC_Extern:
7780 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7781 // to names of variables declared in a block or to function parameters.
7782 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7783 // of class members
7784
7785 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7786 DiagID: diag::err_storage_class_for_static_member)
7787 << FixItHint::CreateRemoval(
7788 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7789 break;
7790 case SC_PrivateExtern:
7791 llvm_unreachable("C storage class in c++!");
7792 }
7793 }
7794
7795 if (IsVariableTemplateSpecialization) {
7796 SourceLocation TemplateKWLoc =
7797 TemplateParamLists.size() > 0
7798 ? TemplateParamLists[0]->getTemplateLoc()
7799 : SourceLocation();
7800 DeclResult Res = ActOnVarTemplateSpecialization(
7801 S, D, DI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7802 IsPartialSpecialization);
7803 if (Res.isInvalid())
7804 return nullptr;
7805 NewVD = cast<VarDecl>(Val: Res.get());
7806 AddToScope = false;
7807 } else if (D.isDecompositionDeclarator()) {
7808 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7809 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
7810 Bindings);
7811 } else
7812 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
7813 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
7814
7815 // If this is supposed to be a variable template, create it as such.
7816 if (IsVariableTemplate) {
7817 NewTemplate =
7818 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
7819 Params: TemplateParams, Decl: NewVD);
7820 NewVD->setDescribedVarTemplate(NewTemplate);
7821 }
7822
7823 // If this decl has an auto type in need of deduction, make a note of the
7824 // Decl so we can diagnose uses of it in its own initializer.
7825 if (R->getContainedDeducedType())
7826 ParsingInitForAutoVars.insert(Ptr: NewVD);
7827
7828 if (D.isInvalidType() || Invalid) {
7829 NewVD->setInvalidDecl();
7830 if (NewTemplate)
7831 NewTemplate->setInvalidDecl();
7832 }
7833
7834 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
7835
7836 // If we have any template parameter lists that don't directly belong to
7837 // the variable (matching the scope specifier), store them.
7838 // An explicit variable template specialization does not own any template
7839 // parameter lists.
7840 unsigned VDTemplateParamLists =
7841 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7842 if (TemplateParamLists.size() > VDTemplateParamLists)
7843 NewVD->setTemplateParameterListsInfo(
7844 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
7845 }
7846
7847 if (D.getDeclSpec().isInlineSpecified()) {
7848 if (!getLangOpts().CPlusPlus) {
7849 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
7850 << 0;
7851 } else if (CurContext->isFunctionOrMethod()) {
7852 // 'inline' is not allowed on block scope variable declaration.
7853 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
7854 DiagID: diag::err_inline_declaration_block_scope) << Name
7855 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
7856 } else {
7857 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
7858 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
7859 : diag::compat_pre_cxx17_inline_variable);
7860 NewVD->setInlineSpecified();
7861 }
7862 }
7863
7864 // Set the lexical context. If the declarator has a C++ scope specifier, the
7865 // lexical context will be different from the semantic context.
7866 NewVD->setLexicalDeclContext(CurContext);
7867 if (NewTemplate)
7868 NewTemplate->setLexicalDeclContext(CurContext);
7869
7870 if (IsLocalExternDecl) {
7871 if (D.isDecompositionDeclarator())
7872 for (auto *B : Bindings)
7873 B->setLocalExternDecl();
7874 else
7875 NewVD->setLocalExternDecl();
7876 }
7877
7878 bool EmitTLSUnsupportedError = false;
7879 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7880 // C++11 [dcl.stc]p4:
7881 // When thread_local is applied to a variable of block scope the
7882 // storage-class-specifier static is implied if it does not appear
7883 // explicitly.
7884 // Core issue: 'static' is not implied if the variable is declared
7885 // 'extern'.
7886 if (NewVD->hasLocalStorage() &&
7887 (SCSpec != DeclSpec::SCS_unspecified ||
7888 TSCS != DeclSpec::TSCS_thread_local ||
7889 !DC->isFunctionOrMethod()))
7890 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
7891 DiagID: diag::err_thread_non_global)
7892 << DeclSpec::getSpecifierName(S: TSCS);
7893 else if (!Context.getTargetInfo().isTLSSupported()) {
7894 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
7895 // Postpone error emission until we've collected attributes required to
7896 // figure out whether it's a host or device variable and whether the
7897 // error should be ignored.
7898 EmitTLSUnsupportedError = true;
7899 // We still need to mark the variable as TLS so it shows up in AST with
7900 // proper storage class for other tools to use even if we're not going
7901 // to emit any code for it.
7902 NewVD->setTSCSpec(TSCS);
7903 } else
7904 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
7905 DiagID: diag::err_thread_unsupported);
7906 } else
7907 NewVD->setTSCSpec(TSCS);
7908 }
7909
7910 switch (D.getDeclSpec().getConstexprSpecifier()) {
7911 case ConstexprSpecKind::Unspecified:
7912 break;
7913
7914 case ConstexprSpecKind::Consteval:
7915 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
7916 DiagID: diag::err_constexpr_wrong_decl_kind)
7917 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7918 [[fallthrough]];
7919
7920 case ConstexprSpecKind::Constexpr:
7921 NewVD->setConstexpr(true);
7922 // C++1z [dcl.spec.constexpr]p1:
7923 // A static data member declared with the constexpr specifier is
7924 // implicitly an inline variable.
7925 if (NewVD->isStaticDataMember() &&
7926 (getLangOpts().CPlusPlus17 ||
7927 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7928 NewVD->setImplicitlyInline();
7929 break;
7930
7931 case ConstexprSpecKind::Constinit:
7932 if (!NewVD->hasGlobalStorage())
7933 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
7934 DiagID: diag::err_constinit_local_variable);
7935 else
7936 NewVD->addAttr(
7937 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
7938 S: ConstInitAttr::Keyword_constinit));
7939 break;
7940 }
7941
7942 // C99 6.7.4p3
7943 // An inline definition of a function with external linkage shall
7944 // not contain a definition of a modifiable object with static or
7945 // thread storage duration...
7946 // We only apply this when the function is required to be defined
7947 // elsewhere, i.e. when the function is not 'extern inline'. Note
7948 // that a local variable with thread storage duration still has to
7949 // be marked 'static'. Also note that it's possible to get these
7950 // semantics in C++ using __attribute__((gnu_inline)).
7951 if (SC == SC_Static && S->getFnParent() != nullptr &&
7952 !NewVD->getType().isConstQualified()) {
7953 FunctionDecl *CurFD = getCurFunctionDecl();
7954 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
7955 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7956 DiagID: diag::warn_static_local_in_extern_inline);
7957 MaybeSuggestAddingStaticToDecl(D: CurFD);
7958 }
7959 }
7960
7961 if (D.getDeclSpec().isModulePrivateSpecified()) {
7962 if (IsVariableTemplateSpecialization)
7963 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
7964 << (IsPartialSpecialization ? 1 : 0)
7965 << FixItHint::CreateRemoval(
7966 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
7967 else if (IsMemberSpecialization)
7968 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
7969 << 2
7970 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
7971 else if (NewVD->hasLocalStorage())
7972 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
7973 << 0 << NewVD
7974 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7975 << FixItHint::CreateRemoval(
7976 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
7977 else {
7978 NewVD->setModulePrivate();
7979 if (NewTemplate)
7980 NewTemplate->setModulePrivate();
7981 for (auto *B : Bindings)
7982 B->setModulePrivate();
7983 }
7984 }
7985
7986 if (getLangOpts().OpenCL) {
7987 deduceOpenCLAddressSpace(Decl: NewVD);
7988
7989 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7990 if (TSC != TSCS_unspecified) {
7991 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
7992 DiagID: diag::err_opencl_unknown_type_specifier)
7993 << getLangOpts().getOpenCLVersionString()
7994 << DeclSpec::getSpecifierName(S: TSC) << 1;
7995 NewVD->setInvalidDecl();
7996 }
7997 }
7998
7999 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8000 // address space if the table has local storage (semantic checks elsewhere
8001 // will produce an error anyway).
8002 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8003 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8004 !NewVD->hasLocalStorage()) {
8005 QualType Type = Context.getAddrSpaceQualType(
8006 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8007 NewVD->setType(Type);
8008 }
8009 }
8010
8011 // Handle attributes prior to checking for duplicates in MergeVarDecl
8012 ProcessDeclAttributes(S, D: NewVD, PD: D);
8013
8014 if (getLangOpts().HLSL)
8015 HLSL().ActOnVariableDeclarator(VD: NewVD);
8016
8017 if (getLangOpts().OpenACC)
8018 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8019
8020 // FIXME: This is probably the wrong location to be doing this and we should
8021 // probably be doing this for more attributes (especially for function
8022 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8023 // the code to copy attributes would be generated by TableGen.
8024 if (R->isFunctionPointerType())
8025 if (const auto *TT = R->getAs<TypedefType>())
8026 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8027
8028 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8029 if (EmitTLSUnsupportedError &&
8030 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8031 (getLangOpts().OpenMPIsTargetDevice &&
8032 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8033 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8034 DiagID: diag::err_thread_unsupported);
8035
8036 if (EmitTLSUnsupportedError &&
8037 (LangOpts.SYCLIsDevice ||
8038 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8039 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8040 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8041 // storage [duration]."
8042 if (SC == SC_None && S->getFnParent() != nullptr &&
8043 (NewVD->hasAttr<CUDASharedAttr>() ||
8044 NewVD->hasAttr<CUDAConstantAttr>())) {
8045 NewVD->setStorageClass(SC_Static);
8046 }
8047 }
8048
8049 // Ensure that dllimport globals without explicit storage class are treated as
8050 // extern. The storage class is set above using parsed attributes. Now we can
8051 // check the VarDecl itself.
8052 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8053 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8054 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8055
8056 // In auto-retain/release, infer strong retension for variables of
8057 // retainable type.
8058 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8059 NewVD->setInvalidDecl();
8060
8061 // Handle GNU asm-label extension (encoded as an attribute).
8062 if (Expr *E = (Expr*)D.getAsmLabel()) {
8063 // The parser guarantees this is a string.
8064 StringLiteral *SE = cast<StringLiteral>(Val: E);
8065 StringRef Label = SE->getString();
8066 if (S->getFnParent() != nullptr) {
8067 switch (SC) {
8068 case SC_None:
8069 case SC_Auto:
8070 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
8071 break;
8072 case SC_Register:
8073 // Local Named register
8074 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
8075 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
8076 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
8077 break;
8078 case SC_Static:
8079 case SC_Extern:
8080 case SC_PrivateExtern:
8081 break;
8082 }
8083 } else if (SC == SC_Register) {
8084 // Global Named register
8085 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
8086 const auto &TI = Context.getTargetInfo();
8087 bool HasSizeMismatch;
8088
8089 if (!TI.isValidGCCRegisterName(Name: Label))
8090 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
8091 else if (!TI.validateGlobalRegisterVariable(RegName: Label,
8092 RegSize: Context.getTypeSize(T: R),
8093 HasSizeMismatch))
8094 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
8095 else if (HasSizeMismatch)
8096 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
8097 }
8098
8099 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
8100 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
8101 DiagID: diag::err_asm_unsupported_register_type)
8102 << TInfo->getTypeLoc().getSourceRange();
8103 NewVD->setInvalidDecl(true);
8104 }
8105 }
8106
8107 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label,
8108 /*IsLiteralLabel=*/true,
8109 Range: SE->getStrTokenLoc(TokNum: 0)));
8110 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8111 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8112 ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier());
8113 if (I != ExtnameUndeclaredIdentifiers.end()) {
8114 if (isDeclExternC(D: NewVD)) {
8115 NewVD->addAttr(A: I->second);
8116 ExtnameUndeclaredIdentifiers.erase(I);
8117 } else
8118 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8119 << /*Variable*/1 << NewVD;
8120 }
8121 }
8122
8123 // Find the shadowed declaration before filtering for scope.
8124 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8125 ? getShadowedDeclaration(D: NewVD, R: Previous)
8126 : nullptr;
8127
8128 // Don't consider existing declarations that are in a different
8129 // scope and are out-of-semantic-context declarations (if the new
8130 // declaration has linkage).
8131 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8132 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8133 IsMemberSpecialization ||
8134 IsVariableTemplateSpecialization);
8135
8136 // Check whether the previous declaration is in the same block scope. This
8137 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8138 if (getLangOpts().CPlusPlus &&
8139 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8140 NewVD->setPreviousDeclInSameBlockScope(
8141 Previous.isSingleResult() && !Previous.isShadowed() &&
8142 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8143
8144 if (!getLangOpts().CPlusPlus) {
8145 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8146 } else {
8147 // If this is an explicit specialization of a static data member, check it.
8148 if (IsMemberSpecialization && !IsVariableTemplate &&
8149 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8150 CheckMemberSpecialization(Member: NewVD, Previous))
8151 NewVD->setInvalidDecl();
8152
8153 // Merge the decl with the existing one if appropriate.
8154 if (!Previous.empty()) {
8155 if (Previous.isSingleResult() &&
8156 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8157 D.getCXXScopeSpec().isSet()) {
8158 // The user tried to define a non-static data member
8159 // out-of-line (C++ [dcl.meaning]p1).
8160 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8161 << D.getCXXScopeSpec().getRange();
8162 Previous.clear();
8163 NewVD->setInvalidDecl();
8164 }
8165 } else if (D.getCXXScopeSpec().isSet() &&
8166 !IsVariableTemplateSpecialization) {
8167 // No previous declaration in the qualifying scope.
8168 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8169 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8170 << D.getCXXScopeSpec().getRange();
8171 NewVD->setInvalidDecl();
8172 }
8173
8174 if (!IsPlaceholderVariable)
8175 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8176
8177 // CheckVariableDeclaration will set NewVD as invalid if something is in
8178 // error like WebAssembly tables being declared as arrays with a non-zero
8179 // size, but then parsing continues and emits further errors on that line.
8180 // To avoid that we check here if it happened and return nullptr.
8181 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8182 return nullptr;
8183
8184 if (NewTemplate) {
8185 VarTemplateDecl *PrevVarTemplate =
8186 NewVD->getPreviousDecl()
8187 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8188 : nullptr;
8189
8190 // Check the template parameter list of this declaration, possibly
8191 // merging in the template parameter list from the previous variable
8192 // template declaration.
8193 if (CheckTemplateParameterList(
8194 NewParams: TemplateParams,
8195 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8196 : nullptr,
8197 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8198 DC->isDependentContext())
8199 ? TPC_ClassTemplateMember
8200 : TPC_Other))
8201 NewVD->setInvalidDecl();
8202
8203 // If we are providing an explicit specialization of a static variable
8204 // template, make a note of that.
8205 if (PrevVarTemplate &&
8206 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8207 PrevVarTemplate->setMemberSpecialization();
8208 }
8209 }
8210
8211 // Diagnose shadowed variables iff this isn't a redeclaration.
8212 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8213 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8214
8215 ProcessPragmaWeak(S, D: NewVD);
8216
8217 // If this is the first declaration of an extern C variable, update
8218 // the map of such variables.
8219 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8220 isIncompleteDeclExternC(S&: *this, D: NewVD))
8221 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8222
8223 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8224 MangleNumberingContext *MCtx;
8225 Decl *ManglingContextDecl;
8226 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8227 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8228 if (MCtx) {
8229 Context.setManglingNumber(
8230 ND: NewVD, Number: MCtx->getManglingNumber(
8231 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8232 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8233 }
8234 }
8235
8236 // Special handling of variable named 'main'.
8237 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8238 // C++ [basic.start.main]p3:
8239 // A program that declares
8240 // - a variable main at global scope, or
8241 // - an entity named main with C language linkage (in any namespace)
8242 // is ill-formed
8243 if (getLangOpts().CPlusPlus)
8244 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8245 << NewVD->isExternC();
8246
8247 // In C, and external-linkage variable named main results in undefined
8248 // behavior.
8249 else if (NewVD->hasExternalFormalLinkage())
8250 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8251 }
8252
8253 if (D.isRedeclaration() && !Previous.empty()) {
8254 NamedDecl *Prev = Previous.getRepresentativeDecl();
8255 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8256 IsDefinition: D.isFunctionDefinition());
8257 }
8258
8259 if (NewTemplate) {
8260 if (NewVD->isInvalidDecl())
8261 NewTemplate->setInvalidDecl();
8262 ActOnDocumentableDecl(D: NewTemplate);
8263 return NewTemplate;
8264 }
8265
8266 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8267 CompleteMemberSpecialization(Member: NewVD, Previous);
8268
8269 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8270
8271 return NewVD;
8272}
8273
8274/// Enum describing the %select options in diag::warn_decl_shadow.
8275enum ShadowedDeclKind {
8276 SDK_Local,
8277 SDK_Global,
8278 SDK_StaticMember,
8279 SDK_Field,
8280 SDK_Typedef,
8281 SDK_Using,
8282 SDK_StructuredBinding
8283};
8284
8285/// Determine what kind of declaration we're shadowing.
8286static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8287 const DeclContext *OldDC) {
8288 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8289 return SDK_Using;
8290 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8291 return SDK_Typedef;
8292 else if (isa<BindingDecl>(Val: ShadowedDecl))
8293 return SDK_StructuredBinding;
8294 else if (isa<RecordDecl>(Val: OldDC))
8295 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8296
8297 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8298}
8299
8300/// Return the location of the capture if the given lambda captures the given
8301/// variable \p VD, or an invalid source location otherwise.
8302static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8303 const VarDecl *VD) {
8304 for (const Capture &Capture : LSI->Captures) {
8305 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8306 return Capture.getLocation();
8307 }
8308 return SourceLocation();
8309}
8310
8311static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8312 const LookupResult &R) {
8313 // Only diagnose if we're shadowing an unambiguous field or variable.
8314 if (R.getResultKind() != LookupResultKind::Found)
8315 return false;
8316
8317 // Return false if warning is ignored.
8318 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8319}
8320
8321NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8322 const LookupResult &R) {
8323 if (!shouldWarnIfShadowedDecl(Diags, R))
8324 return nullptr;
8325
8326 // Don't diagnose declarations at file scope.
8327 if (D->hasGlobalStorage() && !D->isStaticLocal())
8328 return nullptr;
8329
8330 NamedDecl *ShadowedDecl = R.getFoundDecl();
8331 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8332 : nullptr;
8333}
8334
8335NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8336 const LookupResult &R) {
8337 // Don't warn if typedef declaration is part of a class
8338 if (D->getDeclContext()->isRecord())
8339 return nullptr;
8340
8341 if (!shouldWarnIfShadowedDecl(Diags, R))
8342 return nullptr;
8343
8344 NamedDecl *ShadowedDecl = R.getFoundDecl();
8345 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8346}
8347
8348NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8349 const LookupResult &R) {
8350 if (!shouldWarnIfShadowedDecl(Diags, R))
8351 return nullptr;
8352
8353 NamedDecl *ShadowedDecl = R.getFoundDecl();
8354 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8355 : nullptr;
8356}
8357
8358void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8359 const LookupResult &R) {
8360 DeclContext *NewDC = D->getDeclContext();
8361
8362 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDC)) {
8364 // Fields are not shadowed by variables in C++ static methods.
8365 if (MD->isStatic())
8366 return;
8367
8368 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8369 return;
8370 }
8371 // Fields shadowed by constructor parameters are a special case. Usually
8372 // the constructor initializes the field with the parameter.
8373 if (isa<CXXConstructorDecl>(Val: NewDC))
8374 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8375 // Remember that this was shadowed so we can either warn about its
8376 // modification or its existence depending on warning settings.
8377 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8378 return;
8379 }
8380 }
8381
8382 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8383 if (shadowedVar->isExternC()) {
8384 // For shadowing external vars, make sure that we point to the global
8385 // declaration, not a locally scoped extern declaration.
8386 for (auto *I : shadowedVar->redecls())
8387 if (I->isFileVarDecl()) {
8388 ShadowedDecl = I;
8389 break;
8390 }
8391 }
8392
8393 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8394
8395 unsigned WarningDiag = diag::warn_decl_shadow;
8396 SourceLocation CaptureLoc;
8397 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8398 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8399 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8400 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8401 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8402 if (RD->getLambdaCaptureDefault() == LCD_None) {
8403 // Try to avoid warnings for lambdas with an explicit capture
8404 // list. Warn only when the lambda captures the shadowed decl
8405 // explicitly.
8406 CaptureLoc = getCaptureLocation(LSI, VD);
8407 if (CaptureLoc.isInvalid())
8408 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8409 } else {
8410 // Remember that this was shadowed so we can avoid the warning if
8411 // the shadowed decl isn't captured and the warning settings allow
8412 // it.
8413 cast<LambdaScopeInfo>(Val: getCurFunction())
8414 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8415 return;
8416 }
8417 }
8418 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8419 // If lambda can capture this, then emit default shadowing warning,
8420 // Otherwise it is not really a shadowing case since field is not
8421 // available in lambda's body.
8422 // At this point we don't know that lambda can capture this, so
8423 // remember that this was shadowed and delay until we know.
8424 cast<LambdaScopeInfo>(Val: getCurFunction())
8425 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8426 return;
8427 }
8428 }
8429 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl);
8430 VD && VD->hasLocalStorage()) {
8431 // A variable can't shadow a local variable in an enclosing scope, if
8432 // they are separated by a non-capturing declaration context.
8433 for (DeclContext *ParentDC = NewDC;
8434 ParentDC && !ParentDC->Equals(DC: OldDC);
8435 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8436 // Only block literals, captured statements, and lambda expressions
8437 // can capture; other scopes don't.
8438 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8439 !isLambdaCallOperator(DC: ParentDC)) {
8440 return;
8441 }
8442 }
8443 }
8444 }
8445 }
8446
8447 // Never warn about shadowing a placeholder variable.
8448 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8449 return;
8450
8451 // Only warn about certain kinds of shadowing for class members.
8452 if (NewDC) {
8453 // In particular, don't warn about shadowing non-class members.
8454 if (NewDC->isRecord() && !OldDC->isRecord())
8455 return;
8456
8457 // Skip shadowing check if we're in a class scope, dealing with an enum
8458 // constant in a different context.
8459 DeclContext *ReDC = NewDC->getRedeclContext();
8460 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8461 return;
8462
8463 // TODO: should we warn about static data members shadowing
8464 // static data members from base classes?
8465
8466 // TODO: don't diagnose for inaccessible shadowed members.
8467 // This is hard to do perfectly because we might friend the
8468 // shadowing context, but that's just a false negative.
8469 }
8470
8471 DeclarationName Name = R.getLookupName();
8472
8473 // Emit warning and note.
8474 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8475 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8476 if (!CaptureLoc.isInvalid())
8477 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8478 << Name << /*explicitly*/ 1;
8479 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8480}
8481
8482void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8483 for (const auto &Shadow : LSI->ShadowingDecls) {
8484 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8485 // Try to avoid the warning when the shadowed decl isn't captured.
8486 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8487 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl)) {
8488 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8489 Diag(Loc: Shadow.VD->getLocation(),
8490 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8491 : diag::warn_decl_shadow)
8492 << Shadow.VD->getDeclName()
8493 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8494 if (CaptureLoc.isValid())
8495 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8496 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8497 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8498 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8499 Diag(Loc: Shadow.VD->getLocation(),
8500 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8501 : diag::warn_decl_shadow_uncaptured_local)
8502 << Shadow.VD->getDeclName()
8503 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8504 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8505 }
8506 }
8507}
8508
8509void Sema::CheckShadow(Scope *S, VarDecl *D) {
8510 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8511 return;
8512
8513 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8514 Sema::LookupOrdinaryName,
8515 RedeclarationKind::ForVisibleRedeclaration);
8516 LookupName(R, S);
8517 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8518 CheckShadow(D, ShadowedDecl, R);
8519}
8520
8521/// Check if 'E', which is an expression that is about to be modified, refers
8522/// to a constructor parameter that shadows a field.
8523void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8524 // Quickly ignore expressions that can't be shadowing ctor parameters.
8525 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8526 return;
8527 E = E->IgnoreParenImpCasts();
8528 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8529 if (!DRE)
8530 return;
8531 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8532 auto I = ShadowingDecls.find(Val: D);
8533 if (I == ShadowingDecls.end())
8534 return;
8535 const NamedDecl *ShadowedDecl = I->second;
8536 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8537 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8538 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8539 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8540
8541 // Avoid issuing multiple warnings about the same decl.
8542 ShadowingDecls.erase(I);
8543}
8544
8545/// Check for conflict between this global or extern "C" declaration and
8546/// previous global or extern "C" declarations. This is only used in C++.
8547template<typename T>
8548static bool checkGlobalOrExternCConflict(
8549 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8550 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8551 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8552
8553 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8554 // The common case: this global doesn't conflict with any extern "C"
8555 // declaration.
8556 return false;
8557 }
8558
8559 if (Prev) {
8560 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8561 // Both the old and new declarations have C language linkage. This is a
8562 // redeclaration.
8563 Previous.clear();
8564 Previous.addDecl(D: Prev);
8565 return true;
8566 }
8567
8568 // This is a global, non-extern "C" declaration, and there is a previous
8569 // non-global extern "C" declaration. Diagnose if this is a variable
8570 // declaration.
8571 if (!isa<VarDecl>(ND))
8572 return false;
8573 } else {
8574 // The declaration is extern "C". Check for any declaration in the
8575 // translation unit which might conflict.
8576 if (IsGlobal) {
8577 // We have already performed the lookup into the translation unit.
8578 IsGlobal = false;
8579 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8580 I != E; ++I) {
8581 if (isa<VarDecl>(Val: *I)) {
8582 Prev = *I;
8583 break;
8584 }
8585 }
8586 } else {
8587 DeclContext::lookup_result R =
8588 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8589 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8590 I != E; ++I) {
8591 if (isa<VarDecl>(Val: *I)) {
8592 Prev = *I;
8593 break;
8594 }
8595 // FIXME: If we have any other entity with this name in global scope,
8596 // the declaration is ill-formed, but that is a defect: it breaks the
8597 // 'stat' hack, for instance. Only variables can have mangled name
8598 // clashes with extern "C" declarations, so only they deserve a
8599 // diagnostic.
8600 }
8601 }
8602
8603 if (!Prev)
8604 return false;
8605 }
8606
8607 // Use the first declaration's location to ensure we point at something which
8608 // is lexically inside an extern "C" linkage-spec.
8609 assert(Prev && "should have found a previous declaration to diagnose");
8610 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8611 Prev = FD->getFirstDecl();
8612 else
8613 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8614
8615 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8616 << IsGlobal << ND;
8617 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8618 << IsGlobal;
8619 return false;
8620}
8621
8622/// Apply special rules for handling extern "C" declarations. Returns \c true
8623/// if we have found that this is a redeclaration of some prior entity.
8624///
8625/// Per C++ [dcl.link]p6:
8626/// Two declarations [for a function or variable] with C language linkage
8627/// with the same name that appear in different scopes refer to the same
8628/// [entity]. An entity with C language linkage shall not be declared with
8629/// the same name as an entity in global scope.
8630template<typename T>
8631static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8632 LookupResult &Previous) {
8633 if (!S.getLangOpts().CPlusPlus) {
8634 // In C, when declaring a global variable, look for a corresponding 'extern'
8635 // variable declared in function scope. We don't need this in C++, because
8636 // we find local extern decls in the surrounding file-scope DeclContext.
8637 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8638 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8639 Previous.clear();
8640 Previous.addDecl(D: Prev);
8641 return true;
8642 }
8643 }
8644 return false;
8645 }
8646
8647 // A declaration in the translation unit can conflict with an extern "C"
8648 // declaration.
8649 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8650 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8651
8652 // An extern "C" declaration can conflict with a declaration in the
8653 // translation unit or can be a redeclaration of an extern "C" declaration
8654 // in another scope.
8655 if (isIncompleteDeclExternC(S,ND))
8656 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8657
8658 // Neither global nor extern "C": nothing to do.
8659 return false;
8660}
8661
8662static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8663 QualType T) {
8664 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8665 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8666 // any of its members, even recursively, shall not have an atomic type, or a
8667 // variably modified type, or a type that is volatile or restrict qualified.
8668 if (CanonT->isVariablyModifiedType()) {
8669 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8670 return true;
8671 }
8672
8673 // Arrays are qualified by their element type, so get the base type (this
8674 // works on non-arrays as well).
8675 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8676
8677 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8678 CanonT.isRestrictQualified()) {
8679 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8680 return true;
8681 }
8682
8683 if (CanonT->isRecordType()) {
8684 const RecordDecl *RD = CanonT->getAsRecordDecl();
8685 if (!RD->isInvalidDecl() &&
8686 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8687 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8688 }))
8689 return true;
8690 }
8691
8692 return false;
8693}
8694
8695void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8696 // If the decl is already known invalid, don't check it.
8697 if (NewVD->isInvalidDecl())
8698 return;
8699
8700 QualType T = NewVD->getType();
8701
8702 // Defer checking an 'auto' type until its initializer is attached.
8703 if (T->isUndeducedType())
8704 return;
8705
8706 if (NewVD->hasAttrs())
8707 CheckAlignasUnderalignment(D: NewVD);
8708
8709 if (T->isObjCObjectType()) {
8710 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8711 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8712 T = Context.getObjCObjectPointerType(OIT: T);
8713 NewVD->setType(T);
8714 }
8715
8716 // Emit an error if an address space was applied to decl with local storage.
8717 // This includes arrays of objects with address space qualifiers, but not
8718 // automatic variables that point to other address spaces.
8719 // ISO/IEC TR 18037 S5.1.2
8720 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8721 T.getAddressSpace() != LangAS::Default) {
8722 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8723 NewVD->setInvalidDecl();
8724 return;
8725 }
8726
8727 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8728 // scope.
8729 if (getLangOpts().OpenCLVersion == 120 &&
8730 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8731 LO: getLangOpts()) &&
8732 NewVD->isStaticLocal()) {
8733 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8734 NewVD->setInvalidDecl();
8735 return;
8736 }
8737
8738 if (getLangOpts().OpenCL) {
8739 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8740 return;
8741
8742 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8743 if (NewVD->hasAttr<BlocksAttr>()) {
8744 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8745 return;
8746 }
8747
8748 if (T->isBlockPointerType()) {
8749 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8750 // can't use 'extern' storage class.
8751 if (!T.isConstQualified()) {
8752 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8753 << 0 /*const*/;
8754 NewVD->setInvalidDecl();
8755 return;
8756 }
8757 if (NewVD->hasExternalStorage()) {
8758 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8759 NewVD->setInvalidDecl();
8760 return;
8761 }
8762 }
8763
8764 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8765 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8766 NewVD->hasExternalStorage()) {
8767 if (!T->isSamplerT() && !T->isDependentType() &&
8768 !(T.getAddressSpace() == LangAS::opencl_constant ||
8769 (T.getAddressSpace() == LangAS::opencl_global &&
8770 getOpenCLOptions().areProgramScopeVariablesSupported(
8771 Opts: getLangOpts())))) {
8772 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8773 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8774 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8775 << Scope << "global or constant";
8776 else
8777 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8778 << Scope << "constant";
8779 NewVD->setInvalidDecl();
8780 return;
8781 }
8782 } else {
8783 if (T.getAddressSpace() == LangAS::opencl_global) {
8784 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8785 << 1 /*is any function*/ << "global";
8786 NewVD->setInvalidDecl();
8787 return;
8788 }
8789 if (T.getAddressSpace() == LangAS::opencl_constant ||
8790 T.getAddressSpace() == LangAS::opencl_local) {
8791 FunctionDecl *FD = getCurFunctionDecl();
8792 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8793 // in functions.
8794 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8795 if (T.getAddressSpace() == LangAS::opencl_constant)
8796 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8797 << 0 /*non-kernel only*/ << "constant";
8798 else
8799 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8800 << 0 /*non-kernel only*/ << "local";
8801 NewVD->setInvalidDecl();
8802 return;
8803 }
8804 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8805 // in the outermost scope of a kernel function.
8806 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
8807 if (!getCurScope()->isFunctionScope()) {
8808 if (T.getAddressSpace() == LangAS::opencl_constant)
8809 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
8810 << "constant";
8811 else
8812 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
8813 << "local";
8814 NewVD->setInvalidDecl();
8815 return;
8816 }
8817 }
8818 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8819 // If we are parsing a template we didn't deduce an addr
8820 // space yet.
8821 T.getAddressSpace() != LangAS::Default) {
8822 // Do not allow other address spaces on automatic variable.
8823 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
8824 NewVD->setInvalidDecl();
8825 return;
8826 }
8827 }
8828 }
8829
8830 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8831 && !NewVD->hasAttr<BlocksAttr>()) {
8832 if (getLangOpts().getGC() != LangOptions::NonGC)
8833 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
8834 else {
8835 assert(!getLangOpts().ObjCAutoRefCount);
8836 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
8837 }
8838 }
8839
8840 // WebAssembly tables must be static with a zero length and can't be
8841 // declared within functions.
8842 if (T->isWebAssemblyTableType()) {
8843 if (getCurScope()->getParent()) { // Parent is null at top-level
8844 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
8845 NewVD->setInvalidDecl();
8846 return;
8847 }
8848 if (NewVD->getStorageClass() != SC_Static) {
8849 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
8850 NewVD->setInvalidDecl();
8851 return;
8852 }
8853 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
8854 if (!ATy || ATy->getZExtSize() != 0) {
8855 Diag(Loc: NewVD->getLocation(),
8856 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
8857 NewVD->setInvalidDecl();
8858 return;
8859 }
8860 }
8861
8862 // zero sized static arrays are not allowed in HIP device functions
8863 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8864 if (FunctionDecl *FD = getCurFunctionDecl();
8865 FD &&
8866 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8867 if (const ConstantArrayType *ArrayT =
8868 getASTContext().getAsConstantArrayType(T);
8869 ArrayT && ArrayT->isZeroSize()) {
8870 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
8871 }
8872 }
8873 }
8874
8875 bool isVM = T->isVariablyModifiedType();
8876 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8877 NewVD->hasAttr<BlocksAttr>())
8878 setFunctionHasBranchProtectedScope();
8879
8880 if ((isVM && NewVD->hasLinkage()) ||
8881 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8882 bool SizeIsNegative;
8883 llvm::APSInt Oversized;
8884 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8885 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8886 QualType FixedT;
8887 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8888 FixedT = FixedTInfo->getType();
8889 else if (FixedTInfo) {
8890 // Type and type-as-written are canonically different. We need to fix up
8891 // both types separately.
8892 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8893 Oversized);
8894 }
8895 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8896 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8897 // FIXME: This won't give the correct result for
8898 // int a[10][n];
8899 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8900
8901 if (NewVD->isFileVarDecl())
8902 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
8903 << SizeRange;
8904 else if (NewVD->isStaticLocal())
8905 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
8906 << SizeRange;
8907 else
8908 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
8909 << SizeRange;
8910 NewVD->setInvalidDecl();
8911 return;
8912 }
8913
8914 if (!FixedTInfo) {
8915 if (NewVD->isFileVarDecl())
8916 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
8917 else
8918 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
8919 NewVD->setInvalidDecl();
8920 return;
8921 }
8922
8923 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
8924 NewVD->setType(FixedT);
8925 NewVD->setTypeSourceInfo(FixedTInfo);
8926 }
8927
8928 if (T->isVoidType()) {
8929 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8930 // of objects and functions.
8931 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8932 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
8933 << T;
8934 NewVD->setInvalidDecl();
8935 return;
8936 }
8937 }
8938
8939 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8940 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal);
8941 NewVD->setInvalidDecl();
8942 return;
8943 }
8944
8945 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8946 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8947 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
8948 NewVD->setInvalidDecl();
8949 return;
8950 }
8951
8952 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8953 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm);
8954 NewVD->setInvalidDecl();
8955 return;
8956 }
8957
8958 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8959 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
8960 NewVD->setInvalidDecl();
8961 return;
8962 }
8963
8964 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8965 !T->isDependentType() &&
8966 RequireLiteralType(Loc: NewVD->getLocation(), T,
8967 DiagID: diag::err_constexpr_var_non_literal)) {
8968 NewVD->setInvalidDecl();
8969 return;
8970 }
8971
8972 // PPC MMA non-pointer types are not allowed as non-local variable types.
8973 if (Context.getTargetInfo().getTriple().isPPC64() &&
8974 !NewVD->isLocalVarDecl() &&
8975 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
8976 NewVD->setInvalidDecl();
8977 return;
8978 }
8979
8980 // Check that SVE types are only used in functions with SVE available.
8981 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
8982 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
8983 llvm::StringMap<bool> CallerFeatureMap;
8984 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
8985
8986 if (!Builtin::evaluateRequiredTargetFeatures(RequiredFatures: "sve", TargetFetureMap: CallerFeatureMap)) {
8987 if (!Builtin::evaluateRequiredTargetFeatures(RequiredFatures: "sme", TargetFetureMap: CallerFeatureMap)) {
8988 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sve_vector_in_non_sve_target) << T;
8989 NewVD->setInvalidDecl();
8990 return;
8991 } else if (!IsArmStreamingFunction(FD,
8992 /*IncludeLocallyStreaming=*/true)) {
8993 Diag(Loc: NewVD->getLocation(),
8994 DiagID: diag::err_sve_vector_in_non_streaming_function)
8995 << T;
8996 NewVD->setInvalidDecl();
8997 return;
8998 }
8999 }
9000 }
9001
9002 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9003 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9004 llvm::StringMap<bool> CallerFeatureMap;
9005 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9006 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9007 FeatureMap: CallerFeatureMap);
9008 }
9009}
9010
9011bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9012 CheckVariableDeclarationType(NewVD);
9013
9014 // If the decl is already known invalid, don't check it.
9015 if (NewVD->isInvalidDecl())
9016 return false;
9017
9018 // If we did not find anything by this name, look for a non-visible
9019 // extern "C" declaration with the same name.
9020 if (Previous.empty() &&
9021 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9022 Previous.setShadowed();
9023
9024 if (!Previous.empty()) {
9025 MergeVarDecl(New: NewVD, Previous);
9026 return true;
9027 }
9028 return false;
9029}
9030
9031bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9032 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9033
9034 // Look for methods in base classes that this method might override.
9035 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9036 /*DetectVirtual=*/false);
9037 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9038 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9039 DeclarationName Name = MD->getDeclName();
9040
9041 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9042 // We really want to find the base class destructor here.
9043 QualType T = Context.getTypeDeclType(Decl: BaseRecord);
9044 CanQualType CT = Context.getCanonicalType(T);
9045 Name = Context.DeclarationNames.getCXXDestructorName(Ty: CT);
9046 }
9047
9048 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9049 CXXMethodDecl *BaseMD =
9050 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9051 if (!BaseMD || !BaseMD->isVirtual() ||
9052 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9053 /*ConsiderCudaAttrs=*/true))
9054 continue;
9055 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9056 continue;
9057 if (Overridden.insert(Ptr: BaseMD).second) {
9058 MD->addOverriddenMethod(MD: BaseMD);
9059 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9060 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9061 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9062 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9063 }
9064
9065 // A method can only override one function from each base class. We
9066 // don't track indirectly overridden methods from bases of bases.
9067 return true;
9068 }
9069
9070 return false;
9071 };
9072
9073 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9074 return !Overridden.empty();
9075}
9076
9077namespace {
9078 // Struct for holding all of the extra arguments needed by
9079 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9080 struct ActOnFDArgs {
9081 Scope *S;
9082 Declarator &D;
9083 MultiTemplateParamsArg TemplateParamLists;
9084 bool AddToScope;
9085 };
9086} // end anonymous namespace
9087
9088namespace {
9089
9090// Callback to only accept typo corrections that have a non-zero edit distance.
9091// Also only accept corrections that have the same parent decl.
9092class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9093 public:
9094 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9095 CXXRecordDecl *Parent)
9096 : Context(Context), OriginalFD(TypoFD),
9097 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9098
9099 bool ValidateCandidate(const TypoCorrection &candidate) override {
9100 if (candidate.getEditDistance() == 0)
9101 return false;
9102
9103 SmallVector<unsigned, 1> MismatchedParams;
9104 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9105 CDeclEnd = candidate.end();
9106 CDecl != CDeclEnd; ++CDecl) {
9107 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9108
9109 if (FD && !FD->hasBody() &&
9110 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9111 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9112 CXXRecordDecl *Parent = MD->getParent();
9113 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9114 return true;
9115 } else if (!ExpectedParent) {
9116 return true;
9117 }
9118 }
9119 }
9120
9121 return false;
9122 }
9123
9124 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9125 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9126 }
9127
9128 private:
9129 ASTContext &Context;
9130 FunctionDecl *OriginalFD;
9131 CXXRecordDecl *ExpectedParent;
9132};
9133
9134} // end anonymous namespace
9135
9136void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9137 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9138}
9139
9140/// Generate diagnostics for an invalid function redeclaration.
9141///
9142/// This routine handles generating the diagnostic messages for an invalid
9143/// function redeclaration, including finding possible similar declarations
9144/// or performing typo correction if there are no previous declarations with
9145/// the same name.
9146///
9147/// Returns a NamedDecl iff typo correction was performed and substituting in
9148/// the new declaration name does not cause new errors.
9149static NamedDecl *DiagnoseInvalidRedeclaration(
9150 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9151 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9152 DeclarationName Name = NewFD->getDeclName();
9153 DeclContext *NewDC = NewFD->getDeclContext();
9154 SmallVector<unsigned, 1> MismatchedParams;
9155 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9156 TypoCorrection Correction;
9157 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9158 unsigned DiagMsg =
9159 IsLocalFriend ? diag::err_no_matching_local_friend :
9160 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9161 diag::err_member_decl_does_not_match;
9162 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9163 IsLocalFriend ? Sema::LookupLocalFriendName
9164 : Sema::LookupOrdinaryName,
9165 RedeclarationKind::ForVisibleRedeclaration);
9166
9167 NewFD->setInvalidDecl();
9168 if (IsLocalFriend)
9169 SemaRef.LookupName(R&: Prev, S);
9170 else
9171 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9172 assert(!Prev.isAmbiguous() &&
9173 "Cannot have an ambiguity in previous-declaration lookup");
9174 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9175 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9176 MD ? MD->getParent() : nullptr);
9177 if (!Prev.empty()) {
9178 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9179 Func != FuncEnd; ++Func) {
9180 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9181 if (FD &&
9182 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9183 // Add 1 to the index so that 0 can mean the mismatch didn't
9184 // involve a parameter
9185 unsigned ParamNum =
9186 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9187 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9188 }
9189 }
9190 // If the qualified name lookup yielded nothing, try typo correction
9191 } else if ((Correction = SemaRef.CorrectTypo(
9192 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9193 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9194 Mode: CorrectTypoKind::ErrorRecovery,
9195 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9196 // Set up everything for the call to ActOnFunctionDeclarator
9197 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9198 IdLoc: ExtraArgs.D.getIdentifierLoc());
9199 Previous.clear();
9200 Previous.setLookupName(Correction.getCorrection());
9201 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9202 CDeclEnd = Correction.end();
9203 CDecl != CDeclEnd; ++CDecl) {
9204 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9205 if (FD && !FD->hasBody() &&
9206 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9207 Previous.addDecl(D: FD);
9208 }
9209 }
9210 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9211
9212 NamedDecl *Result;
9213 // Retry building the function declaration with the new previous
9214 // declarations, and with errors suppressed.
9215 {
9216 // Trap errors.
9217 Sema::SFINAETrap Trap(SemaRef);
9218
9219 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9220 // pieces need to verify the typo-corrected C++ declaration and hopefully
9221 // eliminate the need for the parameter pack ExtraArgs.
9222 Result = SemaRef.ActOnFunctionDeclarator(
9223 S: ExtraArgs.S, D&: ExtraArgs.D,
9224 DC: Correction.getCorrectionDecl()->getDeclContext(),
9225 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9226 AddToScope&: ExtraArgs.AddToScope);
9227
9228 if (Trap.hasErrorOccurred())
9229 Result = nullptr;
9230 }
9231
9232 if (Result) {
9233 // Determine which correction we picked.
9234 Decl *Canonical = Result->getCanonicalDecl();
9235 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9236 I != E; ++I)
9237 if ((*I)->getCanonicalDecl() == Canonical)
9238 Correction.setCorrectionDecl(*I);
9239
9240 // Let Sema know about the correction.
9241 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9242 SemaRef.diagnoseTypo(
9243 Correction,
9244 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9245 ? diag::err_no_matching_local_friend_suggest
9246 : diag::err_member_decl_does_not_match_suggest)
9247 << Name << NewDC << IsDefinition);
9248 return Result;
9249 }
9250
9251 // Pretend the typo correction never occurred
9252 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9253 IdLoc: ExtraArgs.D.getIdentifierLoc());
9254 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9255 Previous.clear();
9256 Previous.setLookupName(Name);
9257 }
9258
9259 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9260 << Name << NewDC << IsDefinition << NewFD->getLocation();
9261
9262 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9263 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9264 CXXRecordDecl *RD = NewMD->getParent();
9265 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9266 << RD->getName() << RD->getLocation();
9267 }
9268
9269 bool NewFDisConst = NewMD && NewMD->isConst();
9270
9271 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9272 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9273 NearMatch != NearMatchEnd; ++NearMatch) {
9274 FunctionDecl *FD = NearMatch->first;
9275 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9276 bool FDisConst = MD && MD->isConst();
9277 bool IsMember = MD || !IsLocalFriend;
9278
9279 // FIXME: These notes are poorly worded for the local friend case.
9280 if (unsigned Idx = NearMatch->second) {
9281 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9282 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9283 if (Loc.isInvalid()) Loc = FD->getLocation();
9284 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9285 : diag::note_local_decl_close_param_match)
9286 << Idx << FDParam->getType()
9287 << NewFD->getParamDecl(i: Idx - 1)->getType();
9288 } else if (FDisConst != NewFDisConst) {
9289 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9290 DiagID: diag::note_member_def_close_const_match)
9291 << NewFDisConst << FD->getSourceRange().getEnd();
9292 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9293 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9294 Code: " const");
9295 else if (FTI.hasMethodTypeQualifiers() &&
9296 FTI.getConstQualifierLoc().isValid())
9297 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9298 } else {
9299 SemaRef.Diag(Loc: FD->getLocation(),
9300 DiagID: IsMember ? diag::note_member_def_close_match
9301 : diag::note_local_decl_close_match);
9302 }
9303 }
9304 return nullptr;
9305}
9306
9307static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9308 switch (D.getDeclSpec().getStorageClassSpec()) {
9309 default: llvm_unreachable("Unknown storage class!");
9310 case DeclSpec::SCS_auto:
9311 case DeclSpec::SCS_register:
9312 case DeclSpec::SCS_mutable:
9313 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9314 DiagID: diag::err_typecheck_sclass_func);
9315 D.getMutableDeclSpec().ClearStorageClassSpecs();
9316 D.setInvalidType();
9317 break;
9318 case DeclSpec::SCS_unspecified: break;
9319 case DeclSpec::SCS_extern:
9320 if (D.getDeclSpec().isExternInLinkageSpec())
9321 return SC_None;
9322 return SC_Extern;
9323 case DeclSpec::SCS_static: {
9324 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9325 // C99 6.7.1p5:
9326 // The declaration of an identifier for a function that has
9327 // block scope shall have no explicit storage-class specifier
9328 // other than extern
9329 // See also (C++ [dcl.stc]p4).
9330 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9331 DiagID: diag::err_static_block_func);
9332 break;
9333 } else
9334 return SC_Static;
9335 }
9336 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9337 }
9338
9339 // No explicit storage class has already been returned
9340 return SC_None;
9341}
9342
9343static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9344 DeclContext *DC, QualType &R,
9345 TypeSourceInfo *TInfo,
9346 StorageClass SC,
9347 bool &IsVirtualOkay) {
9348 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9349 DeclarationName Name = NameInfo.getName();
9350
9351 FunctionDecl *NewFD = nullptr;
9352 bool isInline = D.getDeclSpec().isInlineSpecified();
9353
9354 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9355 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9356 (SemaRef.getLangOpts().C23 &&
9357 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9358
9359 if (SemaRef.getLangOpts().C23)
9360 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9361 DiagID: diag::err_c23_constexpr_not_variable);
9362 else
9363 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9364 DiagID: diag::err_constexpr_wrong_decl_kind)
9365 << static_cast<int>(ConstexprKind);
9366 ConstexprKind = ConstexprSpecKind::Unspecified;
9367 D.getMutableDeclSpec().ClearConstexprSpec();
9368 }
9369
9370 if (!SemaRef.getLangOpts().CPlusPlus) {
9371 // Determine whether the function was written with a prototype. This is
9372 // true when:
9373 // - there is a prototype in the declarator, or
9374 // - the type R of the function is some kind of typedef or other non-
9375 // attributed reference to a type name (which eventually refers to a
9376 // function type). Note, we can't always look at the adjusted type to
9377 // check this case because attributes may cause a non-function
9378 // declarator to still have a function type. e.g.,
9379 // typedef void func(int a);
9380 // __attribute__((noreturn)) func other_func; // This has a prototype
9381 bool HasPrototype =
9382 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9383 (D.getDeclSpec().isTypeRep() &&
9384 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9385 ->isFunctionProtoType()) ||
9386 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9387 assert(
9388 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9389 "Strict prototypes are required");
9390
9391 NewFD = FunctionDecl::Create(
9392 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9393 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9394 ConstexprKind: ConstexprSpecKind::Unspecified,
9395 /*TrailingRequiresClause=*/{});
9396 if (D.isInvalidType())
9397 NewFD->setInvalidDecl();
9398
9399 return NewFD;
9400 }
9401
9402 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9403 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9404
9405 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9406
9407 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9408 // This is a C++ constructor declaration.
9409 assert(DC->isRecord() &&
9410 "Constructors can only be declared in a member context");
9411
9412 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9413 return CXXConstructorDecl::Create(
9414 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9415 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9416 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9417 Inherited: InheritedConstructor(), TrailingRequiresClause);
9418
9419 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9420 // This is a C++ destructor declaration.
9421 if (DC->isRecord()) {
9422 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9423 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9424 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9425 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9426 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9427 /*isImplicitlyDeclared=*/false, ConstexprKind,
9428 TrailingRequiresClause);
9429 // User defined destructors start as not selected if the class definition is still
9430 // not done.
9431 if (Record->isBeingDefined())
9432 NewDD->setIneligibleOrNotSelected(true);
9433
9434 // If the destructor needs an implicit exception specification, set it
9435 // now. FIXME: It'd be nice to be able to create the right type to start
9436 // with, but the type needs to reference the destructor declaration.
9437 if (SemaRef.getLangOpts().CPlusPlus11)
9438 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9439
9440 IsVirtualOkay = true;
9441 return NewDD;
9442
9443 } else {
9444 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9445 D.setInvalidType();
9446
9447 // Create a FunctionDecl to satisfy the function definition parsing
9448 // code path.
9449 return FunctionDecl::Create(
9450 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9451 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9452 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9453 }
9454
9455 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9456 if (!DC->isRecord()) {
9457 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9458 DiagID: diag::err_conv_function_not_member);
9459 return nullptr;
9460 }
9461
9462 SemaRef.CheckConversionDeclarator(D, R, SC);
9463 if (D.isInvalidType())
9464 return nullptr;
9465
9466 IsVirtualOkay = true;
9467 return CXXConversionDecl::Create(
9468 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9469 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9470 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9471 TrailingRequiresClause);
9472
9473 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9474 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9475 return nullptr;
9476 return CXXDeductionGuideDecl::Create(
9477 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9478 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9479 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9480 } else if (DC->isRecord()) {
9481 // If the name of the function is the same as the name of the record,
9482 // then this must be an invalid constructor that has a return type.
9483 // (The parser checks for a return type and makes the declarator a
9484 // constructor if it has no return type).
9485 if (Name.getAsIdentifierInfo() &&
9486 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9487 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9488 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9489 << SourceRange(D.getIdentifierLoc());
9490 return nullptr;
9491 }
9492
9493 // This is a C++ method declaration.
9494 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9495 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9496 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9497 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9498 IsVirtualOkay = !Ret->isStatic();
9499 return Ret;
9500 } else {
9501 bool isFriend =
9502 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9503 if (!isFriend && SemaRef.CurContext->isRecord())
9504 return nullptr;
9505
9506 // Determine whether the function was written with a
9507 // prototype. This true when:
9508 // - we're in C++ (where every function has a prototype),
9509 return FunctionDecl::Create(
9510 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9511 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9512 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9513 }
9514}
9515
9516enum OpenCLParamType {
9517 ValidKernelParam,
9518 PtrPtrKernelParam,
9519 PtrKernelParam,
9520 InvalidAddrSpacePtrKernelParam,
9521 InvalidKernelParam,
9522 RecordKernelParam
9523};
9524
9525static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9526 // Size dependent types are just typedefs to normal integer types
9527 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9528 // integers other than by their names.
9529 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9530
9531 // Remove typedefs one by one until we reach a typedef
9532 // for a size dependent type.
9533 QualType DesugaredTy = Ty;
9534 do {
9535 ArrayRef<StringRef> Names(SizeTypeNames);
9536 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9537 if (Names.end() != Match)
9538 return true;
9539
9540 Ty = DesugaredTy;
9541 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9542 } while (DesugaredTy != Ty);
9543
9544 return false;
9545}
9546
9547static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9548 if (PT->isDependentType())
9549 return InvalidKernelParam;
9550
9551 if (PT->isPointerOrReferenceType()) {
9552 QualType PointeeType = PT->getPointeeType();
9553 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9554 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9555 PointeeType.getAddressSpace() == LangAS::Default)
9556 return InvalidAddrSpacePtrKernelParam;
9557
9558 if (PointeeType->isPointerType()) {
9559 // This is a pointer to pointer parameter.
9560 // Recursively check inner type.
9561 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9562 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9563 ParamKind == InvalidKernelParam)
9564 return ParamKind;
9565
9566 // OpenCL v3.0 s6.11.a:
9567 // A restriction to pass pointers to pointers only applies to OpenCL C
9568 // v1.2 or below.
9569 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9570 return ValidKernelParam;
9571
9572 return PtrPtrKernelParam;
9573 }
9574
9575 // C++ for OpenCL v1.0 s2.4:
9576 // Moreover the types used in parameters of the kernel functions must be:
9577 // Standard layout types for pointer parameters. The same applies to
9578 // reference if an implementation supports them in kernel parameters.
9579 if (S.getLangOpts().OpenCLCPlusPlus &&
9580 !S.getOpenCLOptions().isAvailableOption(
9581 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9582 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9583 bool IsStandardLayoutType = true;
9584 if (CXXRec) {
9585 // If template type is not ODR-used its definition is only available
9586 // in the template definition not its instantiation.
9587 // FIXME: This logic doesn't work for types that depend on template
9588 // parameter (PR58590).
9589 if (!CXXRec->hasDefinition())
9590 CXXRec = CXXRec->getTemplateInstantiationPattern();
9591 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9592 IsStandardLayoutType = false;
9593 }
9594 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9595 !IsStandardLayoutType)
9596 return InvalidKernelParam;
9597 }
9598
9599 // OpenCL v1.2 s6.9.p:
9600 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9601 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9602 return ValidKernelParam;
9603
9604 return PtrKernelParam;
9605 }
9606
9607 // OpenCL v1.2 s6.9.k:
9608 // Arguments to kernel functions in a program cannot be declared with the
9609 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9610 // uintptr_t or a struct and/or union that contain fields declared to be one
9611 // of these built-in scalar types.
9612 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9613 return InvalidKernelParam;
9614
9615 if (PT->isImageType())
9616 return PtrKernelParam;
9617
9618 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9619 return InvalidKernelParam;
9620
9621 // OpenCL extension spec v1.2 s9.5:
9622 // This extension adds support for half scalar and vector types as built-in
9623 // types that can be used for arithmetic operations, conversions etc.
9624 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9625 PT->isHalfType())
9626 return InvalidKernelParam;
9627
9628 // Look into an array argument to check if it has a forbidden type.
9629 if (PT->isArrayType()) {
9630 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9631 // Call ourself to check an underlying type of an array. Since the
9632 // getPointeeOrArrayElementType returns an innermost type which is not an
9633 // array, this recursive call only happens once.
9634 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9635 }
9636
9637 // C++ for OpenCL v1.0 s2.4:
9638 // Moreover the types used in parameters of the kernel functions must be:
9639 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9640 // types) for parameters passed by value;
9641 if (S.getLangOpts().OpenCLCPlusPlus &&
9642 !S.getOpenCLOptions().isAvailableOption(
9643 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9644 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9645 return InvalidKernelParam;
9646
9647 if (PT->isRecordType())
9648 return RecordKernelParam;
9649
9650 return ValidKernelParam;
9651}
9652
9653static void checkIsValidOpenCLKernelParameter(
9654 Sema &S,
9655 Declarator &D,
9656 ParmVarDecl *Param,
9657 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9658 QualType PT = Param->getType();
9659
9660 // Cache the valid types we encounter to avoid rechecking structs that are
9661 // used again
9662 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9663 return;
9664
9665 switch (getOpenCLKernelParameterType(S, PT)) {
9666 case PtrPtrKernelParam:
9667 // OpenCL v3.0 s6.11.a:
9668 // A kernel function argument cannot be declared as a pointer to a pointer
9669 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9670 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9671 D.setInvalidType();
9672 return;
9673
9674 case InvalidAddrSpacePtrKernelParam:
9675 // OpenCL v1.0 s6.5:
9676 // __kernel function arguments declared to be a pointer of a type can point
9677 // to one of the following address spaces only : __global, __local or
9678 // __constant.
9679 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9680 D.setInvalidType();
9681 return;
9682
9683 // OpenCL v1.2 s6.9.k:
9684 // Arguments to kernel functions in a program cannot be declared with the
9685 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9686 // uintptr_t or a struct and/or union that contain fields declared to be
9687 // one of these built-in scalar types.
9688
9689 case InvalidKernelParam:
9690 // OpenCL v1.2 s6.8 n:
9691 // A kernel function argument cannot be declared
9692 // of event_t type.
9693 // Do not diagnose half type since it is diagnosed as invalid argument
9694 // type for any function elsewhere.
9695 if (!PT->isHalfType()) {
9696 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9697
9698 // Explain what typedefs are involved.
9699 const TypedefType *Typedef = nullptr;
9700 while ((Typedef = PT->getAs<TypedefType>())) {
9701 SourceLocation Loc = Typedef->getDecl()->getLocation();
9702 // SourceLocation may be invalid for a built-in type.
9703 if (Loc.isValid())
9704 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9705 PT = Typedef->desugar();
9706 }
9707 }
9708
9709 D.setInvalidType();
9710 return;
9711
9712 case PtrKernelParam:
9713 case ValidKernelParam:
9714 ValidTypes.insert(Ptr: PT.getTypePtr());
9715 return;
9716
9717 case RecordKernelParam:
9718 break;
9719 }
9720
9721 // Track nested structs we will inspect
9722 SmallVector<const Decl *, 4> VisitStack;
9723
9724 // Track where we are in the nested structs. Items will migrate from
9725 // VisitStack to HistoryStack as we do the DFS for bad field.
9726 SmallVector<const FieldDecl *, 4> HistoryStack;
9727 HistoryStack.push_back(Elt: nullptr);
9728
9729 // At this point we already handled everything except of a RecordType.
9730 assert(PT->isRecordType() && "Unexpected type.");
9731 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
9732 VisitStack.push_back(Elt: PD);
9733 assert(VisitStack.back() && "First decl null?");
9734
9735 do {
9736 const Decl *Next = VisitStack.pop_back_val();
9737 if (!Next) {
9738 assert(!HistoryStack.empty());
9739 // Found a marker, we have gone up a level
9740 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9741 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9742
9743 continue;
9744 }
9745
9746 // Adds everything except the original parameter declaration (which is not a
9747 // field itself) to the history stack.
9748 const RecordDecl *RD;
9749 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9750 HistoryStack.push_back(Elt: Field);
9751
9752 QualType FieldTy = Field->getType();
9753 // Other field types (known to be valid or invalid) are handled while we
9754 // walk around RecordDecl::fields().
9755 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9756 "Unexpected type.");
9757 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9758
9759 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9760 } else {
9761 RD = cast<RecordDecl>(Val: Next);
9762 }
9763
9764 // Add a null marker so we know when we've gone back up a level
9765 VisitStack.push_back(Elt: nullptr);
9766
9767 for (const auto *FD : RD->fields()) {
9768 QualType QT = FD->getType();
9769
9770 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9771 continue;
9772
9773 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9774 if (ParamType == ValidKernelParam)
9775 continue;
9776
9777 if (ParamType == RecordKernelParam) {
9778 VisitStack.push_back(Elt: FD);
9779 continue;
9780 }
9781
9782 // OpenCL v1.2 s6.9.p:
9783 // Arguments to kernel functions that are declared to be a struct or union
9784 // do not allow OpenCL objects to be passed as elements of the struct or
9785 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9786 // of SVM.
9787 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9788 ParamType == InvalidAddrSpacePtrKernelParam) {
9789 S.Diag(Loc: Param->getLocation(),
9790 DiagID: diag::err_record_with_pointers_kernel_param)
9791 << PT->isUnionType()
9792 << PT;
9793 } else {
9794 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9795 }
9796
9797 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
9798 << PD->getDeclName();
9799
9800 // We have an error, now let's go back up through history and show where
9801 // the offending field came from
9802 for (ArrayRef<const FieldDecl *>::const_iterator
9803 I = HistoryStack.begin() + 1,
9804 E = HistoryStack.end();
9805 I != E; ++I) {
9806 const FieldDecl *OuterField = *I;
9807 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
9808 << OuterField->getType();
9809 }
9810
9811 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
9812 << QT->isPointerType()
9813 << QT;
9814 D.setInvalidType();
9815 return;
9816 }
9817 } while (!VisitStack.empty());
9818}
9819
9820/// Find the DeclContext in which a tag is implicitly declared if we see an
9821/// elaborated type specifier in the specified context, and lookup finds
9822/// nothing.
9823static DeclContext *getTagInjectionContext(DeclContext *DC) {
9824 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9825 DC = DC->getParent();
9826 return DC;
9827}
9828
9829/// Find the Scope in which a tag is implicitly declared if we see an
9830/// elaborated type specifier in the specified context, and lookup finds
9831/// nothing.
9832static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9833 while (S->isClassScope() ||
9834 (LangOpts.CPlusPlus &&
9835 S->isFunctionPrototypeScope()) ||
9836 ((S->getFlags() & Scope::DeclScope) == 0) ||
9837 (S->getEntity() && S->getEntity()->isTransparentContext()))
9838 S = S->getParent();
9839 return S;
9840}
9841
9842/// Determine whether a declaration matches a known function in namespace std.
9843static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9844 unsigned BuiltinID) {
9845 switch (BuiltinID) {
9846 case Builtin::BI__GetExceptionInfo:
9847 // No type checking whatsoever.
9848 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9849
9850 case Builtin::BIaddressof:
9851 case Builtin::BI__addressof:
9852 case Builtin::BIforward:
9853 case Builtin::BIforward_like:
9854 case Builtin::BImove:
9855 case Builtin::BImove_if_noexcept:
9856 case Builtin::BIas_const: {
9857 // Ensure that we don't treat the algorithm
9858 // OutputIt std::move(InputIt, InputIt, OutputIt)
9859 // as the builtin std::move.
9860 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9861 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9862 }
9863
9864 default:
9865 return false;
9866 }
9867}
9868
9869NamedDecl*
9870Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9871 TypeSourceInfo *TInfo, LookupResult &Previous,
9872 MultiTemplateParamsArg TemplateParamListsRef,
9873 bool &AddToScope) {
9874 QualType R = TInfo->getType();
9875
9876 assert(R->isFunctionType());
9877 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9878 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
9879
9880 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9881 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
9882 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9883 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9884 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9885 TemplateParamLists.back() = Invented;
9886 else
9887 TemplateParamLists.push_back(Elt: Invented);
9888 }
9889
9890 // TODO: consider using NameInfo for diagnostic.
9891 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9892 DeclarationName Name = NameInfo.getName();
9893 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
9894
9895 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9896 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
9897 DiagID: diag::err_invalid_thread)
9898 << DeclSpec::getSpecifierName(S: TSCS);
9899
9900 if (D.isFirstDeclarationOfMember())
9901 adjustMemberFunctionCC(
9902 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9903 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
9904
9905 bool isFriend = false;
9906 FunctionTemplateDecl *FunctionTemplate = nullptr;
9907 bool isMemberSpecialization = false;
9908 bool isFunctionTemplateSpecialization = false;
9909
9910 bool HasExplicitTemplateArgs = false;
9911 TemplateArgumentListInfo TemplateArgs;
9912
9913 bool isVirtualOkay = false;
9914
9915 DeclContext *OriginalDC = DC;
9916 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9917
9918 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
9919 IsVirtualOkay&: isVirtualOkay);
9920 if (!NewFD) return nullptr;
9921
9922 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9923 NewFD->setTopLevelDeclInObjCContainer();
9924
9925 // Set the lexical context. If this is a function-scope declaration, or has a
9926 // C++ scope specifier, or is the object of a friend declaration, the lexical
9927 // context will be different from the semantic context.
9928 NewFD->setLexicalDeclContext(CurContext);
9929
9930 if (IsLocalExternDecl)
9931 NewFD->setLocalExternDecl();
9932
9933 if (getLangOpts().CPlusPlus) {
9934 // The rules for implicit inlines changed in C++20 for methods and friends
9935 // with an in-class definition (when such a definition is not attached to
9936 // the global module). This does not affect declarations that are already
9937 // inline (whether explicitly or implicitly by being declared constexpr,
9938 // consteval, etc).
9939 // FIXME: We need a better way to separate C++ standard and clang modules.
9940 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9941 !NewFD->getOwningModule() ||
9942 NewFD->isFromGlobalModule() ||
9943 NewFD->getOwningModule()->isHeaderLikeModule();
9944 bool isInline = D.getDeclSpec().isInlineSpecified();
9945 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9946 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9947 isFriend = D.getDeclSpec().isFriendSpecified();
9948 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9949 // Pre-C++20 [class.friend]p5
9950 // A function can be defined in a friend declaration of a
9951 // class . . . . Such a function is implicitly inline.
9952 // Post C++20 [class.friend]p7
9953 // Such a function is implicitly an inline function if it is attached
9954 // to the global module.
9955 NewFD->setImplicitlyInline();
9956 }
9957
9958 // If this is a method defined in an __interface, and is not a constructor
9959 // or an overloaded operator, then set the pure flag (isVirtual will already
9960 // return true).
9961 if (const CXXRecordDecl *Parent =
9962 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
9963 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
9964 NewFD->setIsPureVirtual(true);
9965
9966 // C++ [class.union]p2
9967 // A union can have member functions, but not virtual functions.
9968 if (isVirtual && Parent->isUnion()) {
9969 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
9970 NewFD->setInvalidDecl();
9971 }
9972 if ((Parent->isClass() || Parent->isStruct()) &&
9973 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9974 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9975 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9976 if (auto *Def = Parent->getDefinition())
9977 Def->setInitMethod(true);
9978 }
9979 }
9980
9981 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
9982 isMemberSpecialization = false;
9983 isFunctionTemplateSpecialization = false;
9984 if (D.isInvalidType())
9985 NewFD->setInvalidDecl();
9986
9987 // Match up the template parameter lists with the scope specifier, then
9988 // determine whether we have a template or a template specialization.
9989 bool Invalid = false;
9990 TemplateIdAnnotation *TemplateId =
9991 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9992 ? D.getName().TemplateId
9993 : nullptr;
9994 TemplateParameterList *TemplateParams =
9995 MatchTemplateParametersToScopeSpecifier(
9996 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
9997 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
9998 IsMemberSpecialization&: isMemberSpecialization, Invalid);
9999 if (TemplateParams) {
10000 // Check that we can declare a template here.
10001 if (CheckTemplateDeclScope(S, TemplateParams))
10002 NewFD->setInvalidDecl();
10003
10004 if (TemplateParams->size() > 0) {
10005 // This is a function template
10006
10007 // A destructor cannot be a template.
10008 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10009 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10010 NewFD->setInvalidDecl();
10011 // Function template with explicit template arguments.
10012 } else if (TemplateId) {
10013 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10014 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10015 NewFD->setInvalidDecl();
10016 }
10017
10018 // If we're adding a template to a dependent context, we may need to
10019 // rebuilding some of the types used within the template parameter list,
10020 // now that we know what the current instantiation is.
10021 if (DC->isDependentContext()) {
10022 ContextRAII SavedContext(*this, DC);
10023 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10024 Invalid = true;
10025 }
10026
10027 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10028 L: NewFD->getLocation(),
10029 Name, Params: TemplateParams,
10030 Decl: NewFD);
10031 FunctionTemplate->setLexicalDeclContext(CurContext);
10032 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10033
10034 // For source fidelity, store the other template param lists.
10035 if (TemplateParamLists.size() > 1) {
10036 NewFD->setTemplateParameterListsInfo(Context,
10037 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10038 .drop_back(N: 1));
10039 }
10040 } else {
10041 // This is a function template specialization.
10042 isFunctionTemplateSpecialization = true;
10043 // For source fidelity, store all the template param lists.
10044 if (TemplateParamLists.size() > 0)
10045 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10046
10047 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10048 if (isFriend) {
10049 // We want to remove the "template<>", found here.
10050 SourceRange RemoveRange = TemplateParams->getSourceRange();
10051
10052 // If we remove the template<> and the name is not a
10053 // template-id, we're actually silently creating a problem:
10054 // the friend declaration will refer to an untemplated decl,
10055 // and clearly the user wants a template specialization. So
10056 // we need to insert '<>' after the name.
10057 SourceLocation InsertLoc;
10058 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10059 InsertLoc = D.getName().getSourceRange().getEnd();
10060 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10061 }
10062
10063 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10064 << Name << RemoveRange
10065 << FixItHint::CreateRemoval(RemoveRange)
10066 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10067 Invalid = true;
10068
10069 // Recover by faking up an empty template argument list.
10070 HasExplicitTemplateArgs = true;
10071 TemplateArgs.setLAngleLoc(InsertLoc);
10072 TemplateArgs.setRAngleLoc(InsertLoc);
10073 }
10074 }
10075 } else {
10076 // Check that we can declare a template here.
10077 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10078 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10079 NewFD->setInvalidDecl();
10080
10081 // All template param lists were matched against the scope specifier:
10082 // this is NOT (an explicit specialization of) a template.
10083 if (TemplateParamLists.size() > 0)
10084 // For source fidelity, store all the template param lists.
10085 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10086
10087 // "friend void foo<>(int);" is an implicit specialization decl.
10088 if (isFriend && TemplateId)
10089 isFunctionTemplateSpecialization = true;
10090 }
10091
10092 // If this is a function template specialization and the unqualified-id of
10093 // the declarator-id is a template-id, convert the template argument list
10094 // into our AST format and check for unexpanded packs.
10095 if (isFunctionTemplateSpecialization && TemplateId) {
10096 HasExplicitTemplateArgs = true;
10097
10098 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10099 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10100 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10101 TemplateId->NumArgs);
10102 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10103
10104 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10105 // declaration of a function template partial specialization? Should we
10106 // consider the unexpanded pack context to be a partial specialization?
10107 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10108 if (DiagnoseUnexpandedParameterPack(
10109 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10110 : UPPC_ExplicitSpecialization))
10111 NewFD->setInvalidDecl();
10112 }
10113 }
10114
10115 if (Invalid) {
10116 NewFD->setInvalidDecl();
10117 if (FunctionTemplate)
10118 FunctionTemplate->setInvalidDecl();
10119 }
10120
10121 // C++ [dcl.fct.spec]p5:
10122 // The virtual specifier shall only be used in declarations of
10123 // nonstatic class member functions that appear within a
10124 // member-specification of a class declaration; see 10.3.
10125 //
10126 if (isVirtual && !NewFD->isInvalidDecl()) {
10127 if (!isVirtualOkay) {
10128 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10129 DiagID: diag::err_virtual_non_function);
10130 } else if (!CurContext->isRecord()) {
10131 // 'virtual' was specified outside of the class.
10132 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10133 DiagID: diag::err_virtual_out_of_class)
10134 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10135 } else if (NewFD->getDescribedFunctionTemplate()) {
10136 // C++ [temp.mem]p3:
10137 // A member function template shall not be virtual.
10138 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10139 DiagID: diag::err_virtual_member_function_template)
10140 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10141 } else {
10142 // Okay: Add virtual to the method.
10143 NewFD->setVirtualAsWritten(true);
10144 }
10145
10146 if (getLangOpts().CPlusPlus14 &&
10147 NewFD->getReturnType()->isUndeducedType())
10148 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10149 }
10150
10151 // C++ [dcl.fct.spec]p3:
10152 // The inline specifier shall not appear on a block scope function
10153 // declaration.
10154 if (isInline && !NewFD->isInvalidDecl()) {
10155 if (CurContext->isFunctionOrMethod()) {
10156 // 'inline' is not allowed on block scope function declaration.
10157 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10158 DiagID: diag::err_inline_declaration_block_scope) << Name
10159 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10160 }
10161 }
10162
10163 // C++ [dcl.fct.spec]p6:
10164 // The explicit specifier shall be used only in the declaration of a
10165 // constructor or conversion function within its class definition;
10166 // see 12.3.1 and 12.3.2.
10167 if (hasExplicit && !NewFD->isInvalidDecl() &&
10168 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10169 if (!CurContext->isRecord()) {
10170 // 'explicit' was specified outside of the class.
10171 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10172 DiagID: diag::err_explicit_out_of_class)
10173 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10174 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10175 !isa<CXXConversionDecl>(Val: NewFD)) {
10176 // 'explicit' was specified on a function that wasn't a constructor
10177 // or conversion function.
10178 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10179 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10180 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10181 }
10182 }
10183
10184 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10185 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10186 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10187 // are implicitly inline.
10188 NewFD->setImplicitlyInline();
10189
10190 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10191 // be either constructors or to return a literal type. Therefore,
10192 // destructors cannot be declared constexpr.
10193 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10194 (!getLangOpts().CPlusPlus20 ||
10195 ConstexprKind == ConstexprSpecKind::Consteval)) {
10196 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10197 << static_cast<int>(ConstexprKind);
10198 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10199 ? ConstexprSpecKind::Unspecified
10200 : ConstexprSpecKind::Constexpr);
10201 }
10202 // C++20 [dcl.constexpr]p2: An allocation function, or a
10203 // deallocation function shall not be declared with the consteval
10204 // specifier.
10205 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10206 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10207 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10208 DiagID: diag::err_invalid_consteval_decl_kind)
10209 << NewFD;
10210 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10211 }
10212 }
10213
10214 // If __module_private__ was specified, mark the function accordingly.
10215 if (D.getDeclSpec().isModulePrivateSpecified()) {
10216 if (isFunctionTemplateSpecialization) {
10217 SourceLocation ModulePrivateLoc
10218 = D.getDeclSpec().getModulePrivateSpecLoc();
10219 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10220 << 0
10221 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10222 } else {
10223 NewFD->setModulePrivate();
10224 if (FunctionTemplate)
10225 FunctionTemplate->setModulePrivate();
10226 }
10227 }
10228
10229 if (isFriend) {
10230 if (FunctionTemplate) {
10231 FunctionTemplate->setObjectOfFriendDecl();
10232 FunctionTemplate->setAccess(AS_public);
10233 }
10234 NewFD->setObjectOfFriendDecl();
10235 NewFD->setAccess(AS_public);
10236 }
10237
10238 // If a function is defined as defaulted or deleted, mark it as such now.
10239 // We'll do the relevant checks on defaulted / deleted functions later.
10240 switch (D.getFunctionDefinitionKind()) {
10241 case FunctionDefinitionKind::Declaration:
10242 case FunctionDefinitionKind::Definition:
10243 break;
10244
10245 case FunctionDefinitionKind::Defaulted:
10246 NewFD->setDefaulted();
10247 break;
10248
10249 case FunctionDefinitionKind::Deleted:
10250 NewFD->setDeletedAsWritten();
10251 break;
10252 }
10253
10254 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10255 D.isFunctionDefinition()) {
10256 // Pre C++20 [class.mfct]p2:
10257 // A member function may be defined (8.4) in its class definition, in
10258 // which case it is an inline member function (7.1.2)
10259 // Post C++20 [class.mfct]p1:
10260 // If a member function is attached to the global module and is defined
10261 // in its class definition, it is inline.
10262 NewFD->setImplicitlyInline();
10263 }
10264
10265 if (!isFriend && SC != SC_None) {
10266 // C++ [temp.expl.spec]p2:
10267 // The declaration in an explicit-specialization shall not be an
10268 // export-declaration. An explicit specialization shall not use a
10269 // storage-class-specifier other than thread_local.
10270 //
10271 // We diagnose friend declarations with storage-class-specifiers
10272 // elsewhere.
10273 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10274 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10275 DiagID: diag::ext_explicit_specialization_storage_class)
10276 << FixItHint::CreateRemoval(
10277 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10278 }
10279
10280 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10281 assert(isa<CXXMethodDecl>(NewFD) &&
10282 "Out-of-line member function should be a CXXMethodDecl");
10283 // C++ [class.static]p1:
10284 // A data or function member of a class may be declared static
10285 // in a class definition, in which case it is a static member of
10286 // the class.
10287
10288 // Complain about the 'static' specifier if it's on an out-of-line
10289 // member function definition.
10290
10291 // MSVC permits the use of a 'static' storage specifier on an
10292 // out-of-line member function template declaration and class member
10293 // template declaration (MSVC versions before 2015), warn about this.
10294 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10295 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10296 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10297 (getLangOpts().MSVCCompat &&
10298 NewFD->getDescribedFunctionTemplate()))
10299 ? diag::ext_static_out_of_line
10300 : diag::err_static_out_of_line)
10301 << FixItHint::CreateRemoval(
10302 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10303 }
10304 }
10305
10306 // C++11 [except.spec]p15:
10307 // A deallocation function with no exception-specification is treated
10308 // as if it were specified with noexcept(true).
10309 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10310 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10311 !FPT->hasExceptionSpec())
10312 NewFD->setType(Context.getFunctionType(
10313 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10314 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10315
10316 // C++20 [dcl.inline]/7
10317 // If an inline function or variable that is attached to a named module
10318 // is declared in a definition domain, it shall be defined in that
10319 // domain.
10320 // So, if the current declaration does not have a definition, we must
10321 // check at the end of the TU (or when the PMF starts) to see that we
10322 // have a definition at that point.
10323 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10324 NewFD->isInNamedModule()) {
10325 PendingInlineFuncDecls.insert(Ptr: NewFD);
10326 }
10327 }
10328
10329 // Filter out previous declarations that don't match the scope.
10330 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10331 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10332 isMemberSpecialization ||
10333 isFunctionTemplateSpecialization);
10334
10335 // Handle GNU asm-label extension (encoded as an attribute).
10336 if (Expr *E = (Expr*) D.getAsmLabel()) {
10337 // The parser guarantees this is a string.
10338 StringLiteral *SE = cast<StringLiteral>(Val: E);
10339 NewFD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(),
10340 /*IsLiteralLabel=*/true,
10341 Range: SE->getStrTokenLoc(TokNum: 0)));
10342 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10343 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10344 ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier());
10345 if (I != ExtnameUndeclaredIdentifiers.end()) {
10346 if (isDeclExternC(D: NewFD)) {
10347 NewFD->addAttr(A: I->second);
10348 ExtnameUndeclaredIdentifiers.erase(I);
10349 } else
10350 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10351 << /*Variable*/0 << NewFD;
10352 }
10353 }
10354
10355 // Copy the parameter declarations from the declarator D to the function
10356 // declaration NewFD, if they are available. First scavenge them into Params.
10357 SmallVector<ParmVarDecl*, 16> Params;
10358 unsigned FTIIdx;
10359 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10360 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10361
10362 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10363 // function that takes no arguments, not a function that takes a
10364 // single void argument.
10365 // We let through "const void" here because Sema::GetTypeForDeclarator
10366 // already checks for that case.
10367 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10368 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10369 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10370 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10371 Param->setDeclContext(NewFD);
10372 Params.push_back(Elt: Param);
10373
10374 if (Param->isInvalidDecl())
10375 NewFD->setInvalidDecl();
10376 }
10377 }
10378
10379 if (!getLangOpts().CPlusPlus) {
10380 // In C, find all the tag declarations from the prototype and move them
10381 // into the function DeclContext. Remove them from the surrounding tag
10382 // injection context of the function, which is typically but not always
10383 // the TU.
10384 DeclContext *PrototypeTagContext =
10385 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10386 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10387 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10388
10389 // We don't want to reparent enumerators. Look at their parent enum
10390 // instead.
10391 if (!TD) {
10392 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10393 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10394 }
10395 if (!TD)
10396 continue;
10397 DeclContext *TagDC = TD->getLexicalDeclContext();
10398 if (!TagDC->containsDecl(D: TD))
10399 continue;
10400 TagDC->removeDecl(D: TD);
10401 TD->setDeclContext(NewFD);
10402 NewFD->addDecl(D: TD);
10403
10404 // Preserve the lexical DeclContext if it is not the surrounding tag
10405 // injection context of the FD. In this example, the semantic context of
10406 // E will be f and the lexical context will be S, while both the
10407 // semantic and lexical contexts of S will be f:
10408 // void f(struct S { enum E { a } f; } s);
10409 if (TagDC != PrototypeTagContext)
10410 TD->setLexicalDeclContext(TagDC);
10411 }
10412 }
10413 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10414 // When we're declaring a function with a typedef, typeof, etc as in the
10415 // following example, we'll need to synthesize (unnamed)
10416 // parameters for use in the declaration.
10417 //
10418 // @code
10419 // typedef void fn(int);
10420 // fn f;
10421 // @endcode
10422
10423 // Synthesize a parameter for each argument type.
10424 for (const auto &AI : FT->param_types()) {
10425 ParmVarDecl *Param =
10426 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10427 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10428 Params.push_back(Elt: Param);
10429 }
10430 } else {
10431 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10432 "Should not need args for typedef of non-prototype fn");
10433 }
10434
10435 // Finally, we know we have the right number of parameters, install them.
10436 NewFD->setParams(Params);
10437
10438 // If this declarator is a declaration and not a definition, its parameters
10439 // will not be pushed onto a scope chain. That means we will not issue any
10440 // reserved identifier warnings for the declaration, but we will for the
10441 // definition. Handle those here.
10442 if (!D.isFunctionDefinition()) {
10443 for (const ParmVarDecl *PVD : Params)
10444 warnOnReservedIdentifier(D: PVD);
10445 }
10446
10447 if (D.getDeclSpec().isNoreturnSpecified())
10448 NewFD->addAttr(
10449 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10450
10451 // Functions returning a variably modified type violate C99 6.7.5.2p2
10452 // because all functions have linkage.
10453 if (!NewFD->isInvalidDecl() &&
10454 NewFD->getReturnType()->isVariablyModifiedType()) {
10455 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10456 NewFD->setInvalidDecl();
10457 }
10458
10459 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10460 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10461 !NewFD->hasAttr<SectionAttr>())
10462 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10463 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10464 Range: PragmaClangTextSection.PragmaLocation));
10465
10466 // Apply an implicit SectionAttr if #pragma code_seg is active.
10467 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10468 !NewFD->hasAttr<SectionAttr>()) {
10469 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10470 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10471 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10472 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10473 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10474 ASTContext::PSF_Read,
10475 TheDecl: NewFD))
10476 NewFD->dropAttr<SectionAttr>();
10477 }
10478
10479 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10480 // active.
10481 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10482 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10483 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10484 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10485
10486 // Apply an implicit CodeSegAttr from class declspec or
10487 // apply an implicit SectionAttr from #pragma code_seg if active.
10488 if (!NewFD->hasAttr<CodeSegAttr>()) {
10489 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10490 IsDefinition: D.isFunctionDefinition())) {
10491 NewFD->addAttr(A: SAttr);
10492 }
10493 }
10494
10495 // Handle attributes.
10496 ProcessDeclAttributes(S, D: NewFD, PD: D);
10497 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10498 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10499 !NewTVA->isDefaultVersion() &&
10500 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10501 // Don't add to scope fmv functions declarations if fmv disabled
10502 AddToScope = false;
10503 return NewFD;
10504 }
10505
10506 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10507 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10508 // type.
10509 //
10510 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10511 // type declaration will generate a compilation error.
10512 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10513 if (AddressSpace != LangAS::Default) {
10514 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10515 NewFD->setInvalidDecl();
10516 }
10517 }
10518
10519 if (!getLangOpts().CPlusPlus) {
10520 // Perform semantic checking on the function declaration.
10521 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10522 CheckMain(FD: NewFD, D: D.getDeclSpec());
10523
10524 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10525 CheckMSVCRTEntryPoint(FD: NewFD);
10526
10527 if (!NewFD->isInvalidDecl())
10528 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10529 IsMemberSpecialization: isMemberSpecialization,
10530 DeclIsDefn: D.isFunctionDefinition()));
10531 else if (!Previous.empty())
10532 // Recover gracefully from an invalid redeclaration.
10533 D.setRedeclaration(true);
10534 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10535 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10536 "previous declaration set still overloaded");
10537
10538 // Diagnose no-prototype function declarations with calling conventions that
10539 // don't support variadic calls. Only do this in C and do it after merging
10540 // possibly prototyped redeclarations.
10541 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10542 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10543 CallingConv CC = FT->getExtInfo().getCC();
10544 if (!supportsVariadicCall(CC)) {
10545 // Windows system headers sometimes accidentally use stdcall without
10546 // (void) parameters, so we relax this to a warning.
10547 int DiagID =
10548 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10549 Diag(Loc: NewFD->getLocation(), DiagID)
10550 << FunctionType::getNameForCallConv(CC);
10551 }
10552 }
10553
10554 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10555 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10556 checkNonTrivialCUnion(
10557 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10558 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10559 } else {
10560 // C++11 [replacement.functions]p3:
10561 // The program's definitions shall not be specified as inline.
10562 //
10563 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10564 //
10565 // Suppress the diagnostic if the function is __attribute__((used)), since
10566 // that forces an external definition to be emitted.
10567 if (D.getDeclSpec().isInlineSpecified() &&
10568 NewFD->isReplaceableGlobalAllocationFunction() &&
10569 !NewFD->hasAttr<UsedAttr>())
10570 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10571 DiagID: diag::ext_operator_new_delete_declared_inline)
10572 << NewFD->getDeclName();
10573
10574 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10575 // C++20 [dcl.decl.general]p4:
10576 // The optional requires-clause in an init-declarator or
10577 // member-declarator shall be present only if the declarator declares a
10578 // templated function.
10579 //
10580 // C++20 [temp.pre]p8:
10581 // An entity is templated if it is
10582 // - a template,
10583 // - an entity defined or created in a templated entity,
10584 // - a member of a templated entity,
10585 // - an enumerator for an enumeration that is a templated entity, or
10586 // - the closure type of a lambda-expression appearing in the
10587 // declaration of a templated entity.
10588 //
10589 // [Note 6: A local class, a local or block variable, or a friend
10590 // function defined in a templated entity is a templated entity.
10591 // — end note]
10592 //
10593 // A templated function is a function template or a function that is
10594 // templated. A templated class is a class template or a class that is
10595 // templated. A templated variable is a variable template or a variable
10596 // that is templated.
10597 if (!FunctionTemplate) {
10598 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10599 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10600 // An explicit specialization shall not have a trailing
10601 // requires-clause unless it declares a function template.
10602 //
10603 // Since a friend function template specialization cannot be
10604 // definition, and since a non-template friend declaration with a
10605 // trailing requires-clause must be a definition, we diagnose
10606 // friend function template specializations with trailing
10607 // requires-clauses on the same path as explicit specializations
10608 // even though they aren't necessarily prohibited by the same
10609 // language rule.
10610 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10611 << isFriend;
10612 } else if (isFriend && NewFD->isTemplated() &&
10613 !D.isFunctionDefinition()) {
10614 // C++ [temp.friend]p9:
10615 // A non-template friend declaration with a requires-clause shall be
10616 // a definition.
10617 Diag(Loc: NewFD->getBeginLoc(),
10618 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10619 NewFD->setInvalidDecl();
10620 } else if (!NewFD->isTemplated() ||
10621 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10622 Diag(Loc: TRC->getBeginLoc(),
10623 DiagID: diag::err_constrained_non_templated_function);
10624 }
10625 }
10626 }
10627
10628 // We do not add HD attributes to specializations here because
10629 // they may have different constexpr-ness compared to their
10630 // templates and, after maybeAddHostDeviceAttrs() is applied,
10631 // may end up with different effective targets. Instead, a
10632 // specialization inherits its target attributes from its template
10633 // in the CheckFunctionTemplateSpecialization() call below.
10634 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10635 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10636
10637 // Handle explicit specializations of function templates
10638 // and friend function declarations with an explicit
10639 // template argument list.
10640 if (isFunctionTemplateSpecialization) {
10641 bool isDependentSpecialization = false;
10642 if (isFriend) {
10643 // For friend function specializations, this is a dependent
10644 // specialization if its semantic context is dependent, its
10645 // type is dependent, or if its template-id is dependent.
10646 isDependentSpecialization =
10647 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10648 (HasExplicitTemplateArgs &&
10649 TemplateSpecializationType::
10650 anyInstantiationDependentTemplateArguments(
10651 Args: TemplateArgs.arguments()));
10652 assert((!isDependentSpecialization ||
10653 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10654 "dependent friend function specialization without template "
10655 "args");
10656 } else {
10657 // For class-scope explicit specializations of function templates,
10658 // if the lexical context is dependent, then the specialization
10659 // is dependent.
10660 isDependentSpecialization =
10661 CurContext->isRecord() && CurContext->isDependentContext();
10662 }
10663
10664 TemplateArgumentListInfo *ExplicitTemplateArgs =
10665 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10666 if (isDependentSpecialization) {
10667 // If it's a dependent specialization, it may not be possible
10668 // to determine the primary template (for explicit specializations)
10669 // or befriended declaration (for friends) until the enclosing
10670 // template is instantiated. In such cases, we store the declarations
10671 // found by name lookup and defer resolution until instantiation.
10672 if (CheckDependentFunctionTemplateSpecialization(
10673 FD: NewFD, ExplicitTemplateArgs, Previous))
10674 NewFD->setInvalidDecl();
10675 } else if (!NewFD->isInvalidDecl()) {
10676 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10677 Previous))
10678 NewFD->setInvalidDecl();
10679 }
10680 } else if (isMemberSpecialization && !FunctionTemplate) {
10681 if (CheckMemberSpecialization(Member: NewFD, Previous))
10682 NewFD->setInvalidDecl();
10683 }
10684
10685 // Perform semantic checking on the function declaration.
10686 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10687 CheckMain(FD: NewFD, D: D.getDeclSpec());
10688
10689 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10690 CheckMSVCRTEntryPoint(FD: NewFD);
10691
10692 if (!NewFD->isInvalidDecl())
10693 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10694 IsMemberSpecialization: isMemberSpecialization,
10695 DeclIsDefn: D.isFunctionDefinition()));
10696 else if (!Previous.empty())
10697 // Recover gracefully from an invalid redeclaration.
10698 D.setRedeclaration(true);
10699
10700 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10701 !D.isRedeclaration() ||
10702 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10703 "previous declaration set still overloaded");
10704
10705 NamedDecl *PrincipalDecl = (FunctionTemplate
10706 ? cast<NamedDecl>(Val: FunctionTemplate)
10707 : NewFD);
10708
10709 if (isFriend && NewFD->getPreviousDecl()) {
10710 AccessSpecifier Access = AS_public;
10711 if (!NewFD->isInvalidDecl())
10712 Access = NewFD->getPreviousDecl()->getAccess();
10713
10714 NewFD->setAccess(Access);
10715 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10716 }
10717
10718 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10719 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10720 PrincipalDecl->setNonMemberOperator();
10721
10722 // If we have a function template, check the template parameter
10723 // list. This will check and merge default template arguments.
10724 if (FunctionTemplate) {
10725 FunctionTemplateDecl *PrevTemplate =
10726 FunctionTemplate->getPreviousDecl();
10727 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10728 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10729 : nullptr,
10730 TPC: D.getDeclSpec().isFriendSpecified()
10731 ? (D.isFunctionDefinition()
10732 ? TPC_FriendFunctionTemplateDefinition
10733 : TPC_FriendFunctionTemplate)
10734 : (D.getCXXScopeSpec().isSet() &&
10735 DC && DC->isRecord() &&
10736 DC->isDependentContext())
10737 ? TPC_ClassTemplateMember
10738 : TPC_FunctionTemplate);
10739 }
10740
10741 if (NewFD->isInvalidDecl()) {
10742 // Ignore all the rest of this.
10743 } else if (!D.isRedeclaration()) {
10744 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10745 .AddToScope: AddToScope };
10746 // Fake up an access specifier if it's supposed to be a class member.
10747 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10748 NewFD->setAccess(AS_public);
10749
10750 // Qualified decls generally require a previous declaration.
10751 if (D.getCXXScopeSpec().isSet()) {
10752 // ...with the major exception of templated-scope or
10753 // dependent-scope friend declarations.
10754
10755 // TODO: we currently also suppress this check in dependent
10756 // contexts because (1) the parameter depth will be off when
10757 // matching friend templates and (2) we might actually be
10758 // selecting a friend based on a dependent factor. But there
10759 // are situations where these conditions don't apply and we
10760 // can actually do this check immediately.
10761 //
10762 // Unless the scope is dependent, it's always an error if qualified
10763 // redeclaration lookup found nothing at all. Diagnose that now;
10764 // nothing will diagnose that error later.
10765 if (isFriend &&
10766 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10767 (!Previous.empty() && CurContext->isDependentContext()))) {
10768 // ignore these
10769 } else if (NewFD->isCPUDispatchMultiVersion() ||
10770 NewFD->isCPUSpecificMultiVersion()) {
10771 // ignore this, we allow the redeclaration behavior here to create new
10772 // versions of the function.
10773 } else {
10774 // The user tried to provide an out-of-line definition for a
10775 // function that is a member of a class or namespace, but there
10776 // was no such member function declared (C++ [class.mfct]p2,
10777 // C++ [namespace.memdef]p2). For example:
10778 //
10779 // class X {
10780 // void f() const;
10781 // };
10782 //
10783 // void X::f() { } // ill-formed
10784 //
10785 // Complain about this problem, and attempt to suggest close
10786 // matches (e.g., those that differ only in cv-qualifiers and
10787 // whether the parameter types are references).
10788
10789 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10790 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10791 AddToScope = ExtraArgs.AddToScope;
10792 return Result;
10793 }
10794 }
10795
10796 // Unqualified local friend declarations are required to resolve
10797 // to something.
10798 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10799 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10800 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10801 AddToScope = ExtraArgs.AddToScope;
10802 return Result;
10803 }
10804 }
10805 } else if (!D.isFunctionDefinition() &&
10806 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10807 !isFriend && !isFunctionTemplateSpecialization &&
10808 !isMemberSpecialization) {
10809 // An out-of-line member function declaration must also be a
10810 // definition (C++ [class.mfct]p2).
10811 // Note that this is not the case for explicit specializations of
10812 // function templates or member functions of class templates, per
10813 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10814 // extension for compatibility with old SWIG code which likes to
10815 // generate them.
10816 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
10817 << D.getCXXScopeSpec().getRange();
10818 }
10819 }
10820
10821 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10822 // Any top level function could potentially be specified as an entry.
10823 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10824 HLSL().ActOnTopLevelFunction(FD: NewFD);
10825
10826 if (NewFD->hasAttr<HLSLShaderAttr>())
10827 HLSL().CheckEntryPoint(FD: NewFD);
10828 }
10829
10830 // If this is the first declaration of a library builtin function, add
10831 // attributes as appropriate.
10832 if (!D.isRedeclaration()) {
10833 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10834 if (unsigned BuiltinID = II->getBuiltinID()) {
10835 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
10836 if (!InStdNamespace &&
10837 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10838 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10839 // Validate the type matches unless this builtin is specified as
10840 // matching regardless of its declared type.
10841 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
10842 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
10843 } else {
10844 ASTContext::GetBuiltinTypeError Error;
10845 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
10846 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
10847
10848 if (!Error && !BuiltinType.isNull() &&
10849 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10850 T: NewFD->getType(), U: BuiltinType))
10851 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
10852 }
10853 }
10854 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10855 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
10856 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
10857 }
10858 }
10859 }
10860 }
10861
10862 ProcessPragmaWeak(S, D: NewFD);
10863 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
10864
10865 AddKnownFunctionAttributes(FD: NewFD);
10866
10867 if (NewFD->hasAttr<OverloadableAttr>() &&
10868 !NewFD->getType()->getAs<FunctionProtoType>()) {
10869 Diag(Loc: NewFD->getLocation(),
10870 DiagID: diag::err_attribute_overloadable_no_prototype)
10871 << NewFD;
10872 NewFD->dropAttr<OverloadableAttr>();
10873 }
10874
10875 // If there's a #pragma GCC visibility in scope, and this isn't a class
10876 // member, set the visibility of this function.
10877 if (!DC->isRecord() && NewFD->isExternallyVisible())
10878 AddPushedVisibilityAttribute(RD: NewFD);
10879
10880 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10881 // marking the function.
10882 ObjC().AddCFAuditedAttribute(D: NewFD);
10883
10884 // If this is a function definition, check if we have to apply any
10885 // attributes (i.e. optnone and no_builtin) due to a pragma.
10886 if (D.isFunctionDefinition()) {
10887 AddRangeBasedOptnone(FD: NewFD);
10888 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
10889 AddSectionMSAllocText(FD: NewFD);
10890 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
10891 }
10892
10893 // If this is the first declaration of an extern C variable, update
10894 // the map of such variables.
10895 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10896 isIncompleteDeclExternC(S&: *this, D: NewFD))
10897 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
10898
10899 // Set this FunctionDecl's range up to the right paren.
10900 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10901
10902 if (D.isRedeclaration() && !Previous.empty()) {
10903 NamedDecl *Prev = Previous.getRepresentativeDecl();
10904 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
10905 IsSpecialization: isMemberSpecialization ||
10906 isFunctionTemplateSpecialization,
10907 IsDefinition: D.isFunctionDefinition());
10908 }
10909
10910 if (getLangOpts().CUDA) {
10911 IdentifierInfo *II = NewFD->getIdentifier();
10912 if (II && II->isStr(Str: CUDA().getConfigureFuncName()) &&
10913 !NewFD->isInvalidDecl() &&
10914 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10915 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10916 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
10917 << CUDA().getConfigureFuncName();
10918 Context.setcudaConfigureCallDecl(NewFD);
10919 }
10920
10921 // Variadic functions, other than a *declaration* of printf, are not allowed
10922 // in device-side CUDA code, unless someone passed
10923 // -fcuda-allow-variadic-functions.
10924 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10925 (NewFD->hasAttr<CUDADeviceAttr>() ||
10926 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10927 !(II && II->isStr(Str: "printf") && NewFD->isExternC() &&
10928 !D.isFunctionDefinition())) {
10929 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_variadic_device_fn);
10930 }
10931 }
10932
10933 MarkUnusedFileScopedDecl(D: NewFD);
10934
10935 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
10936 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10937 if (SC == SC_Static) {
10938 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
10939 D.setInvalidType();
10940 }
10941
10942 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10943 if (!NewFD->getReturnType()->isVoidType()) {
10944 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10945 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
10946 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
10947 : FixItHint());
10948 D.setInvalidType();
10949 }
10950
10951 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10952 for (auto *Param : NewFD->parameters())
10953 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
10954
10955 if (getLangOpts().OpenCLCPlusPlus) {
10956 if (DC->isRecord()) {
10957 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
10958 D.setInvalidType();
10959 }
10960 if (FunctionTemplate) {
10961 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
10962 D.setInvalidType();
10963 }
10964 }
10965 }
10966
10967 if (getLangOpts().CPlusPlus) {
10968 // Precalculate whether this is a friend function template with a constraint
10969 // that depends on an enclosing template, per [temp.friend]p9.
10970 if (isFriend && FunctionTemplate &&
10971 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
10972 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10973
10974 // C++ [temp.friend]p9:
10975 // A friend function template with a constraint that depends on a
10976 // template parameter from an enclosing template shall be a definition.
10977 if (!D.isFunctionDefinition()) {
10978 Diag(Loc: NewFD->getBeginLoc(),
10979 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10980 NewFD->setInvalidDecl();
10981 }
10982 }
10983
10984 if (FunctionTemplate) {
10985 if (NewFD->isInvalidDecl())
10986 FunctionTemplate->setInvalidDecl();
10987 return FunctionTemplate;
10988 }
10989
10990 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10991 CompleteMemberSpecialization(Member: NewFD, Previous);
10992 }
10993
10994 for (const ParmVarDecl *Param : NewFD->parameters()) {
10995 QualType PT = Param->getType();
10996
10997 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10998 // types.
10999 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11000 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11001 QualType ElemTy = PipeTy->getElementType();
11002 if (ElemTy->isPointerOrReferenceType()) {
11003 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11004 D.setInvalidType();
11005 }
11006 }
11007 }
11008 // WebAssembly tables can't be used as function parameters.
11009 if (Context.getTargetInfo().getTriple().isWasm()) {
11010 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11011 Diag(Loc: Param->getTypeSpecStartLoc(),
11012 DiagID: diag::err_wasm_table_as_function_parameter);
11013 D.setInvalidType();
11014 }
11015 }
11016 }
11017
11018 // Diagnose availability attributes. Availability cannot be used on functions
11019 // that are run during load/unload.
11020 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11021 if (NewFD->hasAttr<ConstructorAttr>()) {
11022 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11023 << 1;
11024 NewFD->dropAttr<AvailabilityAttr>();
11025 }
11026 if (NewFD->hasAttr<DestructorAttr>()) {
11027 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11028 << 2;
11029 NewFD->dropAttr<AvailabilityAttr>();
11030 }
11031 }
11032
11033 // Diagnose no_builtin attribute on function declaration that are not a
11034 // definition.
11035 // FIXME: We should really be doing this in
11036 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11037 // the FunctionDecl and at this point of the code
11038 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11039 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11040 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11041 switch (D.getFunctionDefinitionKind()) {
11042 case FunctionDefinitionKind::Defaulted:
11043 case FunctionDefinitionKind::Deleted:
11044 Diag(Loc: NBA->getLocation(),
11045 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11046 << NBA->getSpelling();
11047 break;
11048 case FunctionDefinitionKind::Declaration:
11049 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11050 << NBA->getSpelling();
11051 break;
11052 case FunctionDefinitionKind::Definition:
11053 break;
11054 }
11055
11056 // Similar to no_builtin logic above, at this point of the code
11057 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11058 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11059 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11060 !NewFD->isInvalidDecl() &&
11061 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11062 ExternalDeclarations.push_back(Elt: NewFD);
11063
11064 // Used for a warning on the 'next' declaration when used with a
11065 // `routine(name)`.
11066 if (getLangOpts().OpenACC)
11067 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11068
11069 return NewFD;
11070}
11071
11072/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11073/// when __declspec(code_seg) "is applied to a class, all member functions of
11074/// the class and nested classes -- this includes compiler-generated special
11075/// member functions -- are put in the specified segment."
11076/// The actual behavior is a little more complicated. The Microsoft compiler
11077/// won't check outer classes if there is an active value from #pragma code_seg.
11078/// The CodeSeg is always applied from the direct parent but only from outer
11079/// classes when the #pragma code_seg stack is empty. See:
11080/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11081/// available since MS has removed the page.
11082static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11083 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11084 if (!Method)
11085 return nullptr;
11086 const CXXRecordDecl *Parent = Method->getParent();
11087 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11088 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11089 NewAttr->setImplicit(true);
11090 return NewAttr;
11091 }
11092
11093 // The Microsoft compiler won't check outer classes for the CodeSeg
11094 // when the #pragma code_seg stack is active.
11095 if (S.CodeSegStack.CurrentValue)
11096 return nullptr;
11097
11098 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11099 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11100 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11101 NewAttr->setImplicit(true);
11102 return NewAttr;
11103 }
11104 }
11105 return nullptr;
11106}
11107
11108Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11109 bool IsDefinition) {
11110 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11111 return A;
11112 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11113 CodeSegStack.CurrentValue)
11114 return SectionAttr::CreateImplicit(
11115 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11116 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11117 return nullptr;
11118}
11119
11120bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11121 QualType NewT, QualType OldT) {
11122 if (!NewD->getLexicalDeclContext()->isDependentContext())
11123 return true;
11124
11125 // For dependently-typed local extern declarations and friends, we can't
11126 // perform a correct type check in general until instantiation:
11127 //
11128 // int f();
11129 // template<typename T> void g() { T f(); }
11130 //
11131 // (valid if g() is only instantiated with T = int).
11132 if (NewT->isDependentType() &&
11133 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11134 return false;
11135
11136 // Similarly, if the previous declaration was a dependent local extern
11137 // declaration, we don't really know its type yet.
11138 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11139 return false;
11140
11141 return true;
11142}
11143
11144bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11145 if (!D->getLexicalDeclContext()->isDependentContext())
11146 return true;
11147
11148 // Don't chain dependent friend function definitions until instantiation, to
11149 // permit cases like
11150 //
11151 // void func();
11152 // template<typename T> class C1 { friend void func() {} };
11153 // template<typename T> class C2 { friend void func() {} };
11154 //
11155 // ... which is valid if only one of C1 and C2 is ever instantiated.
11156 //
11157 // FIXME: This need only apply to function definitions. For now, we proxy
11158 // this by checking for a file-scope function. We do not want this to apply
11159 // to friend declarations nominating member functions, because that gets in
11160 // the way of access checks.
11161 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11162 return false;
11163
11164 auto *VD = dyn_cast<ValueDecl>(Val: D);
11165 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11166 return !VD || !PrevVD ||
11167 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11168 OldT: PrevVD->getType());
11169}
11170
11171/// Check the target or target_version attribute of the function for
11172/// MultiVersion validity.
11173///
11174/// Returns true if there was an error, false otherwise.
11175static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11176 const auto *TA = FD->getAttr<TargetAttr>();
11177 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11178
11179 assert((TA || TVA) && "Expecting target or target_version attribute");
11180
11181 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11182 enum ErrType { Feature = 0, Architecture = 1 };
11183
11184 if (TA) {
11185 ParsedTargetAttr ParseInfo =
11186 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11187 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11188 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11189 << Architecture << ParseInfo.CPU;
11190 return true;
11191 }
11192 for (const auto &Feat : ParseInfo.Features) {
11193 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11194 if (Feat[0] == '-') {
11195 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11196 << Feature << ("no-" + BareFeat).str();
11197 return true;
11198 }
11199
11200 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11201 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11202 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11203 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11204 << Feature << BareFeat;
11205 return true;
11206 }
11207 }
11208 }
11209
11210 if (TVA) {
11211 llvm::SmallVector<StringRef, 8> Feats;
11212 ParsedTargetAttr ParseInfo;
11213 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11214 ParseInfo =
11215 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11216 for (auto &Feat : ParseInfo.Features)
11217 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11218 } else {
11219 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11220 TVA->getFeatures(Out&: Feats);
11221 }
11222 for (const auto &Feat : Feats) {
11223 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11224 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11225 << Feature << Feat;
11226 return true;
11227 }
11228 }
11229 }
11230 return false;
11231}
11232
11233// Provide a white-list of attributes that are allowed to be combined with
11234// multiversion functions.
11235static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11236 MultiVersionKind MVKind) {
11237 // Note: this list/diagnosis must match the list in
11238 // checkMultiversionAttributesAllSame.
11239 switch (Kind) {
11240 default:
11241 return false;
11242 case attr::ArmLocallyStreaming:
11243 return MVKind == MultiVersionKind::TargetVersion ||
11244 MVKind == MultiVersionKind::TargetClones;
11245 case attr::Used:
11246 return MVKind == MultiVersionKind::Target;
11247 case attr::NonNull:
11248 case attr::NoThrow:
11249 return true;
11250 }
11251}
11252
11253static bool checkNonMultiVersionCompatAttributes(Sema &S,
11254 const FunctionDecl *FD,
11255 const FunctionDecl *CausedFD,
11256 MultiVersionKind MVKind) {
11257 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11258 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11259 << static_cast<unsigned>(MVKind) << A;
11260 if (CausedFD)
11261 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11262 return true;
11263 };
11264
11265 for (const Attr *A : FD->attrs()) {
11266 switch (A->getKind()) {
11267 case attr::CPUDispatch:
11268 case attr::CPUSpecific:
11269 if (MVKind != MultiVersionKind::CPUDispatch &&
11270 MVKind != MultiVersionKind::CPUSpecific)
11271 return Diagnose(S, A);
11272 break;
11273 case attr::Target:
11274 if (MVKind != MultiVersionKind::Target)
11275 return Diagnose(S, A);
11276 break;
11277 case attr::TargetVersion:
11278 if (MVKind != MultiVersionKind::TargetVersion &&
11279 MVKind != MultiVersionKind::TargetClones)
11280 return Diagnose(S, A);
11281 break;
11282 case attr::TargetClones:
11283 if (MVKind != MultiVersionKind::TargetClones &&
11284 MVKind != MultiVersionKind::TargetVersion)
11285 return Diagnose(S, A);
11286 break;
11287 default:
11288 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11289 return Diagnose(S, A);
11290 break;
11291 }
11292 }
11293 return false;
11294}
11295
11296bool Sema::areMultiversionVariantFunctionsCompatible(
11297 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11298 const PartialDiagnostic &NoProtoDiagID,
11299 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11300 const PartialDiagnosticAt &NoSupportDiagIDAt,
11301 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11302 bool ConstexprSupported, bool CLinkageMayDiffer) {
11303 enum DoesntSupport {
11304 FuncTemplates = 0,
11305 VirtFuncs = 1,
11306 DeducedReturn = 2,
11307 Constructors = 3,
11308 Destructors = 4,
11309 DeletedFuncs = 5,
11310 DefaultedFuncs = 6,
11311 ConstexprFuncs = 7,
11312 ConstevalFuncs = 8,
11313 Lambda = 9,
11314 };
11315 enum Different {
11316 CallingConv = 0,
11317 ReturnType = 1,
11318 ConstexprSpec = 2,
11319 InlineSpec = 3,
11320 Linkage = 4,
11321 LanguageLinkage = 5,
11322 };
11323
11324 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11325 !OldFD->getType()->getAs<FunctionProtoType>()) {
11326 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11327 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11328 return true;
11329 }
11330
11331 if (NoProtoDiagID.getDiagID() != 0 &&
11332 !NewFD->getType()->getAs<FunctionProtoType>())
11333 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11334
11335 if (!TemplatesSupported &&
11336 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11337 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11338 << FuncTemplates;
11339
11340 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11341 if (NewCXXFD->isVirtual())
11342 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11343 << VirtFuncs;
11344
11345 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11346 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11347 << Constructors;
11348
11349 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11350 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11351 << Destructors;
11352 }
11353
11354 if (NewFD->isDeleted())
11355 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11356 << DeletedFuncs;
11357
11358 if (NewFD->isDefaulted())
11359 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11360 << DefaultedFuncs;
11361
11362 if (!ConstexprSupported && NewFD->isConstexpr())
11363 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11364 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11365
11366 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11367 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11368 QualType NewReturnType = NewType->getReturnType();
11369
11370 if (NewReturnType->isUndeducedType())
11371 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11372 << DeducedReturn;
11373
11374 // Ensure the return type is identical.
11375 if (OldFD) {
11376 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11377 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11378 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11379 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11380
11381 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11382 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11383
11384 bool ArmStreamingCCMismatched = false;
11385 if (OldFPT && NewFPT) {
11386 unsigned Diff =
11387 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11388 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11389 // cannot be mixed.
11390 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11391 FunctionType::SME_PStateSMCompatibleMask))
11392 ArmStreamingCCMismatched = true;
11393 }
11394
11395 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11396 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11397
11398 QualType OldReturnType = OldType->getReturnType();
11399
11400 if (OldReturnType != NewReturnType)
11401 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11402
11403 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11404 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11405
11406 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11407 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11408
11409 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11410 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11411
11412 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11413 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11414
11415 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11416 NewLoc: NewFD->getLocation()))
11417 return true;
11418 }
11419 return false;
11420}
11421
11422static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11423 const FunctionDecl *NewFD,
11424 bool CausesMV,
11425 MultiVersionKind MVKind) {
11426 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11427 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11428 if (OldFD)
11429 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11430 return true;
11431 }
11432
11433 bool IsCPUSpecificCPUDispatchMVKind =
11434 MVKind == MultiVersionKind::CPUDispatch ||
11435 MVKind == MultiVersionKind::CPUSpecific;
11436
11437 if (CausesMV && OldFD &&
11438 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11439 return true;
11440
11441 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11442 return true;
11443
11444 // Only allow transition to MultiVersion if it hasn't been used.
11445 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11446 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11447 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11448 return true;
11449 }
11450
11451 return S.areMultiversionVariantFunctionsCompatible(
11452 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11453 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11454 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11455 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11456 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11457 << static_cast<unsigned>(MVKind)),
11458 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11459 S.PDiag(DiagID: diag::err_multiversion_diff)),
11460 /*TemplatesSupported=*/false,
11461 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11462 /*CLinkageMayDiffer=*/false);
11463}
11464
11465/// Check the validity of a multiversion function declaration that is the
11466/// first of its kind. Also sets the multiversion'ness' of the function itself.
11467///
11468/// This sets NewFD->isInvalidDecl() to true if there was an error.
11469///
11470/// Returns true if there was an error, false otherwise.
11471static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11472 MultiVersionKind MVKind = FD->getMultiVersionKind();
11473 assert(MVKind != MultiVersionKind::None &&
11474 "Function lacks multiversion attribute");
11475 const auto *TA = FD->getAttr<TargetAttr>();
11476 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11477 // The target attribute only causes MV if this declaration is the default,
11478 // otherwise it is treated as a normal function.
11479 if (TA && !TA->isDefaultVersion())
11480 return false;
11481
11482 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11483 FD->setInvalidDecl();
11484 return true;
11485 }
11486
11487 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11488 FD->setInvalidDecl();
11489 return true;
11490 }
11491
11492 FD->setIsMultiVersion();
11493 return false;
11494}
11495
11496static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11497 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11498 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11499 return true;
11500 }
11501
11502 return false;
11503}
11504
11505static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11506 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11507 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11508 return;
11509
11510 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11511 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11512
11513 if (MVKindTo == MultiVersionKind::None &&
11514 (MVKindFrom == MultiVersionKind::TargetVersion ||
11515 MVKindFrom == MultiVersionKind::TargetClones))
11516 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11517 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11518}
11519
11520static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11521 FunctionDecl *NewFD,
11522 bool &Redeclaration,
11523 NamedDecl *&OldDecl,
11524 LookupResult &Previous) {
11525 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11526
11527 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11528 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11529 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11530 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11531
11532 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11533
11534 // The definitions should be allowed in any order. If we have discovered
11535 // a new target version and the preceeding was the default, then add the
11536 // corresponding attribute to it.
11537 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11538
11539 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11540 // to change, this is a simple redeclaration.
11541 if (NewTA && !NewTA->isDefaultVersion() &&
11542 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11543 return false;
11544
11545 // Otherwise, this decl causes MultiVersioning.
11546 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11547 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11548 : MultiVersionKind::Target)) {
11549 NewFD->setInvalidDecl();
11550 return true;
11551 }
11552
11553 if (CheckMultiVersionValue(S, FD: NewFD)) {
11554 NewFD->setInvalidDecl();
11555 return true;
11556 }
11557
11558 // If this is 'default', permit the forward declaration.
11559 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11560 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11561 Redeclaration = true;
11562 OldDecl = OldFD;
11563 OldFD->setIsMultiVersion();
11564 NewFD->setIsMultiVersion();
11565 return false;
11566 }
11567
11568 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11569 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11570 NewFD->setInvalidDecl();
11571 return true;
11572 }
11573
11574 if (NewTA) {
11575 ParsedTargetAttr OldParsed =
11576 S.getASTContext().getTargetInfo().parseTargetAttr(
11577 Str: OldTA->getFeaturesStr());
11578 llvm::sort(C&: OldParsed.Features);
11579 ParsedTargetAttr NewParsed =
11580 S.getASTContext().getTargetInfo().parseTargetAttr(
11581 Str: NewTA->getFeaturesStr());
11582 // Sort order doesn't matter, it just needs to be consistent.
11583 llvm::sort(C&: NewParsed.Features);
11584 if (OldParsed == NewParsed) {
11585 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11586 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11587 NewFD->setInvalidDecl();
11588 return true;
11589 }
11590 }
11591
11592 for (const auto *FD : OldFD->redecls()) {
11593 const auto *CurTA = FD->getAttr<TargetAttr>();
11594 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11595 // We allow forward declarations before ANY multiversioning attributes, but
11596 // nothing after the fact.
11597 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11598 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11599 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11600 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11601 << (NewTA ? 0 : 2);
11602 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11603 NewFD->setInvalidDecl();
11604 return true;
11605 }
11606 }
11607
11608 OldFD->setIsMultiVersion();
11609 NewFD->setIsMultiVersion();
11610 Redeclaration = false;
11611 OldDecl = nullptr;
11612 Previous.clear();
11613 return false;
11614}
11615
11616static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11617 MultiVersionKind OldKind = Old->getMultiVersionKind();
11618 MultiVersionKind NewKind = New->getMultiVersionKind();
11619
11620 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11621 NewKind == MultiVersionKind::None)
11622 return true;
11623
11624 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11625 switch (OldKind) {
11626 case MultiVersionKind::TargetVersion:
11627 return NewKind == MultiVersionKind::TargetClones;
11628 case MultiVersionKind::TargetClones:
11629 return NewKind == MultiVersionKind::TargetVersion;
11630 default:
11631 return false;
11632 }
11633 } else {
11634 switch (OldKind) {
11635 case MultiVersionKind::CPUDispatch:
11636 return NewKind == MultiVersionKind::CPUSpecific;
11637 case MultiVersionKind::CPUSpecific:
11638 return NewKind == MultiVersionKind::CPUDispatch;
11639 default:
11640 return false;
11641 }
11642 }
11643}
11644
11645/// Check the validity of a new function declaration being added to an existing
11646/// multiversioned declaration collection.
11647static bool CheckMultiVersionAdditionalDecl(
11648 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11649 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11650 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11651 LookupResult &Previous) {
11652
11653 // Disallow mixing of multiversioning types.
11654 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11655 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11656 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11657 NewFD->setInvalidDecl();
11658 return true;
11659 }
11660
11661 // Add the default target_version attribute if it's missing.
11662 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11663 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11664
11665 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11666 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11667 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11668 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11669
11670 ParsedTargetAttr NewParsed;
11671 if (NewTA) {
11672 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11673 Str: NewTA->getFeaturesStr());
11674 llvm::sort(C&: NewParsed.Features);
11675 }
11676 llvm::SmallVector<StringRef, 8> NewFeats;
11677 if (NewTVA) {
11678 NewTVA->getFeatures(Out&: NewFeats);
11679 llvm::sort(C&: NewFeats);
11680 }
11681
11682 bool UseMemberUsingDeclRules =
11683 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11684
11685 bool MayNeedOverloadableChecks =
11686 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11687
11688 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11689 // of a previous member of the MultiVersion set.
11690 for (NamedDecl *ND : Previous) {
11691 FunctionDecl *CurFD = ND->getAsFunction();
11692 if (!CurFD || CurFD->isInvalidDecl())
11693 continue;
11694 if (MayNeedOverloadableChecks &&
11695 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11696 continue;
11697
11698 switch (NewMVKind) {
11699 case MultiVersionKind::None:
11700 assert(OldMVKind == MultiVersionKind::TargetClones &&
11701 "Only target_clones can be omitted in subsequent declarations");
11702 break;
11703 case MultiVersionKind::Target: {
11704 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11705 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11706 NewFD->setIsMultiVersion();
11707 Redeclaration = true;
11708 OldDecl = ND;
11709 return false;
11710 }
11711
11712 ParsedTargetAttr CurParsed =
11713 S.getASTContext().getTargetInfo().parseTargetAttr(
11714 Str: CurTA->getFeaturesStr());
11715 llvm::sort(C&: CurParsed.Features);
11716 if (CurParsed == NewParsed) {
11717 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11718 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11719 NewFD->setInvalidDecl();
11720 return true;
11721 }
11722 break;
11723 }
11724 case MultiVersionKind::TargetVersion: {
11725 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11726 if (CurTVA->getName() == NewTVA->getName()) {
11727 NewFD->setIsMultiVersion();
11728 Redeclaration = true;
11729 OldDecl = ND;
11730 return false;
11731 }
11732 llvm::SmallVector<StringRef, 8> CurFeats;
11733 CurTVA->getFeatures(Out&: CurFeats);
11734 llvm::sort(C&: CurFeats);
11735
11736 if (CurFeats == NewFeats) {
11737 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11738 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11739 NewFD->setInvalidDecl();
11740 return true;
11741 }
11742 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11743 // Default
11744 if (NewFeats.empty())
11745 break;
11746
11747 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11748 llvm::SmallVector<StringRef, 8> CurFeats;
11749 CurClones->getFeatures(Out&: CurFeats, Index: I);
11750 llvm::sort(C&: CurFeats);
11751
11752 if (CurFeats == NewFeats) {
11753 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11754 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11755 NewFD->setInvalidDecl();
11756 return true;
11757 }
11758 }
11759 }
11760 break;
11761 }
11762 case MultiVersionKind::TargetClones: {
11763 assert(NewClones && "MultiVersionKind does not match attribute type");
11764 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11765 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11766 !std::equal(first1: CurClones->featuresStrs_begin(),
11767 last1: CurClones->featuresStrs_end(),
11768 first2: NewClones->featuresStrs_begin())) {
11769 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11770 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11771 NewFD->setInvalidDecl();
11772 return true;
11773 }
11774 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11775 llvm::SmallVector<StringRef, 8> CurFeats;
11776 CurTVA->getFeatures(Out&: CurFeats);
11777 llvm::sort(C&: CurFeats);
11778
11779 // Default
11780 if (CurFeats.empty())
11781 break;
11782
11783 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11784 NewFeats.clear();
11785 NewClones->getFeatures(Out&: NewFeats, Index: I);
11786 llvm::sort(C&: NewFeats);
11787
11788 if (CurFeats == NewFeats) {
11789 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11790 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11791 NewFD->setInvalidDecl();
11792 return true;
11793 }
11794 }
11795 break;
11796 }
11797 Redeclaration = true;
11798 OldDecl = CurFD;
11799 NewFD->setIsMultiVersion();
11800 return false;
11801 }
11802 case MultiVersionKind::CPUSpecific:
11803 case MultiVersionKind::CPUDispatch: {
11804 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11805 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11806 // Handle CPUDispatch/CPUSpecific versions.
11807 // Only 1 CPUDispatch function is allowed, this will make it go through
11808 // the redeclaration errors.
11809 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11810 CurFD->hasAttr<CPUDispatchAttr>()) {
11811 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11812 std::equal(
11813 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
11814 first2: NewCPUDisp->cpus_begin(),
11815 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11816 return Cur->getName() == New->getName();
11817 })) {
11818 NewFD->setIsMultiVersion();
11819 Redeclaration = true;
11820 OldDecl = ND;
11821 return false;
11822 }
11823
11824 // If the declarations don't match, this is an error condition.
11825 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
11826 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11827 NewFD->setInvalidDecl();
11828 return true;
11829 }
11830 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11831 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11832 std::equal(
11833 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
11834 first2: NewCPUSpec->cpus_begin(),
11835 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11836 return Cur->getName() == New->getName();
11837 })) {
11838 NewFD->setIsMultiVersion();
11839 Redeclaration = true;
11840 OldDecl = ND;
11841 return false;
11842 }
11843
11844 // Only 1 version of CPUSpecific is allowed for each CPU.
11845 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11846 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11847 if (CurII == NewII) {
11848 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
11849 << NewII;
11850 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11851 NewFD->setInvalidDecl();
11852 return true;
11853 }
11854 }
11855 }
11856 }
11857 break;
11858 }
11859 }
11860 }
11861
11862 // Else, this is simply a non-redecl case. Checking the 'value' is only
11863 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11864 // handled in the attribute adding step.
11865 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
11866 NewFD->setInvalidDecl();
11867 return true;
11868 }
11869
11870 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11871 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
11872 NewFD->setInvalidDecl();
11873 return true;
11874 }
11875
11876 // Permit forward declarations in the case where these two are compatible.
11877 if (!OldFD->isMultiVersion()) {
11878 OldFD->setIsMultiVersion();
11879 NewFD->setIsMultiVersion();
11880 Redeclaration = true;
11881 OldDecl = OldFD;
11882 return false;
11883 }
11884
11885 NewFD->setIsMultiVersion();
11886 Redeclaration = false;
11887 OldDecl = nullptr;
11888 Previous.clear();
11889 return false;
11890}
11891
11892/// Check the validity of a mulitversion function declaration.
11893/// Also sets the multiversion'ness' of the function itself.
11894///
11895/// This sets NewFD->isInvalidDecl() to true if there was an error.
11896///
11897/// Returns true if there was an error, false otherwise.
11898static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11899 bool &Redeclaration, NamedDecl *&OldDecl,
11900 LookupResult &Previous) {
11901 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11902
11903 // Check if FMV is disabled.
11904 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
11905 return false;
11906
11907 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11908 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11909 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11910 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11911 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11912 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11913
11914 // Main isn't allowed to become a multiversion function, however it IS
11915 // permitted to have 'main' be marked with the 'target' optimization hint,
11916 // for 'target_version' only default is allowed.
11917 if (NewFD->isMain()) {
11918 if (MVKind != MultiVersionKind::None &&
11919 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11920 !(MVKind == MultiVersionKind::TargetVersion &&
11921 NewTVA->isDefaultVersion())) {
11922 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
11923 NewFD->setInvalidDecl();
11924 return true;
11925 }
11926 return false;
11927 }
11928
11929 // Target attribute on AArch64 is not used for multiversioning
11930 if (NewTA && TI.getTriple().isAArch64())
11931 return false;
11932
11933 // Target attribute on RISCV is not used for multiversioning
11934 if (NewTA && TI.getTriple().isRISCV())
11935 return false;
11936
11937 if (!OldDecl || !OldDecl->getAsFunction() ||
11938 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11939 DC: NewFD->getDeclContext()->getRedeclContext())) {
11940 // If there's no previous declaration, AND this isn't attempting to cause
11941 // multiversioning, this isn't an error condition.
11942 if (MVKind == MultiVersionKind::None)
11943 return false;
11944 return CheckMultiVersionFirstFunction(S, FD: NewFD);
11945 }
11946
11947 FunctionDecl *OldFD = OldDecl->getAsFunction();
11948
11949 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11950 return false;
11951
11952 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11953 // for target_clones and target_version.
11954 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11955 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11956 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11957 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11958 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11959 NewFD->setInvalidDecl();
11960 return true;
11961 }
11962
11963 if (!OldFD->isMultiVersion()) {
11964 switch (MVKind) {
11965 case MultiVersionKind::Target:
11966 case MultiVersionKind::TargetVersion:
11967 return CheckDeclarationCausesMultiVersioning(
11968 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11969 case MultiVersionKind::TargetClones:
11970 if (OldFD->isUsed(CheckUsedAttr: false)) {
11971 NewFD->setInvalidDecl();
11972 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11973 }
11974 OldFD->setIsMultiVersion();
11975 break;
11976
11977 case MultiVersionKind::CPUDispatch:
11978 case MultiVersionKind::CPUSpecific:
11979 case MultiVersionKind::None:
11980 break;
11981 }
11982 }
11983
11984 // At this point, we have a multiversion function decl (in OldFD) AND an
11985 // appropriate attribute in the current function decl. Resolve that these are
11986 // still compatible with previous declarations.
11987 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11988 NewCPUSpec, NewClones, Redeclaration,
11989 OldDecl, Previous);
11990}
11991
11992static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
11993 bool IsPure = NewFD->hasAttr<PureAttr>();
11994 bool IsConst = NewFD->hasAttr<ConstAttr>();
11995
11996 // If there are no pure or const attributes, there's nothing to check.
11997 if (!IsPure && !IsConst)
11998 return;
11999
12000 // If the function is marked both pure and const, we retain the const
12001 // attribute because it makes stronger guarantees than the pure attribute, and
12002 // we drop the pure attribute explicitly to prevent later confusion about
12003 // semantics.
12004 if (IsPure && IsConst) {
12005 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12006 NewFD->dropAttrs<PureAttr>();
12007 }
12008
12009 // Constructors and destructors are functions which return void, so are
12010 // handled here as well.
12011 if (NewFD->getReturnType()->isVoidType()) {
12012 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12013 << IsConst;
12014 NewFD->dropAttrs<PureAttr, ConstAttr>();
12015 }
12016}
12017
12018bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12019 LookupResult &Previous,
12020 bool IsMemberSpecialization,
12021 bool DeclIsDefn) {
12022 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12023 "Variably modified return types are not handled here");
12024
12025 // Determine whether the type of this function should be merged with
12026 // a previous visible declaration. This never happens for functions in C++,
12027 // and always happens in C if the previous declaration was visible.
12028 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12029 !Previous.isShadowed();
12030
12031 bool Redeclaration = false;
12032 NamedDecl *OldDecl = nullptr;
12033 bool MayNeedOverloadableChecks = false;
12034
12035 inferLifetimeCaptureByAttribute(FD: NewFD);
12036 // Merge or overload the declaration with an existing declaration of
12037 // the same name, if appropriate.
12038 if (!Previous.empty()) {
12039 // Determine whether NewFD is an overload of PrevDecl or
12040 // a declaration that requires merging. If it's an overload,
12041 // there's no more work to do here; we'll just add the new
12042 // function to the scope.
12043 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12044 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12045 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12046 Redeclaration = true;
12047 OldDecl = Candidate;
12048 }
12049 } else {
12050 MayNeedOverloadableChecks = true;
12051 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12052 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12053 case OverloadKind::Match:
12054 Redeclaration = true;
12055 break;
12056
12057 case OverloadKind::NonFunction:
12058 Redeclaration = true;
12059 break;
12060
12061 case OverloadKind::Overload:
12062 Redeclaration = false;
12063 break;
12064 }
12065 }
12066 }
12067
12068 // Check for a previous extern "C" declaration with this name.
12069 if (!Redeclaration &&
12070 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12071 if (!Previous.empty()) {
12072 // This is an extern "C" declaration with the same name as a previous
12073 // declaration, and thus redeclares that entity...
12074 Redeclaration = true;
12075 OldDecl = Previous.getFoundDecl();
12076 MergeTypeWithPrevious = false;
12077
12078 // ... except in the presence of __attribute__((overloadable)).
12079 if (OldDecl->hasAttr<OverloadableAttr>() ||
12080 NewFD->hasAttr<OverloadableAttr>()) {
12081 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12082 MayNeedOverloadableChecks = true;
12083 Redeclaration = false;
12084 OldDecl = nullptr;
12085 }
12086 }
12087 }
12088 }
12089
12090 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12091 return Redeclaration;
12092
12093 // PPC MMA non-pointer types are not allowed as function return types.
12094 if (Context.getTargetInfo().getTriple().isPPC64() &&
12095 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12096 NewFD->setInvalidDecl();
12097 }
12098
12099 CheckConstPureAttributesUsage(S&: *this, NewFD);
12100
12101 // C++ [dcl.spec.auto.general]p12:
12102 // Return type deduction for a templated function with a placeholder in its
12103 // declared type occurs when the definition is instantiated even if the
12104 // function body contains a return statement with a non-type-dependent
12105 // operand.
12106 //
12107 // C++ [temp.dep.expr]p3:
12108 // An id-expression is type-dependent if it is a template-id that is not a
12109 // concept-id and is dependent; or if its terminal name is:
12110 // - [...]
12111 // - associated by name lookup with one or more declarations of member
12112 // functions of a class that is the current instantiation declared with a
12113 // return type that contains a placeholder type,
12114 // - [...]
12115 //
12116 // If this is a templated function with a placeholder in its return type,
12117 // make the placeholder type dependent since it won't be deduced until the
12118 // definition is instantiated. We do this here because it needs to happen
12119 // for implicitly instantiated member functions/member function templates.
12120 if (getLangOpts().CPlusPlus14 &&
12121 (NewFD->isDependentContext() &&
12122 NewFD->getReturnType()->isUndeducedType())) {
12123 const FunctionProtoType *FPT =
12124 NewFD->getType()->castAs<FunctionProtoType>();
12125 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12126 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12127 EPI: FPT->getExtProtoInfo()));
12128 }
12129
12130 // C++11 [dcl.constexpr]p8:
12131 // A constexpr specifier for a non-static member function that is not
12132 // a constructor declares that member function to be const.
12133 //
12134 // This needs to be delayed until we know whether this is an out-of-line
12135 // definition of a static member function.
12136 //
12137 // This rule is not present in C++1y, so we produce a backwards
12138 // compatibility warning whenever it happens in C++11.
12139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12140 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12141 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12142 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12143 CXXMethodDecl *OldMD = nullptr;
12144 if (OldDecl)
12145 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12146 if (!OldMD || !OldMD->isStatic()) {
12147 const FunctionProtoType *FPT =
12148 MD->getType()->castAs<FunctionProtoType>();
12149 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12150 EPI.TypeQuals.addConst();
12151 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12152 Args: FPT->getParamTypes(), EPI));
12153
12154 // Warn that we did this, if we're not performing template instantiation.
12155 // In that case, we'll have warned already when the template was defined.
12156 if (!inTemplateInstantiation()) {
12157 SourceLocation AddConstLoc;
12158 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12159 .IgnoreParens().getAs<FunctionTypeLoc>())
12160 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12161
12162 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12163 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12164 }
12165 }
12166 }
12167
12168 if (Redeclaration) {
12169 // NewFD and OldDecl represent declarations that need to be
12170 // merged.
12171 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12172 NewDeclIsDefn: DeclIsDefn)) {
12173 NewFD->setInvalidDecl();
12174 return Redeclaration;
12175 }
12176
12177 Previous.clear();
12178 Previous.addDecl(D: OldDecl);
12179
12180 if (FunctionTemplateDecl *OldTemplateDecl =
12181 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12182 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12183 FunctionTemplateDecl *NewTemplateDecl
12184 = NewFD->getDescribedFunctionTemplate();
12185 assert(NewTemplateDecl && "Template/non-template mismatch");
12186
12187 // The call to MergeFunctionDecl above may have created some state in
12188 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12189 // can add it as a redeclaration.
12190 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12191
12192 NewFD->setPreviousDeclaration(OldFD);
12193 if (NewFD->isCXXClassMember()) {
12194 NewFD->setAccess(OldTemplateDecl->getAccess());
12195 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12196 }
12197
12198 // If this is an explicit specialization of a member that is a function
12199 // template, mark it as a member specialization.
12200 if (IsMemberSpecialization &&
12201 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12202 NewTemplateDecl->setMemberSpecialization();
12203 assert(OldTemplateDecl->isMemberSpecialization());
12204 // Explicit specializations of a member template do not inherit deleted
12205 // status from the parent member template that they are specializing.
12206 if (OldFD->isDeleted()) {
12207 // FIXME: This assert will not hold in the presence of modules.
12208 assert(OldFD->getCanonicalDecl() == OldFD);
12209 // FIXME: We need an update record for this AST mutation.
12210 OldFD->setDeletedAsWritten(D: false);
12211 }
12212 }
12213
12214 } else {
12215 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12216 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12217 // This needs to happen first so that 'inline' propagates.
12218 NewFD->setPreviousDeclaration(OldFD);
12219 if (NewFD->isCXXClassMember())
12220 NewFD->setAccess(OldFD->getAccess());
12221 }
12222 }
12223 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12224 !NewFD->getAttr<OverloadableAttr>()) {
12225 assert((Previous.empty() ||
12226 llvm::any_of(Previous,
12227 [](const NamedDecl *ND) {
12228 return ND->hasAttr<OverloadableAttr>();
12229 })) &&
12230 "Non-redecls shouldn't happen without overloadable present");
12231
12232 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12233 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12234 return FD && !FD->hasAttr<OverloadableAttr>();
12235 });
12236
12237 if (OtherUnmarkedIter != Previous.end()) {
12238 Diag(Loc: NewFD->getLocation(),
12239 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12240 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12241 DiagID: diag::note_attribute_overloadable_prev_overload)
12242 << false;
12243
12244 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12245 }
12246 }
12247
12248 if (LangOpts.OpenMP)
12249 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12250
12251 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12252 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12253
12254 // Semantic checking for this function declaration (in isolation).
12255
12256 if (getLangOpts().CPlusPlus) {
12257 // C++-specific checks.
12258 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12259 CheckConstructor(Constructor);
12260 } else if (CXXDestructorDecl *Destructor =
12261 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12262 // We check here for invalid destructor names.
12263 // If we have a friend destructor declaration that is dependent, we can't
12264 // diagnose right away because cases like this are still valid:
12265 // template <class T> struct A { friend T::X::~Y(); };
12266 // struct B { struct Y { ~Y(); }; using X = Y; };
12267 // template struct A<B>;
12268 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12269 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12270 CXXRecordDecl *Record = Destructor->getParent();
12271 QualType ClassType = Context.getTypeDeclType(Decl: Record);
12272
12273 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12274 Ty: Context.getCanonicalType(T: ClassType));
12275 if (NewFD->getDeclName() != Name) {
12276 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12277 NewFD->setInvalidDecl();
12278 return Redeclaration;
12279 }
12280 }
12281 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12282 if (auto *TD = Guide->getDescribedFunctionTemplate())
12283 CheckDeductionGuideTemplate(TD);
12284
12285 // A deduction guide is not on the list of entities that can be
12286 // explicitly specialized.
12287 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12288 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12289 << /*explicit specialization*/ 1;
12290 }
12291
12292 // Find any virtual functions that this function overrides.
12293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12294 if (!Method->isFunctionTemplateSpecialization() &&
12295 !Method->getDescribedFunctionTemplate() &&
12296 Method->isCanonicalDecl()) {
12297 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12298 }
12299 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12300 // C++2a [class.virtual]p6
12301 // A virtual method shall not have a requires-clause.
12302 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12303 DiagID: diag::err_constrained_virtual_method);
12304
12305 if (Method->isStatic())
12306 checkThisInStaticMemberFunctionType(Method);
12307 }
12308
12309 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12310 ActOnConversionDeclarator(Conversion);
12311
12312 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12313 if (NewFD->isOverloadedOperator() &&
12314 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12315 NewFD->setInvalidDecl();
12316 return Redeclaration;
12317 }
12318
12319 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12320 if (NewFD->getLiteralIdentifier() &&
12321 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12322 NewFD->setInvalidDecl();
12323 return Redeclaration;
12324 }
12325
12326 // In C++, check default arguments now that we have merged decls. Unless
12327 // the lexical context is the class, because in this case this is done
12328 // during delayed parsing anyway.
12329 if (!CurContext->isRecord())
12330 CheckCXXDefaultArguments(FD: NewFD);
12331
12332 // If this function is declared as being extern "C", then check to see if
12333 // the function returns a UDT (class, struct, or union type) that is not C
12334 // compatible, and if it does, warn the user.
12335 // But, issue any diagnostic on the first declaration only.
12336 if (Previous.empty() && NewFD->isExternC()) {
12337 QualType R = NewFD->getReturnType();
12338 if (R->isIncompleteType() && !R->isVoidType())
12339 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12340 << NewFD << R;
12341 else if (!R.isPODType(Context) && !R->isVoidType() &&
12342 !R->isObjCObjectPointerType())
12343 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12344 }
12345
12346 // C++1z [dcl.fct]p6:
12347 // [...] whether the function has a non-throwing exception-specification
12348 // [is] part of the function type
12349 //
12350 // This results in an ABI break between C++14 and C++17 for functions whose
12351 // declared type includes an exception-specification in a parameter or
12352 // return type. (Exception specifications on the function itself are OK in
12353 // most cases, and exception specifications are not permitted in most other
12354 // contexts where they could make it into a mangling.)
12355 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12356 auto HasNoexcept = [&](QualType T) -> bool {
12357 // Strip off declarator chunks that could be between us and a function
12358 // type. We don't need to look far, exception specifications are very
12359 // restricted prior to C++17.
12360 if (auto *RT = T->getAs<ReferenceType>())
12361 T = RT->getPointeeType();
12362 else if (T->isAnyPointerType())
12363 T = T->getPointeeType();
12364 else if (auto *MPT = T->getAs<MemberPointerType>())
12365 T = MPT->getPointeeType();
12366 if (auto *FPT = T->getAs<FunctionProtoType>())
12367 if (FPT->isNothrow())
12368 return true;
12369 return false;
12370 };
12371
12372 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12373 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12374 for (QualType T : FPT->param_types())
12375 AnyNoexcept |= HasNoexcept(T);
12376 if (AnyNoexcept)
12377 Diag(Loc: NewFD->getLocation(),
12378 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12379 << NewFD;
12380 }
12381
12382 if (!Redeclaration && LangOpts.CUDA) {
12383 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12384 for (auto *Parm : NewFD->parameters()) {
12385 if (!Parm->getType()->isDependentType() &&
12386 Parm->hasAttr<CUDAGridConstantAttr>() &&
12387 !(IsKernel && Parm->getType().isConstQualified()))
12388 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12389 DiagID: diag::err_cuda_grid_constant_not_allowed);
12390 }
12391 CUDA().checkTargetOverload(NewFD, Previous);
12392 }
12393 }
12394
12395 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12396 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12397
12398 return Redeclaration;
12399}
12400
12401void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12402 // [basic.start.main]p3
12403 // The main function shall not be declared with C linkage-specification.
12404 if (FD->isExternCContext())
12405 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12406
12407 // C++11 [basic.start.main]p3:
12408 // A program that [...] declares main to be inline, static or
12409 // constexpr is ill-formed.
12410 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12411 // appear in a declaration of main.
12412 // static main is not an error under C99, but we should warn about it.
12413 // We accept _Noreturn main as an extension.
12414 if (FD->getStorageClass() == SC_Static)
12415 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12416 ? diag::err_static_main : diag::warn_static_main)
12417 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12418 if (FD->isInlineSpecified())
12419 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12420 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12421 if (DS.isNoreturnSpecified()) {
12422 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12423 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12424 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12425 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12426 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12427 }
12428 if (FD->isConstexpr()) {
12429 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12430 << FD->isConsteval()
12431 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12432 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12433 }
12434
12435 if (getLangOpts().OpenCL) {
12436 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12437 << FD->hasAttr<DeviceKernelAttr>();
12438 FD->setInvalidDecl();
12439 return;
12440 }
12441
12442 // Functions named main in hlsl are default entries, but don't have specific
12443 // signatures they are required to conform to.
12444 if (getLangOpts().HLSL)
12445 return;
12446
12447 QualType T = FD->getType();
12448 assert(T->isFunctionType() && "function decl is not of function type");
12449 const FunctionType* FT = T->castAs<FunctionType>();
12450
12451 // Set default calling convention for main()
12452 if (FT->getCallConv() != CC_C) {
12453 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12454 FD->setType(QualType(FT, 0));
12455 T = Context.getCanonicalType(T: FD->getType());
12456 }
12457
12458 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12459 // In C with GNU extensions we allow main() to have non-integer return
12460 // type, but we should warn about the extension, and we disable the
12461 // implicit-return-zero rule.
12462
12463 // GCC in C mode accepts qualified 'int'.
12464 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12465 FD->setHasImplicitReturnZero(true);
12466 else {
12467 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12468 SourceRange RTRange = FD->getReturnTypeSourceRange();
12469 if (RTRange.isValid())
12470 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12471 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12472 }
12473 } else {
12474 // In C and C++, main magically returns 0 if you fall off the end;
12475 // set the flag which tells us that.
12476 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12477
12478 // All the standards say that main() should return 'int'.
12479 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12480 FD->setHasImplicitReturnZero(true);
12481 else {
12482 // Otherwise, this is just a flat-out error.
12483 SourceRange RTRange = FD->getReturnTypeSourceRange();
12484 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12485 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12486 : FixItHint());
12487 FD->setInvalidDecl(true);
12488 }
12489
12490 // [basic.start.main]p3:
12491 // A program that declares a function main that belongs to the global scope
12492 // and is attached to a named module is ill-formed.
12493 if (FD->isInNamedModule()) {
12494 const SourceLocation start = FD->getTypeSpecStartLoc();
12495 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12496 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12497 }
12498 }
12499
12500 // Treat protoless main() as nullary.
12501 if (isa<FunctionNoProtoType>(Val: FT)) return;
12502
12503 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12504 unsigned nparams = FTP->getNumParams();
12505 assert(FD->getNumParams() == nparams);
12506
12507 bool HasExtraParameters = (nparams > 3);
12508
12509 if (FTP->isVariadic()) {
12510 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12511 // FIXME: if we had information about the location of the ellipsis, we
12512 // could add a FixIt hint to remove it as a parameter.
12513 }
12514
12515 // Darwin passes an undocumented fourth argument of type char**. If
12516 // other platforms start sprouting these, the logic below will start
12517 // getting shifty.
12518 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12519 HasExtraParameters = false;
12520
12521 if (HasExtraParameters) {
12522 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12523 FD->setInvalidDecl(true);
12524 nparams = 3;
12525 }
12526
12527 // FIXME: a lot of the following diagnostics would be improved
12528 // if we had some location information about types.
12529
12530 QualType CharPP =
12531 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12532 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12533
12534 for (unsigned i = 0; i < nparams; ++i) {
12535 QualType AT = FTP->getParamType(i);
12536
12537 bool mismatch = true;
12538
12539 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12540 mismatch = false;
12541 else if (Expected[i] == CharPP) {
12542 // As an extension, the following forms are okay:
12543 // char const **
12544 // char const * const *
12545 // char * const *
12546
12547 QualifierCollector qs;
12548 const PointerType* PT;
12549 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12550 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12551 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12552 T2: Context.CharTy)) {
12553 qs.removeConst();
12554 mismatch = !qs.empty();
12555 }
12556 }
12557
12558 if (mismatch) {
12559 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12560 // TODO: suggest replacing given type with expected type
12561 FD->setInvalidDecl(true);
12562 }
12563 }
12564
12565 if (nparams == 1 && !FD->isInvalidDecl()) {
12566 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12567 }
12568
12569 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12570 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12571 FD->setInvalidDecl();
12572 }
12573}
12574
12575static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12576
12577 // Default calling convention for main and wmain is __cdecl
12578 if (FD->getName() == "main" || FD->getName() == "wmain")
12579 return false;
12580
12581 // Default calling convention for MinGW is __cdecl
12582 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12583 if (T.isWindowsGNUEnvironment())
12584 return false;
12585
12586 // Default calling convention for WinMain, wWinMain and DllMain
12587 // is __stdcall on 32 bit Windows
12588 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12589 return true;
12590
12591 return false;
12592}
12593
12594void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12595 QualType T = FD->getType();
12596 assert(T->isFunctionType() && "function decl is not of function type");
12597 const FunctionType *FT = T->castAs<FunctionType>();
12598
12599 // Set an implicit return of 'zero' if the function can return some integral,
12600 // enumeration, pointer or nullptr type.
12601 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12602 FT->getReturnType()->isAnyPointerType() ||
12603 FT->getReturnType()->isNullPtrType())
12604 // DllMain is exempt because a return value of zero means it failed.
12605 if (FD->getName() != "DllMain")
12606 FD->setHasImplicitReturnZero(true);
12607
12608 // Explicitly specified calling conventions are applied to MSVC entry points
12609 if (!hasExplicitCallingConv(T)) {
12610 if (isDefaultStdCall(FD, S&: *this)) {
12611 if (FT->getCallConv() != CC_X86StdCall) {
12612 FT = Context.adjustFunctionType(
12613 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12614 FD->setType(QualType(FT, 0));
12615 }
12616 } else if (FT->getCallConv() != CC_C) {
12617 FT = Context.adjustFunctionType(Fn: FT,
12618 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12619 FD->setType(QualType(FT, 0));
12620 }
12621 }
12622
12623 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12624 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12625 FD->setInvalidDecl();
12626 }
12627}
12628
12629bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12630 // FIXME: Need strict checking. In C89, we need to check for
12631 // any assignment, increment, decrement, function-calls, or
12632 // commas outside of a sizeof. In C99, it's the same list,
12633 // except that the aforementioned are allowed in unevaluated
12634 // expressions. Everything else falls under the
12635 // "may accept other forms of constant expressions" exception.
12636 //
12637 // Regular C++ code will not end up here (exceptions: language extensions,
12638 // OpenCL C++ etc), so the constant expression rules there don't matter.
12639 if (Init->isValueDependent()) {
12640 assert(Init->containsErrors() &&
12641 "Dependent code should only occur in error-recovery path.");
12642 return true;
12643 }
12644 const Expr *Culprit;
12645 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12646 return false;
12647 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12648 return true;
12649}
12650
12651namespace {
12652 // Visits an initialization expression to see if OrigDecl is evaluated in
12653 // its own initialization and throws a warning if it does.
12654 class SelfReferenceChecker
12655 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12656 Sema &S;
12657 Decl *OrigDecl;
12658 bool isRecordType;
12659 bool isPODType;
12660 bool isReferenceType;
12661 bool isInCXXOperatorCall;
12662
12663 bool isInitList;
12664 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12665
12666 public:
12667 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12668
12669 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12670 S(S), OrigDecl(OrigDecl) {
12671 isPODType = false;
12672 isRecordType = false;
12673 isReferenceType = false;
12674 isInCXXOperatorCall = false;
12675 isInitList = false;
12676 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12677 isPODType = VD->getType().isPODType(Context: S.Context);
12678 isRecordType = VD->getType()->isRecordType();
12679 isReferenceType = VD->getType()->isReferenceType();
12680 }
12681 }
12682
12683 // For most expressions, just call the visitor. For initializer lists,
12684 // track the index of the field being initialized since fields are
12685 // initialized in order allowing use of previously initialized fields.
12686 void CheckExpr(Expr *E) {
12687 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12688 if (!InitList) {
12689 Visit(S: E);
12690 return;
12691 }
12692
12693 // Track and increment the index here.
12694 isInitList = true;
12695 InitFieldIndex.push_back(Elt: 0);
12696 for (auto *Child : InitList->children()) {
12697 CheckExpr(E: cast<Expr>(Val: Child));
12698 ++InitFieldIndex.back();
12699 }
12700 InitFieldIndex.pop_back();
12701 }
12702
12703 // Returns true if MemberExpr is checked and no further checking is needed.
12704 // Returns false if additional checking is required.
12705 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12706 llvm::SmallVector<FieldDecl*, 4> Fields;
12707 Expr *Base = E;
12708 bool ReferenceField = false;
12709
12710 // Get the field members used.
12711 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12712 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12713 if (!FD)
12714 return false;
12715 Fields.push_back(Elt: FD);
12716 if (FD->getType()->isReferenceType())
12717 ReferenceField = true;
12718 Base = ME->getBase()->IgnoreParenImpCasts();
12719 }
12720
12721 // Keep checking only if the base Decl is the same.
12722 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12723 if (!DRE || DRE->getDecl() != OrigDecl)
12724 return false;
12725
12726 // A reference field can be bound to an unininitialized field.
12727 if (CheckReference && !ReferenceField)
12728 return true;
12729
12730 // Convert FieldDecls to their index number.
12731 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12732 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12733 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12734
12735 // See if a warning is needed by checking the first difference in index
12736 // numbers. If field being used has index less than the field being
12737 // initialized, then the use is safe.
12738 for (auto UsedIter = UsedFieldIndex.begin(),
12739 UsedEnd = UsedFieldIndex.end(),
12740 OrigIter = InitFieldIndex.begin(),
12741 OrigEnd = InitFieldIndex.end();
12742 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12743 if (*UsedIter < *OrigIter)
12744 return true;
12745 if (*UsedIter > *OrigIter)
12746 break;
12747 }
12748
12749 // TODO: Add a different warning which will print the field names.
12750 HandleDeclRefExpr(DRE);
12751 return true;
12752 }
12753
12754 // For most expressions, the cast is directly above the DeclRefExpr.
12755 // For conditional operators, the cast can be outside the conditional
12756 // operator if both expressions are DeclRefExpr's.
12757 void HandleValue(Expr *E) {
12758 E = E->IgnoreParens();
12759 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12760 HandleDeclRefExpr(DRE);
12761 return;
12762 }
12763
12764 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12765 Visit(S: CO->getCond());
12766 HandleValue(E: CO->getTrueExpr());
12767 HandleValue(E: CO->getFalseExpr());
12768 return;
12769 }
12770
12771 if (BinaryConditionalOperator *BCO =
12772 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12773 Visit(S: BCO->getCond());
12774 HandleValue(E: BCO->getFalseExpr());
12775 return;
12776 }
12777
12778 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12779 if (Expr *SE = OVE->getSourceExpr())
12780 HandleValue(E: SE);
12781 return;
12782 }
12783
12784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
12785 if (BO->getOpcode() == BO_Comma) {
12786 Visit(S: BO->getLHS());
12787 HandleValue(E: BO->getRHS());
12788 return;
12789 }
12790 }
12791
12792 if (isa<MemberExpr>(Val: E)) {
12793 if (isInitList) {
12794 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
12795 CheckReference: false /*CheckReference*/))
12796 return;
12797 }
12798
12799 Expr *Base = E->IgnoreParenImpCasts();
12800 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12801 // Check for static member variables and don't warn on them.
12802 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12803 return;
12804 Base = ME->getBase()->IgnoreParenImpCasts();
12805 }
12806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
12807 HandleDeclRefExpr(DRE);
12808 return;
12809 }
12810
12811 Visit(S: E);
12812 }
12813
12814 // Reference types not handled in HandleValue are handled here since all
12815 // uses of references are bad, not just r-value uses.
12816 void VisitDeclRefExpr(DeclRefExpr *E) {
12817 if (isReferenceType)
12818 HandleDeclRefExpr(DRE: E);
12819 }
12820
12821 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12822 if (E->getCastKind() == CK_LValueToRValue) {
12823 HandleValue(E: E->getSubExpr());
12824 return;
12825 }
12826
12827 Inherited::VisitImplicitCastExpr(S: E);
12828 }
12829
12830 void VisitMemberExpr(MemberExpr *E) {
12831 if (isInitList) {
12832 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
12833 return;
12834 }
12835
12836 // Don't warn on arrays since they can be treated as pointers.
12837 if (E->getType()->canDecayToPointerType()) return;
12838
12839 // Warn when a non-static method call is followed by non-static member
12840 // field accesses, which is followed by a DeclRefExpr.
12841 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
12842 bool Warn = (MD && !MD->isStatic());
12843 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12844 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12845 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
12846 Warn = false;
12847 Base = ME->getBase()->IgnoreParenImpCasts();
12848 }
12849
12850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
12851 if (Warn)
12852 HandleDeclRefExpr(DRE);
12853 return;
12854 }
12855
12856 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12857 // Visit that expression.
12858 Visit(S: Base);
12859 }
12860
12861 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12862 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
12863 Expr *Callee = E->getCallee();
12864
12865 if (isa<UnresolvedLookupExpr>(Val: Callee))
12866 return Inherited::VisitCXXOperatorCallExpr(S: E);
12867
12868 Visit(S: Callee);
12869 for (auto Arg: E->arguments())
12870 HandleValue(E: Arg->IgnoreParenImpCasts());
12871 }
12872
12873 void VisitLambdaExpr(LambdaExpr *E) {
12874 if (!isInCXXOperatorCall) {
12875 Inherited::VisitLambdaExpr(LE: E);
12876 return;
12877 }
12878
12879 for (Expr *Init : E->capture_inits())
12880 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
12881 HandleDeclRefExpr(DRE);
12882 else if (Init)
12883 Visit(S: Init);
12884 }
12885
12886 void VisitUnaryOperator(UnaryOperator *E) {
12887 // For POD record types, addresses of its own members are well-defined.
12888 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12889 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
12890 if (!isPODType)
12891 HandleValue(E: E->getSubExpr());
12892 return;
12893 }
12894
12895 if (E->isIncrementDecrementOp()) {
12896 HandleValue(E: E->getSubExpr());
12897 return;
12898 }
12899
12900 Inherited::VisitUnaryOperator(S: E);
12901 }
12902
12903 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12904
12905 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12906 if (E->getConstructor()->isCopyConstructor()) {
12907 Expr *ArgExpr = E->getArg(Arg: 0);
12908 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
12909 if (ILE->getNumInits() == 1)
12910 ArgExpr = ILE->getInit(Init: 0);
12911 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
12912 if (ICE->getCastKind() == CK_NoOp)
12913 ArgExpr = ICE->getSubExpr();
12914 HandleValue(E: ArgExpr);
12915 return;
12916 }
12917 Inherited::VisitCXXConstructExpr(S: E);
12918 }
12919
12920 void VisitCallExpr(CallExpr *E) {
12921 // Treat std::move as a use.
12922 if (E->isCallToStdMove()) {
12923 HandleValue(E: E->getArg(Arg: 0));
12924 return;
12925 }
12926
12927 Inherited::VisitCallExpr(CE: E);
12928 }
12929
12930 void VisitBinaryOperator(BinaryOperator *E) {
12931 if (E->isCompoundAssignmentOp()) {
12932 HandleValue(E: E->getLHS());
12933 Visit(S: E->getRHS());
12934 return;
12935 }
12936
12937 Inherited::VisitBinaryOperator(S: E);
12938 }
12939
12940 // A custom visitor for BinaryConditionalOperator is needed because the
12941 // regular visitor would check the condition and true expression separately
12942 // but both point to the same place giving duplicate diagnostics.
12943 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12944 Visit(S: E->getCond());
12945 Visit(S: E->getFalseExpr());
12946 }
12947
12948 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12949 Decl* ReferenceDecl = DRE->getDecl();
12950 if (OrigDecl != ReferenceDecl) return;
12951 unsigned diag;
12952 if (isReferenceType) {
12953 diag = diag::warn_uninit_self_reference_in_reference_init;
12954 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
12955 diag = diag::warn_static_self_reference_in_init;
12956 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
12957 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
12958 DRE->getDecl()->getType()->isRecordType()) {
12959 diag = diag::warn_uninit_self_reference_in_init;
12960 } else {
12961 // Local variables will be handled by the CFG analysis.
12962 return;
12963 }
12964
12965 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
12966 PD: S.PDiag(DiagID: diag)
12967 << DRE->getDecl() << OrigDecl->getLocation()
12968 << DRE->getSourceRange());
12969 }
12970 };
12971
12972 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12973 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12974 bool DirectInit) {
12975 // Parameters arguments are occassionially constructed with itself,
12976 // for instance, in recursive functions. Skip them.
12977 if (isa<ParmVarDecl>(Val: OrigDecl))
12978 return;
12979
12980 E = E->IgnoreParens();
12981
12982 // Skip checking T a = a where T is not a record or reference type.
12983 // Doing so is a way to silence uninitialized warnings.
12984 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
12985 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12986 if (ICE->getCastKind() == CK_LValueToRValue)
12987 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
12988 if (DRE->getDecl() == OrigDecl)
12989 return;
12990
12991 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12992 }
12993} // end anonymous namespace
12994
12995namespace {
12996 // Simple wrapper to add the name of a variable or (if no variable is
12997 // available) a DeclarationName into a diagnostic.
12998 struct VarDeclOrName {
12999 VarDecl *VDecl;
13000 DeclarationName Name;
13001
13002 friend const Sema::SemaDiagnosticBuilder &
13003 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13004 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13005 }
13006 };
13007} // end anonymous namespace
13008
13009QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13010 DeclarationName Name, QualType Type,
13011 TypeSourceInfo *TSI,
13012 SourceRange Range, bool DirectInit,
13013 Expr *Init) {
13014 bool IsInitCapture = !VDecl;
13015 assert((!VDecl || !VDecl->isInitCapture()) &&
13016 "init captures are expected to be deduced prior to initialization");
13017
13018 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13019
13020 DeducedType *Deduced = Type->getContainedDeducedType();
13021 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13022
13023 // Diagnose auto array declarations in C23, unless it's a supported extension.
13024 if (getLangOpts().C23 && Type->isArrayType() &&
13025 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13026 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13027 << (int)Deduced->getContainedAutoType()->getKeyword()
13028 << /*in array decl*/ 23 << Range;
13029 return QualType();
13030 }
13031
13032 // C++11 [dcl.spec.auto]p3
13033 if (!Init) {
13034 assert(VDecl && "no init for init capture deduction?");
13035
13036 // Except for class argument deduction, and then for an initializing
13037 // declaration only, i.e. no static at class scope or extern.
13038 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13039 VDecl->hasExternalStorage() ||
13040 VDecl->isStaticDataMember()) {
13041 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13042 << VDecl->getDeclName() << Type;
13043 return QualType();
13044 }
13045 }
13046
13047 ArrayRef<Expr*> DeduceInits;
13048 if (Init)
13049 DeduceInits = Init;
13050
13051 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13052 if (DirectInit && PL)
13053 DeduceInits = PL->exprs();
13054
13055 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13056 assert(VDecl && "non-auto type for init capture deduction?");
13057 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13058 InitializationKind Kind = InitializationKind::CreateForInit(
13059 Loc: VDecl->getLocation(), DirectInit, Init);
13060 // FIXME: Initialization should not be taking a mutable list of inits.
13061 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13062 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13063 Init: InitsCopy);
13064 }
13065
13066 if (DirectInit) {
13067 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13068 DeduceInits = IL->inits();
13069 }
13070
13071 // Deduction only works if we have exactly one source expression.
13072 if (DeduceInits.empty()) {
13073 // It isn't possible to write this directly, but it is possible to
13074 // end up in this situation with "auto x(some_pack...);"
13075 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13076 ? diag::err_init_capture_no_expression
13077 : diag::err_auto_var_init_no_expression)
13078 << VN << Type << Range;
13079 return QualType();
13080 }
13081
13082 if (DeduceInits.size() > 1) {
13083 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13084 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13085 : diag::err_auto_var_init_multiple_expressions)
13086 << VN << Type << Range;
13087 return QualType();
13088 }
13089
13090 Expr *DeduceInit = DeduceInits[0];
13091 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13092 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13093 ? diag::err_init_capture_paren_braces
13094 : diag::err_auto_var_init_paren_braces)
13095 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13096 return QualType();
13097 }
13098
13099 // Expressions default to 'id' when we're in a debugger.
13100 bool DefaultedAnyToId = false;
13101 if (getLangOpts().DebuggerCastResultToId &&
13102 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13103 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13104 if (Result.isInvalid()) {
13105 return QualType();
13106 }
13107 Init = Result.get();
13108 DefaultedAnyToId = true;
13109 }
13110
13111 // C++ [dcl.decomp]p1:
13112 // If the assignment-expression [...] has array type A and no ref-qualifier
13113 // is present, e has type cv A
13114 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13115 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13116 DeduceInit->getType()->isConstantArrayType())
13117 return Context.getQualifiedType(T: DeduceInit->getType(),
13118 Qs: Type.getQualifiers());
13119
13120 QualType DeducedType;
13121 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13122 TemplateDeductionResult Result =
13123 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13124 if (Result != TemplateDeductionResult::Success &&
13125 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13126 if (!IsInitCapture)
13127 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13128 else if (isa<InitListExpr>(Val: Init))
13129 Diag(Loc: Range.getBegin(),
13130 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13131 << VN
13132 << (DeduceInit->getType().isNull() ? TSI->getType()
13133 : DeduceInit->getType())
13134 << DeduceInit->getSourceRange();
13135 else
13136 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13137 << VN << TSI->getType()
13138 << (DeduceInit->getType().isNull() ? TSI->getType()
13139 : DeduceInit->getType())
13140 << DeduceInit->getSourceRange();
13141 }
13142
13143 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13144 // 'id' instead of a specific object type prevents most of our usual
13145 // checks.
13146 // We only want to warn outside of template instantiations, though:
13147 // inside a template, the 'id' could have come from a parameter.
13148 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13149 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13150 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13151 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13152 }
13153
13154 return DeducedType;
13155}
13156
13157bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13158 Expr *Init) {
13159 assert(!Init || !Init->containsErrors());
13160 QualType DeducedType = deduceVarTypeFromInitializer(
13161 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13162 Range: VDecl->getSourceRange(), DirectInit, Init);
13163 if (DeducedType.isNull()) {
13164 VDecl->setInvalidDecl();
13165 return true;
13166 }
13167
13168 VDecl->setType(DeducedType);
13169 assert(VDecl->isLinkageValid());
13170
13171 // In ARC, infer lifetime.
13172 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13173 VDecl->setInvalidDecl();
13174
13175 if (getLangOpts().OpenCL)
13176 deduceOpenCLAddressSpace(Decl: VDecl);
13177
13178 if (getLangOpts().HLSL)
13179 HLSL().deduceAddressSpace(Decl: VDecl);
13180
13181 // If this is a redeclaration, check that the type we just deduced matches
13182 // the previously declared type.
13183 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13184 // We never need to merge the type, because we cannot form an incomplete
13185 // array of auto, nor deduce such a type.
13186 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13187 }
13188
13189 // Check the deduced type is valid for a variable declaration.
13190 CheckVariableDeclarationType(NewVD: VDecl);
13191 return VDecl->isInvalidDecl();
13192}
13193
13194void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13195 SourceLocation Loc) {
13196 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13197 Init = EWC->getSubExpr();
13198
13199 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13200 Init = CE->getSubExpr();
13201
13202 QualType InitType = Init->getType();
13203 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13204 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13205 "shouldn't be called if type doesn't have a non-trivial C struct");
13206 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13207 for (auto *I : ILE->inits()) {
13208 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13209 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13210 continue;
13211 SourceLocation SL = I->getExprLoc();
13212 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13213 }
13214 return;
13215 }
13216
13217 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13218 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13219 checkNonTrivialCUnion(QT: InitType, Loc,
13220 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13221 NonTrivialKind: NTCUK_Init);
13222 } else {
13223 // Assume all other explicit initializers involving copying some existing
13224 // object.
13225 // TODO: ignore any explicit initializers where we can guarantee
13226 // copy-elision.
13227 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13228 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13229 NonTrivialKind: NTCUK_Copy);
13230 }
13231}
13232
13233namespace {
13234
13235bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13236 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13237 // in the source code or implicitly by the compiler if it is in a union
13238 // defined in a system header and has non-trivial ObjC ownership
13239 // qualifications. We don't want those fields to participate in determining
13240 // whether the containing union is non-trivial.
13241 return FD->hasAttr<UnavailableAttr>();
13242}
13243
13244struct DiagNonTrivalCUnionDefaultInitializeVisitor
13245 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13246 void> {
13247 using Super =
13248 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13249 void>;
13250
13251 DiagNonTrivalCUnionDefaultInitializeVisitor(
13252 QualType OrigTy, SourceLocation OrigLoc,
13253 NonTrivialCUnionContext UseContext, Sema &S)
13254 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13255
13256 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13257 const FieldDecl *FD, bool InNonTrivialUnion) {
13258 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13259 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13260 Args&: InNonTrivialUnion);
13261 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13262 }
13263
13264 void visitARCStrong(QualType QT, const FieldDecl *FD,
13265 bool InNonTrivialUnion) {
13266 if (InNonTrivialUnion)
13267 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13268 << 1 << 0 << QT << FD->getName();
13269 }
13270
13271 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13272 if (InNonTrivialUnion)
13273 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13274 << 1 << 0 << QT << FD->getName();
13275 }
13276
13277 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13278 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13279 if (RD->isUnion()) {
13280 if (OrigLoc.isValid()) {
13281 bool IsUnion = false;
13282 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13283 IsUnion = OrigRD->isUnion();
13284 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13285 << 0 << OrigTy << IsUnion << UseContext;
13286 // Reset OrigLoc so that this diagnostic is emitted only once.
13287 OrigLoc = SourceLocation();
13288 }
13289 InNonTrivialUnion = true;
13290 }
13291
13292 if (InNonTrivialUnion)
13293 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13294 << 0 << 0 << QT.getUnqualifiedType() << "";
13295
13296 for (const FieldDecl *FD : RD->fields())
13297 if (!shouldIgnoreForRecordTriviality(FD))
13298 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13299 }
13300
13301 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13302
13303 // The non-trivial C union type or the struct/union type that contains a
13304 // non-trivial C union.
13305 QualType OrigTy;
13306 SourceLocation OrigLoc;
13307 NonTrivialCUnionContext UseContext;
13308 Sema &S;
13309};
13310
13311struct DiagNonTrivalCUnionDestructedTypeVisitor
13312 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13313 using Super =
13314 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13315
13316 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13317 SourceLocation OrigLoc,
13318 NonTrivialCUnionContext UseContext,
13319 Sema &S)
13320 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13321
13322 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13323 const FieldDecl *FD, bool InNonTrivialUnion) {
13324 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13325 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13326 Args&: InNonTrivialUnion);
13327 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13328 }
13329
13330 void visitARCStrong(QualType QT, const FieldDecl *FD,
13331 bool InNonTrivialUnion) {
13332 if (InNonTrivialUnion)
13333 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13334 << 1 << 1 << QT << FD->getName();
13335 }
13336
13337 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13338 if (InNonTrivialUnion)
13339 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13340 << 1 << 1 << QT << FD->getName();
13341 }
13342
13343 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13344 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13345 if (RD->isUnion()) {
13346 if (OrigLoc.isValid()) {
13347 bool IsUnion = false;
13348 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13349 IsUnion = OrigRD->isUnion();
13350 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13351 << 1 << OrigTy << IsUnion << UseContext;
13352 // Reset OrigLoc so that this diagnostic is emitted only once.
13353 OrigLoc = SourceLocation();
13354 }
13355 InNonTrivialUnion = true;
13356 }
13357
13358 if (InNonTrivialUnion)
13359 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13360 << 0 << 1 << QT.getUnqualifiedType() << "";
13361
13362 for (const FieldDecl *FD : RD->fields())
13363 if (!shouldIgnoreForRecordTriviality(FD))
13364 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13365 }
13366
13367 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13368 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13369 bool InNonTrivialUnion) {}
13370
13371 // The non-trivial C union type or the struct/union type that contains a
13372 // non-trivial C union.
13373 QualType OrigTy;
13374 SourceLocation OrigLoc;
13375 NonTrivialCUnionContext UseContext;
13376 Sema &S;
13377};
13378
13379struct DiagNonTrivalCUnionCopyVisitor
13380 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13381 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13382
13383 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13384 NonTrivialCUnionContext UseContext, Sema &S)
13385 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13386
13387 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13388 const FieldDecl *FD, bool InNonTrivialUnion) {
13389 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13390 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13391 Args&: InNonTrivialUnion);
13392 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13393 }
13394
13395 void visitARCStrong(QualType QT, const FieldDecl *FD,
13396 bool InNonTrivialUnion) {
13397 if (InNonTrivialUnion)
13398 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13399 << 1 << 2 << QT << FD->getName();
13400 }
13401
13402 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13403 if (InNonTrivialUnion)
13404 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13405 << 1 << 2 << QT << FD->getName();
13406 }
13407
13408 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13409 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13410 if (RD->isUnion()) {
13411 if (OrigLoc.isValid()) {
13412 bool IsUnion = false;
13413 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13414 IsUnion = OrigRD->isUnion();
13415 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13416 << 2 << OrigTy << IsUnion << UseContext;
13417 // Reset OrigLoc so that this diagnostic is emitted only once.
13418 OrigLoc = SourceLocation();
13419 }
13420 InNonTrivialUnion = true;
13421 }
13422
13423 if (InNonTrivialUnion)
13424 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13425 << 0 << 2 << QT.getUnqualifiedType() << "";
13426
13427 for (const FieldDecl *FD : RD->fields())
13428 if (!shouldIgnoreForRecordTriviality(FD))
13429 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13430 }
13431
13432 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13433 if (InNonTrivialUnion)
13434 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13435 << 1 << 2 << QT << FD->getName();
13436 }
13437
13438 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13439 const FieldDecl *FD, bool InNonTrivialUnion) {}
13440 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13441 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13442 bool InNonTrivialUnion) {}
13443
13444 // The non-trivial C union type or the struct/union type that contains a
13445 // non-trivial C union.
13446 QualType OrigTy;
13447 SourceLocation OrigLoc;
13448 NonTrivialCUnionContext UseContext;
13449 Sema &S;
13450};
13451
13452} // namespace
13453
13454void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13455 NonTrivialCUnionContext UseContext,
13456 unsigned NonTrivialKind) {
13457 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13458 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13459 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13460 "shouldn't be called if type doesn't have a non-trivial C union");
13461
13462 if ((NonTrivialKind & NTCUK_Init) &&
13463 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13464 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13465 .visit(FT: QT, Args: nullptr, Args: false);
13466 if ((NonTrivialKind & NTCUK_Destruct) &&
13467 QT.hasNonTrivialToPrimitiveDestructCUnion())
13468 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13469 .visit(FT: QT, Args: nullptr, Args: false);
13470 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13471 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13472 .visit(FT: QT, Args: nullptr, Args: false);
13473}
13474
13475bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13476 const VarDecl *Dcl) {
13477 if (!getLangOpts().CPlusPlus)
13478 return false;
13479
13480 // We only need to warn if the definition is in a header file, so wait to
13481 // diagnose until we've seen the definition.
13482 if (!Dcl->isThisDeclarationADefinition())
13483 return false;
13484
13485 // If an object is defined in a source file, its definition can't get
13486 // duplicated since it will never appear in more than one TU.
13487 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13488 return false;
13489
13490 // If the variable we're looking at is a static local, then we actually care
13491 // about the properties of the function containing it.
13492 const ValueDecl *Target = Dcl;
13493 // VarDecls and FunctionDecls have different functions for checking
13494 // inline-ness, and whether they were originally templated, so we have to
13495 // call the appropriate functions manually.
13496 bool TargetIsInline = Dcl->isInline();
13497 bool TargetWasTemplated =
13498 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13499
13500 // Update the Target and TargetIsInline property if necessary
13501 if (Dcl->isStaticLocal()) {
13502 const DeclContext *Ctx = Dcl->getDeclContext();
13503 if (!Ctx)
13504 return false;
13505
13506 const FunctionDecl *FunDcl =
13507 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13508 if (!FunDcl)
13509 return false;
13510
13511 Target = FunDcl;
13512 // IsInlined() checks for the C++ inline property
13513 TargetIsInline = FunDcl->isInlined();
13514 TargetWasTemplated =
13515 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13516 }
13517
13518 // Non-inline functions/variables can only legally appear in one TU
13519 // unless they were part of a template. Unfortunately, making complex
13520 // template instantiations visible is infeasible in practice, since
13521 // everything the template depends on also has to be visible. To avoid
13522 // giving impractical-to-fix warnings, don't warn if we're inside
13523 // something that was templated, even on inline stuff.
13524 if (!TargetIsInline || TargetWasTemplated)
13525 return false;
13526
13527 // If the object isn't hidden, the dynamic linker will prevent duplication.
13528 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13529
13530 // The target is "hidden" (from the dynamic linker) if:
13531 // 1. On posix, it has hidden visibility, or
13532 // 2. On windows, it has no import/export annotation, and neither does the
13533 // class which directly contains it.
13534 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13535 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13536 return false;
13537
13538 // If the variable isn't directly annotated, check to see if it's a member
13539 // of an annotated class.
13540 const CXXRecordDecl *Ctx =
13541 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13542 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13543 return false;
13544
13545 } else if (Lnk.getVisibility() != HiddenVisibility) {
13546 // Posix case
13547 return false;
13548 }
13549
13550 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13551 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13552 return false;
13553
13554 return true;
13555}
13556
13557// Determine whether the object seems mutable for the purpose of diagnosing
13558// possible unique object duplication, i.e. non-const-qualified, and
13559// not an always-constant type like a function.
13560// Not perfect: doesn't account for mutable members, for example, or
13561// elements of container types.
13562// For nested pointers, any individual level being non-const is sufficient.
13563static bool looksMutable(QualType T, const ASTContext &Ctx) {
13564 T = T.getNonReferenceType();
13565 if (T->isFunctionType())
13566 return false;
13567 if (!T.isConstant(Ctx))
13568 return true;
13569 if (T->isPointerType())
13570 return looksMutable(T: T->getPointeeType(), Ctx);
13571 return false;
13572}
13573
13574void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13575 // If this object has external linkage and hidden visibility, it might be
13576 // duplicated when built into a shared library, which causes problems if it's
13577 // mutable (since the copies won't be in sync) or its initialization has side
13578 // effects (since it will run once per copy instead of once globally).
13579
13580 // Don't diagnose if we're inside a template, because it's not practical to
13581 // fix the warning in most cases.
13582 if (!VD->isTemplated() &&
13583 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13584
13585 QualType Type = VD->getType();
13586 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13587 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13588 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13589 }
13590
13591 // To keep false positives low, only warn if we're certain that the
13592 // initializer has side effects. Don't warn on operator new, since a mutable
13593 // pointer will trigger the previous warning, and an immutable pointer
13594 // getting duplicated just results in a little extra memory usage.
13595 const Expr *Init = VD->getAnyInitializer();
13596 if (Init &&
13597 Init->HasSideEffects(Ctx: VD->getASTContext(),
13598 /*IncludePossibleEffects=*/false) &&
13599 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13600 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13601 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13602 }
13603 }
13604}
13605
13606void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13607 // If there is no declaration, there was an error parsing it. Just ignore
13608 // the initializer.
13609 if (!RealDecl) {
13610 return;
13611 }
13612
13613 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13614 if (!Method->isInvalidDecl()) {
13615 // Pure-specifiers are handled in ActOnPureSpecifier.
13616 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13617 << Method->getDeclName() << Init->getSourceRange();
13618 Method->setInvalidDecl();
13619 }
13620 return;
13621 }
13622
13623 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13624 if (!VDecl) {
13625 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13626 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13627 RealDecl->setInvalidDecl();
13628 return;
13629 }
13630
13631 if (VDecl->isInvalidDecl()) {
13632 ExprResult Recovery =
13633 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13634 if (Expr *E = Recovery.get())
13635 VDecl->setInit(E);
13636 return;
13637 }
13638
13639 // WebAssembly tables can't be used to initialise a variable.
13640 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13641 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13642 VDecl->setInvalidDecl();
13643 return;
13644 }
13645
13646 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13647 if (VDecl->getType()->isUndeducedType()) {
13648 if (Init->containsErrors()) {
13649 // Invalidate the decl as we don't know the type for recovery-expr yet.
13650 RealDecl->setInvalidDecl();
13651 VDecl->setInit(Init);
13652 return;
13653 }
13654
13655 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13656 return;
13657 }
13658
13659 // dllimport cannot be used on variable definitions.
13660 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13661 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13662 VDecl->setInvalidDecl();
13663 return;
13664 }
13665
13666 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13667 // the identifier has external or internal linkage, the declaration shall
13668 // have no initializer for the identifier.
13669 // C++14 [dcl.init]p5 is the same restriction for C++.
13670 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13671 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
13672 VDecl->setInvalidDecl();
13673 return;
13674 }
13675
13676 if (!VDecl->getType()->isDependentType()) {
13677 // A definition must end up with a complete type, which means it must be
13678 // complete with the restriction that an array type might be completed by
13679 // the initializer; note that later code assumes this restriction.
13680 QualType BaseDeclType = VDecl->getType();
13681 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13682 BaseDeclType = Array->getElementType();
13683 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
13684 DiagID: diag::err_typecheck_decl_incomplete_type)) {
13685 RealDecl->setInvalidDecl();
13686 return;
13687 }
13688
13689 // The variable can not have an abstract class type.
13690 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
13691 DiagID: diag::err_abstract_type_in_decl,
13692 Args: AbstractVariableType))
13693 VDecl->setInvalidDecl();
13694 }
13695
13696 // C++ [module.import/6] external definitions are not permitted in header
13697 // units.
13698 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13699 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13700 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13701 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
13702 !VDecl->getInstantiatedFromStaticDataMember()) {
13703 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
13704 VDecl->setInvalidDecl();
13705 }
13706
13707 // If adding the initializer will turn this declaration into a definition,
13708 // and we already have a definition for this variable, diagnose or otherwise
13709 // handle the situation.
13710 if (VarDecl *Def = VDecl->getDefinition())
13711 if (Def != VDecl &&
13712 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13713 !VDecl->isThisDeclarationADemotedDefinition() &&
13714 checkVarDeclRedefinition(Old: Def, New: VDecl))
13715 return;
13716
13717 if (getLangOpts().CPlusPlus) {
13718 // C++ [class.static.data]p4
13719 // If a static data member is of const integral or const
13720 // enumeration type, its declaration in the class definition can
13721 // specify a constant-initializer which shall be an integral
13722 // constant expression (5.19). In that case, the member can appear
13723 // in integral constant expressions. The member shall still be
13724 // defined in a namespace scope if it is used in the program and the
13725 // namespace scope definition shall not contain an initializer.
13726 //
13727 // We already performed a redefinition check above, but for static
13728 // data members we also need to check whether there was an in-class
13729 // declaration with an initializer.
13730 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13731 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
13732 << VDecl->getDeclName();
13733 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13734 DiagID: diag::note_previous_initializer)
13735 << 0;
13736 return;
13737 }
13738
13739 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13740 VDecl->setInvalidDecl();
13741 return;
13742 }
13743 }
13744
13745 // If the variable has an initializer and local storage, check whether
13746 // anything jumps over the initialization.
13747 if (VDecl->hasLocalStorage())
13748 setFunctionHasBranchProtectedScope();
13749
13750 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13751 // a kernel function cannot be initialized."
13752 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13753 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
13754 VDecl->setInvalidDecl();
13755 return;
13756 }
13757
13758 // The LoaderUninitialized attribute acts as a definition (of undef).
13759 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13760 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
13761 VDecl->setInvalidDecl();
13762 return;
13763 }
13764
13765 if (getLangOpts().HLSL)
13766 if (!HLSL().handleInitialization(VDecl, Init))
13767 return;
13768
13769 // Get the decls type and save a reference for later, since
13770 // CheckInitializerTypes may change it.
13771 QualType DclT = VDecl->getType(), SavT = DclT;
13772
13773 // Expressions default to 'id' when we're in a debugger
13774 // and we are assigning it to a variable of Objective-C pointer type.
13775 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13776 Init->getType() == Context.UnknownAnyTy) {
13777 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13778 if (!Result.isUsable()) {
13779 VDecl->setInvalidDecl();
13780 return;
13781 }
13782 Init = Result.get();
13783 }
13784
13785 // Perform the initialization.
13786 bool InitializedFromParenListExpr = false;
13787 bool IsParenListInit = false;
13788 if (!VDecl->isInvalidDecl()) {
13789 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13790 InitializationKind Kind = InitializationKind::CreateForInit(
13791 Loc: VDecl->getLocation(), DirectInit, Init);
13792
13793 MultiExprArg Args = Init;
13794 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
13795 Args =
13796 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
13797 InitializedFromParenListExpr = true;
13798 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
13799 Args = CXXDirectInit->getInitExprs();
13800 InitializedFromParenListExpr = true;
13801 }
13802
13803 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13804 /*TopLevelOfInitList=*/false,
13805 /*TreatUnavailableAsInvalid=*/false);
13806 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
13807 if (!Result.isUsable()) {
13808 // If the provided initializer fails to initialize the var decl,
13809 // we attach a recovery expr for better recovery.
13810 auto RecoveryExpr =
13811 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
13812 if (RecoveryExpr.get())
13813 VDecl->setInit(RecoveryExpr.get());
13814 // In general, for error recovery purposes, the initializer doesn't play
13815 // part in the valid bit of the declaration. There are a few exceptions:
13816 // 1) if the var decl has a deduced auto type, and the type cannot be
13817 // deduced by an invalid initializer;
13818 // 2) if the var decl is a decomposition decl with a non-deduced type,
13819 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13820 // Case 1) was already handled elsewhere.
13821 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
13822 VDecl->setInvalidDecl();
13823 return;
13824 }
13825
13826 Init = Result.getAs<Expr>();
13827 IsParenListInit = !InitSeq.steps().empty() &&
13828 InitSeq.step_begin()->Kind ==
13829 InitializationSequence::SK_ParenthesizedListInit;
13830 QualType VDeclType = VDecl->getType();
13831 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13832 !VDeclType->isDependentType() &&
13833 Context.getAsIncompleteArrayType(T: VDeclType) &&
13834 Context.getAsIncompleteArrayType(T: Init->getType())) {
13835 // Bail out if it is not possible to deduce array size from the
13836 // initializer.
13837 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
13838 << VDeclType;
13839 VDecl->setInvalidDecl();
13840 return;
13841 }
13842 }
13843
13844 // Check for self-references within variable initializers.
13845 // Variables declared within a function/method body (except for references)
13846 // are handled by a dataflow analysis.
13847 // This is undefined behavior in C++, but valid in C.
13848 if (getLangOpts().CPlusPlus)
13849 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13850 VDecl->getType()->isReferenceType())
13851 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
13852
13853 // If the type changed, it means we had an incomplete type that was
13854 // completed by the initializer. For example:
13855 // int ary[] = { 1, 3, 5 };
13856 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13857 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13858 VDecl->setType(DclT);
13859
13860 if (!VDecl->isInvalidDecl()) {
13861 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
13862
13863 if (VDecl->hasAttr<BlocksAttr>())
13864 ObjC().checkRetainCycles(Var: VDecl, Init);
13865
13866 // It is safe to assign a weak reference into a strong variable.
13867 // Although this code can still have problems:
13868 // id x = self.weakProp;
13869 // id y = self.weakProp;
13870 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13871 // paths through the function. This should be revisited if
13872 // -Wrepeated-use-of-weak is made flow-sensitive.
13873 if (FunctionScopeInfo *FSI = getCurFunction())
13874 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13875 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13876 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
13877 Loc: Init->getBeginLoc()))
13878 FSI->markSafeWeakUse(E: Init);
13879 }
13880
13881 // The initialization is usually a full-expression.
13882 //
13883 // FIXME: If this is a braced initialization of an aggregate, it is not
13884 // an expression, and each individual field initializer is a separate
13885 // full-expression. For instance, in:
13886 //
13887 // struct Temp { ~Temp(); };
13888 // struct S { S(Temp); };
13889 // struct T { S a, b; } t = { Temp(), Temp() }
13890 //
13891 // we should destroy the first Temp before constructing the second.
13892 ExprResult Result =
13893 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
13894 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
13895 if (!Result.isUsable()) {
13896 VDecl->setInvalidDecl();
13897 return;
13898 }
13899 Init = Result.get();
13900
13901 // Attach the initializer to the decl.
13902 VDecl->setInit(Init);
13903
13904 if (VDecl->isLocalVarDecl()) {
13905 // Don't check the initializer if the declaration is malformed.
13906 if (VDecl->isInvalidDecl()) {
13907 // do nothing
13908
13909 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13910 // This is true even in C++ for OpenCL.
13911 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13912 CheckForConstantInitializer(Init);
13913
13914 // Otherwise, C++ does not restrict the initializer.
13915 } else if (getLangOpts().CPlusPlus) {
13916 // do nothing
13917
13918 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13919 // static storage duration shall be constant expressions or string literals.
13920 } else if (VDecl->getStorageClass() == SC_Static) {
13921 CheckForConstantInitializer(Init);
13922
13923 // C89 is stricter than C99 for aggregate initializers.
13924 // C89 6.5.7p3: All the expressions [...] in an initializer list
13925 // for an object that has aggregate or union type shall be
13926 // constant expressions.
13927 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13928 isa<InitListExpr>(Val: Init)) {
13929 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
13930 }
13931
13932 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
13933 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
13934 if (VDecl->hasLocalStorage())
13935 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13936 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13937 VDecl->getLexicalDeclContext()->isRecord()) {
13938 // This is an in-class initialization for a static data member, e.g.,
13939 //
13940 // struct S {
13941 // static const int value = 17;
13942 // };
13943
13944 // C++ [class.mem]p4:
13945 // A member-declarator can contain a constant-initializer only
13946 // if it declares a static member (9.4) of const integral or
13947 // const enumeration type, see 9.4.2.
13948 //
13949 // C++11 [class.static.data]p3:
13950 // If a non-volatile non-inline const static data member is of integral
13951 // or enumeration type, its declaration in the class definition can
13952 // specify a brace-or-equal-initializer in which every initializer-clause
13953 // that is an assignment-expression is a constant expression. A static
13954 // data member of literal type can be declared in the class definition
13955 // with the constexpr specifier; if so, its declaration shall specify a
13956 // brace-or-equal-initializer in which every initializer-clause that is
13957 // an assignment-expression is a constant expression.
13958
13959 // Do nothing on dependent types.
13960 if (DclT->isDependentType()) {
13961
13962 // Allow any 'static constexpr' members, whether or not they are of literal
13963 // type. We separately check that every constexpr variable is of literal
13964 // type.
13965 } else if (VDecl->isConstexpr()) {
13966
13967 // Require constness.
13968 } else if (!DclT.isConstQualified()) {
13969 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
13970 << Init->getSourceRange();
13971 VDecl->setInvalidDecl();
13972
13973 // We allow integer constant expressions in all cases.
13974 } else if (DclT->isIntegralOrEnumerationType()) {
13975 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13976 // In C++11, a non-constexpr const static data member with an
13977 // in-class initializer cannot be volatile.
13978 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
13979
13980 // We allow foldable floating-point constants as an extension.
13981 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13982 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13983 // it anyway and provide a fixit to add the 'constexpr'.
13984 if (getLangOpts().CPlusPlus11) {
13985 Diag(Loc: VDecl->getLocation(),
13986 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
13987 << DclT << Init->getSourceRange();
13988 Diag(Loc: VDecl->getBeginLoc(),
13989 DiagID: diag::note_in_class_initializer_float_type_cxx11)
13990 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
13991 } else {
13992 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
13993 << DclT << Init->getSourceRange();
13994
13995 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
13996 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
13997 << Init->getSourceRange();
13998 VDecl->setInvalidDecl();
13999 }
14000 }
14001
14002 // Suggest adding 'constexpr' in C++11 for literal types.
14003 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14004 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14005 << DclT << Init->getSourceRange()
14006 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14007 VDecl->setConstexpr(true);
14008
14009 } else {
14010 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14011 << DclT << Init->getSourceRange();
14012 VDecl->setInvalidDecl();
14013 }
14014 } else if (VDecl->isFileVarDecl()) {
14015 // In C, extern is typically used to avoid tentative definitions when
14016 // declaring variables in headers, but adding an initializer makes it a
14017 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14018 // In C++, extern is often used to give implicitly static const variables
14019 // external linkage, so don't warn in that case. If selectany is present,
14020 // this might be header code intended for C and C++ inclusion, so apply the
14021 // C++ rules.
14022 if (VDecl->getStorageClass() == SC_Extern &&
14023 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14024 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14025 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14026 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14027 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14028
14029 // In Microsoft C++ mode, a const variable defined in namespace scope has
14030 // external linkage by default if the variable is declared with
14031 // __declspec(dllexport).
14032 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14033 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14034 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14035 VDecl->setStorageClass(SC_Extern);
14036
14037 // C99 6.7.8p4. All file scoped initializers need to be constant.
14038 // Avoid duplicate diagnostics for constexpr variables.
14039 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14040 !VDecl->isConstexpr())
14041 CheckForConstantInitializer(Init);
14042 }
14043
14044 QualType InitType = Init->getType();
14045 if (!InitType.isNull() &&
14046 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14047 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14048 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14049
14050 // We will represent direct-initialization similarly to copy-initialization:
14051 // int x(1); -as-> int x = 1;
14052 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14053 //
14054 // Clients that want to distinguish between the two forms, can check for
14055 // direct initializer using VarDecl::getInitStyle().
14056 // A major benefit is that clients that don't particularly care about which
14057 // exactly form was it (like the CodeGen) can handle both cases without
14058 // special case code.
14059
14060 // C++ 8.5p11:
14061 // The form of initialization (using parentheses or '=') matters
14062 // when the entity being initialized has class type.
14063 if (InitializedFromParenListExpr) {
14064 assert(DirectInit && "Call-style initializer must be direct init.");
14065 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14066 : VarDecl::CallInit);
14067 } else if (DirectInit) {
14068 // This must be list-initialization. No other way is direct-initialization.
14069 VDecl->setInitStyle(VarDecl::ListInit);
14070 }
14071
14072 if (LangOpts.OpenMP &&
14073 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14074 VDecl->isFileVarDecl())
14075 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14076 CheckCompleteVariableDeclaration(VD: VDecl);
14077
14078 if (LangOpts.OpenACC && !InitType.isNull())
14079 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14080}
14081
14082void Sema::ActOnInitializerError(Decl *D) {
14083 // Our main concern here is re-establishing invariants like "a
14084 // variable's type is either dependent or complete".
14085 if (!D || D->isInvalidDecl()) return;
14086
14087 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14088 if (!VD) return;
14089
14090 // Bindings are not usable if we can't make sense of the initializer.
14091 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14092 for (auto *BD : DD->bindings())
14093 BD->setInvalidDecl();
14094
14095 // Auto types are meaningless if we can't make sense of the initializer.
14096 if (VD->getType()->isUndeducedType()) {
14097 D->setInvalidDecl();
14098 return;
14099 }
14100
14101 QualType Ty = VD->getType();
14102 if (Ty->isDependentType()) return;
14103
14104 // Require a complete type.
14105 if (RequireCompleteType(Loc: VD->getLocation(),
14106 T: Context.getBaseElementType(QT: Ty),
14107 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14108 VD->setInvalidDecl();
14109 return;
14110 }
14111
14112 // Require a non-abstract type.
14113 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14114 DiagID: diag::err_abstract_type_in_decl,
14115 Args: AbstractVariableType)) {
14116 VD->setInvalidDecl();
14117 return;
14118 }
14119
14120 // Don't bother complaining about constructors or destructors,
14121 // though.
14122}
14123
14124void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14125 // If there is no declaration, there was an error parsing it. Just ignore it.
14126 if (!RealDecl)
14127 return;
14128
14129 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14130 QualType Type = Var->getType();
14131
14132 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14133 if (isa<DecompositionDecl>(Val: RealDecl)) {
14134 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14135 Var->setInvalidDecl();
14136 return;
14137 }
14138
14139 if (Type->isUndeducedType() &&
14140 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14141 return;
14142
14143 // C++11 [class.static.data]p3: A static data member can be declared with
14144 // the constexpr specifier; if so, its declaration shall specify
14145 // a brace-or-equal-initializer.
14146 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14147 // the definition of a variable [...] or the declaration of a static data
14148 // member.
14149 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14150 !Var->isThisDeclarationADemotedDefinition()) {
14151 if (Var->isStaticDataMember()) {
14152 // C++1z removes the relevant rule; the in-class declaration is always
14153 // a definition there.
14154 if (!getLangOpts().CPlusPlus17 &&
14155 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14156 Diag(Loc: Var->getLocation(),
14157 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14158 << Var;
14159 Var->setInvalidDecl();
14160 return;
14161 }
14162 } else {
14163 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14164 Var->setInvalidDecl();
14165 return;
14166 }
14167 }
14168
14169 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14170 // be initialized.
14171 if (!Var->isInvalidDecl() &&
14172 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14173 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14174 bool HasConstExprDefaultConstructor = false;
14175 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14176 for (auto *Ctor : RD->ctors()) {
14177 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14178 Ctor->getMethodQualifiers().getAddressSpace() ==
14179 LangAS::opencl_constant) {
14180 HasConstExprDefaultConstructor = true;
14181 }
14182 }
14183 }
14184 if (!HasConstExprDefaultConstructor) {
14185 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14186 Var->setInvalidDecl();
14187 return;
14188 }
14189 }
14190
14191 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14192 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14193 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14194 Var->setInvalidDecl();
14195 return;
14196 }
14197
14198 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14199 if (Var->getStorageClass() == SC_Extern) {
14200 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14201 << Var;
14202 Var->setInvalidDecl();
14203 return;
14204 }
14205 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14206 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14207 Var->setInvalidDecl();
14208 return;
14209 }
14210 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14211 if (!RD->hasTrivialDefaultConstructor()) {
14212 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14213 Var->setInvalidDecl();
14214 return;
14215 }
14216 }
14217 // The declaration is uninitialized, no need for further checks.
14218 return;
14219 }
14220
14221 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14222 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14223 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14224 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14225 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14226 NonTrivialKind: NTCUK_Init);
14227
14228 switch (DefKind) {
14229 case VarDecl::Definition:
14230 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14231 break;
14232
14233 // We have an out-of-line definition of a static data member
14234 // that has an in-class initializer, so we type-check this like
14235 // a declaration.
14236 //
14237 [[fallthrough]];
14238
14239 case VarDecl::DeclarationOnly:
14240 // It's only a declaration.
14241
14242 // Block scope. C99 6.7p7: If an identifier for an object is
14243 // declared with no linkage (C99 6.2.2p6), the type for the
14244 // object shall be complete.
14245 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14246 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14247 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14248 DiagID: diag::err_typecheck_decl_incomplete_type))
14249 Var->setInvalidDecl();
14250
14251 // Make sure that the type is not abstract.
14252 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14253 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14254 DiagID: diag::err_abstract_type_in_decl,
14255 Args: AbstractVariableType))
14256 Var->setInvalidDecl();
14257 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14258 Var->getStorageClass() == SC_PrivateExtern) {
14259 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14260 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14261 }
14262
14263 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14264 !Var->isInvalidDecl())
14265 ExternalDeclarations.push_back(Elt: Var);
14266
14267 return;
14268
14269 case VarDecl::TentativeDefinition:
14270 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14271 // object that has file scope without an initializer, and without a
14272 // storage-class specifier or with the storage-class specifier "static",
14273 // constitutes a tentative definition. Note: A tentative definition with
14274 // external linkage is valid (C99 6.2.2p5).
14275 if (!Var->isInvalidDecl()) {
14276 if (const IncompleteArrayType *ArrayT
14277 = Context.getAsIncompleteArrayType(T: Type)) {
14278 if (RequireCompleteSizedType(
14279 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14280 DiagID: diag::err_array_incomplete_or_sizeless_type))
14281 Var->setInvalidDecl();
14282 }
14283 if (Var->getStorageClass() == SC_Static) {
14284 // C99 6.9.2p3: If the declaration of an identifier for an object is
14285 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14286 // declared type shall not be an incomplete type.
14287 // NOTE: code such as the following
14288 // static struct s;
14289 // struct s { int a; };
14290 // is accepted by gcc. Hence here we issue a warning instead of
14291 // an error and we do not invalidate the static declaration.
14292 // NOTE: to avoid multiple warnings, only check the first declaration.
14293 if (Var->isFirstDecl())
14294 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14295 DiagID: diag::ext_typecheck_decl_incomplete_type,
14296 Args: Type->isArrayType());
14297 }
14298 }
14299
14300 // Record the tentative definition; we're done.
14301 if (!Var->isInvalidDecl())
14302 TentativeDefinitions.push_back(LocalValue: Var);
14303 return;
14304 }
14305
14306 // Provide a specific diagnostic for uninitialized variable
14307 // definitions with incomplete array type.
14308 if (Type->isIncompleteArrayType()) {
14309 if (Var->isConstexpr())
14310 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14311 << Var;
14312 else
14313 Diag(Loc: Var->getLocation(),
14314 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14315 Var->setInvalidDecl();
14316 return;
14317 }
14318
14319 // Provide a specific diagnostic for uninitialized variable
14320 // definitions with reference type.
14321 if (Type->isReferenceType()) {
14322 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14323 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14324 return;
14325 }
14326
14327 // Do not attempt to type-check the default initializer for a
14328 // variable with dependent type.
14329 if (Type->isDependentType())
14330 return;
14331
14332 if (Var->isInvalidDecl())
14333 return;
14334
14335 if (!Var->hasAttr<AliasAttr>()) {
14336 if (RequireCompleteType(Loc: Var->getLocation(),
14337 T: Context.getBaseElementType(QT: Type),
14338 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14339 Var->setInvalidDecl();
14340 return;
14341 }
14342 } else {
14343 return;
14344 }
14345
14346 // The variable can not have an abstract class type.
14347 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14348 DiagID: diag::err_abstract_type_in_decl,
14349 Args: AbstractVariableType)) {
14350 Var->setInvalidDecl();
14351 return;
14352 }
14353
14354 // In C, if the definition is const-qualified and has no initializer, it
14355 // is left uninitialized unless it has static or thread storage duration.
14356 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14357 unsigned DiagID = diag::warn_default_init_const_unsafe;
14358 if (Var->getStorageDuration() == SD_Static ||
14359 Var->getStorageDuration() == SD_Thread)
14360 DiagID = diag::warn_default_init_const;
14361
14362 bool EmitCppCompat = !Diags.isIgnored(
14363 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14364 Loc: Var->getLocation());
14365
14366 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14367 }
14368
14369 // Check for jumps past the implicit initializer. C++0x
14370 // clarifies that this applies to a "variable with automatic
14371 // storage duration", not a "local variable".
14372 // C++11 [stmt.dcl]p3
14373 // A program that jumps from a point where a variable with automatic
14374 // storage duration is not in scope to a point where it is in scope is
14375 // ill-formed unless the variable has scalar type, class type with a
14376 // trivial default constructor and a trivial destructor, a cv-qualified
14377 // version of one of these types, or an array of one of the preceding
14378 // types and is declared without an initializer.
14379 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14380 if (const RecordType *Record
14381 = Context.getBaseElementType(QT: Type)->getAs<RecordType>()) {
14382 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record->getDecl());
14383 // Mark the function (if we're in one) for further checking even if the
14384 // looser rules of C++11 do not require such checks, so that we can
14385 // diagnose incompatibilities with C++98.
14386 if (!CXXRecord->isPOD())
14387 setFunctionHasBranchProtectedScope();
14388 }
14389 }
14390 // In OpenCL, we can't initialize objects in the __local address space,
14391 // even implicitly, so don't synthesize an implicit initializer.
14392 if (getLangOpts().OpenCL &&
14393 Var->getType().getAddressSpace() == LangAS::opencl_local)
14394 return;
14395
14396 // Handle HLSL uninitialized decls
14397 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14398 return;
14399
14400 // HLSL input variables are expected to be externally initialized, even
14401 // when marked `static`.
14402 if (getLangOpts().HLSL &&
14403 Var->getType().getAddressSpace() == LangAS::hlsl_input)
14404 return;
14405
14406 // C++03 [dcl.init]p9:
14407 // If no initializer is specified for an object, and the
14408 // object is of (possibly cv-qualified) non-POD class type (or
14409 // array thereof), the object shall be default-initialized; if
14410 // the object is of const-qualified type, the underlying class
14411 // type shall have a user-declared default
14412 // constructor. Otherwise, if no initializer is specified for
14413 // a non- static object, the object and its subobjects, if
14414 // any, have an indeterminate initial value); if the object
14415 // or any of its subobjects are of const-qualified type, the
14416 // program is ill-formed.
14417 // C++0x [dcl.init]p11:
14418 // If no initializer is specified for an object, the object is
14419 // default-initialized; [...].
14420 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14421 InitializationKind Kind
14422 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14423
14424 InitializationSequence InitSeq(*this, Entity, Kind, {});
14425 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14426
14427 if (Init.get()) {
14428 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14429 // This is important for template substitution.
14430 Var->setInitStyle(VarDecl::CallInit);
14431 } else if (Init.isInvalid()) {
14432 // If default-init fails, attach a recovery-expr initializer to track
14433 // that initialization was attempted and failed.
14434 auto RecoveryExpr =
14435 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14436 if (RecoveryExpr.get())
14437 Var->setInit(RecoveryExpr.get());
14438 }
14439
14440 CheckCompleteVariableDeclaration(VD: Var);
14441 }
14442}
14443
14444void Sema::ActOnCXXForRangeDecl(Decl *D) {
14445 // If there is no declaration, there was an error parsing it. Ignore it.
14446 if (!D)
14447 return;
14448
14449 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14450 if (!VD) {
14451 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14452 D->setInvalidDecl();
14453 return;
14454 }
14455
14456 VD->setCXXForRangeDecl(true);
14457
14458 // for-range-declaration cannot be given a storage class specifier.
14459 int Error = -1;
14460 switch (VD->getStorageClass()) {
14461 case SC_None:
14462 break;
14463 case SC_Extern:
14464 Error = 0;
14465 break;
14466 case SC_Static:
14467 Error = 1;
14468 break;
14469 case SC_PrivateExtern:
14470 Error = 2;
14471 break;
14472 case SC_Auto:
14473 Error = 3;
14474 break;
14475 case SC_Register:
14476 Error = 4;
14477 break;
14478 }
14479
14480 // for-range-declaration cannot be given a storage class specifier con't.
14481 switch (VD->getTSCSpec()) {
14482 case TSCS_thread_local:
14483 Error = 6;
14484 break;
14485 case TSCS___thread:
14486 case TSCS__Thread_local:
14487 case TSCS_unspecified:
14488 break;
14489 }
14490
14491 if (Error != -1) {
14492 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14493 << VD << Error;
14494 D->setInvalidDecl();
14495 }
14496}
14497
14498StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14499 IdentifierInfo *Ident,
14500 ParsedAttributes &Attrs) {
14501 // C++1y [stmt.iter]p1:
14502 // A range-based for statement of the form
14503 // for ( for-range-identifier : for-range-initializer ) statement
14504 // is equivalent to
14505 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14506 DeclSpec DS(Attrs.getPool().getFactory());
14507
14508 const char *PrevSpec;
14509 unsigned DiagID;
14510 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14511 Policy: getPrintingPolicy());
14512
14513 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14514 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14515 D.takeAttributes(attrs&: Attrs);
14516
14517 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14518 EndLoc: IdentLoc);
14519 Decl *Var = ActOnDeclarator(S, D);
14520 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14521 FinalizeDeclaration(D: Var);
14522 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14523 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14524 : IdentLoc);
14525}
14526
14527void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14528 if (var->isInvalidDecl()) return;
14529
14530 CUDA().MaybeAddConstantAttr(VD: var);
14531
14532 if (getLangOpts().OpenCL) {
14533 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14534 // initialiser
14535 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14536 !var->hasInit()) {
14537 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14538 << 1 /*Init*/;
14539 var->setInvalidDecl();
14540 return;
14541 }
14542 }
14543
14544 // In Objective-C, don't allow jumps past the implicit initialization of a
14545 // local retaining variable.
14546 if (getLangOpts().ObjC &&
14547 var->hasLocalStorage()) {
14548 switch (var->getType().getObjCLifetime()) {
14549 case Qualifiers::OCL_None:
14550 case Qualifiers::OCL_ExplicitNone:
14551 case Qualifiers::OCL_Autoreleasing:
14552 break;
14553
14554 case Qualifiers::OCL_Weak:
14555 case Qualifiers::OCL_Strong:
14556 setFunctionHasBranchProtectedScope();
14557 break;
14558 }
14559 }
14560
14561 if (var->hasLocalStorage() &&
14562 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14563 setFunctionHasBranchProtectedScope();
14564
14565 // Warn about externally-visible variables being defined without a
14566 // prior declaration. We only want to do this for global
14567 // declarations, but we also specifically need to avoid doing it for
14568 // class members because the linkage of an anonymous class can
14569 // change if it's later given a typedef name.
14570 if (var->isThisDeclarationADefinition() &&
14571 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14572 var->isExternallyVisible() && var->hasLinkage() &&
14573 !var->isInline() && !var->getDescribedVarTemplate() &&
14574 var->getStorageClass() != SC_Register &&
14575 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14576 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14577 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14578 Loc: var->getLocation())) {
14579 // Find a previous declaration that's not a definition.
14580 VarDecl *prev = var->getPreviousDecl();
14581 while (prev && prev->isThisDeclarationADefinition())
14582 prev = prev->getPreviousDecl();
14583
14584 if (!prev) {
14585 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14586 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14587 << /* variable */ 0;
14588 }
14589 }
14590
14591 // Cache the result of checking for constant initialization.
14592 std::optional<bool> CacheHasConstInit;
14593 const Expr *CacheCulprit = nullptr;
14594 auto checkConstInit = [&]() mutable {
14595 const Expr *Init = var->getInit();
14596 if (Init->isInstantiationDependent())
14597 return true;
14598
14599 if (!CacheHasConstInit)
14600 CacheHasConstInit = var->getInit()->isConstantInitializer(
14601 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14602 return *CacheHasConstInit;
14603 };
14604
14605 if (var->getTLSKind() == VarDecl::TLS_Static) {
14606 if (var->getType().isDestructedType()) {
14607 // GNU C++98 edits for __thread, [basic.start.term]p3:
14608 // The type of an object with thread storage duration shall not
14609 // have a non-trivial destructor.
14610 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14611 if (getLangOpts().CPlusPlus11)
14612 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14613 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14614 if (!checkConstInit()) {
14615 // GNU C++98 edits for __thread, [basic.start.init]p4:
14616 // An object of thread storage duration shall not require dynamic
14617 // initialization.
14618 // FIXME: Need strict checking here.
14619 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14620 << CacheCulprit->getSourceRange();
14621 if (getLangOpts().CPlusPlus11)
14622 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14623 }
14624 }
14625 }
14626
14627
14628 if (!var->getType()->isStructureType() && var->hasInit() &&
14629 isa<InitListExpr>(Val: var->getInit())) {
14630 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14631 unsigned NumInits = ILE->getNumInits();
14632 if (NumInits > 2)
14633 for (unsigned I = 0; I < NumInits; ++I) {
14634 const auto *Init = ILE->getInit(Init: I);
14635 if (!Init)
14636 break;
14637 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14638 if (!SL)
14639 break;
14640
14641 unsigned NumConcat = SL->getNumConcatenated();
14642 // Diagnose missing comma in string array initialization.
14643 // Do not warn when all the elements in the initializer are concatenated
14644 // together. Do not warn for macros too.
14645 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14646 bool OnlyOneMissingComma = true;
14647 for (unsigned J = I + 1; J < NumInits; ++J) {
14648 const auto *Init = ILE->getInit(Init: J);
14649 if (!Init)
14650 break;
14651 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14652 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14653 OnlyOneMissingComma = false;
14654 break;
14655 }
14656 }
14657
14658 if (OnlyOneMissingComma) {
14659 SmallVector<FixItHint, 1> Hints;
14660 for (unsigned i = 0; i < NumConcat - 1; ++i)
14661 Hints.push_back(Elt: FixItHint::CreateInsertion(
14662 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14663
14664 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
14665 DiagID: diag::warn_concatenated_literal_array_init)
14666 << Hints;
14667 Diag(Loc: SL->getBeginLoc(),
14668 DiagID: diag::note_concatenated_string_literal_silence);
14669 }
14670 // In any case, stop now.
14671 break;
14672 }
14673 }
14674 }
14675
14676
14677 QualType type = var->getType();
14678
14679 if (var->hasAttr<BlocksAttr>())
14680 getCurFunction()->addByrefBlockVar(VD: var);
14681
14682 Expr *Init = var->getInit();
14683 bool GlobalStorage = var->hasGlobalStorage();
14684 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14685 QualType baseType = Context.getBaseElementType(QT: type);
14686 bool HasConstInit = true;
14687
14688 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14689 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14690 << var;
14691
14692 // Check whether the initializer is sufficiently constant.
14693 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14694 !type->isDependentType() && Init && !Init->isValueDependent() &&
14695 (GlobalStorage || var->isConstexpr() ||
14696 var->mightBeUsableInConstantExpressions(C: Context))) {
14697 // If this variable might have a constant initializer or might be usable in
14698 // constant expressions, check whether or not it actually is now. We can't
14699 // do this lazily, because the result might depend on things that change
14700 // later, such as which constexpr functions happen to be defined.
14701 SmallVector<PartialDiagnosticAt, 8> Notes;
14702 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14703 // Prior to C++11, in contexts where a constant initializer is required,
14704 // the set of valid constant initializers is described by syntactic rules
14705 // in [expr.const]p2-6.
14706 // FIXME: Stricter checking for these rules would be useful for constinit /
14707 // -Wglobal-constructors.
14708 HasConstInit = checkConstInit();
14709
14710 // Compute and cache the constant value, and remember that we have a
14711 // constant initializer.
14712 if (HasConstInit) {
14713 if (var->isStaticDataMember() && !var->isInline() &&
14714 var->getLexicalDeclContext()->isRecord() &&
14715 type->isIntegralOrEnumerationType()) {
14716 // In C++98, in-class initialization for a static data member must
14717 // be an integer constant expression.
14718 SourceLocation Loc;
14719 if (!Init->isIntegerConstantExpr(Ctx: Context, Loc: &Loc)) {
14720 Diag(Loc, DiagID: diag::ext_in_class_initializer_non_constant)
14721 << Init->getSourceRange();
14722 }
14723 }
14724 (void)var->checkForConstantInitialization(Notes);
14725 Notes.clear();
14726 } else if (CacheCulprit) {
14727 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
14728 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
14729 Notes.back().second << CacheCulprit->getSourceRange();
14730 }
14731 } else {
14732 // Evaluate the initializer to see if it's a constant initializer.
14733 HasConstInit = var->checkForConstantInitialization(Notes);
14734 }
14735
14736 if (HasConstInit) {
14737 // FIXME: Consider replacing the initializer with a ConstantExpr.
14738 } else if (var->isConstexpr()) {
14739 SourceLocation DiagLoc = var->getLocation();
14740 // If the note doesn't add any useful information other than a source
14741 // location, fold it into the primary diagnostic.
14742 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14743 diag::note_invalid_subexpr_in_const_expr) {
14744 DiagLoc = Notes[0].first;
14745 Notes.clear();
14746 }
14747 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
14748 << var << Init->getSourceRange();
14749 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14750 Diag(Loc: Notes[I].first, PD: Notes[I].second);
14751 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14752 auto *Attr = var->getAttr<ConstInitAttr>();
14753 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
14754 << Init->getSourceRange();
14755 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
14756 << Attr->getRange() << Attr->isConstinit();
14757 for (auto &it : Notes)
14758 Diag(Loc: it.first, PD: it.second);
14759 } else if (var->isStaticDataMember() && !var->isInline() &&
14760 var->getLexicalDeclContext()->isRecord()) {
14761 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
14762 << Init->getSourceRange();
14763 for (auto &it : Notes)
14764 Diag(Loc: it.first, PD: it.second);
14765 var->setInvalidDecl();
14766 } else if (IsGlobal &&
14767 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
14768 Loc: var->getLocation())) {
14769 // Warn about globals which don't have a constant initializer. Don't
14770 // warn about globals with a non-trivial destructor because we already
14771 // warned about them.
14772 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14773 if (!(RD && !RD->hasTrivialDestructor())) {
14774 // checkConstInit() here permits trivial default initialization even in
14775 // C++11 onwards, where such an initializer is not a constant initializer
14776 // but nonetheless doesn't require a global constructor.
14777 if (!checkConstInit())
14778 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
14779 << Init->getSourceRange();
14780 }
14781 }
14782 }
14783
14784 // Apply section attributes and pragmas to global variables.
14785 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14786 !inTemplateInstantiation()) {
14787 PragmaStack<StringLiteral *> *Stack = nullptr;
14788 int SectionFlags = ASTContext::PSF_Read;
14789 bool MSVCEnv =
14790 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14791 std::optional<QualType::NonConstantStorageReason> Reason;
14792 if (HasConstInit &&
14793 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
14794 Stack = &ConstSegStack;
14795 } else {
14796 SectionFlags |= ASTContext::PSF_Write;
14797 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14798 }
14799 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14800 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14801 SectionFlags |= ASTContext::PSF_Implicit;
14802 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
14803 } else if (Stack->CurrentValue) {
14804 if (Stack != &ConstSegStack && MSVCEnv &&
14805 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14806 var->getType().isConstQualified()) {
14807 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14808 NonConstNonReferenceType) &&
14809 "This case should've already been handled elsewhere");
14810 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
14811 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14812 ? QualType::NonConstantStorageReason::NonTrivialCtor
14813 : *Reason);
14814 }
14815 SectionFlags |= ASTContext::PSF_Implicit;
14816 auto SectionName = Stack->CurrentValue->getString();
14817 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
14818 Range: Stack->CurrentPragmaLocation,
14819 S: SectionAttr::Declspec_allocate));
14820 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
14821 var->dropAttr<SectionAttr>();
14822 }
14823
14824 // Apply the init_seg attribute if this has an initializer. If the
14825 // initializer turns out to not be dynamic, we'll end up ignoring this
14826 // attribute.
14827 if (CurInitSeg && var->getInit())
14828 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
14829 Range: CurInitSegLoc));
14830 }
14831
14832 // All the following checks are C++ only.
14833 if (!getLangOpts().CPlusPlus) {
14834 // If this variable must be emitted, add it as an initializer for the
14835 // current module.
14836 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
14837 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
14838 return;
14839 }
14840
14841 DiagnoseUniqueObjectDuplication(VD: var);
14842
14843 // Require the destructor.
14844 if (!type->isDependentType())
14845 if (const RecordType *recordType = baseType->getAs<RecordType>())
14846 FinalizeVarWithDestructor(VD: var, DeclInitType: recordType);
14847
14848 // If this variable must be emitted, add it as an initializer for the current
14849 // module.
14850 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
14851 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
14852
14853 // Build the bindings if this is a structured binding declaration.
14854 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
14855 CheckCompleteDecompositionDeclaration(DD);
14856}
14857
14858void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14859 assert(VD->isStaticLocal());
14860
14861 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
14862
14863 // Find outermost function when VD is in lambda function.
14864 while (FD && !getDLLAttr(D: FD) &&
14865 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14866 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14867 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
14868 }
14869
14870 if (!FD)
14871 return;
14872
14873 // Static locals inherit dll attributes from their function.
14874 if (Attr *A = getDLLAttr(D: FD)) {
14875 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
14876 NewAttr->setInherited(true);
14877 VD->addAttr(A: NewAttr);
14878 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14879 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
14880 NewAttr->setInherited(true);
14881 VD->addAttr(A: NewAttr);
14882
14883 // Export this function to enforce exporting this static variable even
14884 // if it is not used in this compilation unit.
14885 if (!FD->hasAttr<DLLExportAttr>())
14886 FD->addAttr(A: NewAttr);
14887
14888 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14889 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
14890 NewAttr->setInherited(true);
14891 VD->addAttr(A: NewAttr);
14892 }
14893}
14894
14895void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14896 assert(VD->getTLSKind());
14897
14898 // Perform TLS alignment check here after attributes attached to the variable
14899 // which may affect the alignment have been processed. Only perform the check
14900 // if the target has a maximum TLS alignment (zero means no constraints).
14901 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14902 // Protect the check so that it's not performed on dependent types and
14903 // dependent alignments (we can't determine the alignment in that case).
14904 if (!VD->hasDependentAlignment()) {
14905 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
14906 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
14907 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
14908 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
14909 << (unsigned)MaxAlignChars.getQuantity();
14910 }
14911 }
14912 }
14913}
14914
14915void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14916 // Note that we are no longer parsing the initializer for this declaration.
14917 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
14918
14919 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
14920 if (!VD)
14921 return;
14922
14923 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14924 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14925 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14926 if (PragmaClangBSSSection.Valid)
14927 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
14928 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
14929 Range: PragmaClangBSSSection.PragmaLocation));
14930 if (PragmaClangDataSection.Valid)
14931 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
14932 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
14933 Range: PragmaClangDataSection.PragmaLocation));
14934 if (PragmaClangRodataSection.Valid)
14935 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
14936 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
14937 Range: PragmaClangRodataSection.PragmaLocation));
14938 if (PragmaClangRelroSection.Valid)
14939 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
14940 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
14941 Range: PragmaClangRelroSection.PragmaLocation));
14942 }
14943
14944 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
14945 for (auto *BD : DD->bindings()) {
14946 FinalizeDeclaration(ThisDecl: BD);
14947 }
14948 }
14949
14950 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
14951 K: BuiltinCountedByRefKind::Initializer);
14952
14953 checkAttributesAfterMerging(S&: *this, ND&: *VD);
14954
14955 if (VD->isStaticLocal())
14956 CheckStaticLocalForDllExport(VD);
14957
14958 if (VD->getTLSKind())
14959 CheckThreadLocalForLargeAlignment(VD);
14960
14961 // Perform check for initializers of device-side global variables.
14962 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14963 // 7.5). We must also apply the same checks to all __shared__
14964 // variables whether they are local or not. CUDA also allows
14965 // constant initializers for __constant__ and __device__ variables.
14966 if (getLangOpts().CUDA)
14967 CUDA().checkAllowedInitializer(VD);
14968
14969 // Grab the dllimport or dllexport attribute off of the VarDecl.
14970 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
14971
14972 // Imported static data members cannot be defined out-of-line.
14973 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
14974 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14975 VD->isThisDeclarationADefinition()) {
14976 // We allow definitions of dllimport class template static data members
14977 // with a warning.
14978 CXXRecordDecl *Context =
14979 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
14980 bool IsClassTemplateMember =
14981 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
14982 Context->getDescribedClassTemplate();
14983
14984 Diag(Loc: VD->getLocation(),
14985 DiagID: IsClassTemplateMember
14986 ? diag::warn_attribute_dllimport_static_field_definition
14987 : diag::err_attribute_dllimport_static_field_definition);
14988 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
14989 if (!IsClassTemplateMember)
14990 VD->setInvalidDecl();
14991 }
14992 }
14993
14994 // dllimport/dllexport variables cannot be thread local, their TLS index
14995 // isn't exported with the variable.
14996 if (DLLAttr && VD->getTLSKind()) {
14997 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
14998 if (F && getDLLAttr(D: F)) {
14999 assert(VD->isStaticLocal());
15000 // But if this is a static local in a dlimport/dllexport function, the
15001 // function will never be inlined, which means the var would never be
15002 // imported, so having it marked import/export is safe.
15003 } else {
15004 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15005 << DLLAttr;
15006 VD->setInvalidDecl();
15007 }
15008 }
15009
15010 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15011 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15012 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15013 << Attr;
15014 VD->dropAttr<UsedAttr>();
15015 }
15016 }
15017 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15018 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15019 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15020 << Attr;
15021 VD->dropAttr<RetainAttr>();
15022 }
15023 }
15024
15025 const DeclContext *DC = VD->getDeclContext();
15026 // If there's a #pragma GCC visibility in scope, and this isn't a class
15027 // member, set the visibility of this variable.
15028 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15029 AddPushedVisibilityAttribute(RD: VD);
15030
15031 // FIXME: Warn on unused var template partial specializations.
15032 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15033 MarkUnusedFileScopedDecl(D: VD);
15034
15035 // Now we have parsed the initializer and can update the table of magic
15036 // tag values.
15037 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15038 !VD->getType()->isIntegralOrEnumerationType())
15039 return;
15040
15041 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15042 const Expr *MagicValueExpr = VD->getInit();
15043 if (!MagicValueExpr) {
15044 continue;
15045 }
15046 std::optional<llvm::APSInt> MagicValueInt;
15047 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15048 Diag(Loc: I->getRange().getBegin(),
15049 DiagID: diag::err_type_tag_for_datatype_not_ice)
15050 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15051 continue;
15052 }
15053 if (MagicValueInt->getActiveBits() > 64) {
15054 Diag(Loc: I->getRange().getBegin(),
15055 DiagID: diag::err_type_tag_for_datatype_too_large)
15056 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15057 continue;
15058 }
15059 uint64_t MagicValue = MagicValueInt->getZExtValue();
15060 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15061 MagicValue,
15062 Type: I->getMatchingCType(),
15063 LayoutCompatible: I->getLayoutCompatible(),
15064 MustBeNull: I->getMustBeNull());
15065 }
15066}
15067
15068static bool hasDeducedAuto(DeclaratorDecl *DD) {
15069 auto *VD = dyn_cast<VarDecl>(Val: DD);
15070 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15071}
15072
15073Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15074 ArrayRef<Decl *> Group) {
15075 SmallVector<Decl*, 8> Decls;
15076
15077 if (DS.isTypeSpecOwned())
15078 Decls.push_back(Elt: DS.getRepAsDecl());
15079
15080 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15081 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15082 bool DiagnosedMultipleDecomps = false;
15083 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15084 bool DiagnosedNonDeducedAuto = false;
15085
15086 for (Decl *D : Group) {
15087 if (!D)
15088 continue;
15089 // Check if the Decl has been declared in '#pragma omp declare target'
15090 // directive and has static storage duration.
15091 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15092 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15093 VD->hasGlobalStorage())
15094 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15095 // For declarators, there are some additional syntactic-ish checks we need
15096 // to perform.
15097 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15098 if (!FirstDeclaratorInGroup)
15099 FirstDeclaratorInGroup = DD;
15100 if (!FirstDecompDeclaratorInGroup)
15101 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15102 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15103 !hasDeducedAuto(DD))
15104 FirstNonDeducedAutoInGroup = DD;
15105
15106 if (FirstDeclaratorInGroup != DD) {
15107 // A decomposition declaration cannot be combined with any other
15108 // declaration in the same group.
15109 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15110 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15111 DiagID: diag::err_decomp_decl_not_alone)
15112 << FirstDeclaratorInGroup->getSourceRange()
15113 << DD->getSourceRange();
15114 DiagnosedMultipleDecomps = true;
15115 }
15116
15117 // A declarator that uses 'auto' in any way other than to declare a
15118 // variable with a deduced type cannot be combined with any other
15119 // declarator in the same group.
15120 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15121 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15122 DiagID: diag::err_auto_non_deduced_not_alone)
15123 << FirstNonDeducedAutoInGroup->getType()
15124 ->hasAutoForTrailingReturnType()
15125 << FirstDeclaratorInGroup->getSourceRange()
15126 << DD->getSourceRange();
15127 DiagnosedNonDeducedAuto = true;
15128 }
15129 }
15130 }
15131
15132 Decls.push_back(Elt: D);
15133 }
15134
15135 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15136 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15137 handleTagNumbering(Tag, TagScope: S);
15138 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15139 getLangOpts().CPlusPlus)
15140 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15141 }
15142 }
15143
15144 return BuildDeclaratorGroup(Group: Decls);
15145}
15146
15147Sema::DeclGroupPtrTy
15148Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15149 // C++14 [dcl.spec.auto]p7: (DR1347)
15150 // If the type that replaces the placeholder type is not the same in each
15151 // deduction, the program is ill-formed.
15152 if (Group.size() > 1) {
15153 QualType Deduced;
15154 VarDecl *DeducedDecl = nullptr;
15155 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15156 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15157 if (!D || D->isInvalidDecl())
15158 break;
15159 DeducedType *DT = D->getType()->getContainedDeducedType();
15160 if (!DT || DT->getDeducedType().isNull())
15161 continue;
15162 if (Deduced.isNull()) {
15163 Deduced = DT->getDeducedType();
15164 DeducedDecl = D;
15165 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15166 auto *AT = dyn_cast<AutoType>(Val: DT);
15167 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15168 DiagID: diag::err_auto_different_deductions)
15169 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15170 << DeducedDecl->getDeclName() << DT->getDeducedType()
15171 << D->getDeclName();
15172 if (DeducedDecl->hasInit())
15173 Dia << DeducedDecl->getInit()->getSourceRange();
15174 if (D->getInit())
15175 Dia << D->getInit()->getSourceRange();
15176 D->setInvalidDecl();
15177 break;
15178 }
15179 }
15180 }
15181
15182 ActOnDocumentableDecls(Group);
15183
15184 return DeclGroupPtrTy::make(
15185 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15186}
15187
15188void Sema::ActOnDocumentableDecl(Decl *D) {
15189 ActOnDocumentableDecls(Group: D);
15190}
15191
15192void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15193 // Don't parse the comment if Doxygen diagnostics are ignored.
15194 if (Group.empty() || !Group[0])
15195 return;
15196
15197 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15198 Loc: Group[0]->getLocation()) &&
15199 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15200 Loc: Group[0]->getLocation()))
15201 return;
15202
15203 if (Group.size() >= 2) {
15204 // This is a decl group. Normally it will contain only declarations
15205 // produced from declarator list. But in case we have any definitions or
15206 // additional declaration references:
15207 // 'typedef struct S {} S;'
15208 // 'typedef struct S *S;'
15209 // 'struct S *pS;'
15210 // FinalizeDeclaratorGroup adds these as separate declarations.
15211 Decl *MaybeTagDecl = Group[0];
15212 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15213 Group = Group.slice(N: 1);
15214 }
15215 }
15216
15217 // FIMXE: We assume every Decl in the group is in the same file.
15218 // This is false when preprocessor constructs the group from decls in
15219 // different files (e. g. macros or #include).
15220 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15221}
15222
15223void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15224 // Check that there are no default arguments inside the type of this
15225 // parameter.
15226 if (getLangOpts().CPlusPlus)
15227 CheckExtraCXXDefaultArguments(D);
15228
15229 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15230 if (D.getCXXScopeSpec().isSet()) {
15231 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15232 << D.getCXXScopeSpec().getRange();
15233 }
15234
15235 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15236 // simple identifier except [...irrelevant cases...].
15237 switch (D.getName().getKind()) {
15238 case UnqualifiedIdKind::IK_Identifier:
15239 break;
15240
15241 case UnqualifiedIdKind::IK_OperatorFunctionId:
15242 case UnqualifiedIdKind::IK_ConversionFunctionId:
15243 case UnqualifiedIdKind::IK_LiteralOperatorId:
15244 case UnqualifiedIdKind::IK_ConstructorName:
15245 case UnqualifiedIdKind::IK_DestructorName:
15246 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15247 case UnqualifiedIdKind::IK_DeductionGuideName:
15248 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15249 << GetNameForDeclarator(D).getName();
15250 break;
15251
15252 case UnqualifiedIdKind::IK_TemplateId:
15253 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15254 // GetNameForDeclarator would not produce a useful name in this case.
15255 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15256 break;
15257 }
15258}
15259
15260void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15261 // This only matters in C.
15262 if (getLangOpts().CPlusPlus)
15263 return;
15264
15265 // This only matters if the declaration has a type.
15266 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15267 if (!VD)
15268 return;
15269
15270 // Get the type, this only matters for tag types.
15271 QualType QT = VD->getType();
15272 const auto *TD = QT->getAsTagDecl();
15273 if (!TD)
15274 return;
15275
15276 // Check if the tag declaration is lexically declared somewhere different
15277 // from the lexical declaration of the given object, then it will be hidden
15278 // in C++ and we should warn on it.
15279 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15280 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15281 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15282 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15283 }
15284}
15285
15286static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15287 SourceLocation ExplicitThisLoc) {
15288 if (!ExplicitThisLoc.isValid())
15289 return;
15290 assert(S.getLangOpts().CPlusPlus &&
15291 "explicit parameter in non-cplusplus mode");
15292 if (!S.getLangOpts().CPlusPlus23)
15293 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15294 << P->getSourceRange();
15295
15296 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15297 // parameter pack.
15298 if (P->isParameterPack()) {
15299 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15300 << P->getSourceRange();
15301 return;
15302 }
15303 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15304 if (LambdaScopeInfo *LSI = S.getCurLambda())
15305 LSI->ExplicitObjectParameter = P;
15306}
15307
15308Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15309 SourceLocation ExplicitThisLoc) {
15310 const DeclSpec &DS = D.getDeclSpec();
15311
15312 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15313 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15314 // except for the special case of a single unnamed parameter of type void
15315 // with no storage class specifier, no type qualifier, and no following
15316 // ellipsis terminator.
15317 // Clang applies the C2y rules for 'register void' in all C language modes,
15318 // same as GCC, because it's questionable what that could possibly mean.
15319
15320 // C++03 [dcl.stc]p2 also permits 'auto'.
15321 StorageClass SC = SC_None;
15322 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15323 SC = SC_Register;
15324 // In C++11, the 'register' storage class specifier is deprecated.
15325 // In C++17, it is not allowed, but we tolerate it as an extension.
15326 if (getLangOpts().CPlusPlus11) {
15327 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15328 ? diag::ext_register_storage_class
15329 : diag::warn_deprecated_register)
15330 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15331 } else if (!getLangOpts().CPlusPlus &&
15332 DS.getTypeSpecType() == DeclSpec::TST_void &&
15333 D.getNumTypeObjects() == 0) {
15334 Diag(Loc: DS.getStorageClassSpecLoc(),
15335 DiagID: diag::err_invalid_storage_class_in_func_decl)
15336 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15337 D.getMutableDeclSpec().ClearStorageClassSpecs();
15338 }
15339 } else if (getLangOpts().CPlusPlus &&
15340 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15341 SC = SC_Auto;
15342 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15343 Diag(Loc: DS.getStorageClassSpecLoc(),
15344 DiagID: diag::err_invalid_storage_class_in_func_decl);
15345 D.getMutableDeclSpec().ClearStorageClassSpecs();
15346 }
15347
15348 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15349 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15350 << DeclSpec::getSpecifierName(S: TSCS);
15351 if (DS.isInlineSpecified())
15352 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15353 << getLangOpts().CPlusPlus17;
15354 if (DS.hasConstexprSpecifier())
15355 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15356 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15357
15358 DiagnoseFunctionSpecifiers(DS);
15359
15360 CheckFunctionOrTemplateParamDeclarator(S, D);
15361
15362 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15363 QualType parmDeclType = TInfo->getType();
15364
15365 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15366 const IdentifierInfo *II = D.getIdentifier();
15367 if (II) {
15368 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15369 RedeclarationKind::ForVisibleRedeclaration);
15370 LookupName(R, S);
15371 if (!R.empty()) {
15372 NamedDecl *PrevDecl = *R.begin();
15373 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15374 // Maybe we will complain about the shadowed template parameter.
15375 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15376 // Just pretend that we didn't see the previous declaration.
15377 PrevDecl = nullptr;
15378 }
15379 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15380 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15381 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15382 // Recover by removing the name
15383 II = nullptr;
15384 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15385 D.setInvalidType(true);
15386 }
15387 }
15388 }
15389
15390 // Temporarily put parameter variables in the translation unit, not
15391 // the enclosing context. This prevents them from accidentally
15392 // looking like class members in C++.
15393 ParmVarDecl *New =
15394 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15395 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15396
15397 if (D.isInvalidType())
15398 New->setInvalidDecl();
15399
15400 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15401
15402 assert(S->isFunctionPrototypeScope());
15403 assert(S->getFunctionPrototypeDepth() >= 1);
15404 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15405 parameterIndex: S->getNextFunctionPrototypeIndex());
15406
15407 warnOnCTypeHiddenInCPlusPlus(D: New);
15408
15409 // Add the parameter declaration into this scope.
15410 S->AddDecl(D: New);
15411 if (II)
15412 IdResolver.AddDecl(D: New);
15413
15414 ProcessDeclAttributes(S, D: New, PD: D);
15415
15416 if (D.getDeclSpec().isModulePrivateSpecified())
15417 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15418 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15419 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15420
15421 if (New->hasAttr<BlocksAttr>()) {
15422 Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal);
15423 }
15424
15425 if (getLangOpts().OpenCL)
15426 deduceOpenCLAddressSpace(Decl: New);
15427
15428 return New;
15429}
15430
15431ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15432 SourceLocation Loc,
15433 QualType T) {
15434 /* FIXME: setting StartLoc == Loc.
15435 Would it be worth to modify callers so as to provide proper source
15436 location for the unnamed parameters, embedding the parameter's type? */
15437 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15438 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15439 S: SC_None, DefArg: nullptr);
15440 Param->setImplicit();
15441 return Param;
15442}
15443
15444void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15445 // Don't diagnose unused-parameter errors in template instantiations; we
15446 // will already have done so in the template itself.
15447 if (inTemplateInstantiation())
15448 return;
15449
15450 for (const ParmVarDecl *Parameter : Parameters) {
15451 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15452 !Parameter->hasAttr<UnusedAttr>() &&
15453 !Parameter->getIdentifier()->isPlaceholder()) {
15454 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15455 << Parameter->getDeclName();
15456 }
15457 }
15458}
15459
15460void Sema::DiagnoseSizeOfParametersAndReturnValue(
15461 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15462 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15463 return;
15464
15465 // Warn if the return value is pass-by-value and larger than the specified
15466 // threshold.
15467 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15468 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15469 if (Size > LangOpts.NumLargeByValueCopy)
15470 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15471 }
15472
15473 // Warn if any parameter is pass-by-value and larger than the specified
15474 // threshold.
15475 for (const ParmVarDecl *Parameter : Parameters) {
15476 QualType T = Parameter->getType();
15477 if (T->isDependentType() || !T.isPODType(Context))
15478 continue;
15479 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15480 if (Size > LangOpts.NumLargeByValueCopy)
15481 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15482 << Parameter << Size;
15483 }
15484}
15485
15486ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15487 SourceLocation NameLoc,
15488 const IdentifierInfo *Name, QualType T,
15489 TypeSourceInfo *TSInfo, StorageClass SC) {
15490 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15491 if (getLangOpts().ObjCAutoRefCount &&
15492 T.getObjCLifetime() == Qualifiers::OCL_None &&
15493 T->isObjCLifetimeType()) {
15494
15495 Qualifiers::ObjCLifetime lifetime;
15496
15497 // Special cases for arrays:
15498 // - if it's const, use __unsafe_unretained
15499 // - otherwise, it's an error
15500 if (T->isArrayType()) {
15501 if (!T.isConstQualified()) {
15502 if (DelayedDiagnostics.shouldDelayDiagnostics())
15503 DelayedDiagnostics.add(
15504 diag: sema::DelayedDiagnostic::makeForbiddenType(
15505 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15506 else
15507 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15508 << TSInfo->getTypeLoc().getSourceRange();
15509 }
15510 lifetime = Qualifiers::OCL_ExplicitNone;
15511 } else {
15512 lifetime = T->getObjCARCImplicitLifetime();
15513 }
15514 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15515 }
15516
15517 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15518 T: Context.getAdjustedParameterType(T),
15519 TInfo: TSInfo, S: SC, DefArg: nullptr);
15520
15521 // Make a note if we created a new pack in the scope of a lambda, so that
15522 // we know that references to that pack must also be expanded within the
15523 // lambda scope.
15524 if (New->isParameterPack())
15525 if (auto *CSI = getEnclosingLambdaOrBlock())
15526 CSI->LocalPacks.push_back(Elt: New);
15527
15528 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15529 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15530 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15531 UseContext: NonTrivialCUnionContext::FunctionParam,
15532 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15533
15534 // Parameter declarators cannot be interface types. All ObjC objects are
15535 // passed by reference.
15536 if (T->isObjCObjectType()) {
15537 SourceLocation TypeEndLoc =
15538 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15539 Diag(Loc: NameLoc,
15540 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15541 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15542 T = Context.getObjCObjectPointerType(OIT: T);
15543 New->setType(T);
15544 }
15545
15546 // __ptrauth is forbidden on parameters.
15547 if (T.getPointerAuth()) {
15548 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15549 New->setInvalidDecl();
15550 }
15551
15552 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15553 // duration shall not be qualified by an address-space qualifier."
15554 // Since all parameters have automatic store duration, they can not have
15555 // an address space.
15556 if (T.getAddressSpace() != LangAS::Default &&
15557 // OpenCL allows function arguments declared to be an array of a type
15558 // to be qualified with an address space.
15559 !(getLangOpts().OpenCL &&
15560 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15561 // WebAssembly allows reference types as parameters. Funcref in particular
15562 // lives in a different address space.
15563 !(T->isFunctionPointerType() &&
15564 T.getAddressSpace() == LangAS::wasm_funcref)) {
15565 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15566 New->setInvalidDecl();
15567 }
15568
15569 // PPC MMA non-pointer types are not allowed as function argument types.
15570 if (Context.getTargetInfo().getTriple().isPPC64() &&
15571 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15572 New->setInvalidDecl();
15573 }
15574
15575 return New;
15576}
15577
15578void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15579 SourceLocation LocAfterDecls) {
15580 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15581
15582 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15583 // in the declaration list shall have at least one declarator, those
15584 // declarators shall only declare identifiers from the identifier list, and
15585 // every identifier in the identifier list shall be declared.
15586 //
15587 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15588 // identifiers it names shall be declared in the declaration list."
15589 //
15590 // This is why we only diagnose in C99 and later. Note, the other conditions
15591 // listed are checked elsewhere.
15592 if (!FTI.hasPrototype) {
15593 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15594 --i;
15595 if (FTI.Params[i].Param == nullptr) {
15596 if (getLangOpts().C99) {
15597 SmallString<256> Code;
15598 llvm::raw_svector_ostream(Code)
15599 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15600 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
15601 << FTI.Params[i].Ident
15602 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
15603 }
15604
15605 // Implicitly declare the argument as type 'int' for lack of a better
15606 // type.
15607 AttributeFactory attrs;
15608 DeclSpec DS(attrs);
15609 const char* PrevSpec; // unused
15610 unsigned DiagID; // unused
15611 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15612 DiagID, Policy: Context.getPrintingPolicy());
15613 // Use the identifier location for the type source range.
15614 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15615 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15616 Declarator ParamD(DS, ParsedAttributesView::none(),
15617 DeclaratorContext::KNRTypeList);
15618 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15619 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15620 }
15621 }
15622 }
15623}
15624
15625Decl *
15626Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15627 MultiTemplateParamsArg TemplateParameterLists,
15628 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15629 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15630 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15631 Scope *ParentScope = FnBodyScope->getParent();
15632
15633 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15634 // we define a non-templated function definition, we will create a declaration
15635 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15636 // The base function declaration will have the equivalent of an `omp declare
15637 // variant` annotation which specifies the mangled definition as a
15638 // specialization function under the OpenMP context defined as part of the
15639 // `omp begin declare variant`.
15640 SmallVector<FunctionDecl *, 4> Bases;
15641 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15642 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15643 S: ParentScope, D, TemplateParameterLists, Bases);
15644
15645 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15646 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15647 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15648
15649 if (!Bases.empty())
15650 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15651 Bases);
15652
15653 return Dcl;
15654}
15655
15656void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15657 Consumer.HandleInlineFunctionDefinition(D);
15658}
15659
15660static bool FindPossiblePrototype(const FunctionDecl *FD,
15661 const FunctionDecl *&PossiblePrototype) {
15662 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15663 Prev = Prev->getPreviousDecl()) {
15664 // Ignore any declarations that occur in function or method
15665 // scope, because they aren't visible from the header.
15666 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15667 continue;
15668
15669 PossiblePrototype = Prev;
15670 return Prev->getType()->isFunctionProtoType();
15671 }
15672 return false;
15673}
15674
15675static bool
15676ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15677 const FunctionDecl *&PossiblePrototype) {
15678 // Don't warn about invalid declarations.
15679 if (FD->isInvalidDecl())
15680 return false;
15681
15682 // Or declarations that aren't global.
15683 if (!FD->isGlobal())
15684 return false;
15685
15686 // Don't warn about C++ member functions.
15687 if (isa<CXXMethodDecl>(Val: FD))
15688 return false;
15689
15690 // Don't warn about 'main'.
15691 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
15692 if (IdentifierInfo *II = FD->getIdentifier())
15693 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15694 return false;
15695
15696 if (FD->isMSVCRTEntryPoint())
15697 return false;
15698
15699 // Don't warn about inline functions.
15700 if (FD->isInlined())
15701 return false;
15702
15703 // Don't warn about function templates.
15704 if (FD->getDescribedFunctionTemplate())
15705 return false;
15706
15707 // Don't warn about function template specializations.
15708 if (FD->isFunctionTemplateSpecialization())
15709 return false;
15710
15711 // Don't warn for OpenCL kernels.
15712 if (FD->hasAttr<DeviceKernelAttr>())
15713 return false;
15714
15715 // Don't warn on explicitly deleted functions.
15716 if (FD->isDeleted())
15717 return false;
15718
15719 // Don't warn on implicitly local functions (such as having local-typed
15720 // parameters).
15721 if (!FD->isExternallyVisible())
15722 return false;
15723
15724 // If we were able to find a potential prototype, don't warn.
15725 if (FindPossiblePrototype(FD, PossiblePrototype))
15726 return false;
15727
15728 return true;
15729}
15730
15731void
15732Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15733 const FunctionDecl *EffectiveDefinition,
15734 SkipBodyInfo *SkipBody) {
15735 const FunctionDecl *Definition = EffectiveDefinition;
15736 if (!Definition &&
15737 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15738 return;
15739
15740 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15741 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15742 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15743 // A merged copy of the same function, instantiated as a member of
15744 // the same class, is OK.
15745 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
15746 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
15747 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
15748 return;
15749 }
15750 }
15751 }
15752
15753 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
15754 return;
15755
15756 // Don't emit an error when this is redefinition of a typo-corrected
15757 // definition.
15758 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
15759 return;
15760
15761 // If we don't have a visible definition of the function, and it's inline or
15762 // a template, skip the new definition.
15763 if (SkipBody && !hasVisibleDefinition(D: Definition) &&
15764 (Definition->getFormalLinkage() == Linkage::Internal ||
15765 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15766 Definition->getNumTemplateParameterLists())) {
15767 SkipBody->ShouldSkip = true;
15768 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15769 if (auto *TD = Definition->getDescribedFunctionTemplate())
15770 makeMergedDefinitionVisible(ND: TD);
15771 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl*>(Definition));
15772 return;
15773 }
15774
15775 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15776 Definition->getStorageClass() == SC_Extern)
15777 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
15778 << FD << getLangOpts().CPlusPlus;
15779 else
15780 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
15781
15782 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
15783 FD->setInvalidDecl();
15784}
15785
15786LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15787 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15788
15789 LambdaScopeInfo *LSI = PushLambdaScope();
15790 LSI->CallOperator = CallOperator;
15791 LSI->Lambda = LambdaClass;
15792 LSI->ReturnType = CallOperator->getReturnType();
15793 // When this function is called in situation where the context of the call
15794 // operator is not entered, we set AfterParameterList to false, so that
15795 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15796 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15797 // where we would set the CurContext to the lambda operator before
15798 // substituting into it. In this case the flag needs to be true such that
15799 // tryCaptureVariable can correctly handle potential captures thereof.
15800 LSI->AfterParameterList = CurContext == CallOperator;
15801
15802 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15803 // used at the point of dealing with potential captures.
15804 //
15805 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15806 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15807 // associated. (Technically, we could recover that list from their
15808 // instantiation patterns, but for now, the GLTemplateParameterList seems
15809 // unnecessary in these cases.)
15810 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15811 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15812 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15813
15814 if (LCD == LCD_None)
15815 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15816 else if (LCD == LCD_ByCopy)
15817 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15818 else if (LCD == LCD_ByRef)
15819 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15820 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15821
15822 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15823 LSI->Mutable = !CallOperator->isConst();
15824 if (CallOperator->isExplicitObjectMemberFunction())
15825 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
15826
15827 // Add the captures to the LSI so they can be noted as already
15828 // captured within tryCaptureVar.
15829 auto I = LambdaClass->field_begin();
15830 for (const auto &C : LambdaClass->captures()) {
15831 if (C.capturesVariable()) {
15832 ValueDecl *VD = C.getCapturedVar();
15833 if (VD->isInitCapture())
15834 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
15835 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15836 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
15837 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
15838 /*EllipsisLoc*/C.isPackExpansion()
15839 ? C.getEllipsisLoc() : SourceLocation(),
15840 CaptureType: I->getType(), /*Invalid*/false);
15841
15842 } else if (C.capturesThis()) {
15843 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
15844 ByCopy: C.getCaptureKind() == LCK_StarThis);
15845 } else {
15846 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
15847 CaptureType: I->getType());
15848 }
15849 ++I;
15850 }
15851 return LSI;
15852}
15853
15854Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15855 SkipBodyInfo *SkipBody,
15856 FnBodyKind BodyKind) {
15857 if (!D) {
15858 // Parsing the function declaration failed in some way. Push on a fake scope
15859 // anyway so we can try to parse the function body.
15860 PushFunctionScope();
15861 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
15862 return D;
15863 }
15864
15865 FunctionDecl *FD = nullptr;
15866
15867 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
15868 FD = FunTmpl->getTemplatedDecl();
15869 else
15870 FD = cast<FunctionDecl>(Val: D);
15871
15872 // Do not push if it is a lambda because one is already pushed when building
15873 // the lambda in ActOnStartOfLambdaDefinition().
15874 if (!isLambdaCallOperator(DC: FD))
15875 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
15876 FD);
15877
15878 // Check for defining attributes before the check for redefinition.
15879 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15880 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
15881 FD->dropAttr<AliasAttr>();
15882 FD->setInvalidDecl();
15883 }
15884 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15885 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
15886 FD->dropAttr<IFuncAttr>();
15887 FD->setInvalidDecl();
15888 }
15889 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15890 if (Context.getTargetInfo().getTriple().isAArch64() &&
15891 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
15892 !Attr->isDefaultVersion()) {
15893 // If function multi versioning disabled skip parsing function body
15894 // defined with non-default target_version attribute
15895 if (SkipBody)
15896 SkipBody->ShouldSkip = true;
15897 return nullptr;
15898 }
15899 }
15900
15901 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
15902 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15903 Ctor->isDefaultConstructor() &&
15904 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15905 // If this is an MS ABI dllexport default constructor, instantiate any
15906 // default arguments.
15907 InstantiateDefaultCtorDefaultArgs(Ctor);
15908 }
15909 }
15910
15911 // See if this is a redefinition. If 'will have body' (or similar) is already
15912 // set, then these checks were already performed when it was set.
15913 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15914 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15915 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
15916
15917 // If we're skipping the body, we're done. Don't enter the scope.
15918 if (SkipBody && SkipBody->ShouldSkip)
15919 return D;
15920 }
15921
15922 // Mark this function as "will have a body eventually". This lets users to
15923 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15924 // this function.
15925 FD->setWillHaveBody();
15926
15927 // If we are instantiating a generic lambda call operator, push
15928 // a LambdaScopeInfo onto the function stack. But use the information
15929 // that's already been calculated (ActOnLambdaExpr) to prime the current
15930 // LambdaScopeInfo.
15931 // When the template operator is being specialized, the LambdaScopeInfo,
15932 // has to be properly restored so that tryCaptureVariable doesn't try
15933 // and capture any new variables. In addition when calculating potential
15934 // captures during transformation of nested lambdas, it is necessary to
15935 // have the LSI properly restored.
15936 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
15937 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15938 // instantiated, explicitly specialized.
15939 if (FD->getTemplateSpecializationInfo()
15940 ->isExplicitInstantiationOrSpecialization()) {
15941 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec);
15942 FD->setInvalidDecl();
15943 PushFunctionScope();
15944 } else {
15945 assert(inTemplateInstantiation() &&
15946 "There should be an active template instantiation on the stack "
15947 "when instantiating a generic lambda!");
15948 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
15949 }
15950 } else {
15951 // Enter a new function scope
15952 PushFunctionScope();
15953 }
15954
15955 // Builtin functions cannot be defined.
15956 if (unsigned BuiltinID = FD->getBuiltinID()) {
15957 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
15958 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
15959 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
15960 FD->setInvalidDecl();
15961 }
15962 }
15963
15964 // The return type of a function definition must be complete (C99 6.9.1p3).
15965 // C++23 [dcl.fct.def.general]/p2
15966 // The type of [...] the return for a function definition
15967 // shall not be a (possibly cv-qualified) class type that is incomplete
15968 // or abstract within the function body unless the function is deleted.
15969 QualType ResultType = FD->getReturnType();
15970 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15971 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15972 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
15973 DiagID: diag::err_func_def_incomplete_result) ||
15974 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
15975 DiagID: diag::err_abstract_type_in_decl,
15976 Args: AbstractReturnType)))
15977 FD->setInvalidDecl();
15978
15979 if (FnBodyScope)
15980 PushDeclContext(S: FnBodyScope, DC: FD);
15981
15982 // Check the validity of our function parameters
15983 if (BodyKind != FnBodyKind::Delete)
15984 CheckParmsForFunctionDef(Parameters: FD->parameters(),
15985 /*CheckParameterNames=*/true);
15986
15987 // Add non-parameter declarations already in the function to the current
15988 // scope.
15989 if (FnBodyScope) {
15990 for (Decl *NPD : FD->decls()) {
15991 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
15992 if (!NonParmDecl)
15993 continue;
15994 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15995 "parameters should not be in newly created FD yet");
15996
15997 // If the decl has a name, make it accessible in the current scope.
15998 if (NonParmDecl->getDeclName())
15999 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16000
16001 // Similarly, dive into enums and fish their constants out, making them
16002 // accessible in this scope.
16003 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16004 for (auto *EI : ED->enumerators())
16005 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16006 }
16007 }
16008 }
16009
16010 // Introduce our parameters into the function scope
16011 for (auto *Param : FD->parameters()) {
16012 Param->setOwningFunction(FD);
16013
16014 // If this has an identifier, add it to the scope stack.
16015 if (Param->getIdentifier() && FnBodyScope) {
16016 CheckShadow(S: FnBodyScope, D: Param);
16017
16018 PushOnScopeChains(D: Param, S: FnBodyScope);
16019 }
16020 }
16021
16022 // C++ [module.import/6] external definitions are not permitted in header
16023 // units. Deleted and Defaulted functions are implicitly inline (but the
16024 // inline state is not set at this point, so check the BodyKind explicitly).
16025 // FIXME: Consider an alternate location for the test where the inlined()
16026 // state is complete.
16027 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16028 !FD->isInvalidDecl() && !FD->isInlined() &&
16029 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16030 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16031 !FD->isTemplateInstantiation()) {
16032 assert(FD->isThisDeclarationADefinition());
16033 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16034 FD->setInvalidDecl();
16035 }
16036
16037 // Ensure that the function's exception specification is instantiated.
16038 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16039 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16040
16041 // dllimport cannot be applied to non-inline function definitions.
16042 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16043 !FD->isTemplateInstantiation()) {
16044 assert(!FD->hasAttr<DLLExportAttr>());
16045 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16046 FD->setInvalidDecl();
16047 return D;
16048 }
16049
16050 // Some function attributes (like OptimizeNoneAttr) need actions before
16051 // parsing body started.
16052 applyFunctionAttributesBeforeParsingBody(FD: D);
16053
16054 // We want to attach documentation to original Decl (which might be
16055 // a function template).
16056 ActOnDocumentableDecl(D);
16057 if (getCurLexicalContext()->isObjCContainer() &&
16058 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16059 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16060 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16061
16062 maybeAddDeclWithEffects(D: FD);
16063
16064 return D;
16065}
16066
16067void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16068 if (!FD || FD->isInvalidDecl())
16069 return;
16070 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16071 FD = TD->getTemplatedDecl();
16072 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16073 FPOptionsOverride FPO;
16074 FPO.setDisallowOptimizations();
16075 CurFPFeatures.applyChanges(FPO);
16076 FpPragmaStack.CurrentValue =
16077 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16078 }
16079}
16080
16081void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16082 ReturnStmt **Returns = Scope->Returns.data();
16083
16084 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16085 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16086 if (!NRVOCandidate->isNRVOVariable()) {
16087 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16088 DiagID: diag::warn_not_eliding_copy_on_return);
16089 Returns[I]->setNRVOCandidate(nullptr);
16090 }
16091 }
16092 }
16093}
16094
16095bool Sema::canDelayFunctionBody(const Declarator &D) {
16096 // We can't delay parsing the body of a constexpr function template (yet).
16097 if (D.getDeclSpec().hasConstexprSpecifier())
16098 return false;
16099
16100 // We can't delay parsing the body of a function template with a deduced
16101 // return type (yet).
16102 if (D.getDeclSpec().hasAutoTypeSpec()) {
16103 // If the placeholder introduces a non-deduced trailing return type,
16104 // we can still delay parsing it.
16105 if (D.getNumTypeObjects()) {
16106 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16107 if (Outer.Kind == DeclaratorChunk::Function &&
16108 Outer.Fun.hasTrailingReturnType()) {
16109 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16110 return Ty.isNull() || !Ty->isUndeducedType();
16111 }
16112 }
16113 return false;
16114 }
16115
16116 return true;
16117}
16118
16119bool Sema::canSkipFunctionBody(Decl *D) {
16120 // We cannot skip the body of a function (or function template) which is
16121 // constexpr, since we may need to evaluate its body in order to parse the
16122 // rest of the file.
16123 // We cannot skip the body of a function with an undeduced return type,
16124 // because any callers of that function need to know the type.
16125 if (const FunctionDecl *FD = D->getAsFunction()) {
16126 if (FD->isConstexpr())
16127 return false;
16128 // We can't simply call Type::isUndeducedType here, because inside template
16129 // auto can be deduced to a dependent type, which is not considered
16130 // "undeduced".
16131 if (FD->getReturnType()->getContainedDeducedType())
16132 return false;
16133 }
16134 return Consumer.shouldSkipFunctionBody(D);
16135}
16136
16137Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16138 if (!Decl)
16139 return nullptr;
16140 if (FunctionDecl *FD = Decl->getAsFunction())
16141 FD->setHasSkippedBody();
16142 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16143 MD->setHasSkippedBody();
16144 return Decl;
16145}
16146
16147Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
16148 return ActOnFinishFunctionBody(Decl: D, Body: BodyArg, /*IsInstantiation=*/false);
16149}
16150
16151/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16152/// body.
16153class ExitFunctionBodyRAII {
16154public:
16155 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16156 ~ExitFunctionBodyRAII() {
16157 if (!IsLambda)
16158 S.PopExpressionEvaluationContext();
16159 }
16160
16161private:
16162 Sema &S;
16163 bool IsLambda = false;
16164};
16165
16166static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16167 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16168
16169 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16170 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16171 if (!Inserted)
16172 return It->second;
16173
16174 bool R = false;
16175 const BlockDecl *CurBD = BD;
16176
16177 do {
16178 R = !CurBD->doesNotEscape();
16179 if (R)
16180 break;
16181 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16182 } while (CurBD);
16183
16184 return It->second = R;
16185 };
16186
16187 // If the location where 'self' is implicitly retained is inside a escaping
16188 // block, emit a diagnostic.
16189 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16190 S.ImplicitlyRetainedSelfLocs)
16191 if (IsOrNestedInEscapingBlock(P.second))
16192 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16193 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16194}
16195
16196static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16197 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16198 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16199}
16200
16201bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16202 return methodHasName(FD, Name: "get_return_object");
16203}
16204
16205bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16206 return FD->isStatic() &&
16207 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16208}
16209
16210void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16211 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16212 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16213 return;
16214 // Allow some_promise_type::get_return_object().
16215 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16216 return;
16217 if (!FD->hasAttr<CoroWrapperAttr>())
16218 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16219}
16220
16221Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
16222 bool IsInstantiation) {
16223 FunctionScopeInfo *FSI = getCurFunction();
16224 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16225
16226 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16227 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16228
16229 SourceLocation AnalysisLoc;
16230 if (Body)
16231 AnalysisLoc = Body->getEndLoc();
16232 else if (FD)
16233 AnalysisLoc = FD->getEndLoc();
16234 sema::AnalysisBasedWarnings::Policy WP =
16235 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16236 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16237
16238 // If we skip function body, we can't tell if a function is a coroutine.
16239 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16240 if (FSI->isCoroutine())
16241 CheckCompletedCoroutineBody(FD, Body);
16242 else
16243 CheckCoroutineWrapper(FD);
16244 }
16245
16246 // Diagnose invalid SYCL kernel entry point function declarations
16247 // and build SYCLKernelCallStmts for valid ones.
16248 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16249 SYCLKernelEntryPointAttr *SKEPAttr =
16250 FD->getAttr<SYCLKernelEntryPointAttr>();
16251 if (FD->isDefaulted()) {
16252 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16253 << /*defaulted function*/ 3;
16254 SKEPAttr->setInvalidAttr();
16255 } else if (FD->isDeleted()) {
16256 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16257 << /*deleted function*/ 2;
16258 SKEPAttr->setInvalidAttr();
16259 } else if (FSI->isCoroutine()) {
16260 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16261 << /*coroutine*/ 7;
16262 SKEPAttr->setInvalidAttr();
16263 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16264 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16265 << /*function defined with a function try block*/ 8;
16266 SKEPAttr->setInvalidAttr();
16267 }
16268
16269 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16270 StmtResult SR =
16271 SYCL().BuildSYCLKernelCallStmt(FD, Body: cast<CompoundStmt>(Val: Body));
16272 if (SR.isInvalid())
16273 return nullptr;
16274 Body = SR.get();
16275 }
16276 }
16277
16278 {
16279 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16280 // one is already popped when finishing the lambda in BuildLambdaExpr().
16281 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16282 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16283 if (FD) {
16284 // The function body and the DefaultedOrDeletedInfo, if present, use
16285 // the same storage; don't overwrite the latter if the former is null
16286 // (the body is initialised to null anyway, so even if the latter isn't
16287 // present, this would still be a no-op).
16288 if (Body)
16289 FD->setBody(Body);
16290 FD->setWillHaveBody(false);
16291
16292 if (getLangOpts().CPlusPlus14) {
16293 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16294 FD->getReturnType()->isUndeducedType()) {
16295 // For a function with a deduced result type to return void,
16296 // the result type as written must be 'auto' or 'decltype(auto)',
16297 // possibly cv-qualified or constrained, but not ref-qualified.
16298 if (!FD->getReturnType()->getAs<AutoType>()) {
16299 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16300 << FD->getReturnType();
16301 FD->setInvalidDecl();
16302 } else {
16303 // Falling off the end of the function is the same as 'return;'.
16304 Expr *Dummy = nullptr;
16305 if (DeduceFunctionTypeFromReturnExpr(
16306 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16307 AT: FD->getReturnType()->getAs<AutoType>()))
16308 FD->setInvalidDecl();
16309 }
16310 }
16311 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16312 // In C++11, we don't use 'auto' deduction rules for lambda call
16313 // operators because we don't support return type deduction.
16314 auto *LSI = getCurLambda();
16315 if (LSI->HasImplicitReturnType) {
16316 deduceClosureReturnType(CSI&: *LSI);
16317
16318 // C++11 [expr.prim.lambda]p4:
16319 // [...] if there are no return statements in the compound-statement
16320 // [the deduced type is] the type void
16321 QualType RetType =
16322 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16323
16324 // Update the return type to the deduced type.
16325 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16326 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16327 EPI: Proto->getExtProtoInfo()));
16328 }
16329 }
16330
16331 // If the function implicitly returns zero (like 'main') or is naked,
16332 // don't complain about missing return statements.
16333 // Clang implicitly returns 0 in C89 mode, but that's considered an
16334 // extension. The check is necessary to ensure the expected extension
16335 // warning is emitted in C89 mode.
16336 if ((FD->hasImplicitReturnZero() &&
16337 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16338 FD->hasAttr<NakedAttr>())
16339 WP.disableCheckFallThrough();
16340
16341 // MSVC permits the use of pure specifier (=0) on function definition,
16342 // defined at class scope, warn about this non-standard construct.
16343 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16344 !FD->isOutOfLine())
16345 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16346
16347 if (!FD->isInvalidDecl()) {
16348 // Don't diagnose unused parameters of defaulted, deleted or naked
16349 // functions.
16350 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16351 !FD->hasAttr<NakedAttr>())
16352 DiagnoseUnusedParameters(Parameters: FD->parameters());
16353 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16354 ReturnTy: FD->getReturnType(), D: FD);
16355
16356 // If this is a structor, we need a vtable.
16357 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16358 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16359 else if (CXXDestructorDecl *Destructor =
16360 dyn_cast<CXXDestructorDecl>(Val: FD))
16361 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16362
16363 // Try to apply the named return value optimization. We have to check
16364 // if we can do this here because lambdas keep return statements around
16365 // to deduce an implicit return type.
16366 if (FD->getReturnType()->isRecordType() &&
16367 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16368 computeNRVO(Body, Scope: FSI);
16369 }
16370
16371 // GNU warning -Wmissing-prototypes:
16372 // Warn if a global function is defined without a previous
16373 // prototype declaration. This warning is issued even if the
16374 // definition itself provides a prototype. The aim is to detect
16375 // global functions that fail to be declared in header files.
16376 const FunctionDecl *PossiblePrototype = nullptr;
16377 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16378 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16379
16380 if (PossiblePrototype) {
16381 // We found a declaration that is not a prototype,
16382 // but that could be a zero-parameter prototype
16383 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16384 TypeLoc TL = TI->getTypeLoc();
16385 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16386 Diag(Loc: PossiblePrototype->getLocation(),
16387 DiagID: diag::note_declaration_not_a_prototype)
16388 << (FD->getNumParams() != 0)
16389 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16390 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16391 : FixItHint{});
16392 }
16393 } else {
16394 // Returns true if the token beginning at this Loc is `const`.
16395 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16396 const LangOptions &LangOpts) {
16397 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16398 if (LocInfo.first.isInvalid())
16399 return false;
16400
16401 bool Invalid = false;
16402 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16403 if (Invalid)
16404 return false;
16405
16406 if (LocInfo.second > Buffer.size())
16407 return false;
16408
16409 const char *LexStart = Buffer.data() + LocInfo.second;
16410 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16411
16412 return StartTok.consume_front(Prefix: "const") &&
16413 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16414 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16415 };
16416
16417 auto findBeginLoc = [&]() {
16418 // If the return type has `const` qualifier, we want to insert
16419 // `static` before `const` (and not before the typename).
16420 if ((FD->getReturnType()->isAnyPointerType() &&
16421 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16422 FD->getReturnType().isConstQualified()) {
16423 // But only do this if we can determine where the `const` is.
16424
16425 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16426 getLangOpts()))
16427
16428 return FD->getBeginLoc();
16429 }
16430 return FD->getTypeSpecStartLoc();
16431 };
16432 Diag(Loc: FD->getTypeSpecStartLoc(),
16433 DiagID: diag::note_static_for_internal_linkage)
16434 << /* function */ 1
16435 << (FD->getStorageClass() == SC_None
16436 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16437 : FixItHint{});
16438 }
16439 }
16440
16441 // We might not have found a prototype because we didn't wish to warn on
16442 // the lack of a missing prototype. Try again without the checks for
16443 // whether we want to warn on the missing prototype.
16444 if (!PossiblePrototype)
16445 (void)FindPossiblePrototype(FD, PossiblePrototype);
16446
16447 // If the function being defined does not have a prototype, then we may
16448 // need to diagnose it as changing behavior in C23 because we now know
16449 // whether the function accepts arguments or not. This only handles the
16450 // case where the definition has no prototype but does have parameters
16451 // and either there is no previous potential prototype, or the previous
16452 // potential prototype also has no actual prototype. This handles cases
16453 // like:
16454 // void f(); void f(a) int a; {}
16455 // void g(a) int a; {}
16456 // See MergeFunctionDecl() for other cases of the behavior change
16457 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16458 // type without a prototype.
16459 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16460 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16461 !PossiblePrototype->isImplicit()))) {
16462 // The function definition has parameters, so this will change behavior
16463 // in C23. If there is a possible prototype, it comes before the
16464 // function definition.
16465 // FIXME: The declaration may have already been diagnosed as being
16466 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16467 // there's no way to test for the "changes behavior" condition in
16468 // SemaType.cpp when forming the declaration's function type. So, we do
16469 // this awkward dance instead.
16470 //
16471 // If we have a possible prototype and it declares a function with a
16472 // prototype, we don't want to diagnose it; if we have a possible
16473 // prototype and it has no prototype, it may have already been
16474 // diagnosed in SemaType.cpp as deprecated depending on whether
16475 // -Wstrict-prototypes is enabled. If we already warned about it being
16476 // deprecated, add a note that it also changes behavior. If we didn't
16477 // warn about it being deprecated (because the diagnostic is not
16478 // enabled), warn now that it is deprecated and changes behavior.
16479
16480 // This K&R C function definition definitely changes behavior in C23,
16481 // so diagnose it.
16482 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16483 << /*definition*/ 1 << /* not supported in C23 */ 0;
16484
16485 // If we have a possible prototype for the function which is a user-
16486 // visible declaration, we already tested that it has no prototype.
16487 // This will change behavior in C23. This gets a warning rather than a
16488 // note because it's the same behavior-changing problem as with the
16489 // definition.
16490 if (PossiblePrototype)
16491 Diag(Loc: PossiblePrototype->getLocation(),
16492 DiagID: diag::warn_non_prototype_changes_behavior)
16493 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16494 << /*definition*/ 1;
16495 }
16496
16497 // Warn on CPUDispatch with an actual body.
16498 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16499 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16500 if (!CmpndBody->body_empty())
16501 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16502 DiagID: diag::warn_dispatch_body_ignored);
16503
16504 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16505 const CXXMethodDecl *KeyFunction;
16506 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16507 MD->isVirtual() &&
16508 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16509 MD == KeyFunction->getCanonicalDecl()) {
16510 // Update the key-function state if necessary for this ABI.
16511 if (FD->isInlined() &&
16512 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16513 Context.setNonKeyFunction(MD);
16514
16515 // If the newly-chosen key function is already defined, then we
16516 // need to mark the vtable as used retroactively.
16517 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16518 const FunctionDecl *Definition;
16519 if (KeyFunction && KeyFunction->isDefined(Definition))
16520 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16521 } else {
16522 // We just defined they key function; mark the vtable as used.
16523 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16524 }
16525 }
16526 }
16527
16528 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16529 "Function parsing confused");
16530 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16531 assert(MD == getCurMethodDecl() && "Method parsing confused");
16532 MD->setBody(Body);
16533 if (!MD->isInvalidDecl()) {
16534 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
16535 ReturnTy: MD->getReturnType(), D: MD);
16536
16537 if (Body)
16538 computeNRVO(Body, Scope: FSI);
16539 }
16540 if (FSI->ObjCShouldCallSuper) {
16541 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
16542 << MD->getSelector().getAsString();
16543 FSI->ObjCShouldCallSuper = false;
16544 }
16545 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16546 const ObjCMethodDecl *InitMethod = nullptr;
16547 bool isDesignated =
16548 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16549 assert(isDesignated && InitMethod);
16550 (void)isDesignated;
16551
16552 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16553 auto IFace = MD->getClassInterface();
16554 if (!IFace)
16555 return false;
16556 auto SuperD = IFace->getSuperClass();
16557 if (!SuperD)
16558 return false;
16559 return SuperD->getIdentifier() ==
16560 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
16561 };
16562 // Don't issue this warning for unavailable inits or direct subclasses
16563 // of NSObject.
16564 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16565 Diag(Loc: MD->getLocation(),
16566 DiagID: diag::warn_objc_designated_init_missing_super_call);
16567 Diag(Loc: InitMethod->getLocation(),
16568 DiagID: diag::note_objc_designated_init_marked_here);
16569 }
16570 FSI->ObjCWarnForNoDesignatedInitChain = false;
16571 }
16572 if (FSI->ObjCWarnForNoInitDelegation) {
16573 // Don't issue this warning for unavailable inits.
16574 if (!MD->isUnavailable())
16575 Diag(Loc: MD->getLocation(),
16576 DiagID: diag::warn_objc_secondary_init_missing_init_call);
16577 FSI->ObjCWarnForNoInitDelegation = false;
16578 }
16579
16580 diagnoseImplicitlyRetainedSelf(S&: *this);
16581 } else {
16582 // Parsing the function declaration failed in some way. Pop the fake scope
16583 // we pushed on.
16584 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16585 return nullptr;
16586 }
16587
16588 if (Body && FSI->HasPotentialAvailabilityViolations)
16589 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16590
16591 assert(!FSI->ObjCShouldCallSuper &&
16592 "This should only be set for ObjC methods, which should have been "
16593 "handled in the block above.");
16594
16595 // Verify and clean out per-function state.
16596 if (Body && (!FD || !FD->isDefaulted())) {
16597 // C++ constructors that have function-try-blocks can't have return
16598 // statements in the handlers of that block. (C++ [except.handle]p14)
16599 // Verify this.
16600 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16601 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16602
16603 // Verify that gotos and switch cases don't jump into scopes illegally.
16604 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16605 DiagnoseInvalidJumps(Body);
16606
16607 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16608 if (!Destructor->getParent()->isDependentType())
16609 CheckDestructor(Destructor);
16610
16611 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16612 Record: Destructor->getParent());
16613 }
16614
16615 // If any errors have occurred, clear out any temporaries that may have
16616 // been leftover. This ensures that these temporaries won't be picked up
16617 // for deletion in some later function.
16618 if (hasUncompilableErrorOccurred() ||
16619 hasAnyUnrecoverableErrorsInThisFunction() ||
16620 getDiagnostics().getSuppressAllDiagnostics()) {
16621 DiscardCleanupsInEvaluationContext();
16622 }
16623 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16624 // Since the body is valid, issue any analysis-based warnings that are
16625 // enabled.
16626 ActivePolicy = &WP;
16627 }
16628
16629 if (!IsInstantiation && FD &&
16630 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16631 !FD->isInvalidDecl() &&
16632 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
16633 FD->setInvalidDecl();
16634
16635 if (FD && FD->hasAttr<NakedAttr>()) {
16636 for (const Stmt *S : Body->children()) {
16637 // Allow local register variables without initializer as they don't
16638 // require prologue.
16639 bool RegisterVariables = false;
16640 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16641 for (const auto *Decl : DS->decls()) {
16642 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16643 RegisterVariables =
16644 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16645 if (!RegisterVariables)
16646 break;
16647 }
16648 }
16649 }
16650 if (RegisterVariables)
16651 continue;
16652 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16653 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
16654 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
16655 FD->setInvalidDecl();
16656 break;
16657 }
16658 }
16659 }
16660
16661 assert(ExprCleanupObjects.size() ==
16662 ExprEvalContexts.back().NumCleanupObjects &&
16663 "Leftover temporaries in function");
16664 assert(!Cleanup.exprNeedsCleanups() &&
16665 "Unaccounted cleanups in function");
16666 assert(MaybeODRUseExprs.empty() &&
16667 "Leftover expressions for odr-use checking");
16668 }
16669 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16670 // the declaration context below. Otherwise, we're unable to transform
16671 // 'this' expressions when transforming immediate context functions.
16672
16673 if (FD)
16674 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
16675
16676 if (!IsInstantiation)
16677 PopDeclContext();
16678
16679 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16680 // If any errors have occurred, clear out any temporaries that may have
16681 // been leftover. This ensures that these temporaries won't be picked up for
16682 // deletion in some later function.
16683 if (hasUncompilableErrorOccurred()) {
16684 DiscardCleanupsInEvaluationContext();
16685 }
16686
16687 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16688 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16689 auto ES = getEmissionStatus(Decl: FD);
16690 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16691 ES == Sema::FunctionEmissionStatus::Unknown)
16692 DeclsToCheckForDeferredDiags.insert(X: FD);
16693 }
16694
16695 if (FD && !FD->isDeleted())
16696 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16697
16698 return dcl;
16699}
16700
16701/// When we finish delayed parsing of an attribute, we must attach it to the
16702/// relevant Decl.
16703void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16704 ParsedAttributes &Attrs) {
16705 // Always attach attributes to the underlying decl.
16706 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
16707 D = TD->getTemplatedDecl();
16708 ProcessDeclAttributeList(S, D, AttrList: Attrs);
16709 ProcessAPINotes(D);
16710
16711 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
16712 if (Method->isStatic())
16713 checkThisInStaticMemberFunctionAttributes(Method);
16714}
16715
16716NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16717 IdentifierInfo &II, Scope *S) {
16718 // It is not valid to implicitly define a function in C23.
16719 assert(LangOpts.implicitFunctionsAllowed() &&
16720 "Implicit function declarations aren't allowed in this language mode");
16721
16722 // Find the scope in which the identifier is injected and the corresponding
16723 // DeclContext.
16724 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16725 // In that case, we inject the declaration into the translation unit scope
16726 // instead.
16727 Scope *BlockScope = S;
16728 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16729 BlockScope = BlockScope->getParent();
16730
16731 // Loop until we find a DeclContext that is either a function/method or the
16732 // translation unit, which are the only two valid places to implicitly define
16733 // a function. This avoids accidentally defining the function within a tag
16734 // declaration, for example.
16735 Scope *ContextScope = BlockScope;
16736 while (!ContextScope->getEntity() ||
16737 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16738 !ContextScope->getEntity()->isTranslationUnit()))
16739 ContextScope = ContextScope->getParent();
16740 ContextRAII SavedContext(*this, ContextScope->getEntity());
16741
16742 // Before we produce a declaration for an implicitly defined
16743 // function, see whether there was a locally-scoped declaration of
16744 // this name as a function or variable. If so, use that
16745 // (non-visible) declaration, and complain about it.
16746 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
16747 if (ExternCPrev) {
16748 // We still need to inject the function into the enclosing block scope so
16749 // that later (non-call) uses can see it.
16750 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
16751
16752 // C89 footnote 38:
16753 // If in fact it is not defined as having type "function returning int",
16754 // the behavior is undefined.
16755 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
16756 !Context.typesAreCompatible(
16757 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
16758 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
16759 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
16760 << ExternCPrev << !getLangOpts().C99;
16761 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
16762 return ExternCPrev;
16763 }
16764 }
16765
16766 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16767 unsigned diag_id;
16768 if (II.getName().starts_with(Prefix: "__builtin_"))
16769 diag_id = diag::warn_builtin_unknown;
16770 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16771 else if (getLangOpts().C99)
16772 diag_id = diag::ext_implicit_function_decl_c99;
16773 else
16774 diag_id = diag::warn_implicit_function_decl;
16775
16776 TypoCorrection Corrected;
16777 // Because typo correction is expensive, only do it if the implicit
16778 // function declaration is going to be treated as an error.
16779 //
16780 // Perform the correction before issuing the main diagnostic, as some
16781 // consumers use typo-correction callbacks to enhance the main diagnostic.
16782 if (S && !ExternCPrev &&
16783 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
16784 DeclFilterCCC<FunctionDecl> CCC{};
16785 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
16786 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
16787 }
16788
16789 Diag(Loc, DiagID: diag_id) << &II;
16790 if (Corrected) {
16791 // If the correction is going to suggest an implicitly defined function,
16792 // skip the correction as not being a particularly good idea.
16793 bool Diagnose = true;
16794 if (const auto *D = Corrected.getCorrectionDecl())
16795 Diagnose = !D->isImplicit();
16796 if (Diagnose)
16797 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
16798 /*ErrorRecovery*/ false);
16799 }
16800
16801 // If we found a prior declaration of this function, don't bother building
16802 // another one. We've already pushed that one into scope, so there's nothing
16803 // more to do.
16804 if (ExternCPrev)
16805 return ExternCPrev;
16806
16807 // Set a Declarator for the implicit definition: int foo();
16808 const char *Dummy;
16809 AttributeFactory attrFactory;
16810 DeclSpec DS(attrFactory);
16811 unsigned DiagID;
16812 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
16813 Policy: Context.getPrintingPolicy());
16814 (void)Error; // Silence warning.
16815 assert(!Error && "Error setting up implicit decl!");
16816 SourceLocation NoLoc;
16817 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16818 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
16819 /*IsAmbiguous=*/false,
16820 /*LParenLoc=*/NoLoc,
16821 /*Params=*/nullptr,
16822 /*NumParams=*/0,
16823 /*EllipsisLoc=*/NoLoc,
16824 /*RParenLoc=*/NoLoc,
16825 /*RefQualifierIsLvalueRef=*/true,
16826 /*RefQualifierLoc=*/NoLoc,
16827 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
16828 /*ESpecRange=*/SourceRange(),
16829 /*Exceptions=*/nullptr,
16830 /*ExceptionRanges=*/nullptr,
16831 /*NumExceptions=*/0,
16832 /*NoexceptExpr=*/nullptr,
16833 /*ExceptionSpecTokens=*/nullptr,
16834 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
16835 TheDeclarator&: D),
16836 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
16837 D.SetIdentifier(Id: &II, IdLoc: Loc);
16838
16839 // Insert this function into the enclosing block scope.
16840 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
16841 FD->setImplicit();
16842
16843 AddKnownFunctionAttributes(FD);
16844
16845 return FD;
16846}
16847
16848void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16849 FunctionDecl *FD) {
16850 if (FD->isInvalidDecl())
16851 return;
16852
16853 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16854 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16855 return;
16856
16857 UnsignedOrNone AlignmentParam = std::nullopt;
16858 bool IsNothrow = false;
16859 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
16860 return;
16861
16862 // C++2a [basic.stc.dynamic.allocation]p4:
16863 // An allocation function that has a non-throwing exception specification
16864 // indicates failure by returning a null pointer value. Any other allocation
16865 // function never returns a null pointer value and indicates failure only by
16866 // throwing an exception [...]
16867 //
16868 // However, -fcheck-new invalidates this possible assumption, so don't add
16869 // NonNull when that is enabled.
16870 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16871 !getLangOpts().CheckNew)
16872 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
16873
16874 // C++2a [basic.stc.dynamic.allocation]p2:
16875 // An allocation function attempts to allocate the requested amount of
16876 // storage. [...] If the request succeeds, the value returned by a
16877 // replaceable allocation function is a [...] pointer value p0 different
16878 // from any previously returned value p1 [...]
16879 //
16880 // However, this particular information is being added in codegen,
16881 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16882
16883 // C++2a [basic.stc.dynamic.allocation]p2:
16884 // An allocation function attempts to allocate the requested amount of
16885 // storage. If it is successful, it returns the address of the start of a
16886 // block of storage whose length in bytes is at least as large as the
16887 // requested size.
16888 if (!FD->hasAttr<AllocSizeAttr>()) {
16889 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
16890 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16891 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
16892 }
16893
16894 // C++2a [basic.stc.dynamic.allocation]p3:
16895 // For an allocation function [...], the pointer returned on a successful
16896 // call shall represent the address of storage that is aligned as follows:
16897 // (3.1) If the allocation function takes an argument of type
16898 // std​::​align_­val_­t, the storage will have the alignment
16899 // specified by the value of this argument.
16900 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16901 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
16902 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
16903 }
16904
16905 // FIXME:
16906 // C++2a [basic.stc.dynamic.allocation]p3:
16907 // For an allocation function [...], the pointer returned on a successful
16908 // call shall represent the address of storage that is aligned as follows:
16909 // (3.2) Otherwise, if the allocation function is named operator new[],
16910 // the storage is aligned for any object that does not have
16911 // new-extended alignment ([basic.align]) and is no larger than the
16912 // requested size.
16913 // (3.3) Otherwise, the storage is aligned for any object that does not
16914 // have new-extended alignment and is of the requested size.
16915}
16916
16917void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16918 if (FD->isInvalidDecl())
16919 return;
16920
16921 // If this is a built-in function, map its builtin attributes to
16922 // actual attributes.
16923 if (unsigned BuiltinID = FD->getBuiltinID()) {
16924 // Handle printf-formatting attributes.
16925 unsigned FormatIdx;
16926 bool HasVAListArg;
16927 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
16928 if (!FD->hasAttr<FormatAttr>()) {
16929 const char *fmt = "printf";
16930 unsigned int NumParams = FD->getNumParams();
16931 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16932 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
16933 fmt = "NSString";
16934 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
16935 Type: &Context.Idents.get(Name: fmt),
16936 FormatIdx: FormatIdx+1,
16937 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
16938 Range: FD->getLocation()));
16939 }
16940 }
16941 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
16942 HasVAListArg)) {
16943 if (!FD->hasAttr<FormatAttr>())
16944 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
16945 Type: &Context.Idents.get(Name: "scanf"),
16946 FormatIdx: FormatIdx+1,
16947 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
16948 Range: FD->getLocation()));
16949 }
16950
16951 // Handle automatically recognized callbacks.
16952 SmallVector<int, 4> Encoding;
16953 if (!FD->hasAttr<CallbackAttr>() &&
16954 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
16955 FD->addAttr(A: CallbackAttr::CreateImplicit(
16956 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
16957
16958 // Mark const if we don't care about errno and/or floating point exceptions
16959 // that are the only thing preventing the function from being const. This
16960 // allows IRgen to use LLVM intrinsics for such functions.
16961 bool NoExceptions =
16962 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16963 bool ConstWithoutErrnoAndExceptions =
16964 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
16965 bool ConstWithoutExceptions =
16966 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
16967 if (!FD->hasAttr<ConstAttr>() &&
16968 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16969 (!ConstWithoutErrnoAndExceptions ||
16970 (!getLangOpts().MathErrno && NoExceptions)) &&
16971 (!ConstWithoutExceptions || NoExceptions))
16972 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
16973
16974 // We make "fma" on GNU or Windows const because we know it does not set
16975 // errno in those environments even though it could set errno based on the
16976 // C standard.
16977 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16978 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16979 !FD->hasAttr<ConstAttr>()) {
16980 switch (BuiltinID) {
16981 case Builtin::BI__builtin_fma:
16982 case Builtin::BI__builtin_fmaf:
16983 case Builtin::BI__builtin_fmal:
16984 case Builtin::BIfma:
16985 case Builtin::BIfmaf:
16986 case Builtin::BIfmal:
16987 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
16988 break;
16989 default:
16990 break;
16991 }
16992 }
16993
16994 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
16995 !FD->hasAttr<ReturnsTwiceAttr>())
16996 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
16997 Range: FD->getLocation()));
16998 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16999 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17000 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17001 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17002 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17003 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17004 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17005 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17006 // Add the appropriate attribute, depending on the CUDA compilation mode
17007 // and which target the builtin belongs to. For example, during host
17008 // compilation, aux builtins are __device__, while the rest are __host__.
17009 if (getLangOpts().CUDAIsDevice !=
17010 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17011 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17012 else
17013 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17014 }
17015
17016 // Add known guaranteed alignment for allocation functions.
17017 switch (BuiltinID) {
17018 case Builtin::BImemalign:
17019 case Builtin::BIaligned_alloc:
17020 if (!FD->hasAttr<AllocAlignAttr>())
17021 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17022 Range: FD->getLocation()));
17023 break;
17024 default:
17025 break;
17026 }
17027
17028 // Add allocsize attribute for allocation functions.
17029 switch (BuiltinID) {
17030 case Builtin::BIcalloc:
17031 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17032 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17033 break;
17034 case Builtin::BImemalign:
17035 case Builtin::BIaligned_alloc:
17036 case Builtin::BIrealloc:
17037 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17038 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17039 break;
17040 case Builtin::BImalloc:
17041 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17042 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17043 break;
17044 default:
17045 break;
17046 }
17047 }
17048
17049 LazyProcessLifetimeCaptureByParams(FD);
17050 inferLifetimeBoundAttribute(FD);
17051 inferLifetimeCaptureByAttribute(FD);
17052 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17053
17054 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17055 // throw, add an implicit nothrow attribute to any extern "C" function we come
17056 // across.
17057 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17058 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17059 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17060 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17061 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17062 }
17063
17064 IdentifierInfo *Name = FD->getIdentifier();
17065 if (!Name)
17066 return;
17067 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17068 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17069 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17070 LinkageSpecLanguageIDs::C)) {
17071 // Okay: this could be a libc/libm/Objective-C function we know
17072 // about.
17073 } else
17074 return;
17075
17076 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17077 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17078 // target-specific builtins, perhaps?
17079 if (!FD->hasAttr<FormatAttr>())
17080 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17081 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17082 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17083 Range: FD->getLocation()));
17084 }
17085
17086 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17087 // We already have a __builtin___CFStringMakeConstantString,
17088 // but builds that use -fno-constant-cfstrings don't go through that.
17089 if (!FD->hasAttr<FormatArgAttr>())
17090 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17091 Range: FD->getLocation()));
17092 }
17093}
17094
17095TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17096 TypeSourceInfo *TInfo) {
17097 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17098 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17099
17100 if (!TInfo) {
17101 assert(D.isInvalidType() && "no declarator info for valid type");
17102 TInfo = Context.getTrivialTypeSourceInfo(T);
17103 }
17104
17105 // Scope manipulation handled by caller.
17106 TypedefDecl *NewTD =
17107 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17108 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17109
17110 // Bail out immediately if we have an invalid declaration.
17111 if (D.isInvalidType()) {
17112 NewTD->setInvalidDecl();
17113 return NewTD;
17114 }
17115
17116 if (D.getDeclSpec().isModulePrivateSpecified()) {
17117 if (CurContext->isFunctionOrMethod())
17118 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17119 << 2 << NewTD
17120 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17121 << FixItHint::CreateRemoval(
17122 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17123 else
17124 NewTD->setModulePrivate();
17125 }
17126
17127 // C++ [dcl.typedef]p8:
17128 // If the typedef declaration defines an unnamed class (or
17129 // enum), the first typedef-name declared by the declaration
17130 // to be that class type (or enum type) is used to denote the
17131 // class type (or enum type) for linkage purposes only.
17132 // We need to check whether the type was declared in the declaration.
17133 switch (D.getDeclSpec().getTypeSpecType()) {
17134 case TST_enum:
17135 case TST_struct:
17136 case TST_interface:
17137 case TST_union:
17138 case TST_class: {
17139 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17140 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17141 break;
17142 }
17143
17144 default:
17145 break;
17146 }
17147
17148 return NewTD;
17149}
17150
17151bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17152 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17153 QualType T = TI->getType();
17154
17155 if (T->isDependentType())
17156 return false;
17157
17158 // This doesn't use 'isIntegralType' despite the error message mentioning
17159 // integral type because isIntegralType would also allow enum types in C.
17160 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17161 if (BT->isInteger())
17162 return false;
17163
17164 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17165 << T << T->isBitIntType();
17166}
17167
17168bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17169 QualType EnumUnderlyingTy, bool IsFixed,
17170 const EnumDecl *Prev) {
17171 if (IsScoped != Prev->isScoped()) {
17172 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17173 << Prev->isScoped();
17174 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17175 return true;
17176 }
17177
17178 if (IsFixed && Prev->isFixed()) {
17179 if (!EnumUnderlyingTy->isDependentType() &&
17180 !Prev->getIntegerType()->isDependentType() &&
17181 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17182 T2: Prev->getIntegerType())) {
17183 // TODO: Highlight the underlying type of the redeclaration.
17184 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17185 << EnumUnderlyingTy << Prev->getIntegerType();
17186 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17187 << Prev->getIntegerTypeRange();
17188 return true;
17189 }
17190 } else if (IsFixed != Prev->isFixed()) {
17191 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17192 << Prev->isFixed();
17193 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17194 return true;
17195 }
17196
17197 return false;
17198}
17199
17200/// Get diagnostic %select index for tag kind for
17201/// redeclaration diagnostic message.
17202/// WARNING: Indexes apply to particular diagnostics only!
17203///
17204/// \returns diagnostic %select index.
17205static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17206 switch (Tag) {
17207 case TagTypeKind::Struct:
17208 return 0;
17209 case TagTypeKind::Interface:
17210 return 1;
17211 case TagTypeKind::Class:
17212 return 2;
17213 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17214 }
17215}
17216
17217/// Determine if tag kind is a class-key compatible with
17218/// class for redeclaration (class, struct, or __interface).
17219///
17220/// \returns true iff the tag kind is compatible.
17221static bool isClassCompatTagKind(TagTypeKind Tag)
17222{
17223 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17224 Tag == TagTypeKind::Interface;
17225}
17226
17227NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17228 if (isa<TypedefDecl>(Val: PrevDecl))
17229 return NonTagKind::Typedef;
17230 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17231 return NonTagKind::TypeAlias;
17232 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17233 return NonTagKind::Template;
17234 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17235 return NonTagKind::TypeAliasTemplate;
17236 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17237 return NonTagKind::TemplateTemplateArgument;
17238 switch (TTK) {
17239 case TagTypeKind::Struct:
17240 case TagTypeKind::Interface:
17241 case TagTypeKind::Class:
17242 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17243 : NonTagKind::NonStruct;
17244 case TagTypeKind::Union:
17245 return NonTagKind::NonUnion;
17246 case TagTypeKind::Enum:
17247 return NonTagKind::NonEnum;
17248 }
17249 llvm_unreachable("invalid TTK");
17250}
17251
17252bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17253 TagTypeKind NewTag, bool isDefinition,
17254 SourceLocation NewTagLoc,
17255 const IdentifierInfo *Name) {
17256 // C++ [dcl.type.elab]p3:
17257 // The class-key or enum keyword present in the
17258 // elaborated-type-specifier shall agree in kind with the
17259 // declaration to which the name in the elaborated-type-specifier
17260 // refers. This rule also applies to the form of
17261 // elaborated-type-specifier that declares a class-name or
17262 // friend class since it can be construed as referring to the
17263 // definition of the class. Thus, in any
17264 // elaborated-type-specifier, the enum keyword shall be used to
17265 // refer to an enumeration (7.2), the union class-key shall be
17266 // used to refer to a union (clause 9), and either the class or
17267 // struct class-key shall be used to refer to a class (clause 9)
17268 // declared using the class or struct class-key.
17269 TagTypeKind OldTag = Previous->getTagKind();
17270 if (OldTag != NewTag &&
17271 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17272 return false;
17273
17274 // Tags are compatible, but we might still want to warn on mismatched tags.
17275 // Non-class tags can't be mismatched at this point.
17276 if (!isClassCompatTagKind(Tag: NewTag))
17277 return true;
17278
17279 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17280 // by our warning analysis. We don't want to warn about mismatches with (eg)
17281 // declarations in system headers that are designed to be specialized, but if
17282 // a user asks us to warn, we should warn if their code contains mismatched
17283 // declarations.
17284 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17285 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17286 Loc);
17287 };
17288 if (IsIgnoredLoc(NewTagLoc))
17289 return true;
17290
17291 auto IsIgnored = [&](const TagDecl *Tag) {
17292 return IsIgnoredLoc(Tag->getLocation());
17293 };
17294 while (IsIgnored(Previous)) {
17295 Previous = Previous->getPreviousDecl();
17296 if (!Previous)
17297 return true;
17298 OldTag = Previous->getTagKind();
17299 }
17300
17301 bool isTemplate = false;
17302 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17303 isTemplate = Record->getDescribedClassTemplate();
17304
17305 if (inTemplateInstantiation()) {
17306 if (OldTag != NewTag) {
17307 // In a template instantiation, do not offer fix-its for tag mismatches
17308 // since they usually mess up the template instead of fixing the problem.
17309 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17310 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17311 << getRedeclDiagFromTagKind(Tag: OldTag);
17312 // FIXME: Note previous location?
17313 }
17314 return true;
17315 }
17316
17317 if (isDefinition) {
17318 // On definitions, check all previous tags and issue a fix-it for each
17319 // one that doesn't match the current tag.
17320 if (Previous->getDefinition()) {
17321 // Don't suggest fix-its for redefinitions.
17322 return true;
17323 }
17324
17325 bool previousMismatch = false;
17326 for (const TagDecl *I : Previous->redecls()) {
17327 if (I->getTagKind() != NewTag) {
17328 // Ignore previous declarations for which the warning was disabled.
17329 if (IsIgnored(I))
17330 continue;
17331
17332 if (!previousMismatch) {
17333 previousMismatch = true;
17334 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17335 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17336 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17337 }
17338 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17339 << getRedeclDiagFromTagKind(Tag: NewTag)
17340 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17341 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17342 }
17343 }
17344 return true;
17345 }
17346
17347 // Identify the prevailing tag kind: this is the kind of the definition (if
17348 // there is a non-ignored definition), or otherwise the kind of the prior
17349 // (non-ignored) declaration.
17350 const TagDecl *PrevDef = Previous->getDefinition();
17351 if (PrevDef && IsIgnored(PrevDef))
17352 PrevDef = nullptr;
17353 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17354 if (Redecl->getTagKind() != NewTag) {
17355 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17356 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17357 << getRedeclDiagFromTagKind(Tag: OldTag);
17358 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17359
17360 // If there is a previous definition, suggest a fix-it.
17361 if (PrevDef) {
17362 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17363 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17364 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17365 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17366 }
17367 }
17368
17369 return true;
17370}
17371
17372/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17373/// from an outer enclosing namespace or file scope inside a friend declaration.
17374/// This should provide the commented out code in the following snippet:
17375/// namespace N {
17376/// struct X;
17377/// namespace M {
17378/// struct Y { friend struct /*N::*/ X; };
17379/// }
17380/// }
17381static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17382 SourceLocation NameLoc) {
17383 // While the decl is in a namespace, do repeated lookup of that name and see
17384 // if we get the same namespace back. If we do not, continue until
17385 // translation unit scope, at which point we have a fully qualified NNS.
17386 SmallVector<IdentifierInfo *, 4> Namespaces;
17387 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17388 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17389 // This tag should be declared in a namespace, which can only be enclosed by
17390 // other namespaces. Bail if there's an anonymous namespace in the chain.
17391 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17392 if (!Namespace || Namespace->isAnonymousNamespace())
17393 return FixItHint();
17394 IdentifierInfo *II = Namespace->getIdentifier();
17395 Namespaces.push_back(Elt: II);
17396 NamedDecl *Lookup = SemaRef.LookupSingleName(
17397 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17398 if (Lookup == Namespace)
17399 break;
17400 }
17401
17402 // Once we have all the namespaces, reverse them to go outermost first, and
17403 // build an NNS.
17404 SmallString<64> Insertion;
17405 llvm::raw_svector_ostream OS(Insertion);
17406 if (DC->isTranslationUnit())
17407 OS << "::";
17408 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17409 for (auto *II : Namespaces)
17410 OS << II->getName() << "::";
17411 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17412}
17413
17414/// Determine whether a tag originally declared in context \p OldDC can
17415/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17416/// found a declaration in \p OldDC as a previous decl, perhaps through a
17417/// using-declaration).
17418static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17419 DeclContext *NewDC) {
17420 OldDC = OldDC->getRedeclContext();
17421 NewDC = NewDC->getRedeclContext();
17422
17423 if (OldDC->Equals(DC: NewDC))
17424 return true;
17425
17426 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17427 // encloses the other).
17428 if (S.getLangOpts().MSVCCompat &&
17429 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17430 return true;
17431
17432 return false;
17433}
17434
17435DeclResult
17436Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17437 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17438 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17439 SourceLocation ModulePrivateLoc,
17440 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17441 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17442 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17443 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17444 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17445 // If this is not a definition, it must have a name.
17446 IdentifierInfo *OrigName = Name;
17447 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17448 "Nameless record must be a definition!");
17449 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17450
17451 OwnedDecl = false;
17452 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17453 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17454
17455 // FIXME: Check member specializations more carefully.
17456 bool isMemberSpecialization = false;
17457 bool Invalid = false;
17458
17459 // We only need to do this matching if we have template parameters
17460 // or a scope specifier, which also conveniently avoids this work
17461 // for non-C++ cases.
17462 if (TemplateParameterLists.size() > 0 ||
17463 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17464 TemplateParameterList *TemplateParams =
17465 MatchTemplateParametersToScopeSpecifier(
17466 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17467 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17468
17469 // C++23 [dcl.type.elab] p2:
17470 // If an elaborated-type-specifier is the sole constituent of a
17471 // declaration, the declaration is ill-formed unless it is an explicit
17472 // specialization, an explicit instantiation or it has one of the
17473 // following forms: [...]
17474 // C++23 [dcl.enum] p1:
17475 // If the enum-head-name of an opaque-enum-declaration contains a
17476 // nested-name-specifier, the declaration shall be an explicit
17477 // specialization.
17478 //
17479 // FIXME: Class template partial specializations can be forward declared
17480 // per CWG2213, but the resolution failed to allow qualified forward
17481 // declarations. This is almost certainly unintentional, so we allow them.
17482 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17483 !isMemberSpecialization)
17484 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
17485 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17486
17487 if (TemplateParams) {
17488 if (Kind == TagTypeKind::Enum) {
17489 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
17490 return true;
17491 }
17492
17493 if (TemplateParams->size() > 0) {
17494 // This is a declaration or definition of a class template (which may
17495 // be a member of another template).
17496
17497 if (Invalid)
17498 return true;
17499
17500 OwnedDecl = false;
17501 DeclResult Result = CheckClassTemplate(
17502 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17503 AS, ModulePrivateLoc,
17504 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17505 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17506 return Result.get();
17507 } else {
17508 // The "template<>" header is extraneous.
17509 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
17510 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17511 isMemberSpecialization = true;
17512 }
17513 }
17514
17515 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17516 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17517 return true;
17518 }
17519
17520 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17521 // C++23 [dcl.type.elab]p4:
17522 // If an elaborated-type-specifier appears with the friend specifier as
17523 // an entire member-declaration, the member-declaration shall have one
17524 // of the following forms:
17525 // friend class-key nested-name-specifier(opt) identifier ;
17526 // friend class-key simple-template-id ;
17527 // friend class-key nested-name-specifier template(opt)
17528 // simple-template-id ;
17529 //
17530 // Since enum is not a class-key, so declarations like "friend enum E;"
17531 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17532 // invalid, most implementations accept so we issue a pedantic warning.
17533 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
17534 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17535 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17536 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
17537 << (ScopedEnum + ScopedEnumUsesClassTag);
17538 }
17539
17540 // Figure out the underlying type if this a enum declaration. We need to do
17541 // this early, because it's needed to detect if this is an incompatible
17542 // redeclaration.
17543 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17544 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17545
17546 if (Kind == TagTypeKind::Enum) {
17547 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17548 // No underlying type explicitly specified, or we failed to parse the
17549 // type, default to int.
17550 EnumUnderlying = Context.IntTy.getTypePtr();
17551 } else if (UnderlyingType.get()) {
17552 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17553 // integral type; any cv-qualification is ignored.
17554 TypeSourceInfo *TI = nullptr;
17555 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17556 EnumUnderlying = TI;
17557
17558 if (CheckEnumUnderlyingType(TI))
17559 // Recover by falling back to int.
17560 EnumUnderlying = Context.IntTy.getTypePtr();
17561
17562 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17563 UPPC: UPPC_FixedUnderlyingType))
17564 EnumUnderlying = Context.IntTy.getTypePtr();
17565
17566 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17567 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17568 // of 'int'. However, if this is an unfixed forward declaration, don't set
17569 // the underlying type unless the user enables -fms-compatibility. This
17570 // makes unfixed forward declared enums incomplete and is more conforming.
17571 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17572 EnumUnderlying = Context.IntTy.getTypePtr();
17573 }
17574 }
17575
17576 DeclContext *SearchDC = CurContext;
17577 DeclContext *DC = CurContext;
17578 bool isStdBadAlloc = false;
17579 bool isStdAlignValT = false;
17580
17581 RedeclarationKind Redecl = forRedeclarationInCurContext();
17582 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17583 Redecl = RedeclarationKind::NotForRedeclaration;
17584
17585 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17586 /// implemented asks for structural equivalence checking, the returned decl
17587 /// here is passed back to the parser, allowing the tag body to be parsed.
17588 auto createTagFromNewDecl = [&]() -> TagDecl * {
17589 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17590 // If there is an identifier, use the location of the identifier as the
17591 // location of the decl, otherwise use the location of the struct/union
17592 // keyword.
17593 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17594 TagDecl *New = nullptr;
17595
17596 if (Kind == TagTypeKind::Enum) {
17597 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17598 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17599 // If this is an undefined enum, bail.
17600 if (TUK != TagUseKind::Definition && !Invalid)
17601 return nullptr;
17602 if (EnumUnderlying) {
17603 EnumDecl *ED = cast<EnumDecl>(Val: New);
17604 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
17605 ED->setIntegerTypeSourceInfo(TI);
17606 else
17607 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
17608 QualType EnumTy = ED->getIntegerType();
17609 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17610 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17611 : EnumTy);
17612 }
17613 } else { // struct/union
17614 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17615 PrevDecl: nullptr);
17616 }
17617
17618 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17619 // Add alignment attributes if necessary; these attributes are checked
17620 // when the ASTContext lays out the structure.
17621 //
17622 // It is important for implementing the correct semantics that this
17623 // happen here (in ActOnTag). The #pragma pack stack is
17624 // maintained as a result of parser callbacks which can occur at
17625 // many points during the parsing of a struct declaration (because
17626 // the #pragma tokens are effectively skipped over during the
17627 // parsing of the struct).
17628 if (TUK == TagUseKind::Definition &&
17629 (!SkipBody || !SkipBody->ShouldSkip)) {
17630 if (LangOpts.HLSL)
17631 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
17632 AddAlignmentAttributesForRecord(RD);
17633 AddMsStructLayoutForRecord(RD);
17634 }
17635 }
17636 New->setLexicalDeclContext(CurContext);
17637 return New;
17638 };
17639
17640 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17641 if (Name && SS.isNotEmpty()) {
17642 // We have a nested-name tag ('struct foo::bar').
17643
17644 // Check for invalid 'foo::'.
17645 if (SS.isInvalid()) {
17646 Name = nullptr;
17647 goto CreateNewDecl;
17648 }
17649
17650 // If this is a friend or a reference to a class in a dependent
17651 // context, don't try to make a decl for it.
17652 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17653 DC = computeDeclContext(SS, EnteringContext: false);
17654 if (!DC) {
17655 IsDependent = true;
17656 return true;
17657 }
17658 } else {
17659 DC = computeDeclContext(SS, EnteringContext: true);
17660 if (!DC) {
17661 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
17662 << SS.getRange();
17663 return true;
17664 }
17665 }
17666
17667 if (RequireCompleteDeclContext(SS, DC))
17668 return true;
17669
17670 SearchDC = DC;
17671 // Look-up name inside 'foo::'.
17672 LookupQualifiedName(R&: Previous, LookupCtx: DC);
17673
17674 if (Previous.isAmbiguous())
17675 return true;
17676
17677 if (Previous.empty()) {
17678 // Name lookup did not find anything. However, if the
17679 // nested-name-specifier refers to the current instantiation,
17680 // and that current instantiation has any dependent base
17681 // classes, we might find something at instantiation time: treat
17682 // this as a dependent elaborated-type-specifier.
17683 // But this only makes any sense for reference-like lookups.
17684 if (Previous.wasNotFoundInCurrentInstantiation() &&
17685 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17686 IsDependent = true;
17687 return true;
17688 }
17689
17690 // A tag 'foo::bar' must already exist.
17691 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
17692 << Kind << Name << DC << SS.getRange();
17693 Name = nullptr;
17694 Invalid = true;
17695 goto CreateNewDecl;
17696 }
17697 } else if (Name) {
17698 // C++14 [class.mem]p14:
17699 // If T is the name of a class, then each of the following shall have a
17700 // name different from T:
17701 // -- every member of class T that is itself a type
17702 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17703 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
17704 return true;
17705
17706 // If this is a named struct, check to see if there was a previous forward
17707 // declaration or definition.
17708 // FIXME: We're looking into outer scopes here, even when we
17709 // shouldn't be. Doing so can result in ambiguities that we
17710 // shouldn't be diagnosing.
17711 LookupName(R&: Previous, S);
17712
17713 // When declaring or defining a tag, ignore ambiguities introduced
17714 // by types using'ed into this scope.
17715 if (Previous.isAmbiguous() &&
17716 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
17717 LookupResult::Filter F = Previous.makeFilter();
17718 while (F.hasNext()) {
17719 NamedDecl *ND = F.next();
17720 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17721 DC: SearchDC->getRedeclContext()))
17722 F.erase();
17723 }
17724 F.done();
17725 }
17726
17727 // C++11 [namespace.memdef]p3:
17728 // If the name in a friend declaration is neither qualified nor
17729 // a template-id and the declaration is a function or an
17730 // elaborated-type-specifier, the lookup to determine whether
17731 // the entity has been previously declared shall not consider
17732 // any scopes outside the innermost enclosing namespace.
17733 //
17734 // MSVC doesn't implement the above rule for types, so a friend tag
17735 // declaration may be a redeclaration of a type declared in an enclosing
17736 // scope. They do implement this rule for friend functions.
17737 //
17738 // Does it matter that this should be by scope instead of by
17739 // semantic context?
17740 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17741 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17742 LookupResult::Filter F = Previous.makeFilter();
17743 bool FriendSawTagOutsideEnclosingNamespace = false;
17744 while (F.hasNext()) {
17745 NamedDecl *ND = F.next();
17746 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17747 if (DC->isFileContext() &&
17748 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
17749 if (getLangOpts().MSVCCompat)
17750 FriendSawTagOutsideEnclosingNamespace = true;
17751 else
17752 F.erase();
17753 }
17754 }
17755 F.done();
17756
17757 // Diagnose this MSVC extension in the easy case where lookup would have
17758 // unambiguously found something outside the enclosing namespace.
17759 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17760 NamedDecl *ND = Previous.getFoundDecl();
17761 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
17762 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
17763 }
17764 }
17765
17766 // Note: there used to be some attempt at recovery here.
17767 if (Previous.isAmbiguous())
17768 return true;
17769
17770 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17771 // FIXME: This makes sure that we ignore the contexts associated
17772 // with C structs, unions, and enums when looking for a matching
17773 // tag declaration or definition. See the similar lookup tweak
17774 // in Sema::LookupName; is there a better way to deal with this?
17775 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
17776 SearchDC = SearchDC->getParent();
17777 } else if (getLangOpts().CPlusPlus) {
17778 // Inside ObjCContainer want to keep it as a lexical decl context but go
17779 // past it (most often to TranslationUnit) to find the semantic decl
17780 // context.
17781 while (isa<ObjCContainerDecl>(Val: SearchDC))
17782 SearchDC = SearchDC->getParent();
17783 }
17784 } else if (getLangOpts().CPlusPlus) {
17785 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17786 // TagDecl the same way as we skip it for named TagDecl.
17787 while (isa<ObjCContainerDecl>(Val: SearchDC))
17788 SearchDC = SearchDC->getParent();
17789 }
17790
17791 if (Previous.isSingleResult() &&
17792 Previous.getFoundDecl()->isTemplateParameter()) {
17793 // Maybe we will complain about the shadowed template parameter.
17794 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
17795 // Just pretend that we didn't see the previous declaration.
17796 Previous.clear();
17797 }
17798
17799 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17800 DC->Equals(DC: getStdNamespace())) {
17801 if (Name->isStr(Str: "bad_alloc")) {
17802 // This is a declaration of or a reference to "std::bad_alloc".
17803 isStdBadAlloc = true;
17804
17805 // If std::bad_alloc has been implicitly declared (but made invisible to
17806 // name lookup), fill in this implicit declaration as the previous
17807 // declaration, so that the declarations get chained appropriately.
17808 if (Previous.empty() && StdBadAlloc)
17809 Previous.addDecl(D: getStdBadAlloc());
17810 } else if (Name->isStr(Str: "align_val_t")) {
17811 isStdAlignValT = true;
17812 if (Previous.empty() && StdAlignValT)
17813 Previous.addDecl(D: getStdAlignValT());
17814 }
17815 }
17816
17817 // If we didn't find a previous declaration, and this is a reference
17818 // (or friend reference), move to the correct scope. In C++, we
17819 // also need to do a redeclaration lookup there, just in case
17820 // there's a shadow friend decl.
17821 if (Name && Previous.empty() &&
17822 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17823 IsTemplateParamOrArg)) {
17824 if (Invalid) goto CreateNewDecl;
17825 assert(SS.isEmpty());
17826
17827 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17828 // C++ [basic.scope.pdecl]p5:
17829 // -- for an elaborated-type-specifier of the form
17830 //
17831 // class-key identifier
17832 //
17833 // if the elaborated-type-specifier is used in the
17834 // decl-specifier-seq or parameter-declaration-clause of a
17835 // function defined in namespace scope, the identifier is
17836 // declared as a class-name in the namespace that contains
17837 // the declaration; otherwise, except as a friend
17838 // declaration, the identifier is declared in the smallest
17839 // non-class, non-function-prototype scope that contains the
17840 // declaration.
17841 //
17842 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17843 // C structs and unions.
17844 //
17845 // It is an error in C++ to declare (rather than define) an enum
17846 // type, including via an elaborated type specifier. We'll
17847 // diagnose that later; for now, declare the enum in the same
17848 // scope as we would have picked for any other tag type.
17849 //
17850 // GNU C also supports this behavior as part of its incomplete
17851 // enum types extension, while GNU C++ does not.
17852 //
17853 // Find the context where we'll be declaring the tag.
17854 // FIXME: We would like to maintain the current DeclContext as the
17855 // lexical context,
17856 SearchDC = getTagInjectionContext(DC: SearchDC);
17857
17858 // Find the scope where we'll be declaring the tag.
17859 S = getTagInjectionScope(S, LangOpts: getLangOpts());
17860 } else {
17861 assert(TUK == TagUseKind::Friend);
17862 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
17863
17864 // C++ [namespace.memdef]p3:
17865 // If a friend declaration in a non-local class first declares a
17866 // class or function, the friend class or function is a member of
17867 // the innermost enclosing namespace.
17868 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17869 : SearchDC->getEnclosingNamespaceContext();
17870 }
17871
17872 // In C++, we need to do a redeclaration lookup to properly
17873 // diagnose some problems.
17874 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17875 // hidden declaration so that we don't get ambiguity errors when using a
17876 // type declared by an elaborated-type-specifier. In C that is not correct
17877 // and we should instead merge compatible types found by lookup.
17878 if (getLangOpts().CPlusPlus) {
17879 // FIXME: This can perform qualified lookups into function contexts,
17880 // which are meaningless.
17881 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17882 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
17883 } else {
17884 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17885 LookupName(R&: Previous, S);
17886 }
17887 }
17888
17889 // If we have a known previous declaration to use, then use it.
17890 if (Previous.empty() && SkipBody && SkipBody->Previous)
17891 Previous.addDecl(D: SkipBody->Previous);
17892
17893 if (!Previous.empty()) {
17894 NamedDecl *PrevDecl = Previous.getFoundDecl();
17895 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17896
17897 // It's okay to have a tag decl in the same scope as a typedef
17898 // which hides a tag decl in the same scope. Finding this
17899 // with a redeclaration lookup can only actually happen in C++.
17900 //
17901 // This is also okay for elaborated-type-specifiers, which is
17902 // technically forbidden by the current standard but which is
17903 // okay according to the likely resolution of an open issue;
17904 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17905 if (getLangOpts().CPlusPlus) {
17906 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
17907 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17908 TagDecl *Tag = TT->getDecl();
17909 if (Tag->getDeclName() == Name &&
17910 Tag->getDeclContext()->getRedeclContext()
17911 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
17912 PrevDecl = Tag;
17913 Previous.clear();
17914 Previous.addDecl(D: Tag);
17915 Previous.resolveKind();
17916 }
17917 }
17918 }
17919 }
17920
17921 // If this is a redeclaration of a using shadow declaration, it must
17922 // declare a tag in the same context. In MSVC mode, we allow a
17923 // redefinition if either context is within the other.
17924 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
17925 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
17926 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17927 TUK != TagUseKind::Friend &&
17928 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
17929 !(OldTag && isAcceptableTagRedeclContext(
17930 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
17931 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
17932 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
17933 DiagID: diag::note_using_decl_target);
17934 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
17935 << 0;
17936 // Recover by ignoring the old declaration.
17937 Previous.clear();
17938 goto CreateNewDecl;
17939 }
17940 }
17941
17942 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
17943 // If this is a use of a previous tag, or if the tag is already declared
17944 // in the same scope (so that the definition/declaration completes or
17945 // rementions the tag), reuse the decl.
17946 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17947 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
17948 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
17949 // Make sure that this wasn't declared as an enum and now used as a
17950 // struct or something similar.
17951 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
17952 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
17953 Name)) {
17954 bool SafeToContinue =
17955 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17956 Kind != TagTypeKind::Enum);
17957 if (SafeToContinue)
17958 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
17959 << Name
17960 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
17961 Code: PrevTagDecl->getKindName());
17962 else
17963 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
17964 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
17965
17966 if (SafeToContinue)
17967 Kind = PrevTagDecl->getTagKind();
17968 else {
17969 // Recover by making this an anonymous redefinition.
17970 Name = nullptr;
17971 Previous.clear();
17972 Invalid = true;
17973 }
17974 }
17975
17976 if (Kind == TagTypeKind::Enum &&
17977 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17978 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
17979 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17980 return PrevTagDecl;
17981
17982 QualType EnumUnderlyingTy;
17983 if (TypeSourceInfo *TI =
17984 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
17985 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17986 else if (const Type *T =
17987 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
17988 EnumUnderlyingTy = QualType(T, 0);
17989
17990 // All conflicts with previous declarations are recovered by
17991 // returning the previous declaration, unless this is a definition,
17992 // in which case we want the caller to bail out.
17993 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
17994 IsScoped: ScopedEnum, EnumUnderlyingTy,
17995 IsFixed, Prev: PrevEnum))
17996 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17997 }
17998
17999 // C++11 [class.mem]p1:
18000 // A member shall not be declared twice in the member-specification,
18001 // except that a nested class or member class template can be declared
18002 // and then later defined.
18003 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18004 S->isDeclScope(D: PrevDecl)) {
18005 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18006 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18007 }
18008
18009 if (!Invalid) {
18010 // If this is a use, just return the declaration we found, unless
18011 // we have attributes.
18012 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18013 if (!Attrs.empty()) {
18014 // FIXME: Diagnose these attributes. For now, we create a new
18015 // declaration to hold them.
18016 } else if (TUK == TagUseKind::Reference &&
18017 (PrevTagDecl->getFriendObjectKind() ==
18018 Decl::FOK_Undeclared ||
18019 PrevDecl->getOwningModule() != getCurrentModule()) &&
18020 SS.isEmpty()) {
18021 // This declaration is a reference to an existing entity, but
18022 // has different visibility from that entity: it either makes
18023 // a friend visible or it makes a type visible in a new module.
18024 // In either case, create a new declaration. We only do this if
18025 // the declaration would have meant the same thing if no prior
18026 // declaration were found, that is, if it was found in the same
18027 // scope where we would have injected a declaration.
18028 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18029 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18030 return PrevTagDecl;
18031 // This is in the injected scope, create a new declaration in
18032 // that scope.
18033 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18034 } else {
18035 return PrevTagDecl;
18036 }
18037 }
18038
18039 // Diagnose attempts to redefine a tag.
18040 if (TUK == TagUseKind::Definition) {
18041 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
18042 // If we're defining a specialization and the previous definition
18043 // is from an implicit instantiation, don't emit an error
18044 // here; we'll catch this in the general case below.
18045 bool IsExplicitSpecializationAfterInstantiation = false;
18046 if (isMemberSpecialization) {
18047 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18048 IsExplicitSpecializationAfterInstantiation =
18049 RD->getTemplateSpecializationKind() !=
18050 TSK_ExplicitSpecialization;
18051 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18052 IsExplicitSpecializationAfterInstantiation =
18053 ED->getTemplateSpecializationKind() !=
18054 TSK_ExplicitSpecialization;
18055 }
18056
18057 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
18058 // not keep more that one definition around (merge them). However,
18059 // ensure the decl passes the structural compatibility check in
18060 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18061 NamedDecl *Hidden = nullptr;
18062 if (SkipBody &&
18063 (!hasVisibleDefinition(D: Def, Suggested: &Hidden) || getLangOpts().C23)) {
18064 // There is a definition of this tag, but it is not visible. We
18065 // explicitly make use of C++'s one definition rule here, and
18066 // assume that this definition is identical to the hidden one
18067 // we already have. Make the existing definition visible and
18068 // use it in place of this one.
18069 if (!getLangOpts().CPlusPlus) {
18070 // Postpone making the old definition visible until after we
18071 // complete parsing the new one and do the structural
18072 // comparison.
18073 SkipBody->CheckSameAsPrevious = true;
18074 SkipBody->New = createTagFromNewDecl();
18075 SkipBody->Previous = Def;
18076
18077 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18078 return Def;
18079 } else {
18080 SkipBody->ShouldSkip = true;
18081 SkipBody->Previous = Def;
18082 makeMergedDefinitionVisible(ND: Hidden);
18083 // Carry on and handle it like a normal definition. We'll
18084 // skip starting the definition later.
18085 }
18086 } else if (!IsExplicitSpecializationAfterInstantiation) {
18087 // A redeclaration in function prototype scope in C isn't
18088 // visible elsewhere, so merely issue a warning.
18089 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
18090 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list) << Name;
18091 else
18092 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18093 notePreviousDefinition(Old: Def,
18094 New: NameLoc.isValid() ? NameLoc : KWLoc);
18095 // If this is a redefinition, recover by making this
18096 // struct be anonymous, which will make any later
18097 // references get the previous definition.
18098 Name = nullptr;
18099 Previous.clear();
18100 Invalid = true;
18101 }
18102 } else {
18103 // If the type is currently being defined, complain
18104 // about a nested redefinition.
18105 auto *TD = Context.getTagDeclType(Decl: PrevTagDecl)->getAsTagDecl();
18106 if (TD->isBeingDefined()) {
18107 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18108 Diag(Loc: PrevTagDecl->getLocation(),
18109 DiagID: diag::note_previous_definition);
18110 Name = nullptr;
18111 Previous.clear();
18112 Invalid = true;
18113 }
18114 }
18115
18116 // Okay, this is definition of a previously declared or referenced
18117 // tag. We're going to create a new Decl for it.
18118 }
18119
18120 // Okay, we're going to make a redeclaration. If this is some kind
18121 // of reference, make sure we build the redeclaration in the same DC
18122 // as the original, and ignore the current access specifier.
18123 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18124 SearchDC = PrevTagDecl->getDeclContext();
18125 AS = AS_none;
18126 }
18127 }
18128 // If we get here we have (another) forward declaration or we
18129 // have a definition. Just create a new decl.
18130
18131 } else {
18132 // If we get here, this is a definition of a new tag type in a nested
18133 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18134 // new decl/type. We set PrevDecl to NULL so that the entities
18135 // have distinct types.
18136 Previous.clear();
18137 }
18138 // If we get here, we're going to create a new Decl. If PrevDecl
18139 // is non-NULL, it's a definition of the tag declared by
18140 // PrevDecl. If it's NULL, we have a new definition.
18141
18142 // Otherwise, PrevDecl is not a tag, but was found with tag
18143 // lookup. This is only actually possible in C++, where a few
18144 // things like templates still live in the tag namespace.
18145 } else {
18146 // Use a better diagnostic if an elaborated-type-specifier
18147 // found the wrong kind of type on the first
18148 // (non-redeclaration) lookup.
18149 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18150 !Previous.isForRedeclaration()) {
18151 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18152 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18153 << PrevDecl << NTK << Kind;
18154 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18155 Invalid = true;
18156
18157 // Otherwise, only diagnose if the declaration is in scope.
18158 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18159 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18160 // do nothing
18161
18162 // Diagnose implicit declarations introduced by elaborated types.
18163 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18164 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18165 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18166 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18167 Invalid = true;
18168
18169 // Otherwise it's a declaration. Call out a particularly common
18170 // case here.
18171 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18172 unsigned Kind = 0;
18173 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18174 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18175 << Name << Kind << TND->getUnderlyingType();
18176 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18177 Invalid = true;
18178
18179 // Otherwise, diagnose.
18180 } else {
18181 // The tag name clashes with something else in the target scope,
18182 // issue an error and recover by making this tag be anonymous.
18183 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18184 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18185 Name = nullptr;
18186 Invalid = true;
18187 }
18188
18189 // The existing declaration isn't relevant to us; we're in a
18190 // new scope, so clear out the previous declaration.
18191 Previous.clear();
18192 }
18193 }
18194
18195CreateNewDecl:
18196
18197 TagDecl *PrevDecl = nullptr;
18198 if (Previous.isSingleResult())
18199 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18200
18201 // If there is an identifier, use the location of the identifier as the
18202 // location of the decl, otherwise use the location of the struct/union
18203 // keyword.
18204 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18205
18206 // Otherwise, create a new declaration. If there is a previous
18207 // declaration of the same entity, the two will be linked via
18208 // PrevDecl.
18209 TagDecl *New;
18210
18211 if (Kind == TagTypeKind::Enum) {
18212 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18213 // enum X { A, B, C } D; D should chain to X.
18214 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18215 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18216 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18217
18218 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18219 StdAlignValT = cast<EnumDecl>(Val: New);
18220
18221 // If this is an undefined enum, warn.
18222 if (TUK != TagUseKind::Definition && !Invalid) {
18223 TagDecl *Def;
18224 if (IsFixed && cast<EnumDecl>(Val: New)->isFixed()) {
18225 // C++0x: 7.2p2: opaque-enum-declaration.
18226 // Conflicts are diagnosed above. Do nothing.
18227 }
18228 else if (PrevDecl && (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18229 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18230 << New;
18231 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18232 } else {
18233 unsigned DiagID = diag::ext_forward_ref_enum;
18234 if (getLangOpts().MSVCCompat)
18235 DiagID = diag::ext_ms_forward_ref_enum;
18236 else if (getLangOpts().CPlusPlus)
18237 DiagID = diag::err_forward_ref_enum;
18238 Diag(Loc, DiagID);
18239 }
18240 }
18241
18242 if (EnumUnderlying) {
18243 EnumDecl *ED = cast<EnumDecl>(Val: New);
18244 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18245 ED->setIntegerTypeSourceInfo(TI);
18246 else
18247 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18248 QualType EnumTy = ED->getIntegerType();
18249 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18250 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18251 : EnumTy);
18252 assert(ED->isComplete() && "enum with type should be complete");
18253 }
18254 } else {
18255 // struct/union/class
18256
18257 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18258 // struct X { int A; } D; D should chain to X.
18259 if (getLangOpts().CPlusPlus) {
18260 // FIXME: Look for a way to use RecordDecl for simple structs.
18261 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18262 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18263
18264 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18265 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18266 } else
18267 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18268 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18269 }
18270
18271 // Only C23 and later allow defining new types in 'offsetof()'.
18272 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18273 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18274 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18275 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18276
18277 // C++11 [dcl.type]p3:
18278 // A type-specifier-seq shall not define a class or enumeration [...].
18279 if (!Invalid && getLangOpts().CPlusPlus &&
18280 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18281 TUK == TagUseKind::Definition) {
18282 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18283 << Context.getTagDeclType(Decl: New);
18284 Invalid = true;
18285 }
18286
18287 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18288 DC->getDeclKind() == Decl::Enum) {
18289 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18290 << Context.getTagDeclType(Decl: New);
18291 Invalid = true;
18292 }
18293
18294 // Maybe add qualifier info.
18295 if (SS.isNotEmpty()) {
18296 if (SS.isSet()) {
18297 // If this is either a declaration or a definition, check the
18298 // nested-name-specifier against the current context.
18299 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18300 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18301 /*TemplateId=*/nullptr,
18302 IsMemberSpecialization: isMemberSpecialization))
18303 Invalid = true;
18304
18305 New->setQualifierInfo(SS.getWithLocInContext(Context));
18306 if (TemplateParameterLists.size() > 0) {
18307 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18308 }
18309 }
18310 else
18311 Invalid = true;
18312 }
18313
18314 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18315 // Add alignment attributes if necessary; these attributes are checked when
18316 // the ASTContext lays out the structure.
18317 //
18318 // It is important for implementing the correct semantics that this
18319 // happen here (in ActOnTag). The #pragma pack stack is
18320 // maintained as a result of parser callbacks which can occur at
18321 // many points during the parsing of a struct declaration (because
18322 // the #pragma tokens are effectively skipped over during the
18323 // parsing of the struct).
18324 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18325 if (LangOpts.HLSL)
18326 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18327 AddAlignmentAttributesForRecord(RD);
18328 AddMsStructLayoutForRecord(RD);
18329 }
18330 }
18331
18332 if (ModulePrivateLoc.isValid()) {
18333 if (isMemberSpecialization)
18334 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18335 << 2
18336 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18337 // __module_private__ does not apply to local classes. However, we only
18338 // diagnose this as an error when the declaration specifiers are
18339 // freestanding. Here, we just ignore the __module_private__.
18340 else if (!SearchDC->isFunctionOrMethod())
18341 New->setModulePrivate();
18342 }
18343
18344 // If this is a specialization of a member class (of a class template),
18345 // check the specialization.
18346 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18347 Invalid = true;
18348
18349 // If we're declaring or defining a tag in function prototype scope in C,
18350 // note that this type can only be used within the function and add it to
18351 // the list of decls to inject into the function definition scope. However,
18352 // in C23 and later, while the type is only visible within the function, the
18353 // function can be called with a compatible type defined in the same TU, so
18354 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18355 if ((Name || Kind == TagTypeKind::Enum) &&
18356 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18357 if (getLangOpts().CPlusPlus) {
18358 // C++ [dcl.fct]p6:
18359 // Types shall not be defined in return or parameter types.
18360 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18361 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18362 << Name;
18363 Invalid = true;
18364 }
18365 if (TUK == TagUseKind::Declaration)
18366 Invalid = true;
18367 } else if (!PrevDecl) {
18368 // In C23 mode, if the declaration is complete, we do not want to
18369 // diagnose.
18370 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18371 Diag(Loc, DiagID: diag::warn_decl_in_param_list) << Context.getTagDeclType(Decl: New);
18372 }
18373 }
18374
18375 if (Invalid)
18376 New->setInvalidDecl();
18377
18378 // Set the lexical context. If the tag has a C++ scope specifier, the
18379 // lexical context will be different from the semantic context.
18380 New->setLexicalDeclContext(CurContext);
18381
18382 // Mark this as a friend decl if applicable.
18383 // In Microsoft mode, a friend declaration also acts as a forward
18384 // declaration so we always pass true to setObjectOfFriendDecl to make
18385 // the tag name visible.
18386 if (TUK == TagUseKind::Friend)
18387 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18388
18389 // Set the access specifier.
18390 if (!Invalid && SearchDC->isRecord())
18391 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18392
18393 if (PrevDecl)
18394 CheckRedeclarationInModule(New, Old: PrevDecl);
18395
18396 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18397 New->startDefinition();
18398
18399 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18400 AddPragmaAttributes(S, D: New);
18401
18402 // If this has an identifier, add it to the scope stack.
18403 if (TUK == TagUseKind::Friend) {
18404 // We might be replacing an existing declaration in the lookup tables;
18405 // if so, borrow its access specifier.
18406 if (PrevDecl)
18407 New->setAccess(PrevDecl->getAccess());
18408
18409 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18410 DC->makeDeclVisibleInContext(D: New);
18411 if (Name) // can be null along some error paths
18412 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18413 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18414 } else if (Name) {
18415 S = getNonFieldDeclScope(S);
18416 PushOnScopeChains(D: New, S, AddToContext: true);
18417 } else {
18418 CurContext->addDecl(D: New);
18419 }
18420
18421 // If this is the C FILE type, notify the AST context.
18422 if (IdentifierInfo *II = New->getIdentifier())
18423 if (!New->isInvalidDecl() &&
18424 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18425 II->isStr(Str: "FILE"))
18426 Context.setFILEDecl(New);
18427
18428 if (PrevDecl)
18429 mergeDeclAttributes(New, Old: PrevDecl);
18430
18431 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18432 inferGslOwnerPointerAttribute(Record: CXXRD);
18433 inferNullableClassAttribute(CRD: CXXRD);
18434 }
18435
18436 // If there's a #pragma GCC visibility in scope, set the visibility of this
18437 // record.
18438 AddPushedVisibilityAttribute(RD: New);
18439
18440 if (isMemberSpecialization && !New->isInvalidDecl())
18441 CompleteMemberSpecialization(Member: New, Previous);
18442
18443 OwnedDecl = true;
18444 // In C++, don't return an invalid declaration. We can't recover well from
18445 // the cases where we make the type anonymous.
18446 if (Invalid && getLangOpts().CPlusPlus) {
18447 if (New->isBeingDefined())
18448 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18449 RD->completeDefinition();
18450 return true;
18451 } else if (SkipBody && SkipBody->ShouldSkip) {
18452 return SkipBody->Previous;
18453 } else {
18454 return New;
18455 }
18456}
18457
18458void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18459 AdjustDeclIfTemplate(Decl&: TagD);
18460 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18461
18462 // Enter the tag context.
18463 PushDeclContext(S, DC: Tag);
18464
18465 ActOnDocumentableDecl(D: TagD);
18466
18467 // If there's a #pragma GCC visibility in scope, set the visibility of this
18468 // record.
18469 AddPushedVisibilityAttribute(RD: Tag);
18470}
18471
18472bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18473 SkipBodyInfo &SkipBody) {
18474 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
18475 return false;
18476
18477 // Make the previous decl visible.
18478 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18479 CleanupMergedEnum(S, New: SkipBody.New);
18480 return true;
18481}
18482
18483void Sema::ActOnStartCXXMemberDeclarations(
18484 Scope *S, Decl *TagD, SourceLocation FinalLoc, bool IsFinalSpelledSealed,
18485 bool IsAbstract, SourceLocation TriviallyRelocatable,
18486 SourceLocation Replaceable, SourceLocation LBraceLoc) {
18487 AdjustDeclIfTemplate(Decl&: TagD);
18488 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18489
18490 FieldCollector->StartClass();
18491
18492 if (!Record->getIdentifier())
18493 return;
18494
18495 if (IsAbstract)
18496 Record->markAbstract();
18497
18498 if (FinalLoc.isValid()) {
18499 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
18500 S: IsFinalSpelledSealed
18501 ? FinalAttr::Keyword_sealed
18502 : FinalAttr::Keyword_final));
18503 }
18504
18505 if (TriviallyRelocatable.isValid())
18506 Record->addAttr(
18507 A: TriviallyRelocatableAttr::Create(Ctx&: Context, Range: TriviallyRelocatable));
18508
18509 if (Replaceable.isValid())
18510 Record->addAttr(A: ReplaceableAttr::Create(Ctx&: Context, Range: Replaceable));
18511
18512 // C++ [class]p2:
18513 // [...] The class-name is also inserted into the scope of the
18514 // class itself; this is known as the injected-class-name. For
18515 // purposes of access checking, the injected-class-name is treated
18516 // as if it were a public member name.
18517 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18518 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18519 IdLoc: Record->getLocation(), Id: Record->getIdentifier(),
18520 /*PrevDecl=*/nullptr,
18521 /*DelayTypeCreation=*/true);
18522 Context.getTypeDeclType(Decl: InjectedClassName, PrevDecl: Record);
18523 InjectedClassName->setImplicit();
18524 InjectedClassName->setAccess(AS_public);
18525 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18526 InjectedClassName->setDescribedClassTemplate(Template);
18527 PushOnScopeChains(D: InjectedClassName, S);
18528 assert(InjectedClassName->isInjectedClassName() &&
18529 "Broken injected-class-name");
18530}
18531
18532void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18533 SourceRange BraceRange) {
18534 AdjustDeclIfTemplate(Decl&: TagD);
18535 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18536 Tag->setBraceRange(BraceRange);
18537
18538 // Make sure we "complete" the definition even it is invalid.
18539 if (Tag->isBeingDefined()) {
18540 assert(Tag->isInvalidDecl() && "We should already have completed it");
18541 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18542 RD->completeDefinition();
18543 }
18544
18545 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18546 FieldCollector->FinishClass();
18547 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18548 auto *Def = RD->getDefinition();
18549 assert(Def && "The record is expected to have a completed definition");
18550 unsigned NumInitMethods = 0;
18551 for (auto *Method : Def->methods()) {
18552 if (!Method->getIdentifier())
18553 continue;
18554 if (Method->getName() == "__init")
18555 NumInitMethods++;
18556 }
18557 if (NumInitMethods > 1 || !Def->hasInitMethod())
18558 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
18559 }
18560
18561 // If we're defining a dynamic class in a module interface unit, we always
18562 // need to produce the vtable for it, even if the vtable is not used in the
18563 // current TU.
18564 //
18565 // The case where the current class is not dynamic is handled in
18566 // MarkVTableUsed.
18567 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18568 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
18569 }
18570
18571 // Exit this scope of this tag's definition.
18572 PopDeclContext();
18573
18574 if (getCurLexicalContext()->isObjCContainer() &&
18575 Tag->getDeclContext()->isFileContext())
18576 Tag->setTopLevelDeclInObjCContainer();
18577
18578 // Notify the consumer that we've defined a tag.
18579 if (!Tag->isInvalidDecl())
18580 Consumer.HandleTagDeclDefinition(D: Tag);
18581
18582 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18583 // from XLs and instead matches the XL #pragma pack(1) behavior.
18584 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18585 AlignPackStack.hasValue()) {
18586 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18587 // Only diagnose #pragma align(packed).
18588 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18589 return;
18590 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18591 if (!RD)
18592 return;
18593 // Only warn if there is at least 1 bitfield member.
18594 if (llvm::any_of(Range: RD->fields(),
18595 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
18596 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
18597 }
18598}
18599
18600void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18601 AdjustDeclIfTemplate(Decl&: TagD);
18602 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18603 Tag->setInvalidDecl();
18604
18605 // Make sure we "complete" the definition even it is invalid.
18606 if (Tag->isBeingDefined()) {
18607 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18608 RD->completeDefinition();
18609 }
18610
18611 // We're undoing ActOnTagStartDefinition here, not
18612 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18613 // the FieldCollector.
18614
18615 PopDeclContext();
18616}
18617
18618// Note that FieldName may be null for anonymous bitfields.
18619ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18620 const IdentifierInfo *FieldName,
18621 QualType FieldTy, bool IsMsStruct,
18622 Expr *BitWidth) {
18623 assert(BitWidth);
18624 if (BitWidth->containsErrors())
18625 return ExprError();
18626
18627 // C99 6.7.2.1p4 - verify the field type.
18628 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18629 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18630 // Handle incomplete and sizeless types with a specific error.
18631 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
18632 DiagID: diag::err_field_incomplete_or_sizeless))
18633 return ExprError();
18634 if (FieldName)
18635 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
18636 << FieldName << FieldTy << BitWidth->getSourceRange();
18637 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
18638 << FieldTy << BitWidth->getSourceRange();
18639 } else if (DiagnoseUnexpandedParameterPack(E: const_cast<Expr *>(BitWidth),
18640 UPPC: UPPC_BitFieldWidth))
18641 return ExprError();
18642
18643 // If the bit-width is type- or value-dependent, don't try to check
18644 // it now.
18645 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18646 return BitWidth;
18647
18648 llvm::APSInt Value;
18649 ExprResult ICE =
18650 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
18651 if (ICE.isInvalid())
18652 return ICE;
18653 BitWidth = ICE.get();
18654
18655 // Zero-width bitfield is ok for anonymous field.
18656 if (Value == 0 && FieldName)
18657 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
18658 << FieldName << BitWidth->getSourceRange();
18659
18660 if (Value.isSigned() && Value.isNegative()) {
18661 if (FieldName)
18662 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
18663 << FieldName << toString(I: Value, Radix: 10);
18664 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
18665 << toString(I: Value, Radix: 10);
18666 }
18667
18668 // The size of the bit-field must not exceed our maximum permitted object
18669 // size.
18670 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18671 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
18672 << !FieldName << FieldName << toString(I: Value, Radix: 10);
18673 }
18674
18675 if (!FieldTy->isDependentType()) {
18676 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
18677 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
18678 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
18679
18680 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18681 // ABI.
18682 bool CStdConstraintViolation =
18683 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18684 bool MSBitfieldViolation =
18685 Value.ugt(RHS: TypeStorageSize) &&
18686 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18687 if (CStdConstraintViolation || MSBitfieldViolation) {
18688 unsigned DiagWidth =
18689 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18690 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
18691 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
18692 << !CStdConstraintViolation << DiagWidth;
18693 }
18694
18695 // Warn on types where the user might conceivably expect to get all
18696 // specified bits as value bits: that's all integral types other than
18697 // 'bool'.
18698 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18699 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
18700 << FieldName << toString(I: Value, Radix: 10)
18701 << (unsigned)TypeWidth;
18702 }
18703 }
18704
18705 if (isa<ConstantExpr>(Val: BitWidth))
18706 return BitWidth;
18707 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
18708}
18709
18710Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18711 Declarator &D, Expr *BitfieldWidth) {
18712 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
18713 D, BitfieldWidth,
18714 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
18715 return Res;
18716}
18717
18718FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18719 SourceLocation DeclStart,
18720 Declarator &D, Expr *BitWidth,
18721 InClassInitStyle InitStyle,
18722 AccessSpecifier AS) {
18723 if (D.isDecompositionDeclarator()) {
18724 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18725 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
18726 << Decomp.getSourceRange();
18727 return nullptr;
18728 }
18729
18730 const IdentifierInfo *II = D.getIdentifier();
18731 SourceLocation Loc = DeclStart;
18732 if (II) Loc = D.getIdentifierLoc();
18733
18734 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18735 QualType T = TInfo->getType();
18736 if (getLangOpts().CPlusPlus) {
18737 CheckExtraCXXDefaultArguments(D);
18738
18739 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
18740 UPPC: UPPC_DataMemberType)) {
18741 D.setInvalidType();
18742 T = Context.IntTy;
18743 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18744 }
18745 }
18746
18747 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
18748
18749 if (D.getDeclSpec().isInlineSpecified())
18750 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
18751 << getLangOpts().CPlusPlus17;
18752 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18753 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
18754 DiagID: diag::err_invalid_thread)
18755 << DeclSpec::getSpecifierName(S: TSCS);
18756
18757 // Check to see if this name was declared as a member previously
18758 NamedDecl *PrevDecl = nullptr;
18759 LookupResult Previous(*this, II, Loc, LookupMemberName,
18760 RedeclarationKind::ForVisibleRedeclaration);
18761 LookupName(R&: Previous, S);
18762 switch (Previous.getResultKind()) {
18763 case LookupResultKind::Found:
18764 case LookupResultKind::FoundUnresolvedValue:
18765 PrevDecl = Previous.getAsSingle<NamedDecl>();
18766 break;
18767
18768 case LookupResultKind::FoundOverloaded:
18769 PrevDecl = Previous.getRepresentativeDecl();
18770 break;
18771
18772 case LookupResultKind::NotFound:
18773 case LookupResultKind::NotFoundInCurrentInstantiation:
18774 case LookupResultKind::Ambiguous:
18775 break;
18776 }
18777 Previous.suppressDiagnostics();
18778
18779 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18780 // Maybe we will complain about the shadowed template parameter.
18781 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
18782 // Just pretend that we didn't see the previous declaration.
18783 PrevDecl = nullptr;
18784 }
18785
18786 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
18787 PrevDecl = nullptr;
18788
18789 bool Mutable
18790 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18791 SourceLocation TSSL = D.getBeginLoc();
18792 FieldDecl *NewFD
18793 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
18794 TSSL, AS, PrevDecl, D: &D);
18795
18796 if (NewFD->isInvalidDecl())
18797 Record->setInvalidDecl();
18798
18799 if (D.getDeclSpec().isModulePrivateSpecified())
18800 NewFD->setModulePrivate();
18801
18802 if (NewFD->isInvalidDecl() && PrevDecl) {
18803 // Don't introduce NewFD into scope; there's already something
18804 // with the same name in the same scope.
18805 } else if (II) {
18806 PushOnScopeChains(D: NewFD, S);
18807 } else
18808 Record->addDecl(D: NewFD);
18809
18810 return NewFD;
18811}
18812
18813FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18814 TypeSourceInfo *TInfo,
18815 RecordDecl *Record, SourceLocation Loc,
18816 bool Mutable, Expr *BitWidth,
18817 InClassInitStyle InitStyle,
18818 SourceLocation TSSL,
18819 AccessSpecifier AS, NamedDecl *PrevDecl,
18820 Declarator *D) {
18821 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18822 bool InvalidDecl = false;
18823 if (D) InvalidDecl = D->isInvalidType();
18824
18825 // If we receive a broken type, recover by assuming 'int' and
18826 // marking this declaration as invalid.
18827 if (T.isNull() || T->containsErrors()) {
18828 InvalidDecl = true;
18829 T = Context.IntTy;
18830 }
18831
18832 QualType EltTy = Context.getBaseElementType(QT: T);
18833 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18834 bool isIncomplete =
18835 LangOpts.HLSL // HLSL allows sizeless builtin types
18836 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
18837 : RequireCompleteSizedType(Loc, T: EltTy,
18838 DiagID: diag::err_field_incomplete_or_sizeless);
18839 if (isIncomplete) {
18840 // Fields of incomplete type force their record to be invalid.
18841 Record->setInvalidDecl();
18842 InvalidDecl = true;
18843 } else {
18844 NamedDecl *Def;
18845 EltTy->isIncompleteType(Def: &Def);
18846 if (Def && Def->isInvalidDecl()) {
18847 Record->setInvalidDecl();
18848 InvalidDecl = true;
18849 }
18850 }
18851 }
18852
18853 // TR 18037 does not allow fields to be declared with address space
18854 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18855 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18856 Diag(Loc, DiagID: diag::err_field_with_address_space);
18857 Record->setInvalidDecl();
18858 InvalidDecl = true;
18859 }
18860
18861 if (LangOpts.OpenCL) {
18862 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18863 // used as structure or union field: image, sampler, event or block types.
18864 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18865 T->isBlockPointerType()) {
18866 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
18867 Record->setInvalidDecl();
18868 InvalidDecl = true;
18869 }
18870 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18871 // is enabled.
18872 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18873 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
18874 Diag(Loc, DiagID: diag::err_opencl_bitfields);
18875 InvalidDecl = true;
18876 }
18877 }
18878
18879 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18880 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18881 T.hasQualifiers()) {
18882 InvalidDecl = true;
18883 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
18884 }
18885
18886 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18887 // than a variably modified type.
18888 if (!InvalidDecl && T->isVariablyModifiedType()) {
18889 if (!tryToFixVariablyModifiedVarType(
18890 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
18891 InvalidDecl = true;
18892 }
18893
18894 // Fields can not have abstract class types
18895 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18896 DiagID: diag::err_abstract_type_in_decl,
18897 Args: AbstractFieldType))
18898 InvalidDecl = true;
18899
18900 if (InvalidDecl)
18901 BitWidth = nullptr;
18902 // If this is declared as a bit-field, check the bit-field.
18903 if (BitWidth) {
18904 BitWidth =
18905 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
18906 if (!BitWidth) {
18907 InvalidDecl = true;
18908 BitWidth = nullptr;
18909 }
18910 }
18911
18912 // Check that 'mutable' is consistent with the type of the declaration.
18913 if (!InvalidDecl && Mutable) {
18914 unsigned DiagID = 0;
18915 if (T->isReferenceType())
18916 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18917 : diag::err_mutable_reference;
18918 else if (T.isConstQualified())
18919 DiagID = diag::err_mutable_const;
18920
18921 if (DiagID) {
18922 SourceLocation ErrLoc = Loc;
18923 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18924 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18925 Diag(Loc: ErrLoc, DiagID);
18926 if (DiagID != diag::ext_mutable_reference) {
18927 Mutable = false;
18928 InvalidDecl = true;
18929 }
18930 }
18931 }
18932
18933 // C++11 [class.union]p8 (DR1460):
18934 // At most one variant member of a union may have a
18935 // brace-or-equal-initializer.
18936 if (InitStyle != ICIS_NoInit)
18937 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
18938
18939 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
18940 BW: BitWidth, Mutable, InitStyle);
18941 if (InvalidDecl)
18942 NewFD->setInvalidDecl();
18943
18944 if (!InvalidDecl)
18945 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
18946
18947 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
18948 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
18949 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
18950 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
18951 NewFD->setInvalidDecl();
18952 }
18953
18954 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18955 if (Record->isUnion()) {
18956 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18957 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
18958 if (RDecl->getDefinition()) {
18959 // C++ [class.union]p1: An object of a class with a non-trivial
18960 // constructor, a non-trivial copy constructor, a non-trivial
18961 // destructor, or a non-trivial copy assignment operator
18962 // cannot be a member of a union, nor can an array of such
18963 // objects.
18964 if (CheckNontrivialField(FD: NewFD))
18965 NewFD->setInvalidDecl();
18966 }
18967 }
18968
18969 // C++ [class.union]p1: If a union contains a member of reference type,
18970 // the program is ill-formed, except when compiling with MSVC extensions
18971 // enabled.
18972 if (EltTy->isReferenceType()) {
18973 const bool HaveMSExt =
18974 getLangOpts().MicrosoftExt &&
18975 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
18976
18977 Diag(Loc: NewFD->getLocation(),
18978 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
18979 : diag::err_union_member_of_reference_type)
18980 << NewFD->getDeclName() << EltTy;
18981 if (!HaveMSExt)
18982 NewFD->setInvalidDecl();
18983 }
18984 }
18985 }
18986
18987 // FIXME: We need to pass in the attributes given an AST
18988 // representation, not a parser representation.
18989 if (D) {
18990 // FIXME: The current scope is almost... but not entirely... correct here.
18991 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
18992
18993 if (NewFD->hasAttrs())
18994 CheckAlignasUnderalignment(D: NewFD);
18995 }
18996
18997 // In auto-retain/release, infer strong retension for fields of
18998 // retainable type.
18999 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19000 NewFD->setInvalidDecl();
19001
19002 if (T.isObjCGCWeak())
19003 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19004
19005 // PPC MMA non-pointer types are not allowed as field types.
19006 if (Context.getTargetInfo().getTriple().isPPC64() &&
19007 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19008 NewFD->setInvalidDecl();
19009
19010 NewFD->setAccess(AS);
19011 return NewFD;
19012}
19013
19014bool Sema::CheckNontrivialField(FieldDecl *FD) {
19015 assert(FD);
19016 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19017
19018 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19019 return false;
19020
19021 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19022 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
19023 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(Val: RT->getDecl());
19024 if (RDecl->getDefinition()) {
19025 // We check for copy constructors before constructors
19026 // because otherwise we'll never get complaints about
19027 // copy constructors.
19028
19029 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19030 // We're required to check for any non-trivial constructors. Since the
19031 // implicit default constructor is suppressed if there are any
19032 // user-declared constructors, we just need to check that there is a
19033 // trivial default constructor and a trivial copy constructor. (We don't
19034 // worry about move constructors here, since this is a C++98 check.)
19035 if (RDecl->hasNonTrivialCopyConstructor())
19036 member = CXXSpecialMemberKind::CopyConstructor;
19037 else if (!RDecl->hasTrivialDefaultConstructor())
19038 member = CXXSpecialMemberKind::DefaultConstructor;
19039 else if (RDecl->hasNonTrivialCopyAssignment())
19040 member = CXXSpecialMemberKind::CopyAssignment;
19041 else if (RDecl->hasNonTrivialDestructor())
19042 member = CXXSpecialMemberKind::Destructor;
19043
19044 if (member != CXXSpecialMemberKind::Invalid) {
19045 if (!getLangOpts().CPlusPlus11 &&
19046 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
19047 // Objective-C++ ARC: it is an error to have a non-trivial field of
19048 // a union. However, system headers in Objective-C programs
19049 // occasionally have Objective-C lifetime objects within unions,
19050 // and rather than cause the program to fail, we make those
19051 // members unavailable.
19052 SourceLocation Loc = FD->getLocation();
19053 if (getSourceManager().isInSystemHeader(Loc)) {
19054 if (!FD->hasAttr<UnavailableAttr>())
19055 FD->addAttr(A: UnavailableAttr::CreateImplicit(Ctx&: Context, Message: "",
19056 ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19057 return false;
19058 }
19059 }
19060
19061 Diag(
19062 Loc: FD->getLocation(),
19063 DiagID: getLangOpts().CPlusPlus11
19064 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19065 : diag::err_illegal_union_or_anon_struct_member)
19066 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19067 DiagnoseNontrivial(Record: RDecl, CSM: member);
19068 return !getLangOpts().CPlusPlus11;
19069 }
19070 }
19071 }
19072
19073 return false;
19074}
19075
19076void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19077 SmallVectorImpl<Decl *> &AllIvarDecls) {
19078 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19079 return;
19080
19081 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19082 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19083
19084 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19085 return;
19086 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19087 if (!ID) {
19088 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19089 if (!CD->IsClassExtension())
19090 return;
19091 }
19092 // No need to add this to end of @implementation.
19093 else
19094 return;
19095 }
19096 // All conditions are met. Add a new bitfield to the tail end of ivars.
19097 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19098 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19099 Expr *BitWidth =
19100 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19101
19102 Ivar = ObjCIvarDecl::Create(
19103 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19104 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19105 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19106 AllIvarDecls.push_back(Elt: Ivar);
19107}
19108
19109/// [class.dtor]p4:
19110/// At the end of the definition of a class, overload resolution is
19111/// performed among the prospective destructors declared in that class with
19112/// an empty argument list to select the destructor for the class, also
19113/// known as the selected destructor.
19114///
19115/// We do the overload resolution here, then mark the selected constructor in the AST.
19116/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19117static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19118 if (!Record->hasUserDeclaredDestructor()) {
19119 return;
19120 }
19121
19122 SourceLocation Loc = Record->getLocation();
19123 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19124
19125 for (auto *Decl : Record->decls()) {
19126 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19127 if (DD->isInvalidDecl())
19128 continue;
19129 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19130 CandidateSet&: OCS);
19131 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19132 }
19133 }
19134
19135 if (OCS.empty()) {
19136 return;
19137 }
19138 OverloadCandidateSet::iterator Best;
19139 unsigned Msg = 0;
19140 OverloadCandidateDisplayKind DisplayKind;
19141
19142 switch (OCS.BestViableFunction(S, Loc, Best)) {
19143 case OR_Success:
19144 case OR_Deleted:
19145 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19146 break;
19147
19148 case OR_Ambiguous:
19149 Msg = diag::err_ambiguous_destructor;
19150 DisplayKind = OCD_AmbiguousCandidates;
19151 break;
19152
19153 case OR_No_Viable_Function:
19154 Msg = diag::err_no_viable_destructor;
19155 DisplayKind = OCD_AllCandidates;
19156 break;
19157 }
19158
19159 if (Msg) {
19160 // OpenCL have got their own thing going with destructors. It's slightly broken,
19161 // but we allow it.
19162 if (!S.LangOpts.OpenCL) {
19163 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19164 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19165 Record->setInvalidDecl();
19166 }
19167 // It's a bit hacky: At this point we've raised an error but we want the
19168 // rest of the compiler to continue somehow working. However almost
19169 // everything we'll try to do with the class will depend on there being a
19170 // destructor. So let's pretend the first one is selected and hope for the
19171 // best.
19172 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19173 }
19174}
19175
19176/// [class.mem.special]p5
19177/// Two special member functions are of the same kind if:
19178/// - they are both default constructors,
19179/// - they are both copy or move constructors with the same first parameter
19180/// type, or
19181/// - they are both copy or move assignment operators with the same first
19182/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19183static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19184 CXXMethodDecl *M1,
19185 CXXMethodDecl *M2,
19186 CXXSpecialMemberKind CSM) {
19187 // We don't want to compare templates to non-templates: See
19188 // https://github.com/llvm/llvm-project/issues/59206
19189 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19190 return bool(M1->getDescribedFunctionTemplate()) ==
19191 bool(M2->getDescribedFunctionTemplate());
19192 // FIXME: better resolve CWG
19193 // https://cplusplus.github.io/CWG/issues/2787.html
19194 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19195 T2: M2->getNonObjectParameter(I: 0)->getType()))
19196 return false;
19197 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19198 T2: M2->getFunctionObjectParameterReferenceType()))
19199 return false;
19200
19201 return true;
19202}
19203
19204/// [class.mem.special]p6:
19205/// An eligible special member function is a special member function for which:
19206/// - the function is not deleted,
19207/// - the associated constraints, if any, are satisfied, and
19208/// - no special member function of the same kind whose associated constraints
19209/// [CWG2595], if any, are satisfied is more constrained.
19210static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19211 ArrayRef<CXXMethodDecl *> Methods,
19212 CXXSpecialMemberKind CSM) {
19213 SmallVector<bool, 4> SatisfactionStatus;
19214
19215 for (CXXMethodDecl *Method : Methods) {
19216 if (!Method->getTrailingRequiresClause())
19217 SatisfactionStatus.push_back(Elt: true);
19218 else {
19219 ConstraintSatisfaction Satisfaction;
19220 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19221 SatisfactionStatus.push_back(Elt: false);
19222 else
19223 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19224 }
19225 }
19226
19227 for (size_t i = 0; i < Methods.size(); i++) {
19228 if (!SatisfactionStatus[i])
19229 continue;
19230 CXXMethodDecl *Method = Methods[i];
19231 CXXMethodDecl *OrigMethod = Method;
19232 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19233 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19234
19235 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19236 bool AnotherMethodIsMoreConstrained = false;
19237 for (size_t j = 0; j < Methods.size(); j++) {
19238 if (i == j || !SatisfactionStatus[j])
19239 continue;
19240 CXXMethodDecl *OtherMethod = Methods[j];
19241 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19242 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19243
19244 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19245 CSM))
19246 continue;
19247
19248 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19249 if (!Other)
19250 continue;
19251 if (!Orig) {
19252 AnotherMethodIsMoreConstrained = true;
19253 break;
19254 }
19255 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19256 Result&: AnotherMethodIsMoreConstrained)) {
19257 // There was an error with the constraints comparison. Exit the loop
19258 // and don't consider this function eligible.
19259 AnotherMethodIsMoreConstrained = true;
19260 }
19261 if (AnotherMethodIsMoreConstrained)
19262 break;
19263 }
19264 // FIXME: Do not consider deleted methods as eligible after implementing
19265 // DR1734 and DR1496.
19266 if (!AnotherMethodIsMoreConstrained) {
19267 Method->setIneligibleOrNotSelected(false);
19268 Record->addedEligibleSpecialMemberFunction(MD: Method,
19269 SMKind: 1 << llvm::to_underlying(E: CSM));
19270 }
19271 }
19272}
19273
19274static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19275 CXXRecordDecl *Record) {
19276 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19277 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19278 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19279 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19280 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19281
19282 for (auto *Decl : Record->decls()) {
19283 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19284 if (!MD) {
19285 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19286 if (FTD)
19287 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19288 }
19289 if (!MD)
19290 continue;
19291 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19292 if (CD->isInvalidDecl())
19293 continue;
19294 if (CD->isDefaultConstructor())
19295 DefaultConstructors.push_back(Elt: MD);
19296 else if (CD->isCopyConstructor())
19297 CopyConstructors.push_back(Elt: MD);
19298 else if (CD->isMoveConstructor())
19299 MoveConstructors.push_back(Elt: MD);
19300 } else if (MD->isCopyAssignmentOperator()) {
19301 CopyAssignmentOperators.push_back(Elt: MD);
19302 } else if (MD->isMoveAssignmentOperator()) {
19303 MoveAssignmentOperators.push_back(Elt: MD);
19304 }
19305 }
19306
19307 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19308 CSM: CXXSpecialMemberKind::DefaultConstructor);
19309 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19310 CSM: CXXSpecialMemberKind::CopyConstructor);
19311 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19312 CSM: CXXSpecialMemberKind::MoveConstructor);
19313 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19314 CSM: CXXSpecialMemberKind::CopyAssignment);
19315 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19316 CSM: CXXSpecialMemberKind::MoveAssignment);
19317}
19318
19319bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19320 // Check to see if a FieldDecl is a pointer to a function.
19321 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19322 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19323 if (!FD) {
19324 // Check whether this is a forward declaration that was inserted by
19325 // Clang. This happens when a non-forward declared / defined type is
19326 // used, e.g.:
19327 //
19328 // struct foo {
19329 // struct bar *(*f)();
19330 // struct bar *(*g)();
19331 // };
19332 //
19333 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19334 // incomplete definition.
19335 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19336 return !TD->isCompleteDefinition();
19337 return false;
19338 }
19339 QualType FieldType = FD->getType().getDesugaredType(Context);
19340 if (isa<PointerType>(Val: FieldType)) {
19341 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19342 return PointeeType.getDesugaredType(Context)->isFunctionType();
19343 }
19344 // If a member is a struct entirely of function pointers, that counts too.
19345 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
19346 const RecordDecl *Record = RT->getDecl();
19347 if (Record->isStruct() && EntirelyFunctionPointers(Record))
19348 return true;
19349 }
19350 return false;
19351 };
19352
19353 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19354}
19355
19356void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19357 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19358 SourceLocation RBrac,
19359 const ParsedAttributesView &Attrs) {
19360 assert(EnclosingDecl && "missing record or interface decl");
19361
19362 // If this is an Objective-C @implementation or category and we have
19363 // new fields here we should reset the layout of the interface since
19364 // it will now change.
19365 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19366 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19367 switch (DC->getKind()) {
19368 default: break;
19369 case Decl::ObjCCategory:
19370 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19371 break;
19372 case Decl::ObjCImplementation:
19373 Context.
19374 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19375 break;
19376 }
19377 }
19378
19379 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19380 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19381
19382 // Start counting up the number of named members; make sure to include
19383 // members of anonymous structs and unions in the total.
19384 unsigned NumNamedMembers = 0;
19385 if (Record) {
19386 for (const auto *I : Record->decls()) {
19387 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19388 if (IFD->getDeclName())
19389 ++NumNamedMembers;
19390 }
19391 }
19392
19393 // Verify that all the fields are okay.
19394 SmallVector<FieldDecl*, 32> RecFields;
19395 const FieldDecl *PreviousField = nullptr;
19396 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19397 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19398 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19399
19400 // Get the type for the field.
19401 const Type *FDTy = FD->getType().getTypePtr();
19402
19403 if (!FD->isAnonymousStructOrUnion()) {
19404 // Remember all fields written by the user.
19405 RecFields.push_back(Elt: FD);
19406 }
19407
19408 // If the field is already invalid for some reason, don't emit more
19409 // diagnostics about it.
19410 if (FD->isInvalidDecl()) {
19411 EnclosingDecl->setInvalidDecl();
19412 continue;
19413 }
19414
19415 // C99 6.7.2.1p2:
19416 // A structure or union shall not contain a member with
19417 // incomplete or function type (hence, a structure shall not
19418 // contain an instance of itself, but may contain a pointer to
19419 // an instance of itself), except that the last member of a
19420 // structure with more than one named member may have incomplete
19421 // array type; such a structure (and any union containing,
19422 // possibly recursively, a member that is such a structure)
19423 // shall not be a member of a structure or an element of an
19424 // array.
19425 bool IsLastField = (i + 1 == Fields.end());
19426 if (FDTy->isFunctionType()) {
19427 // Field declared as a function.
19428 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19429 << FD->getDeclName();
19430 FD->setInvalidDecl();
19431 EnclosingDecl->setInvalidDecl();
19432 continue;
19433 } else if (FDTy->isIncompleteArrayType() &&
19434 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19435 if (Record) {
19436 // Flexible array member.
19437 // Microsoft and g++ is more permissive regarding flexible array.
19438 // It will accept flexible array in union and also
19439 // as the sole element of a struct/class.
19440 unsigned DiagID = 0;
19441 if (!Record->isUnion() && !IsLastField) {
19442 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
19443 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19444 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
19445 FD->setInvalidDecl();
19446 EnclosingDecl->setInvalidDecl();
19447 continue;
19448 } else if (Record->isUnion())
19449 DiagID = getLangOpts().MicrosoftExt
19450 ? diag::ext_flexible_array_union_ms
19451 : diag::ext_flexible_array_union_gnu;
19452 else if (NumNamedMembers < 1)
19453 DiagID = getLangOpts().MicrosoftExt
19454 ? diag::ext_flexible_array_empty_aggregate_ms
19455 : diag::ext_flexible_array_empty_aggregate_gnu;
19456
19457 if (DiagID)
19458 Diag(Loc: FD->getLocation(), DiagID)
19459 << FD->getDeclName() << Record->getTagKind();
19460 // While the layout of types that contain virtual bases is not specified
19461 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19462 // virtual bases after the derived members. This would make a flexible
19463 // array member declared at the end of an object not adjacent to the end
19464 // of the type.
19465 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19466 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
19467 << FD->getDeclName() << Record->getTagKind();
19468 if (!getLangOpts().C99)
19469 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
19470 << FD->getDeclName() << Record->getTagKind();
19471
19472 // If the element type has a non-trivial destructor, we would not
19473 // implicitly destroy the elements, so disallow it for now.
19474 //
19475 // FIXME: GCC allows this. We should probably either implicitly delete
19476 // the destructor of the containing class, or just allow this.
19477 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
19478 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19479 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
19480 << FD->getDeclName() << FD->getType();
19481 FD->setInvalidDecl();
19482 EnclosingDecl->setInvalidDecl();
19483 continue;
19484 }
19485 // Okay, we have a legal flexible array member at the end of the struct.
19486 Record->setHasFlexibleArrayMember(true);
19487 } else {
19488 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19489 // unless they are followed by another ivar. That check is done
19490 // elsewhere, after synthesized ivars are known.
19491 }
19492 } else if (!FDTy->isDependentType() &&
19493 (LangOpts.HLSL // HLSL allows sizeless builtin types
19494 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
19495 DiagID: diag::err_incomplete_type)
19496 : RequireCompleteSizedType(
19497 Loc: FD->getLocation(), T: FD->getType(),
19498 DiagID: diag::err_field_incomplete_or_sizeless))) {
19499 // Incomplete type
19500 FD->setInvalidDecl();
19501 EnclosingDecl->setInvalidDecl();
19502 continue;
19503 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19504 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19505 // A type which contains a flexible array member is considered to be a
19506 // flexible array member.
19507 Record->setHasFlexibleArrayMember(true);
19508 if (!Record->isUnion()) {
19509 // If this is a struct/class and this is not the last element, reject
19510 // it. Note that GCC supports variable sized arrays in the middle of
19511 // structures.
19512 if (!IsLastField)
19513 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
19514 << FD->getDeclName() << FD->getType();
19515 else {
19516 // We support flexible arrays at the end of structs in
19517 // other structs as an extension.
19518 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
19519 << FD->getDeclName();
19520 }
19521 }
19522 }
19523 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
19524 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
19525 DiagID: diag::err_abstract_type_in_decl,
19526 Args: AbstractIvarType)) {
19527 // Ivars can not have abstract class types
19528 FD->setInvalidDecl();
19529 }
19530 if (Record && FDTTy->getDecl()->hasObjectMember())
19531 Record->setHasObjectMember(true);
19532 if (Record && FDTTy->getDecl()->hasVolatileMember())
19533 Record->setHasVolatileMember(true);
19534 } else if (FDTy->isObjCObjectType()) {
19535 /// A field cannot be an Objective-c object
19536 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
19537 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
19538 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19539 FD->setType(T);
19540 } else if (Record && Record->isUnion() &&
19541 FD->getType().hasNonTrivialObjCLifetime() &&
19542 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
19543 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19544 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19545 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
19546 // For backward compatibility, fields of C unions declared in system
19547 // headers that have non-trivial ObjC ownership qualifications are marked
19548 // as unavailable unless the qualifier is explicit and __strong. This can
19549 // break ABI compatibility between programs compiled with ARC and MRR, but
19550 // is a better option than rejecting programs using those unions under
19551 // ARC.
19552 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19553 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
19554 Range: FD->getLocation()));
19555 } else if (getLangOpts().ObjC &&
19556 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19557 !Record->hasObjectMember()) {
19558 if (FD->getType()->isObjCObjectPointerType() ||
19559 FD->getType().isObjCGCStrong())
19560 Record->setHasObjectMember(true);
19561 else if (Context.getAsArrayType(T: FD->getType())) {
19562 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
19563 if (BaseType->isRecordType() &&
19564 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19565 Record->setHasObjectMember(true);
19566 else if (BaseType->isObjCObjectPointerType() ||
19567 BaseType.isObjCGCStrong())
19568 Record->setHasObjectMember(true);
19569 }
19570 }
19571
19572 if (Record && !getLangOpts().CPlusPlus &&
19573 !shouldIgnoreForRecordTriviality(FD)) {
19574 QualType FT = FD->getType();
19575 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19576 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19577 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19578 Record->isUnion())
19579 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19580 }
19581 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19582 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19583 Record->setNonTrivialToPrimitiveCopy(true);
19584 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19585 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19586 }
19587 if (FD->hasAttr<ExplicitInitAttr>())
19588 Record->setHasUninitializedExplicitInitFields(true);
19589 if (FT.isDestructedType()) {
19590 Record->setNonTrivialToPrimitiveDestroy(true);
19591 Record->setParamDestroyedInCallee(true);
19592 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19593 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19594 }
19595
19596 if (const auto *RT = FT->getAs<RecordType>()) {
19597 if (RT->getDecl()->getArgPassingRestrictions() ==
19598 RecordArgPassingKind::CanNeverPassInRegs)
19599 Record->setArgPassingRestrictions(
19600 RecordArgPassingKind::CanNeverPassInRegs);
19601 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19602 Record->setArgPassingRestrictions(
19603 RecordArgPassingKind::CanNeverPassInRegs);
19604 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19605 Q && Q.isAddressDiscriminated()) {
19606 Record->setArgPassingRestrictions(
19607 RecordArgPassingKind::CanNeverPassInRegs);
19608 }
19609 }
19610
19611 if (Record && FD->getType().isVolatileQualified())
19612 Record->setHasVolatileMember(true);
19613 bool ReportMSBitfieldStoragePacking =
19614 Record && PreviousField &&
19615 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
19616 Loc: Record->getLocation());
19617 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19618 return FD->isBitField() && !FD->getType()->isDependentType();
19619 };
19620
19621 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19622 IsNonDependentBitField(PreviousField)) {
19623 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
19624 CharUnits PreviousFieldStorageSize =
19625 Context.getTypeSizeInChars(T: PreviousField->getType());
19626 if (FDStorageSize != PreviousFieldStorageSize) {
19627 Diag(Loc: FD->getLocation(),
19628 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
19629 << FD << FD->getType() << FDStorageSize.getQuantity()
19630 << PreviousFieldStorageSize.getQuantity();
19631 Diag(Loc: PreviousField->getLocation(),
19632 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
19633 << PreviousField << PreviousField->getType();
19634 }
19635 }
19636 // Keep track of the number of named members.
19637 if (FD->getIdentifier())
19638 ++NumNamedMembers;
19639 }
19640
19641 // Okay, we successfully defined 'Record'.
19642 if (Record) {
19643 bool Completed = false;
19644 if (S) {
19645 Scope *Parent = S->getParent();
19646 if (Parent && Parent->isTypeAliasScope() &&
19647 Parent->isTemplateParamScope())
19648 Record->setInvalidDecl();
19649 }
19650
19651 if (CXXRecord) {
19652 if (!CXXRecord->isInvalidDecl()) {
19653 // Set access bits correctly on the directly-declared conversions.
19654 for (CXXRecordDecl::conversion_iterator
19655 I = CXXRecord->conversion_begin(),
19656 E = CXXRecord->conversion_end(); I != E; ++I)
19657 I.setAccess((*I)->getAccess());
19658 }
19659
19660 // Add any implicitly-declared members to this class.
19661 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
19662
19663 if (!CXXRecord->isDependentType()) {
19664 if (!CXXRecord->isInvalidDecl()) {
19665 // If we have virtual base classes, we may end up finding multiple
19666 // final overriders for a given virtual function. Check for this
19667 // problem now.
19668 if (CXXRecord->getNumVBases()) {
19669 CXXFinalOverriderMap FinalOverriders;
19670 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
19671
19672 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19673 MEnd = FinalOverriders.end();
19674 M != MEnd; ++M) {
19675 for (OverridingMethods::iterator SO = M->second.begin(),
19676 SOEnd = M->second.end();
19677 SO != SOEnd; ++SO) {
19678 assert(SO->second.size() > 0 &&
19679 "Virtual function without overriding functions?");
19680 if (SO->second.size() == 1)
19681 continue;
19682
19683 // C++ [class.virtual]p2:
19684 // In a derived class, if a virtual member function of a base
19685 // class subobject has more than one final overrider the
19686 // program is ill-formed.
19687 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
19688 << (const NamedDecl *)M->first << Record;
19689 Diag(Loc: M->first->getLocation(),
19690 DiagID: diag::note_overridden_virtual_function);
19691 for (OverridingMethods::overriding_iterator
19692 OM = SO->second.begin(),
19693 OMEnd = SO->second.end();
19694 OM != OMEnd; ++OM)
19695 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
19696 << (const NamedDecl *)M->first << OM->Method->getParent();
19697
19698 Record->setInvalidDecl();
19699 }
19700 }
19701 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
19702 Completed = true;
19703 }
19704 }
19705 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
19706 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
19707 }
19708 }
19709
19710 if (!Completed)
19711 Record->completeDefinition();
19712
19713 // Handle attributes before checking the layout.
19714 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
19715
19716 // Maybe randomize the record's decls. We automatically randomize a record
19717 // of function pointers, unless it has the "no_randomize_layout" attribute.
19718 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
19719 !Record->isRandomized() && !Record->isUnion() &&
19720 (Record->hasAttr<RandomizeLayoutAttr>() ||
19721 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19722 EntirelyFunctionPointers(Record)))) {
19723 SmallVector<Decl *, 32> NewDeclOrdering;
19724 if (randstruct::randomizeStructureLayout(Context, RD: Record,
19725 FinalOrdering&: NewDeclOrdering))
19726 Record->reorderDecls(Decls: NewDeclOrdering);
19727 }
19728
19729 // We may have deferred checking for a deleted destructor. Check now.
19730 if (CXXRecord) {
19731 auto *Dtor = CXXRecord->getDestructor();
19732 if (Dtor && Dtor->isImplicit() &&
19733 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
19734 CXXRecord->setImplicitDestructorIsDeleted();
19735 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
19736 }
19737 }
19738
19739 if (Record->hasAttrs()) {
19740 CheckAlignasUnderalignment(D: Record);
19741
19742 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19743 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
19744 Range: IA->getRange(), BestCase: IA->getBestCase(),
19745 SemanticSpelling: IA->getInheritanceModel());
19746 }
19747
19748 // Check if the structure/union declaration is a type that can have zero
19749 // size in C. For C this is a language extension, for C++ it may cause
19750 // compatibility problems.
19751 bool CheckForZeroSize;
19752 if (!getLangOpts().CPlusPlus) {
19753 CheckForZeroSize = true;
19754 } else {
19755 // For C++ filter out types that cannot be referenced in C code.
19756 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
19757 CheckForZeroSize =
19758 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19759 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19760 CXXRecord->isCLike();
19761 }
19762 if (CheckForZeroSize) {
19763 bool ZeroSize = true;
19764 bool IsEmpty = true;
19765 unsigned NonBitFields = 0;
19766 for (RecordDecl::field_iterator I = Record->field_begin(),
19767 E = Record->field_end();
19768 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19769 IsEmpty = false;
19770 if (I->isUnnamedBitField()) {
19771 if (!I->isZeroLengthBitField())
19772 ZeroSize = false;
19773 } else {
19774 ++NonBitFields;
19775 QualType FieldType = I->getType();
19776 if (FieldType->isIncompleteType() ||
19777 !Context.getTypeSizeInChars(T: FieldType).isZero())
19778 ZeroSize = false;
19779 }
19780 }
19781
19782 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19783 // allowed in C++, but warn if its declaration is inside
19784 // extern "C" block.
19785 if (ZeroSize) {
19786 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
19787 diag::warn_zero_size_struct_union_in_extern_c :
19788 diag::warn_zero_size_struct_union_compat)
19789 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19790 }
19791
19792 // Structs without named members are extension in C (C99 6.7.2.1p7),
19793 // but are accepted by GCC. In C2y, this became implementation-defined
19794 // (C2y 6.7.3.2p10).
19795 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19796 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
19797 : diag::ext_no_named_members_in_struct_union)
19798 << Record->isUnion();
19799 }
19800 }
19801 } else {
19802 ObjCIvarDecl **ClsFields =
19803 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19804 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
19805 ID->setEndOfDefinitionLoc(RBrac);
19806 // Add ivar's to class's DeclContext.
19807 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19808 ClsFields[i]->setLexicalDeclContext(ID);
19809 ID->addDecl(D: ClsFields[i]);
19810 }
19811 // Must enforce the rule that ivars in the base classes may not be
19812 // duplicates.
19813 if (ID->getSuperClass())
19814 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
19815 } else if (ObjCImplementationDecl *IMPDecl =
19816 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
19817 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19818 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19819 // Ivar declared in @implementation never belongs to the implementation.
19820 // Only it is in implementation's lexical context.
19821 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19822 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
19823 Loc: RBrac);
19824 IMPDecl->setIvarLBraceLoc(LBrac);
19825 IMPDecl->setIvarRBraceLoc(RBrac);
19826 } else if (ObjCCategoryDecl *CDecl =
19827 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
19828 // case of ivars in class extension; all other cases have been
19829 // reported as errors elsewhere.
19830 // FIXME. Class extension does not have a LocEnd field.
19831 // CDecl->setLocEnd(RBrac);
19832 // Add ivar's to class extension's DeclContext.
19833 // Diagnose redeclaration of private ivars.
19834 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19835 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19836 if (IDecl) {
19837 if (const ObjCIvarDecl *ClsIvar =
19838 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19839 Diag(Loc: ClsFields[i]->getLocation(),
19840 DiagID: diag::err_duplicate_ivar_declaration);
19841 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
19842 continue;
19843 }
19844 for (const auto *Ext : IDecl->known_extensions()) {
19845 if (const ObjCIvarDecl *ClsExtIvar
19846 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
19847 Diag(Loc: ClsFields[i]->getLocation(),
19848 DiagID: diag::err_duplicate_ivar_declaration);
19849 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
19850 continue;
19851 }
19852 }
19853 }
19854 ClsFields[i]->setLexicalDeclContext(CDecl);
19855 CDecl->addDecl(D: ClsFields[i]);
19856 }
19857 CDecl->setIvarLBraceLoc(LBrac);
19858 CDecl->setIvarRBraceLoc(RBrac);
19859 }
19860 }
19861 ProcessAPINotes(D: Record);
19862}
19863
19864// Given an integral type, return the next larger integral type
19865// (or a NULL type of no such type exists).
19866static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19867 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19868 // enum checking below.
19869 assert((T->isIntegralType(Context) ||
19870 T->isEnumeralType()) && "Integral type required!");
19871 const unsigned NumTypes = 4;
19872 QualType SignedIntegralTypes[NumTypes] = {
19873 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19874 };
19875 QualType UnsignedIntegralTypes[NumTypes] = {
19876 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19877 Context.UnsignedLongLongTy
19878 };
19879
19880 unsigned BitWidth = Context.getTypeSize(T);
19881 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19882 : UnsignedIntegralTypes;
19883 for (unsigned I = 0; I != NumTypes; ++I)
19884 if (Context.getTypeSize(T: Types[I]) > BitWidth)
19885 return Types[I];
19886
19887 return QualType();
19888}
19889
19890EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19891 EnumConstantDecl *LastEnumConst,
19892 SourceLocation IdLoc,
19893 IdentifierInfo *Id,
19894 Expr *Val) {
19895 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19896 llvm::APSInt EnumVal(IntWidth);
19897 QualType EltTy;
19898
19899 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
19900 Val = nullptr;
19901
19902 if (Val)
19903 Val = DefaultLvalueConversion(E: Val).get();
19904
19905 if (Val) {
19906 if (Enum->isDependentType() || Val->isTypeDependent() ||
19907 Val->containsErrors())
19908 EltTy = Context.DependentTy;
19909 else {
19910 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19911 // underlying type, but do allow it in all other contexts.
19912 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19913 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19914 // constant-expression in the enumerator-definition shall be a converted
19915 // constant expression of the underlying type.
19916 EltTy = Enum->getIntegerType();
19917 ExprResult Converted = CheckConvertedConstantExpression(
19918 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
19919 if (Converted.isInvalid())
19920 Val = nullptr;
19921 else
19922 Val = Converted.get();
19923 } else if (!Val->isValueDependent() &&
19924 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
19925 CanFold: AllowFoldKind::Allow)
19926 .get())) {
19927 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19928 } else {
19929 if (Enum->isComplete()) {
19930 EltTy = Enum->getIntegerType();
19931
19932 // In Obj-C and Microsoft mode, require the enumeration value to be
19933 // representable in the underlying type of the enumeration. In C++11,
19934 // we perform a non-narrowing conversion as part of converted constant
19935 // expression checking.
19936 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
19937 if (Context.getTargetInfo()
19938 .getTriple()
19939 .isWindowsMSVCEnvironment()) {
19940 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
19941 } else {
19942 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
19943 }
19944 }
19945
19946 // Cast to the underlying type.
19947 Val = ImpCastExprToType(E: Val, Type: EltTy,
19948 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
19949 : CK_IntegralCast)
19950 .get();
19951 } else if (getLangOpts().CPlusPlus) {
19952 // C++11 [dcl.enum]p5:
19953 // If the underlying type is not fixed, the type of each enumerator
19954 // is the type of its initializing value:
19955 // - If an initializer is specified for an enumerator, the
19956 // initializing value has the same type as the expression.
19957 EltTy = Val->getType();
19958 } else {
19959 // C99 6.7.2.2p2:
19960 // The expression that defines the value of an enumeration constant
19961 // shall be an integer constant expression that has a value
19962 // representable as an int.
19963
19964 // Complain if the value is not representable in an int.
19965 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
19966 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
19967 ? diag::warn_c17_compat_enum_value_not_int
19968 : diag::ext_c23_enum_value_not_int)
19969 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
19970 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19971 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
19972 // Force the type of the expression to 'int'.
19973 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
19974 }
19975 EltTy = Val->getType();
19976 }
19977 }
19978 }
19979 }
19980
19981 if (!Val) {
19982 if (Enum->isDependentType())
19983 EltTy = Context.DependentTy;
19984 else if (!LastEnumConst) {
19985 // C++0x [dcl.enum]p5:
19986 // If the underlying type is not fixed, the type of each enumerator
19987 // is the type of its initializing value:
19988 // - If no initializer is specified for the first enumerator, the
19989 // initializing value has an unspecified integral type.
19990 //
19991 // GCC uses 'int' for its unspecified integral type, as does
19992 // C99 6.7.2.2p3.
19993 if (Enum->isFixed()) {
19994 EltTy = Enum->getIntegerType();
19995 }
19996 else {
19997 EltTy = Context.IntTy;
19998 }
19999 } else {
20000 // Assign the last value + 1.
20001 EnumVal = LastEnumConst->getInitVal();
20002 ++EnumVal;
20003 EltTy = LastEnumConst->getType();
20004
20005 // Check for overflow on increment.
20006 if (EnumVal < LastEnumConst->getInitVal()) {
20007 // C++0x [dcl.enum]p5:
20008 // If the underlying type is not fixed, the type of each enumerator
20009 // is the type of its initializing value:
20010 //
20011 // - Otherwise the type of the initializing value is the same as
20012 // the type of the initializing value of the preceding enumerator
20013 // unless the incremented value is not representable in that type,
20014 // in which case the type is an unspecified integral type
20015 // sufficient to contain the incremented value. If no such type
20016 // exists, the program is ill-formed.
20017 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20018 if (T.isNull() || Enum->isFixed()) {
20019 // There is no integral type larger enough to represent this
20020 // value. Complain, then allow the value to wrap around.
20021 EnumVal = LastEnumConst->getInitVal();
20022 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20023 ++EnumVal;
20024 if (Enum->isFixed())
20025 // When the underlying type is fixed, this is ill-formed.
20026 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20027 << toString(I: EnumVal, Radix: 10)
20028 << EltTy;
20029 else
20030 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20031 << toString(I: EnumVal, Radix: 10);
20032 } else {
20033 EltTy = T;
20034 }
20035
20036 // Retrieve the last enumerator's value, extent that type to the
20037 // type that is supposed to be large enough to represent the incremented
20038 // value, then increment.
20039 EnumVal = LastEnumConst->getInitVal();
20040 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20041 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20042 ++EnumVal;
20043
20044 // If we're not in C++, diagnose the overflow of enumerator values,
20045 // which in C99 means that the enumerator value is not representable in
20046 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20047 // are representable in some larger integral type and we allow it in
20048 // older language modes as an extension.
20049 // Exclude fixed enumerators since they are diagnosed with an error for
20050 // this case.
20051 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20052 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20053 ? diag::warn_c17_compat_enum_value_not_int
20054 : diag::ext_c23_enum_value_not_int)
20055 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20056 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20057 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20058 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20059 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20060 : diag::ext_c23_enum_value_not_int)
20061 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20062 }
20063 }
20064 }
20065
20066 if (!EltTy->isDependentType()) {
20067 // Make the enumerator value match the signedness and size of the
20068 // enumerator's type.
20069 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20070 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20071 }
20072
20073 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20074 E: Val, V: EnumVal);
20075}
20076
20077SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20078 SourceLocation IILoc) {
20079 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20080 !getLangOpts().CPlusPlus)
20081 return SkipBodyInfo();
20082
20083 // We have an anonymous enum definition. Look up the first enumerator to
20084 // determine if we should merge the definition with an existing one and
20085 // skip the body.
20086 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20087 Redecl: forRedeclarationInCurContext());
20088 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20089 if (!PrevECD)
20090 return SkipBodyInfo();
20091
20092 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20093 NamedDecl *Hidden;
20094 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20095 SkipBodyInfo Skip;
20096 Skip.Previous = Hidden;
20097 return Skip;
20098 }
20099
20100 return SkipBodyInfo();
20101}
20102
20103Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20104 SourceLocation IdLoc, IdentifierInfo *Id,
20105 const ParsedAttributesView &Attrs,
20106 SourceLocation EqualLoc, Expr *Val,
20107 SkipBodyInfo *SkipBody) {
20108 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20109 EnumConstantDecl *LastEnumConst =
20110 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20111
20112 // The scope passed in may not be a decl scope. Zip up the scope tree until
20113 // we find one that is.
20114 S = getNonFieldDeclScope(S);
20115
20116 // Verify that there isn't already something declared with this name in this
20117 // scope.
20118 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20119 RedeclarationKind::ForVisibleRedeclaration);
20120 LookupName(R, S);
20121 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20122
20123 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20124 // Maybe we will complain about the shadowed template parameter.
20125 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20126 // Just pretend that we didn't see the previous declaration.
20127 PrevDecl = nullptr;
20128 }
20129
20130 // C++ [class.mem]p15:
20131 // If T is the name of a class, then each of the following shall have a name
20132 // different from T:
20133 // - every enumerator of every member of class T that is an unscoped
20134 // enumerated type
20135 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
20136 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20137 NameInfo: DeclarationNameInfo(Id, IdLoc));
20138
20139 EnumConstantDecl *New =
20140 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20141 if (!New)
20142 return nullptr;
20143
20144 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20145 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20146 // Check for other kinds of shadowing not already handled.
20147 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20148 }
20149
20150 // When in C++, we may get a TagDecl with the same name; in this case the
20151 // enum constant will 'hide' the tag.
20152 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20153 "Received TagDecl when not in C++!");
20154 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20155 if (isa<EnumConstantDecl>(Val: PrevDecl))
20156 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20157 else
20158 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20159 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20160 return nullptr;
20161 }
20162 }
20163
20164 // Process attributes.
20165 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20166 AddPragmaAttributes(S, D: New);
20167 ProcessAPINotes(D: New);
20168
20169 // Register this decl in the current scope stack.
20170 New->setAccess(TheEnumDecl->getAccess());
20171 PushOnScopeChains(D: New, S);
20172
20173 ActOnDocumentableDecl(D: New);
20174
20175 return New;
20176}
20177
20178// Returns true when the enum initial expression does not trigger the
20179// duplicate enum warning. A few common cases are exempted as follows:
20180// Element2 = Element1
20181// Element2 = Element1 + 1
20182// Element2 = Element1 - 1
20183// Where Element2 and Element1 are from the same enum.
20184static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20185 Expr *InitExpr = ECD->getInitExpr();
20186 if (!InitExpr)
20187 return true;
20188 InitExpr = InitExpr->IgnoreImpCasts();
20189
20190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20191 if (!BO->isAdditiveOp())
20192 return true;
20193 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20194 if (!IL)
20195 return true;
20196 if (IL->getValue() != 1)
20197 return true;
20198
20199 InitExpr = BO->getLHS();
20200 }
20201
20202 // This checks if the elements are from the same enum.
20203 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20204 if (!DRE)
20205 return true;
20206
20207 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20208 if (!EnumConstant)
20209 return true;
20210
20211 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20212 Enum)
20213 return true;
20214
20215 return false;
20216}
20217
20218// Emits a warning when an element is implicitly set a value that
20219// a previous element has already been set to.
20220static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20221 EnumDecl *Enum, QualType EnumType) {
20222 // Avoid anonymous enums
20223 if (!Enum->getIdentifier())
20224 return;
20225
20226 // Only check for small enums.
20227 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20228 return;
20229
20230 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20231 return;
20232
20233 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20234 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20235
20236 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20237
20238 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20239 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20240
20241 // Use int64_t as a key to avoid needing special handling for map keys.
20242 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20243 llvm::APSInt Val = D->getInitVal();
20244 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20245 };
20246
20247 DuplicatesVector DupVector;
20248 ValueToVectorMap EnumMap;
20249
20250 // Populate the EnumMap with all values represented by enum constants without
20251 // an initializer.
20252 for (auto *Element : Elements) {
20253 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20254
20255 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20256 // this constant. Skip this enum since it may be ill-formed.
20257 if (!ECD) {
20258 return;
20259 }
20260
20261 // Constants with initializers are handled in the next loop.
20262 if (ECD->getInitExpr())
20263 continue;
20264
20265 // Duplicate values are handled in the next loop.
20266 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20267 }
20268
20269 if (EnumMap.size() == 0)
20270 return;
20271
20272 // Create vectors for any values that has duplicates.
20273 for (auto *Element : Elements) {
20274 // The last loop returned if any constant was null.
20275 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20276 if (!ValidDuplicateEnum(ECD, Enum))
20277 continue;
20278
20279 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20280 if (Iter == EnumMap.end())
20281 continue;
20282
20283 DeclOrVector& Entry = Iter->second;
20284 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20285 // Ensure constants are different.
20286 if (D == ECD)
20287 continue;
20288
20289 // Create new vector and push values onto it.
20290 auto Vec = std::make_unique<ECDVector>();
20291 Vec->push_back(Elt: D);
20292 Vec->push_back(Elt: ECD);
20293
20294 // Update entry to point to the duplicates vector.
20295 Entry = Vec.get();
20296
20297 // Store the vector somewhere we can consult later for quick emission of
20298 // diagnostics.
20299 DupVector.emplace_back(Args: std::move(Vec));
20300 continue;
20301 }
20302
20303 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20304 // Make sure constants are not added more than once.
20305 if (*Vec->begin() == ECD)
20306 continue;
20307
20308 Vec->push_back(Elt: ECD);
20309 }
20310
20311 // Emit diagnostics.
20312 for (const auto &Vec : DupVector) {
20313 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20314
20315 // Emit warning for one enum constant.
20316 auto *FirstECD = Vec->front();
20317 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20318 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20319 << FirstECD->getSourceRange();
20320
20321 // Emit one note for each of the remaining enum constants with
20322 // the same value.
20323 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20324 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20325 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20326 << ECD->getSourceRange();
20327 }
20328}
20329
20330bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20331 bool AllowMask) const {
20332 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20333 assert(ED->isCompleteDefinition() && "expected enum definition");
20334
20335 auto R = FlagBitsCache.try_emplace(Key: ED);
20336 llvm::APInt &FlagBits = R.first->second;
20337
20338 if (R.second) {
20339 for (auto *E : ED->enumerators()) {
20340 const auto &EVal = E->getInitVal();
20341 // Only single-bit enumerators introduce new flag values.
20342 if (EVal.isPowerOf2())
20343 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20344 }
20345 }
20346
20347 // A value is in a flag enum if either its bits are a subset of the enum's
20348 // flag bits (the first condition) or we are allowing masks and the same is
20349 // true of its complement (the second condition). When masks are allowed, we
20350 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20351 //
20352 // While it's true that any value could be used as a mask, the assumption is
20353 // that a mask will have all of the insignificant bits set. Anything else is
20354 // likely a logic error.
20355 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20356 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20357}
20358
20359void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20360 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20361 const ParsedAttributesView &Attrs) {
20362 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20363 QualType EnumType = Context.getTypeDeclType(Decl: Enum);
20364
20365 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20366 ProcessAPINotes(D: Enum);
20367
20368 if (Enum->isDependentType()) {
20369 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20370 EnumConstantDecl *ECD =
20371 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20372 if (!ECD) continue;
20373
20374 ECD->setType(EnumType);
20375 }
20376
20377 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20378 return;
20379 }
20380
20381 // Verify that all the values are okay, compute the size of the values, and
20382 // reverse the list.
20383 unsigned NumNegativeBits = 0;
20384 unsigned NumPositiveBits = 0;
20385 bool MembersRepresentableByInt =
20386 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20387
20388 // Figure out the type that should be used for this enum.
20389 QualType BestType;
20390 unsigned BestWidth;
20391
20392 // C++0x N3000 [conv.prom]p3:
20393 // An rvalue of an unscoped enumeration type whose underlying
20394 // type is not fixed can be converted to an rvalue of the first
20395 // of the following types that can represent all the values of
20396 // the enumeration: int, unsigned int, long int, unsigned long
20397 // int, long long int, or unsigned long long int.
20398 // C99 6.4.4.3p2:
20399 // An identifier declared as an enumeration constant has type int.
20400 // The C99 rule is modified by C23.
20401 QualType BestPromotionType;
20402
20403 bool Packed = Enum->hasAttr<PackedAttr>();
20404 // -fshort-enums is the equivalent to specifying the packed attribute on all
20405 // enum definitions.
20406 if (LangOpts.ShortEnums)
20407 Packed = true;
20408
20409 // If the enum already has a type because it is fixed or dictated by the
20410 // target, promote that type instead of analyzing the enumerators.
20411 if (Enum->isComplete()) {
20412 BestType = Enum->getIntegerType();
20413 if (Context.isPromotableIntegerType(T: BestType))
20414 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20415 else
20416 BestPromotionType = BestType;
20417
20418 BestWidth = Context.getIntWidth(T: BestType);
20419 } else {
20420 bool EnumTooLarge = Context.computeBestEnumTypes(
20421 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20422 BestWidth = Context.getIntWidth(T: BestType);
20423 if (EnumTooLarge)
20424 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
20425 }
20426
20427 // Loop over all of the enumerator constants, changing their types to match
20428 // the type of the enum if needed.
20429 for (auto *D : Elements) {
20430 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20431 if (!ECD) continue; // Already issued a diagnostic.
20432
20433 // C99 says the enumerators have int type, but we allow, as an
20434 // extension, the enumerators to be larger than int size. If each
20435 // enumerator value fits in an int, type it as an int, otherwise type it the
20436 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20437 // that X has type 'int', not 'unsigned'.
20438
20439 // Determine whether the value fits into an int.
20440 llvm::APSInt InitVal = ECD->getInitVal();
20441
20442 // If it fits into an integer type, force it. Otherwise force it to match
20443 // the enum decl type.
20444 QualType NewTy;
20445 unsigned NewWidth;
20446 bool NewSign;
20447 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20448 MembersRepresentableByInt) {
20449 // C23 6.7.3.3.3p15:
20450 // The enumeration member type for an enumerated type without fixed
20451 // underlying type upon completion is:
20452 // - int if all the values of the enumeration are representable as an
20453 // int; or,
20454 // - the enumerated type
20455 NewTy = Context.IntTy;
20456 NewWidth = Context.getTargetInfo().getIntWidth();
20457 NewSign = true;
20458 } else if (ECD->getType() == BestType) {
20459 // Already the right type!
20460 if (getLangOpts().CPlusPlus)
20461 // C++ [dcl.enum]p4: Following the closing brace of an
20462 // enum-specifier, each enumerator has the type of its
20463 // enumeration.
20464 ECD->setType(EnumType);
20465 continue;
20466 } else {
20467 NewTy = BestType;
20468 NewWidth = BestWidth;
20469 NewSign = BestType->isSignedIntegerOrEnumerationType();
20470 }
20471
20472 // Adjust the APSInt value.
20473 InitVal = InitVal.extOrTrunc(width: NewWidth);
20474 InitVal.setIsSigned(NewSign);
20475 ECD->setInitVal(C: Context, V: InitVal);
20476
20477 // Adjust the Expr initializer and type.
20478 if (ECD->getInitExpr() &&
20479 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20480 ECD->setInitExpr(ImplicitCastExpr::Create(
20481 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20482 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20483 if (getLangOpts().CPlusPlus)
20484 // C++ [dcl.enum]p4: Following the closing brace of an
20485 // enum-specifier, each enumerator has the type of its
20486 // enumeration.
20487 ECD->setType(EnumType);
20488 else
20489 ECD->setType(NewTy);
20490 }
20491
20492 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20493 NumPositiveBits, NumNegativeBits);
20494
20495 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20496
20497 if (Enum->isClosedFlag()) {
20498 for (Decl *D : Elements) {
20499 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20500 if (!ECD) continue; // Already issued a diagnostic.
20501
20502 llvm::APSInt InitVal = ECD->getInitVal();
20503 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20504 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
20505 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
20506 << ECD << Enum;
20507 }
20508 }
20509
20510 // Now that the enum type is defined, ensure it's not been underaligned.
20511 if (Enum->hasAttrs())
20512 CheckAlignasUnderalignment(D: Enum);
20513}
20514
20515Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
20516 SourceLocation EndLoc) {
20517
20518 FileScopeAsmDecl *New =
20519 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
20520 CurContext->addDecl(D: New);
20521 return New;
20522}
20523
20524TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20525 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
20526 CurContext->addDecl(D: New);
20527 PushDeclContext(S, DC: New);
20528 PushFunctionScope();
20529 PushCompoundScope(IsStmtExpr: false);
20530 return New;
20531}
20532
20533void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20534 D->setStmt(Statement);
20535 PopCompoundScope();
20536 PopFunctionScopeInfo();
20537 PopDeclContext();
20538}
20539
20540void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20541 IdentifierInfo* AliasName,
20542 SourceLocation PragmaLoc,
20543 SourceLocation NameLoc,
20544 SourceLocation AliasNameLoc) {
20545 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20546 NameKind: LookupOrdinaryName);
20547 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20548 AttributeCommonInfo::Form::Pragma());
20549 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20550 Ctx&: Context, Label: AliasName->getName(), /*IsLiteralLabel=*/true, CommonInfo: Info);
20551
20552 // If a declaration that:
20553 // 1) declares a function or a variable
20554 // 2) has external linkage
20555 // already exists, add a label attribute to it.
20556 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20557 if (isDeclExternC(D: PrevDecl))
20558 PrevDecl->addAttr(A: Attr);
20559 else
20560 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
20561 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
20562 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20563 } else
20564 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
20565}
20566
20567void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20568 SourceLocation PragmaLoc,
20569 SourceLocation NameLoc) {
20570 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
20571
20572 if (PrevDecl) {
20573 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
20574 } else {
20575 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
20576 }
20577}
20578
20579void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20580 IdentifierInfo* AliasName,
20581 SourceLocation PragmaLoc,
20582 SourceLocation NameLoc,
20583 SourceLocation AliasNameLoc) {
20584 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
20585 NameKind: LookupOrdinaryName);
20586 WeakInfo W = WeakInfo(Name, NameLoc);
20587
20588 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20589 if (!PrevDecl->hasAttr<AliasAttr>())
20590 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
20591 DeclApplyPragmaWeak(S: TUScope, ND, W);
20592 } else {
20593 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
20594 }
20595}
20596
20597Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20598 bool Final) {
20599 assert(FD && "Expected non-null FunctionDecl");
20600
20601 // SYCL functions can be template, so we check if they have appropriate
20602 // attribute prior to checking if it is a template.
20603 if (LangOpts.SYCLIsDevice && FD->hasAttr<DeviceKernelAttr>())
20604 return FunctionEmissionStatus::Emitted;
20605
20606 // Templates are emitted when they're instantiated.
20607 if (FD->isDependentContext())
20608 return FunctionEmissionStatus::TemplateDiscarded;
20609
20610 // Check whether this function is an externally visible definition.
20611 auto IsEmittedForExternalSymbol = [this, FD]() {
20612 // We have to check the GVA linkage of the function's *definition* -- if we
20613 // only have a declaration, we don't know whether or not the function will
20614 // be emitted, because (say) the definition could include "inline".
20615 const FunctionDecl *Def = FD->getDefinition();
20616
20617 // We can't compute linkage when we skip function bodies.
20618 return Def && !Def->hasSkippedBody() &&
20619 !isDiscardableGVALinkage(
20620 L: getASTContext().GetGVALinkageForFunction(FD: Def));
20621 };
20622
20623 if (LangOpts.OpenMPIsTargetDevice) {
20624 // In OpenMP device mode we will not emit host only functions, or functions
20625 // we don't need due to their linkage.
20626 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20627 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
20628 // DevTy may be changed later by
20629 // #pragma omp declare target to(*) device_type(*).
20630 // Therefore DevTy having no value does not imply host. The emission status
20631 // will be checked again at the end of compilation unit with Final = true.
20632 if (DevTy)
20633 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20634 return FunctionEmissionStatus::OMPDiscarded;
20635 // If we have an explicit value for the device type, or we are in a target
20636 // declare context, we need to emit all extern and used symbols.
20637 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20638 if (IsEmittedForExternalSymbol())
20639 return FunctionEmissionStatus::Emitted;
20640 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20641 // we'll omit it.
20642 if (Final)
20643 return FunctionEmissionStatus::OMPDiscarded;
20644 } else if (LangOpts.OpenMP > 45) {
20645 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20646 // function. In 5.0, no_host was introduced which might cause a function to
20647 // be omitted.
20648 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20649 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
20650 if (DevTy)
20651 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20652 return FunctionEmissionStatus::OMPDiscarded;
20653 }
20654
20655 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20656 return FunctionEmissionStatus::Emitted;
20657
20658 if (LangOpts.CUDA) {
20659 // When compiling for device, host functions are never emitted. Similarly,
20660 // when compiling for host, device and global functions are never emitted.
20661 // (Technically, we do emit a host-side stub for global functions, but this
20662 // doesn't count for our purposes here.)
20663 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
20664 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20665 return FunctionEmissionStatus::CUDADiscarded;
20666 if (!LangOpts.CUDAIsDevice &&
20667 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
20668 return FunctionEmissionStatus::CUDADiscarded;
20669
20670 if (IsEmittedForExternalSymbol())
20671 return FunctionEmissionStatus::Emitted;
20672
20673 // If FD is a virtual destructor of an explicit instantiation
20674 // of a template class, return Emitted.
20675 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
20676 if (Destructor->isVirtual()) {
20677 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
20678 Val: Destructor->getParent())) {
20679 TemplateSpecializationKind TSK =
20680 Spec->getTemplateSpecializationKind();
20681 if (TSK == TSK_ExplicitInstantiationDeclaration ||
20682 TSK == TSK_ExplicitInstantiationDefinition)
20683 return FunctionEmissionStatus::Emitted;
20684 }
20685 }
20686 }
20687 }
20688
20689 // Otherwise, the function is known-emitted if it's in our set of
20690 // known-emitted functions.
20691 return FunctionEmissionStatus::Unknown;
20692}
20693
20694bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20695 // Host-side references to a __global__ function refer to the stub, so the
20696 // function itself is never emitted and therefore should not be marked.
20697 // If we have host fn calls kernel fn calls host+device, the HD function
20698 // does not get instantiated on the host. We model this by omitting at the
20699 // call to the kernel from the callgraph. This ensures that, when compiling
20700 // for host, only HD functions actually called from the host get marked as
20701 // known-emitted.
20702 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20703 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
20704}
20705