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/ExprObjC.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NonTrivialTypeVisitor.h"
29#include "clang/AST/Randstruct.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticComment.h"
34#include "clang/Basic/HLSLRuntime.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/CXXFieldCollector.h"
43#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/DelayedDiagnostic.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/ParsedTemplate.h"
48#include "clang/Sema/Scope.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaAMDGPU.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaInternal.h"
55#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaOpenACC.h"
57#include "clang/Sema/SemaOpenMP.h"
58#include "clang/Sema/SemaPPC.h"
59#include "clang/Sema/SemaRISCV.h"
60#include "clang/Sema/SemaSYCL.h"
61#include "clang/Sema/SemaSwift.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
81Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
84 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
85 }
86
87 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(D: ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
127 isa<ClassTemplateSpecializationDecl>(Val: RD);
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
149void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
156 Diag(Loc: NameLoc,
157 DiagID: DCK == DiagCtorKind::Typename
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
165 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Val: Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(T: Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
215 if (!isa<TypeDecl>(Val: ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(Val: DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
274}
275
276ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(T: ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(SS: *SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
318 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
319 NNS: SS->getScopeRep(), Name: &II);
320 if (!getLangOpts().CPlusPlus20)
321 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
328 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
331 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
332 QualType T = CheckTypenameType(
333 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
334 : ElaboratedTypeKeyword::None,
335 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
336 return ParsedType::make(P: T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(R&: Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(R&: Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(R&: Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
387 case LookupResultKind::NotFound:
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
393 Mode: CorrectTypoKind::ErrorRecovery);
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
395 TemplateTy Template;
396 bool MemberOfUnknownSpecialization;
397 UnqualifiedId TemplateName;
398 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
399 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
430 case LookupResultKind::NotFoundInCurrentInstantiation:
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
433 NNS: SS->getScopeRep(), Name: &II);
434 TypeLocBuilder TLB;
435 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
436 TL.setElaboratedKeywordLoc(SourceLocation());
437 TL.setQualifierLoc(SS->getWithLocInContext(Context));
438 TL.setNameLoc(NameLoc);
439 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
440 }
441 [[fallthrough]];
442 case LookupResultKind::FoundOverloaded:
443 case LookupResultKind::FoundUnresolvedValue:
444 Result.suppressDiagnostics();
445 return nullptr;
446
447 case LookupResultKind::Ambiguous:
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
462 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
463 Val: RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
491 case LookupResultKind::Found:
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
503 : DiagCtorKind::None,
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
507 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
508 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
509 D: FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(P: T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 QualifierLoc: SS ? SS->getWithLocInContext(Context)
514 : NestedNameSpecifierLoc(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
517 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
518 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(P: T);
522 auto TL = TLB.push<TagTypeLoc>(T);
523 TL.setElaboratedKeywordLoc(SourceLocation());
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
525 : NestedNameSpecifierLoc());
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
528 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
529 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
530 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(P: T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
535 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
538 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
539 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
540 D: UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(P: T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
545 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(Decl: TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(P: T);
551 if (isa<ObjCTypeParamType>(Val: T))
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
556 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(P: ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
570 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(P: T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
580 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
583 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(P: Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
594 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
595 Template);
596 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
597 TL.setElaboratedKeywordLoc(SourceLocation());
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
600 : NestedNameSpecifierLoc());
601 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
611static NestedNameSpecifier
612synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
620 if (isa<TranslationUnitDecl>(Val: DC))
621 return NestedNameSpecifier::getGlobal();
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
631findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
641ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
655 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
656 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
658 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
684 DepTL.setElaboratedKeywordLoc(SourceLocation());
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
687}
688
689DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, AllowBuiltinCreation: false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
697 case TagTypeKind::Struct:
698 return DeclSpec::TST_struct;
699 case TagTypeKind::Interface:
700 return DeclSpec::TST_interface;
701 case TagTypeKind::Union:
702 return DeclSpec::TST_union;
703 case TagTypeKind::Class:
704 return DeclSpec::TST_class;
705 case TagTypeKind::Enum:
706 return DeclSpec::TST_enum;
707 }
708 }
709
710 return DeclSpec::TST_unspecified;
711}
712
713bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
718 case NestedNameSpecifier::Kind::MicrosoftSuper:
719 return true;
720 case NestedNameSpecifier::Kind::Type: {
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
732void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
750 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
751 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Correction: Corrected,
757 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Correction: Corrected,
765 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, ErrorRecovery: CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
769 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Correction: Corrected,
773 TypoDiag: PDiag(DiagID: IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 ErrorRecovery: CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
788 R: SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
792 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(Id: II, IdLoc: IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
822 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
828 } else if (isDependentScopeSpecifier(SS: *SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
835
836 Diag(Loc: SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(Ty: SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(K: tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
853 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
857 return true;
858 }
859
860 return false;
861}
862
863static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
872 case TagTypeKind::Class:
873 FixItTagName = "class ";
874 break;
875
876 case TagTypeKind::Enum:
877 FixItTagName = "enum ";
878 break;
879
880 case TagTypeKind::Struct:
881 FixItTagName = "struct ";
882 break;
883
884 case TagTypeKind::Interface:
885 FixItTagName = "__interface ";
886 break;
887
888 case TagTypeKind::Union:
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
904 Result.clear(Kind: Sema::LookupTagName);
905 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
912Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
916 CorrectionCandidateCallback *CCC) {
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(II: *Name, S, SS: &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
928 return NameClassification::Unknown();
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
936 return NameClassification::Error();
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
952 if (Ivar.isInvalid())
953 return NameClassification::Error();
954 if (Ivar.isUsable())
955 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
959 LookupBuiltin(R&: Result);
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
967 case LookupResultKind::NotFound:
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
973 if (getLangOpts().CPlusPlus)
974 return NameClassification::UndeclaredNonType();
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
992 return NameClassification::NonType(D);
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1001 TemplateName Template =
1002 Context.getAssumedTemplateName(Name: NameInfo.getName());
1003 return NameClassification::UndeclaredTemplate(Name: Template);
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1020 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1045 << Name << computeDeclContext(SS, EnteringContext: false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(D: FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1070 if (R.isInvalid())
1071 return NameClassification::Error();
1072 if (R.isUsable())
1073 return NameClassification::NonType(D: Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1082 return NameClassification::Unknown();
1083
1084 case LookupResultKind::NotFoundInCurrentInstantiation: {
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1099 return NameClassification::DependentNonType();
1100 }
1101
1102 case LookupResultKind::Found:
1103 case LookupResultKind::FoundOverloaded:
1104 case LookupResultKind::FoundUnresolvedValue:
1105 break;
1106
1107 case LookupResultKind::Ambiguous:
1108 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1109 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1122 FilterAcceptableTemplateNames(R&: Result);
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1130 return NameClassification::Error();
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1134 (IsFilteredTemplateName ||
1135 hasAnyAcceptableTemplateNames(
1136 R&: Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1139 getLangOpts().CPlusPlus20))) {
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1151 FilterAcceptableTemplateNames(R&: Result);
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1155 TemplateName Template;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1159 End: Result.end());
1160 } else if (!Result.empty()) {
1161 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1162 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 Qualifier: SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1188 return NameClassification::FunctionTemplate(Name: Template);
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1192 : NameClassification::TypeTemplate(Name: Template);
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1199 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1200 D: USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1205 Decl: Type);
1206 if (isa<TagType>(Val: T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1208 TTL.setElaboratedKeywordLoc(SourceLocation());
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(Val: T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(Val: T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1223 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1228 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1229 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1243
1244 if (NextToken.is(K: tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1248 return NameClassification::Unknown();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Decl: Class);
1252 return ParsedType::make(P: T);
1253 }
1254
1255 if (isa<ConceptDecl>(Val: FirstDecl)) {
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1258 return NameClassification::Concept(Name: TemplateName(USD));
1259 return NameClassification::Concept(
1260 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1265 return NameClassification::Error();
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1269 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1270 !isa<VarTemplateDecl>(Val: FirstDecl))
1271 return NameClassification::TypeTemplate(
1272 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1277 if ((NextToken.is(K: tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1293 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1297 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1298 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1299 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1303ExprResult
1304Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1310}
1311
1312ExprResult
1313Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1323ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1324 NamedDecl *Found,
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(D: Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1340ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(Other: ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1350 LookupOrdinaryName);
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(D: *I, AS: I.getAccess());
1354 Result.resolveKind();
1355 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1356 TemplateArgs: nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1364Sema::TemplateNameKindForDiagnostics
1365Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1366 auto *TD = Name.getAsTemplateDecl();
1367 if (!TD)
1368 return TemplateNameKindForDiagnostics::DependentTemplate;
1369 if (isa<ClassTemplateDecl>(Val: TD))
1370 return TemplateNameKindForDiagnostics::ClassTemplate;
1371 if (isa<FunctionTemplateDecl>(Val: TD))
1372 return TemplateNameKindForDiagnostics::FunctionTemplate;
1373 if (isa<VarTemplateDecl>(Val: TD))
1374 return TemplateNameKindForDiagnostics::VarTemplate;
1375 if (isa<TypeAliasTemplateDecl>(Val: TD))
1376 return TemplateNameKindForDiagnostics::AliasTemplate;
1377 if (isa<TemplateTemplateParmDecl>(Val: TD))
1378 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1379 if (isa<ConceptDecl>(Val: TD))
1380 return TemplateNameKindForDiagnostics::Concept;
1381 return TemplateNameKindForDiagnostics::DependentTemplate;
1382}
1383
1384void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1392void Sema::PopDeclContext() {
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1399Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1413void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1414 CurContext = static_cast<decltype(CurContext)>(Context);
1415}
1416
1417void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1448 EnterTemplatedContext(S: S->getParent(), DC);
1449 }
1450}
1451
1452void Sema::ExitDeclaratorContext(Scope *S) {
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1465void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1508void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1509 // We assume that the caller has already called
1510 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1511 FunctionDecl *FD = D->getAsFunction();
1512 if (!FD)
1513 return;
1514
1515 // Same implementation as PushDeclContext, but enters the context
1516 // from the lexical parent, rather than the top-level class.
1517 assert(CurContext == FD->getLexicalParent() &&
1518 "The next DeclContext should be lexically contained in the current one.");
1519 CurContext = FD;
1520 S->setEntity(CurContext);
1521
1522 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1523 ParmVarDecl *Param = FD->getParamDecl(i: P);
1524 // If the parameter has an identifier, then add it to the scope
1525 if (Param->getIdentifier()) {
1526 S->AddDecl(D: Param);
1527 IdResolver.AddDecl(D: Param);
1528 }
1529 }
1530}
1531
1532void Sema::ActOnExitFunctionContext() {
1533 // Same implementation as PopDeclContext, but returns to the lexical parent,
1534 // rather than the top-level class.
1535 assert(CurContext && "DeclContext imbalance!");
1536 CurContext = CurContext->getLexicalParent();
1537 assert(CurContext && "Popped translation unit!");
1538}
1539
1540/// Determine whether overloading is allowed for a new function
1541/// declaration considering prior declarations of the same name.
1542///
1543/// This routine determines whether overloading is possible, not
1544/// whether a new declaration actually overloads a previous one.
1545/// It will return true in C++ (where overloads are always permitted)
1546/// or, as a C extension, when either the new declaration or a
1547/// previous one is declared with the 'overloadable' attribute.
1548static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1549 ASTContext &Context,
1550 const FunctionDecl *New) {
1551 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1552 return true;
1553
1554 // Multiversion function declarations are not overloads in the
1555 // usual sense of that term, but lookup will report that an
1556 // overload set was found if more than one multiversion function
1557 // declaration is present for the same name. It is therefore
1558 // inadequate to assume that some prior declaration(s) had
1559 // the overloadable attribute; checking is required. Since one
1560 // declaration is permitted to omit the attribute, it is necessary
1561 // to check at least two; hence the 'any_of' check below. Note that
1562 // the overloadable attribute is implicitly added to declarations
1563 // that were required to have it but did not.
1564 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1565 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1566 return ND->hasAttr<OverloadableAttr>();
1567 });
1568 } else if (Previous.getResultKind() == LookupResultKind::Found)
1569 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1570
1571 return false;
1572}
1573
1574void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1575 // Move up the scope chain until we find the nearest enclosing
1576 // non-transparent context. The declaration will be introduced into this
1577 // scope.
1578 while (S->getEntity() && S->getEntity()->isTransparentContext())
1579 S = S->getParent();
1580
1581 // Add scoped declarations into their context, so that they can be
1582 // found later. Declarations without a context won't be inserted
1583 // into any context.
1584 if (AddToContext)
1585 CurContext->addDecl(D);
1586
1587 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1588 // are function-local declarations.
1589 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1590 if (!S->getFnParent())
1591 return;
1592
1593 // Even inside a function, an out-of-line definition of a type that is
1594 // nested inside a local class must not be pushed into the enclosing
1595 // function scope. For example:
1596 //
1597 // class A { public: class B; };
1598 // class A::B {}; // out-of-line definition inside the function
1599 // B b; // must fail - only A::B is valid
1600 // Wrapper{B{}} // must also fail
1601 //
1602 // Per C++ scoping rules only the qualified form A::B is accessible.
1603 // Without this guard, PushOnScopeChains would add B to the function's
1604 // local scope, making it findable via unqualified lookup, which is
1605 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1606 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1607 // of a local class being defined out-of-line.
1608 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1609 return;
1610 }
1611
1612 // Template instantiations should also not be pushed into scope.
1613 if (isa<FunctionDecl>(Val: D) &&
1614 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1615 return;
1616
1617 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1618 S->AddDecl(D);
1619 return;
1620 }
1621 // If this replaces anything in the current scope,
1622 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1623 IEnd = IdResolver.end();
1624 for (; I != IEnd; ++I) {
1625 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1626 S->RemoveDecl(D: *I);
1627 IdResolver.RemoveDecl(D: *I);
1628
1629 // Should only need to replace one decl.
1630 break;
1631 }
1632 }
1633
1634 S->AddDecl(D);
1635
1636 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1637 // Implicitly-generated labels may end up getting generated in an order that
1638 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1639 // the label at the appropriate place in the identifier chain.
1640 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1641 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1642 if (IDC == CurContext) {
1643 if (!S->isDeclScope(D: *I))
1644 continue;
1645 } else if (IDC->Encloses(DC: CurContext))
1646 break;
1647 }
1648
1649 IdResolver.InsertDeclAfter(Pos: I, D);
1650 } else {
1651 IdResolver.AddDecl(D);
1652 }
1653 warnOnReservedIdentifier(D);
1654}
1655
1656bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1657 bool AllowInlineNamespace) const {
1658 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1659}
1660
1661bool Sema::isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1662 bool AllowInlineNamespace) const {
1663 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1664 return true;
1665
1666 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: D))
1667 return isDeclInScope(D: Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1668
1669 return false;
1670}
1671
1672Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1673 DeclContext *TargetDC = DC->getPrimaryContext();
1674 do {
1675 if (DeclContext *ScopeDC = S->getEntity())
1676 if (ScopeDC->getPrimaryContext() == TargetDC)
1677 return S;
1678 } while ((S = S->getParent()));
1679
1680 return nullptr;
1681}
1682
1683static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1684 DeclContext*,
1685 ASTContext&);
1686
1687void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1688 bool ConsiderLinkage,
1689 bool AllowInlineNamespace) {
1690 LookupResult::Filter F = R.makeFilter();
1691 while (F.hasNext()) {
1692 NamedDecl *D = F.next();
1693
1694 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1695 continue;
1696
1697 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1698 continue;
1699
1700 F.erase();
1701 }
1702
1703 F.done();
1704}
1705
1706static bool isImplicitInstantiation(NamedDecl *D) {
1707 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1708 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1709 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1710 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1711 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1712 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1713
1714 return false;
1715}
1716
1717bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1718 // [module.interface]p7:
1719 // A declaration is attached to a module as follows:
1720 // - If the declaration is a non-dependent friend declaration that nominates a
1721 // function with a declarator-id that is a qualified-id or template-id or that
1722 // nominates a class other than with an elaborated-type-specifier with neither
1723 // a nested-name-specifier nor a simple-template-id, it is attached to the
1724 // module to which the friend is attached ([basic.link]).
1725 if (New->getFriendObjectKind() &&
1726 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1727 New->setLocalOwningModule(Old->getOwningModule());
1728 makeMergedDefinitionVisible(ND: New);
1729 return false;
1730 }
1731
1732 // Although we have questions for the module ownership of implicit
1733 // instantiations, it should be sure that we shouldn't diagnose the
1734 // redeclaration of incorrect module ownership for different implicit
1735 // instantiations in different modules. We will diagnose the redeclaration of
1736 // incorrect module ownership for the template itself.
1737 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1738 return false;
1739
1740 Module *NewM = New->getOwningModule();
1741 Module *OldM = Old->getOwningModule();
1742
1743 if (NewM && NewM->isPrivateModule())
1744 NewM = NewM->Parent;
1745 if (OldM && OldM->isPrivateModule())
1746 OldM = OldM->Parent;
1747
1748 if (NewM == OldM)
1749 return false;
1750
1751 if (NewM && OldM) {
1752 // A module implementation unit has visibility of the decls in its
1753 // implicitly imported interface.
1754 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1755 return false;
1756
1757 // Partitions are part of the module, but a partition could import another
1758 // module, so verify that the PMIs agree.
1759 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1760 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1761 return false;
1762 }
1763
1764 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1765 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1766 if (NewIsModuleInterface || OldIsModuleInterface) {
1767 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1768 // if a declaration of D [...] appears in the purview of a module, all
1769 // other such declarations shall appear in the purview of the same module
1770 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1771 << New
1772 << NewIsModuleInterface
1773 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1774 << OldIsModuleInterface
1775 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1776 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1777 New->setInvalidDecl();
1778 return true;
1779 }
1780
1781 return false;
1782}
1783
1784bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1785 // [module.interface]p1:
1786 // An export-declaration shall inhabit a namespace scope.
1787 //
1788 // So it is meaningless to talk about redeclaration which is not at namespace
1789 // scope.
1790 if (!New->getLexicalDeclContext()
1791 ->getNonTransparentContext()
1792 ->isFileContext() ||
1793 !Old->getLexicalDeclContext()
1794 ->getNonTransparentContext()
1795 ->isFileContext())
1796 return false;
1797
1798 bool IsNewExported = New->isInExportDeclContext();
1799 bool IsOldExported = Old->isInExportDeclContext();
1800
1801 // It should be irrevelant if both of them are not exported.
1802 if (!IsNewExported && !IsOldExported)
1803 return false;
1804
1805 if (IsOldExported)
1806 return false;
1807
1808 // If the Old declaration are not attached to named modules
1809 // and the New declaration are attached to global module.
1810 // It should be fine to allow the export since it doesn't change
1811 // the linkage of declarations. See
1812 // https://github.com/llvm/llvm-project/issues/98583 for details.
1813 if (!Old->isInNamedModule() && New->getOwningModule() &&
1814 New->getOwningModule()->isImplicitGlobalModule())
1815 return false;
1816
1817 assert(IsNewExported);
1818
1819 auto Lk = Old->getFormalLinkage();
1820 int S = 0;
1821 if (Lk == Linkage::Internal)
1822 S = 1;
1823 else if (Lk == Linkage::Module)
1824 S = 2;
1825 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1826 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1827 return true;
1828}
1829
1830bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1831 if (CheckRedeclarationModuleOwnership(New, Old))
1832 return true;
1833
1834 if (CheckRedeclarationExported(New, Old))
1835 return true;
1836
1837 return false;
1838}
1839
1840bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1841 const NamedDecl *Old) const {
1842 assert(getASTContext().isSameEntity(New, Old) &&
1843 "New and Old are not the same definition, we should diagnostic it "
1844 "immediately instead of checking it.");
1845 assert(const_cast<Sema *>(this)->isReachable(New) &&
1846 const_cast<Sema *>(this)->isReachable(Old) &&
1847 "We shouldn't see unreachable definitions here.");
1848
1849 Module *NewM = New->getOwningModule();
1850 Module *OldM = Old->getOwningModule();
1851
1852 // We only checks for named modules here. The header like modules is skipped.
1853 // FIXME: This is not right if we import the header like modules in the module
1854 // purview.
1855 //
1856 // For example, assuming "header.h" provides definition for `D`.
1857 // ```C++
1858 // //--- M.cppm
1859 // export module M;
1860 // import "header.h"; // or #include "header.h" but import it by clang modules
1861 // actually.
1862 //
1863 // //--- Use.cpp
1864 // import M;
1865 // import "header.h"; // or uses clang modules.
1866 // ```
1867 //
1868 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1869 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1870 // reject it. But the current implementation couldn't detect the case since we
1871 // don't record the information about the importee modules.
1872 //
1873 // But this might not be painful in practice. Since the design of C++20 Named
1874 // Modules suggests us to use headers in global module fragment instead of
1875 // module purview.
1876 if (NewM && NewM->isHeaderLikeModule())
1877 NewM = nullptr;
1878 if (OldM && OldM->isHeaderLikeModule())
1879 OldM = nullptr;
1880
1881 if (!NewM && !OldM)
1882 return true;
1883
1884 // [basic.def.odr]p14.3
1885 // Each such definition shall not be attached to a named module
1886 // ([module.unit]).
1887 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1888 return true;
1889
1890 // Then New and Old lives in the same TU if their share one same module unit.
1891 if (NewM)
1892 NewM = NewM->getTopLevelModule();
1893 if (OldM)
1894 OldM = OldM->getTopLevelModule();
1895 return OldM == NewM;
1896}
1897
1898static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1899 if (D->getDeclContext()->isFileContext())
1900 return false;
1901
1902 return isa<UsingShadowDecl>(Val: D) ||
1903 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1904 isa<UnresolvedUsingValueDecl>(Val: D);
1905}
1906
1907/// Removes using shadow declarations not at class scope from the lookup
1908/// results.
1909static void RemoveUsingDecls(LookupResult &R) {
1910 LookupResult::Filter F = R.makeFilter();
1911 while (F.hasNext())
1912 if (isUsingDeclNotAtClassScope(D: F.next()))
1913 F.erase();
1914
1915 F.done();
1916}
1917
1918/// Check for this common pattern:
1919/// @code
1920/// class S {
1921/// S(const S&); // DO NOT IMPLEMENT
1922/// void operator=(const S&); // DO NOT IMPLEMENT
1923/// };
1924/// @endcode
1925static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1926 // FIXME: Should check for private access too but access is set after we get
1927 // the decl here.
1928 if (D->doesThisDeclarationHaveABody())
1929 return false;
1930
1931 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1932 return CD->isCopyConstructor();
1933 return D->isCopyAssignmentOperator();
1934}
1935
1936bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1937 const DeclContext *DC = D->getDeclContext();
1938 while (!DC->isTranslationUnit()) {
1939 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1940 if (!RD->hasNameForLinkage())
1941 return true;
1942 }
1943 DC = DC->getParent();
1944 }
1945
1946 return !D->isExternallyVisible();
1947}
1948
1949bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1950 assert(D);
1951
1952 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1953 return false;
1954
1955 // Ignore all entities declared within templates, and out-of-line definitions
1956 // of members of class templates.
1957 if (D->getDeclContext()->isDependentContext() ||
1958 D->getLexicalDeclContext()->isDependentContext())
1959 return false;
1960
1961 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1962 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1963 return false;
1964 // A non-out-of-line declaration of a member specialization was implicitly
1965 // instantiated; it's the out-of-line declaration that we're interested in.
1966 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1967 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1968 return false;
1969
1970 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1971 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1972 return false;
1973 } else {
1974 // 'static inline' functions are defined in headers; don't warn.
1975 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1976 return false;
1977 }
1978
1979 if (FD->doesThisDeclarationHaveABody() &&
1980 Context.DeclMustBeEmitted(D: FD))
1981 return false;
1982 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1983 // Constants and utility variables are defined in headers with internal
1984 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1985 // like "inline".)
1986 if (!isMainFileLoc(Loc: VD->getLocation()))
1987 return false;
1988
1989 if (Context.DeclMustBeEmitted(D: VD))
1990 return false;
1991
1992 if (VD->isStaticDataMember() &&
1993 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1994 return false;
1995 if (VD->isStaticDataMember() &&
1996 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1997 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1998 return false;
1999
2000 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
2001 return false;
2002 } else {
2003 return false;
2004 }
2005
2006 // Only warn for unused decls internal to the translation unit.
2007 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2008 // for inline functions defined in the main source file, for instance.
2009 return mightHaveNonExternalLinkage(D);
2010}
2011
2012void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2013 if (!D)
2014 return;
2015
2016 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2017 const FunctionDecl *First = FD->getFirstDecl();
2018 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2019 return; // First should already be in the vector.
2020 }
2021
2022 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2023 const VarDecl *First = VD->getFirstDecl();
2024 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2025 return; // First should already be in the vector.
2026 }
2027
2028 if (ShouldWarnIfUnusedFileScopedDecl(D))
2029 UnusedFileScopedDecls.push_back(LocalValue: D);
2030}
2031
2032static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2033 const NamedDecl *D) {
2034 if (D->isInvalidDecl())
2035 return false;
2036
2037 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2038 // For a decomposition declaration, warn if none of the bindings are
2039 // referenced, instead of if the variable itself is referenced (which
2040 // it is, by the bindings' expressions).
2041 bool IsAllIgnored = true;
2042 for (const auto *BD : DD->bindings()) {
2043 if (BD->isReferenced())
2044 return false;
2045 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2046 BD->hasAttr<UnusedAttr>());
2047 }
2048 if (IsAllIgnored)
2049 return false;
2050 } else if (!D->getDeclName()) {
2051 return false;
2052 } else if (D->isReferenced() || D->isUsed()) {
2053 return false;
2054 }
2055
2056 if (D->isPlaceholderVar(LangOpts))
2057 return false;
2058
2059 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2060 D->hasAttr<CleanupAttr>())
2061 return false;
2062
2063 if (isa<LabelDecl>(Val: D))
2064 return true;
2065
2066 // Except for labels, we only care about unused decls that are local to
2067 // functions.
2068 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2069 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2070 // For dependent types, the diagnostic is deferred.
2071 WithinFunction =
2072 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2073 if (!WithinFunction)
2074 return false;
2075
2076 if (isa<TypedefNameDecl>(Val: D))
2077 return true;
2078
2079 // White-list anything that isn't a local variable.
2080 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2081 return false;
2082
2083 // Types of valid local variables should be complete, so this should succeed.
2084 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2085
2086 const Expr *Init = VD->getInit();
2087 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2088 Init = Cleanups->getSubExpr();
2089
2090 const auto *Ty = VD->getType().getTypePtr();
2091
2092 // Only look at the outermost level of typedef.
2093 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2094 // Allow anything marked with __attribute__((unused)).
2095 if (TT->getDecl()->hasAttr<UnusedAttr>())
2096 return false;
2097 }
2098
2099 // Warn for reference variables whose initializtion performs lifetime
2100 // extension.
2101 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2102 MTE && MTE->getExtendingDecl()) {
2103 Ty = VD->getType().getNonReferenceType().getTypePtr();
2104 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2105 }
2106
2107 // If we failed to complete the type for some reason, or if the type is
2108 // dependent, don't diagnose the variable.
2109 if (Ty->isIncompleteType() || Ty->isDependentType())
2110 return false;
2111
2112 // Look at the element type to ensure that the warning behaviour is
2113 // consistent for both scalars and arrays.
2114 Ty = Ty->getBaseElementTypeUnsafe();
2115
2116 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2117 if (Tag->hasAttr<UnusedAttr>())
2118 return false;
2119
2120 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2121 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2122 return false;
2123
2124 if (Init) {
2125 const auto *Construct =
2126 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2127 if (Construct && !Construct->isElidable()) {
2128 const CXXConstructorDecl *CD = Construct->getConstructor();
2129 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2130 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2131 return false;
2132 }
2133
2134 // Suppress the warning if we don't know how this is constructed, and
2135 // it could possibly be non-trivial constructor.
2136 if (Init->isTypeDependent()) {
2137 for (const CXXConstructorDecl *Ctor : RD->ctors())
2138 if (!Ctor->isTrivial())
2139 return false;
2140 }
2141
2142 // Suppress the warning if the constructor is unresolved because
2143 // its arguments are dependent.
2144 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2145 return false;
2146 }
2147 }
2148 }
2149
2150 // TODO: __attribute__((unused)) templates?
2151 }
2152
2153 return true;
2154}
2155
2156static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2157 FixItHint &Hint) {
2158 if (isa<LabelDecl>(Val: D)) {
2159 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2160 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2161 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2162 if (AfterColon.isInvalid())
2163 return;
2164 Hint = FixItHint::CreateRemoval(
2165 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2166 }
2167}
2168
2169void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2170 DiagnoseUnusedNestedTypedefs(
2171 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2172}
2173
2174void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2175 DiagReceiverTy DiagReceiver) {
2176 if (D->isDependentType())
2177 return;
2178
2179 for (auto *TmpD : D->decls()) {
2180 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2181 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2182 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2183 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2184 }
2185}
2186
2187void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2188 DiagnoseUnusedDecl(
2189 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2190}
2191
2192void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2193 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2194 return;
2195
2196 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2197 // typedefs can be referenced later on, so the diagnostics are emitted
2198 // at end-of-translation-unit.
2199 UnusedLocalTypedefNameCandidates.insert(Ptr: TD);
2200 return;
2201 }
2202
2203 FixItHint Hint;
2204 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2205
2206 unsigned DiagID;
2207 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2208 DiagID = diag::warn_unused_exception_param;
2209 else if (isa<LabelDecl>(Val: D))
2210 DiagID = diag::warn_unused_label;
2211 else
2212 DiagID = diag::warn_unused_variable;
2213
2214 SourceLocation DiagLoc = D->getLocation();
2215 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2216}
2217
2218void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2219 DiagReceiverTy DiagReceiver) {
2220 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2221 // it's not really unused.
2222 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2223 return;
2224
2225 // In C++, `_` variables behave as if they were maybe_unused
2226 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2227 return;
2228
2229 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2230
2231 if (Ty->isReferenceType() || Ty->isDependentType())
2232 return;
2233
2234 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2235 if (Tag->hasAttr<UnusedAttr>())
2236 return;
2237 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2238 // mimic gcc's behavior.
2239 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2240 RD && !RD->hasAttr<WarnUnusedAttr>())
2241 return;
2242 }
2243
2244 // Don't warn on volatile file-scope variables. They are visible beyond their
2245 // declaring function and writes to them could be observable side effects.
2246 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2247 return;
2248
2249 // Don't warn about __block Objective-C pointer variables, as they might
2250 // be assigned in the block but not used elsewhere for the purpose of lifetime
2251 // extension.
2252 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2253 return;
2254
2255 // Don't warn about Objective-C pointer variables with precise lifetime
2256 // semantics; they can be used to ensure ARC releases the object at a known
2257 // time, which may mean assignment but no other references.
2258 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2259 return;
2260
2261 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2262 if (iter == RefsMinusAssignments.end())
2263 return;
2264
2265 assert(iter->getSecond() >= 0 &&
2266 "Found a negative number of references to a VarDecl");
2267 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2268 // Assume the given VarDecl is "used" if its ref count stored in
2269 // `RefMinusAssignments` is positive, with one exception.
2270 //
2271 // For a C++ variable whose decl (with initializer) entirely consist the
2272 // condition expression of a if/while/for construct,
2273 // Clang creates a DeclRefExpr for the condition expression rather than a
2274 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2275 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2276 // used in the body of the if/while/for construct.
2277 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2278 if (!UnusedCXXCondDecl)
2279 return;
2280 }
2281
2282 unsigned DiagID;
2283 if (isa<ParmVarDecl>(Val: VD))
2284 DiagID = diag::warn_unused_but_set_parameter;
2285 else if (VD->isFileVarDecl())
2286 DiagID = diag::warn_unused_but_set_global;
2287 else
2288 DiagID = diag::warn_unused_but_set_variable;
2289 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2290}
2291
2292static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2293 Sema::DiagReceiverTy DiagReceiver) {
2294 // Verify that we have no forward references left. If so, there was a goto
2295 // or address of a label taken, but no definition of it. Label fwd
2296 // definitions are indicated with a null substmt which is also not a resolved
2297 // MS inline assembly label name.
2298 bool Diagnose = false;
2299 if (L->isMSAsmLabel())
2300 Diagnose = !L->isResolvedMSAsmLabel();
2301 else
2302 Diagnose = L->getStmt() == nullptr;
2303 if (Diagnose)
2304 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2305 << L);
2306}
2307
2308void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2309 S->applyNRVO();
2310
2311 if (S->decl_empty()) return;
2312 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2313 "Scope shouldn't contain decls!");
2314
2315 /// We visit the decls in non-deterministic order, but we want diagnostics
2316 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2317 /// and sort the diagnostics before emitting them, after we visited all decls.
2318 struct LocAndDiag {
2319 SourceLocation Loc;
2320 std::optional<SourceLocation> PreviousDeclLoc;
2321 PartialDiagnostic PD;
2322 };
2323 SmallVector<LocAndDiag, 16> DeclDiags;
2324 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2325 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2326 };
2327 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2328 SourceLocation PreviousDeclLoc,
2329 PartialDiagnostic PD) {
2330 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2331 };
2332
2333 for (auto *TmpD : S->decls()) {
2334 assert(TmpD && "This decl didn't get pushed??");
2335
2336 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2337 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2338
2339 // Diagnose unused variables in this scope.
2340 if (!S->hasUnrecoverableErrorOccurred()) {
2341 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2342 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2343 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2344 // Wait until end of TU to diagnose internal linkage file vars.
2345 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2346 VD && !VD->isInternalLinkageFileVar()) {
2347 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2348 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2349 }
2350 }
2351
2352 if (!D->getDeclName()) continue;
2353
2354 // If this was a forward reference to a label, verify it was defined.
2355 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2356 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2357
2358 // Partial translation units that are created in incremental processing must
2359 // not clean up the IdResolver because PTUs should take into account the
2360 // declarations that came from previous PTUs.
2361 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2362 getLangOpts().CPlusPlus)
2363 IdResolver.RemoveDecl(D);
2364
2365 // Warn on it if we are shadowing a declaration.
2366 auto ShadowI = ShadowingDecls.find(Val: D);
2367 if (ShadowI != ShadowingDecls.end()) {
2368 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2369 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2370 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2371 << D << FD << FD->getParent());
2372 }
2373 ShadowingDecls.erase(I: ShadowI);
2374 }
2375 }
2376
2377 llvm::sort(C&: DeclDiags,
2378 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2379 // The particular order for diagnostics is not important, as long
2380 // as the order is deterministic. Using the raw location is going
2381 // to generally be in source order unless there are macro
2382 // expansions involved.
2383 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2384 });
2385 for (const LocAndDiag &D : DeclDiags) {
2386 Diag(Loc: D.Loc, PD: D.PD);
2387 if (D.PreviousDeclLoc)
2388 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2389 }
2390}
2391
2392Scope *Sema::getNonFieldDeclScope(Scope *S) {
2393 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2394 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2395 (S->isClassScope() && !getLangOpts().CPlusPlus))
2396 S = S->getParent();
2397 return S;
2398}
2399
2400static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2401 ASTContext::GetBuiltinTypeError Error) {
2402 switch (Error) {
2403 case ASTContext::GE_None:
2404 return "";
2405 case ASTContext::GE_Missing_type:
2406 return BuiltinInfo.getHeaderName(ID);
2407 case ASTContext::GE_Missing_stdio:
2408 return "stdio.h";
2409 case ASTContext::GE_Missing_setjmp:
2410 return "setjmp.h";
2411 case ASTContext::GE_Missing_ucontext:
2412 return "ucontext.h";
2413 }
2414 llvm_unreachable("unhandled error kind");
2415}
2416
2417FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2418 unsigned ID, SourceLocation Loc) {
2419 DeclContext *Parent = Context.getTranslationUnitDecl();
2420
2421 if (getLangOpts().CPlusPlus) {
2422 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2423 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2424 CLinkageDecl->setImplicit();
2425 Parent->addDecl(D: CLinkageDecl);
2426 Parent = CLinkageDecl;
2427 }
2428
2429 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2430 if (Context.BuiltinInfo.isImmediate(ID)) {
2431 assert(getLangOpts().CPlusPlus20 &&
2432 "consteval builtins should only be available in C++20 mode");
2433 ConstexprKind = ConstexprSpecKind::Consteval;
2434 }
2435
2436 FunctionDecl *New = FunctionDecl::Create(
2437 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2438 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2439 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2440 New->setImplicit();
2441 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2442
2443 // Create Decl objects for each parameter, adding them to the
2444 // FunctionDecl.
2445 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2446 SmallVector<ParmVarDecl *, 16> Params;
2447 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2448 ParmVarDecl *parm = ParmVarDecl::Create(
2449 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2450 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2451 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2452 Params.push_back(Elt: parm);
2453 }
2454 New->setParams(Params);
2455 }
2456
2457 AddKnownFunctionAttributes(FD: New);
2458 return New;
2459}
2460
2461NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2462 Scope *S, bool ForRedeclaration,
2463 SourceLocation Loc) {
2464 LookupNecessaryTypesForBuiltin(S, ID);
2465
2466 ASTContext::GetBuiltinTypeError Error;
2467 QualType R = Context.GetBuiltinType(ID, Error);
2468 if (Error) {
2469 if (!ForRedeclaration)
2470 return nullptr;
2471
2472 // If we have a builtin without an associated type we should not emit a
2473 // warning when we were not able to find a type for it.
2474 if (Error == ASTContext::GE_Missing_type ||
2475 Context.BuiltinInfo.allowTypeMismatch(ID))
2476 return nullptr;
2477
2478 // If we could not find a type for setjmp it is because the jmp_buf type was
2479 // not defined prior to the setjmp declaration.
2480 if (Error == ASTContext::GE_Missing_setjmp) {
2481 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2482 << Context.BuiltinInfo.getName(ID);
2483 return nullptr;
2484 }
2485
2486 // Generally, we emit a warning that the declaration requires the
2487 // appropriate header.
2488 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2489 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2490 << Context.BuiltinInfo.getName(ID);
2491 return nullptr;
2492 }
2493
2494 if (!ForRedeclaration &&
2495 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2496 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2497 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2498 : diag::ext_implicit_lib_function_decl)
2499 << Context.BuiltinInfo.getName(ID) << R;
2500 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2501 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2502 << Header << Context.BuiltinInfo.getName(ID);
2503 }
2504
2505 if (R.isNull())
2506 return nullptr;
2507
2508 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2509 RegisterLocallyScopedExternCDecl(ND: New, S);
2510
2511 // TUScope is the translation-unit scope to insert this function into.
2512 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2513 // relate Scopes to DeclContexts, and probably eliminate CurContext
2514 // entirely, but we're not there yet.
2515 DeclContext *SavedContext = CurContext;
2516 CurContext = New->getDeclContext();
2517 PushOnScopeChains(D: New, S: TUScope);
2518 CurContext = SavedContext;
2519 return New;
2520}
2521
2522/// Typedef declarations don't have linkage, but they still denote the same
2523/// entity if their types are the same.
2524/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2525/// isSameEntity.
2526static void
2527filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2528 LookupResult &Previous) {
2529 // This is only interesting when modules are enabled.
2530 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2531 return;
2532
2533 // Empty sets are uninteresting.
2534 if (Previous.empty())
2535 return;
2536
2537 LookupResult::Filter Filter = Previous.makeFilter();
2538 while (Filter.hasNext()) {
2539 NamedDecl *Old = Filter.next();
2540
2541 // Non-hidden declarations are never ignored.
2542 if (S.isVisible(D: Old))
2543 continue;
2544
2545 // Declarations of the same entity are not ignored, even if they have
2546 // different linkages.
2547 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2548 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2549 T2: Decl->getUnderlyingType()))
2550 continue;
2551
2552 // If both declarations give a tag declaration a typedef name for linkage
2553 // purposes, then they declare the same entity.
2554 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2555 Decl->getAnonDeclWithTypedefName())
2556 continue;
2557 }
2558
2559 Filter.erase();
2560 }
2561
2562 Filter.done();
2563}
2564
2565bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2566 QualType OldType;
2567 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2568 OldType = OldTypedef->getUnderlyingType();
2569 else
2570 OldType = Context.getTypeDeclType(Decl: Old);
2571 QualType NewType = New->getUnderlyingType();
2572
2573 if (NewType->isVariablyModifiedType()) {
2574 // Must not redefine a typedef with a variably-modified type.
2575 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2576 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2577 << Kind << NewType;
2578 if (Old->getLocation().isValid())
2579 notePreviousDefinition(Old, New: New->getLocation());
2580 New->setInvalidDecl();
2581 return true;
2582 }
2583
2584 if (OldType != NewType &&
2585 !OldType->isDependentType() &&
2586 !NewType->isDependentType() &&
2587 !Context.hasSameType(T1: OldType, T2: NewType)) {
2588 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2589 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2590 << Kind << NewType << OldType;
2591 if (Old->getLocation().isValid())
2592 notePreviousDefinition(Old, New: New->getLocation());
2593 New->setInvalidDecl();
2594 return true;
2595 }
2596 return false;
2597}
2598
2599void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2600 LookupResult &OldDecls) {
2601 // If the new decl is known invalid already, don't bother doing any
2602 // merging checks.
2603 if (New->isInvalidDecl()) return;
2604
2605 // Allow multiple definitions for ObjC built-in typedefs.
2606 // FIXME: Verify the underlying types are equivalent!
2607 if (getLangOpts().ObjC) {
2608 const IdentifierInfo *TypeID = New->getIdentifier();
2609 switch (TypeID->getLength()) {
2610 default: break;
2611 case 2:
2612 {
2613 if (!TypeID->isStr(Str: "id"))
2614 break;
2615 QualType T = New->getUnderlyingType();
2616 if (!T->isPointerType())
2617 break;
2618 if (!T->isVoidPointerType()) {
2619 QualType PT = T->castAs<PointerType>()->getPointeeType();
2620 if (!PT->isStructureType())
2621 break;
2622 }
2623 Context.setObjCIdRedefinitionType(T);
2624 // Install the built-in type for 'id', ignoring the current definition.
2625 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2626 modedTy: Context.getObjCIdType());
2627 return;
2628 }
2629 case 5:
2630 if (!TypeID->isStr(Str: "Class"))
2631 break;
2632 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2633 // Install the built-in type for 'Class', ignoring the current definition.
2634 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2635 modedTy: Context.getObjCClassType());
2636 return;
2637 case 3:
2638 if (!TypeID->isStr(Str: "SEL"))
2639 break;
2640 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2641 // Install the built-in type for 'SEL', ignoring the current definition.
2642 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2643 modedTy: Context.getObjCSelType());
2644 return;
2645 }
2646 // Fall through - the typedef name was not a builtin type.
2647 }
2648
2649 // Verify the old decl was also a type.
2650 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2651 if (!Old) {
2652 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2653 << New->getDeclName();
2654
2655 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2656 if (OldD->getLocation().isValid())
2657 notePreviousDefinition(Old: OldD, New: New->getLocation());
2658
2659 return New->setInvalidDecl();
2660 }
2661
2662 // If the old declaration is invalid, just give up here.
2663 if (Old->isInvalidDecl())
2664 return New->setInvalidDecl();
2665
2666 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2667 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2668 auto *NewTag = New->getAnonDeclWithTypedefName();
2669 NamedDecl *Hidden = nullptr;
2670 if (OldTag && NewTag &&
2671 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2672 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2673 // There is a definition of this tag, but it is not visible. Use it
2674 // instead of our tag.
2675 if (OldTD->isModed())
2676 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2677 modedTy: OldTD->getUnderlyingType());
2678 else
2679 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2680
2681 // An anonymous enum is recognized as a redeclaration only when its
2682 // typedef name gets merged, at which point the new enum and its
2683 // enumerators already have a distinct canonical type. Link the enum
2684 // declarations, but also retype the new enumerators because
2685 // setPreviousDecl() does not update QualTypes built before the merge;
2686 // otherwise the merged typedef and its enumerators disagree on the type
2687 // (GH213299).
2688 //
2689 // FIXME: The global module restriction only limits the impact of this
2690 // change; relax it if the issue shows up in other contexts.
2691 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2692 if (auto *NewEnum = dyn_cast<EnumDecl>(Val: NewTag)) {
2693 if (auto *OldEnum = dyn_cast<EnumDecl>(Val: OldTag)) {
2694 NewEnum->setPreviousDecl(OldEnum);
2695 QualType EnumType = Context.getCanonicalTagType(TD: OldEnum);
2696 for (auto *ECD : NewEnum->enumerators())
2697 ECD->setType(EnumType);
2698 }
2699 }
2700 }
2701
2702 // Make the old tag definition visible.
2703 makeMergedDefinitionVisible(ND: Hidden);
2704
2705 CleanupMergedEnum(S, New: NewTag);
2706 }
2707 }
2708
2709 // If the typedef types are not identical, reject them in all languages and
2710 // with any extensions enabled.
2711 if (isIncompatibleTypedef(Old, New))
2712 return;
2713
2714 // The types match. Link up the redeclaration chain and merge attributes if
2715 // the old declaration was a typedef.
2716 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2717 New->setPreviousDecl(Typedef);
2718 mergeDeclAttributes(New, Old);
2719 }
2720
2721 if (getLangOpts().MicrosoftExt)
2722 return;
2723
2724 if (getLangOpts().CPlusPlus) {
2725 // C++ [dcl.typedef]p2:
2726 // In a given non-class scope, a typedef specifier can be used to
2727 // redefine the name of any type declared in that scope to refer
2728 // to the type to which it already refers.
2729 if (!isa<CXXRecordDecl>(Val: CurContext))
2730 return;
2731
2732 // C++0x [dcl.typedef]p4:
2733 // In a given class scope, a typedef specifier can be used to redefine
2734 // any class-name declared in that scope that is not also a typedef-name
2735 // to refer to the type to which it already refers.
2736 //
2737 // This wording came in via DR424, which was a correction to the
2738 // wording in DR56, which accidentally banned code like:
2739 //
2740 // struct S {
2741 // typedef struct A { } A;
2742 // };
2743 //
2744 // in the C++03 standard. We implement the C++0x semantics, which
2745 // allow the above but disallow
2746 //
2747 // struct S {
2748 // typedef int I;
2749 // typedef int I;
2750 // };
2751 //
2752 // since that was the intent of DR56.
2753 if (!isa<TypedefNameDecl>(Val: Old))
2754 return;
2755
2756 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2757 << New->getDeclName();
2758 notePreviousDefinition(Old, New: New->getLocation());
2759 return New->setInvalidDecl();
2760 }
2761
2762 // Modules always permit redefinition of typedefs, as does C11.
2763 if (getLangOpts().Modules || getLangOpts().C11)
2764 return;
2765
2766 // If we have a redefinition of a typedef in C, emit a warning. This warning
2767 // is normally mapped to an error, but can be controlled with
2768 // -Wtypedef-redefinition. If either the original or the redefinition is
2769 // in a system header, don't emit this for compatibility with GCC.
2770 if (getDiagnostics().getSuppressSystemWarnings() &&
2771 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2772 (Old->isImplicit() ||
2773 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2774 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2775 return;
2776
2777 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2778 << New->getDeclName();
2779 notePreviousDefinition(Old, New: New->getLocation());
2780}
2781
2782void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2783 // If this was an unscoped enumeration, yank all of its enumerators
2784 // out of the scope.
2785 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2786 Scope *EnumScope = getNonFieldDeclScope(S);
2787 for (auto *ECD : ED->enumerators()) {
2788 assert(EnumScope->isDeclScope(ECD));
2789 EnumScope->RemoveDecl(D: ECD);
2790 IdResolver.RemoveDecl(D: ECD);
2791 }
2792 }
2793}
2794
2795/// DeclhasAttr - returns true if decl Declaration already has the target
2796/// attribute.
2797static bool DeclHasAttr(const Decl *D, const Attr *A) {
2798 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2799 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2800 for (const auto *i : D->attrs())
2801 if (i->getKind() == A->getKind()) {
2802 if (Ann) {
2803 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2804 return true;
2805 continue;
2806 }
2807 // FIXME: Don't hardcode this check
2808 if (OA && isa<OwnershipAttr>(Val: i))
2809 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2810 return true;
2811 }
2812
2813 return false;
2814}
2815
2816static bool isAttributeTargetADefinition(Decl *D) {
2817 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2818 return VD->isThisDeclarationADefinition();
2819 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2820 return TD->isCompleteDefinition() || TD->isBeingDefined();
2821 return true;
2822}
2823
2824/// Merge alignment attributes from \p Old to \p New, taking into account the
2825/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2826///
2827/// \return \c true if any attributes were added to \p New.
2828static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2829 // Look for alignas attributes on Old, and pick out whichever attribute
2830 // specifies the strictest alignment requirement.
2831 AlignedAttr *OldAlignasAttr = nullptr;
2832 AlignedAttr *OldStrictestAlignAttr = nullptr;
2833 unsigned OldAlign = 0;
2834 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2835 // FIXME: We have no way of representing inherited dependent alignments
2836 // in a case like:
2837 // template<int A, int B> struct alignas(A) X;
2838 // template<int A, int B> struct alignas(B) X {};
2839 // For now, we just ignore any alignas attributes which are not on the
2840 // definition in such a case.
2841 if (I->isAlignmentDependent())
2842 return false;
2843
2844 if (I->isAlignas())
2845 OldAlignasAttr = I;
2846
2847 unsigned Align = I->getAlignment(Ctx&: S.Context);
2848 if (Align > OldAlign) {
2849 OldAlign = Align;
2850 OldStrictestAlignAttr = I;
2851 }
2852 }
2853
2854 // Look for alignas attributes on New.
2855 AlignedAttr *NewAlignasAttr = nullptr;
2856 unsigned NewAlign = 0;
2857 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2858 if (I->isAlignmentDependent())
2859 return false;
2860
2861 if (I->isAlignas())
2862 NewAlignasAttr = I;
2863
2864 unsigned Align = I->getAlignment(Ctx&: S.Context);
2865 if (Align > NewAlign)
2866 NewAlign = Align;
2867 }
2868
2869 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2870 // Both declarations have 'alignas' attributes. We require them to match.
2871 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2872 // fall short. (If two declarations both have alignas, they must both match
2873 // every definition, and so must match each other if there is a definition.)
2874
2875 // If either declaration only contains 'alignas(0)' specifiers, then it
2876 // specifies the natural alignment for the type.
2877 if (OldAlign == 0 || NewAlign == 0) {
2878 QualType Ty;
2879 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2880 Ty = VD->getType();
2881 else
2882 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2883
2884 if (OldAlign == 0)
2885 OldAlign = S.Context.getTypeAlign(T: Ty);
2886 if (NewAlign == 0)
2887 NewAlign = S.Context.getTypeAlign(T: Ty);
2888 }
2889
2890 if (OldAlign != NewAlign) {
2891 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2892 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2893 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2894 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2895 }
2896 }
2897
2898 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2899 // C++11 [dcl.align]p6:
2900 // if any declaration of an entity has an alignment-specifier,
2901 // every defining declaration of that entity shall specify an
2902 // equivalent alignment.
2903 // C11 6.7.5/7:
2904 // If the definition of an object does not have an alignment
2905 // specifier, any other declaration of that object shall also
2906 // have no alignment specifier.
2907 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2908 << OldAlignasAttr;
2909 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2910 << OldAlignasAttr;
2911 }
2912
2913 bool AnyAdded = false;
2914
2915 // Ensure we have an attribute representing the strictest alignment.
2916 if (OldAlign > NewAlign) {
2917 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2918 Clone->setInherited(true);
2919 New->addAttr(A: Clone);
2920 AnyAdded = true;
2921 }
2922
2923 // Ensure we have an alignas attribute if the old declaration had one.
2924 if (OldAlignasAttr && !NewAlignasAttr &&
2925 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2926 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2927 Clone->setInherited(true);
2928 New->addAttr(A: Clone);
2929 AnyAdded = true;
2930 }
2931
2932 return AnyAdded;
2933}
2934
2935#define WANT_DECL_MERGE_LOGIC
2936#include "clang/Sema/AttrParsedAttrImpl.inc"
2937#undef WANT_DECL_MERGE_LOGIC
2938
2939static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2940 const InheritableAttr *Attr,
2941 AvailabilityMergeKind AMK) {
2942 // Diagnose any mutual exclusions between the attribute that we want to add
2943 // and attributes that already exist on the declaration.
2944 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2945 return false;
2946
2947 // This function copies an attribute Attr from a previous declaration to the
2948 // new declaration D if the new declaration doesn't itself have that attribute
2949 // yet or if that attribute allows duplicates.
2950 // If you're adding a new attribute that requires logic different from
2951 // "use explicit attribute on decl if present, else use attribute from
2952 // previous decl", for example if the attribute needs to be consistent
2953 // between redeclarations, you need to call a custom merge function here.
2954 InheritableAttr *NewAttr = nullptr;
2955 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2956 const IdentifierInfo *InferredPlatformII = nullptr;
2957 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2958 InferredPlatformII = Inf->getPlatform();
2959 NewAttr = S.mergeAndInferAvailabilityAttr(
2960 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2961 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2962 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2963 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2964 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2965 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2966 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2967 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2968 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2969 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2970 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2971 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2972 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2973 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2974 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2975 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2976 FirstArg: FA->getFirstArg());
2977 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2978 NewAttr = S.mergeFormatMatchesAttr(
2979 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2980 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2981 NewAttr = S.mergeModularFormatAttr(
2982 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2983 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2984 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2985 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2986 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2987 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2988 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2989 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2990 Model: IA->getInheritanceModel());
2991 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2992 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2993 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2994 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2995 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2996 isa<CUDAGlobalAttr>(Val: Attr))) {
2997 // CUDA target attributes are part of function signature for
2998 // overloading purposes and must not be merged.
2999 return false;
3000 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
3001 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
3002 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
3003 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
3004 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Val: Attr))
3005 NewAttr = S.Swift().mergeAttrAttr(D, SAA: *SAA);
3006 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
3007 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
3008 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
3009 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
3010 else if (isa<AlignedAttr>(Val: Attr))
3011 // AlignedAttrs are handled separately, because we need to handle all
3012 // such attributes on a declaration at the same time.
3013 NewAttr = nullptr;
3014 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
3015 (AMK == AvailabilityMergeKind::Override ||
3016 AMK == AvailabilityMergeKind::ProtocolImplementation ||
3017 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
3018 NewAttr = nullptr;
3019 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
3020 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
3021 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
3022 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
3023 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
3024 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
3025 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Val: Attr))
3026 NewAttr = S.Wasm().mergeExportNameAttr(D, AL: *ENA);
3027 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
3028 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
3029 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
3030 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
3031 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
3032 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
3033 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
3034 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
3035 Z: NT->getZ());
3036 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3037 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3038 Preferred: WS->getPreferred(),
3039 SpelledArgsCount: WS->getSpelledArgsCount());
3040 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3041 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3042 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3043 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3044 else if (isa<SuppressAttr>(Val: Attr))
3045 // Do nothing. Each redeclaration should be suppressed separately.
3046 NewAttr = nullptr;
3047 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3048 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3049 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3050 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3051 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3052 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3053
3054 if (NewAttr) {
3055 NewAttr->setInherited(true);
3056 D->addAttr(A: NewAttr);
3057 if (isa<MSInheritanceAttr>(Val: NewAttr))
3058 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3059 return true;
3060 }
3061
3062 return false;
3063}
3064
3065static const NamedDecl *getDefinition(const Decl *D) {
3066 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3067 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3068 return Def;
3069 return nullptr;
3070 }
3071 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3072 const VarDecl *Def = VD->getDefinition();
3073 if (Def)
3074 return Def;
3075 return VD->getActingDefinition();
3076 }
3077 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3078 const FunctionDecl *Def = nullptr;
3079 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3080 return Def;
3081 }
3082 return nullptr;
3083}
3084
3085static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3086 for (const auto *Attribute : D->attrs())
3087 if (Attribute->getKind() == Kind)
3088 return true;
3089 return false;
3090}
3091
3092/// checkNewAttributesAfterDef - If we already have a definition, check that
3093/// there are no new attributes in this declaration.
3094static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3095 if (!New->hasAttrs())
3096 return;
3097
3098 const NamedDecl *Def = getDefinition(D: Old);
3099 if (!Def || Def == New)
3100 return;
3101
3102 AttrVec &NewAttributes = New->getAttrs();
3103 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3104 Attr *NewAttribute = NewAttributes[I];
3105
3106 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3107 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3108 SkipBodyInfo SkipBody;
3109 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3110
3111 // If we're skipping this definition, drop the "alias" attribute.
3112 if (SkipBody.ShouldSkip) {
3113 NewAttributes.erase(CI: NewAttributes.begin() + I);
3114 --E;
3115 continue;
3116 }
3117 } else {
3118 VarDecl *VD = cast<VarDecl>(Val: New);
3119 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3120 VarDecl::TentativeDefinition
3121 ? diag::err_alias_after_tentative
3122 : diag::err_redefinition;
3123 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3124 if (Diag == diag::err_redefinition)
3125 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3126 else
3127 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3128 VD->setInvalidDecl();
3129 }
3130 ++I;
3131 continue;
3132 }
3133
3134 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3135 // Tentative definitions are only interesting for the alias check above.
3136 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3137 ++I;
3138 continue;
3139 }
3140 }
3141
3142 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3143 ++I;
3144 continue; // regular attr merging will take care of validating this.
3145 }
3146
3147 if (NewAttribute->getLocation().isInvalid()) {
3148 // An attribute with no source location was not written by the user. API
3149 // notes, in particular, are matched against whichever declaration the
3150 // compiler reaches, which can be a redeclaration that follows the
3151 // definition, possibly in a different module. There is nothing for the
3152 // user to correct, and erasing the attribute would silently change what
3153 // the annotated API means.
3154 ++I;
3155 continue;
3156 }
3157
3158 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3159 // C's _Noreturn is allowed to be added to a function after it is defined.
3160 ++I;
3161 continue;
3162 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3163 // msvc will allow a subsequent definition to add an uuid to a class
3164 ++I;
3165 continue;
3166 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3167 Val: NewAttribute) &&
3168 NewAttribute->isStandardAttributeSyntax()) {
3169 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3170 // deprecated attribute can later be re-declared with the attribute and
3171 // vice-versa.
3172 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3173 // maybe_unused attribute can later be redeclared with the attribute and
3174 // vice versa.
3175 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3176 // nodiscard attribute can later be redeclared with the attribute and
3177 // vice-versa.
3178 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3179 ++I;
3180 continue;
3181 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3182 if (AA->isAlignas()) {
3183 // C++11 [dcl.align]p6:
3184 // if any declaration of an entity has an alignment-specifier,
3185 // every defining declaration of that entity shall specify an
3186 // equivalent alignment.
3187 // C11 6.7.5/7:
3188 // If the definition of an object does not have an alignment
3189 // specifier, any other declaration of that object shall also
3190 // have no alignment specifier.
3191 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3192 << AA;
3193 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3194 << AA;
3195 NewAttributes.erase(CI: NewAttributes.begin() + I);
3196 --E;
3197 continue;
3198 }
3199 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3200 // If there is a C definition followed by a redeclaration with this
3201 // attribute then there are two different definitions. In C++, prefer the
3202 // standard diagnostics.
3203 if (!S.getLangOpts().CPlusPlus) {
3204 S.Diag(Loc: NewAttribute->getLocation(),
3205 DiagID: diag::err_loader_uninitialized_redeclaration);
3206 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3207 NewAttributes.erase(CI: NewAttributes.begin() + I);
3208 --E;
3209 continue;
3210 }
3211 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3212 cast<VarDecl>(Val: New)->isInline() &&
3213 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3214 // Don't warn about applying selectany to implicitly inline variables.
3215 // Older compilers and language modes would require the use of selectany
3216 // to make such variables inline, and it would have no effect if we
3217 // honored it.
3218 ++I;
3219 continue;
3220 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3221 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3222 // declarations after definitions.
3223 ++I;
3224 continue;
3225 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3226 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3227 // error since the definition will have already been created without
3228 // the semantic effects of the attribute having been applied.
3229 S.Diag(Loc: NewAttribute->getLocation(),
3230 DiagID: diag::err_sycl_entry_point_after_definition)
3231 << NewAttribute;
3232 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3233 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3234 ++I;
3235 continue;
3236 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3237 // SYCLExternalAttr may be added after a definition.
3238 ++I;
3239 continue;
3240 }
3241
3242 S.Diag(Loc: NewAttribute->getLocation(),
3243 DiagID: diag::warn_attribute_precede_definition);
3244 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3245 NewAttributes.erase(CI: NewAttributes.begin() + I);
3246 --E;
3247 }
3248}
3249
3250static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3251 const ConstInitAttr *CIAttr,
3252 bool AttrBeforeInit) {
3253 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3254
3255 // Figure out a good way to write this specifier on the old declaration.
3256 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3257 // enough of the attribute list spelling information to extract that without
3258 // heroics.
3259 std::string SuitableSpelling;
3260 if (S.getLangOpts().CPlusPlus20)
3261 SuitableSpelling = std::string(
3262 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3263 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3264 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3265 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3266 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3267 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3268 tok::r_square, tok::r_square}));
3269 if (SuitableSpelling.empty())
3270 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3271 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3272 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3273 tok::r_paren, tok::r_paren}));
3274 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3275 SuitableSpelling = "constinit";
3276 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3277 SuitableSpelling = "[[clang::require_constant_initialization]]";
3278 if (SuitableSpelling.empty())
3279 SuitableSpelling = "__attribute__((require_constant_initialization))";
3280 SuitableSpelling += " ";
3281
3282 if (AttrBeforeInit) {
3283 // extern constinit int a;
3284 // int a = 0; // error (missing 'constinit'), accepted as extension
3285 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3286 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3287 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3288 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3289 } else {
3290 // int a = 0;
3291 // constinit extern int a; // error (missing 'constinit')
3292 S.Diag(Loc: CIAttr->getLocation(),
3293 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3294 : diag::warn_require_const_init_added_too_late)
3295 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3296 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3297 << CIAttr->isConstinit()
3298 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3299 }
3300}
3301
3302void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3303 AvailabilityMergeKind AMK) {
3304 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3305 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3306 NewAttr->setInherited(true);
3307 New->addAttr(A: NewAttr);
3308 }
3309 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3310 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3311 NewAttr->setInherited(true);
3312 New->addAttr(A: NewAttr);
3313 }
3314
3315 if (!Old->hasAttrs() && !New->hasAttrs())
3316 return;
3317
3318 // [dcl.constinit]p1:
3319 // If the [constinit] specifier is applied to any declaration of a
3320 // variable, it shall be applied to the initializing declaration.
3321 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3322 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3323 if (bool(OldConstInit) != bool(NewConstInit)) {
3324 const auto *OldVD = cast<VarDecl>(Val: Old);
3325 auto *NewVD = cast<VarDecl>(Val: New);
3326
3327 // Find the initializing declaration. Note that we might not have linked
3328 // the new declaration into the redeclaration chain yet.
3329 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3330 if (!InitDecl &&
3331 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3332 InitDecl = NewVD;
3333
3334 if (InitDecl == NewVD) {
3335 // This is the initializing declaration. If it would inherit 'constinit',
3336 // that's ill-formed. (Note that we do not apply this to the attribute
3337 // form).
3338 if (OldConstInit && OldConstInit->isConstinit())
3339 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3340 /*AttrBeforeInit=*/true);
3341 } else if (NewConstInit) {
3342 // This is the first time we've been told that this declaration should
3343 // have a constant initializer. If we already saw the initializing
3344 // declaration, this is too late.
3345 if (InitDecl && InitDecl != NewVD) {
3346 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3347 /*AttrBeforeInit=*/false);
3348 NewVD->dropAttr<ConstInitAttr>();
3349 }
3350 }
3351 }
3352
3353 // Attributes declared post-definition are currently ignored.
3354 checkNewAttributesAfterDef(S&: *this, New, Old);
3355
3356 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3357 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3358 if (!OldA->isEquivalent(Other: NewA)) {
3359 // This redeclaration changes __asm__ label.
3360 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3361 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3362 }
3363 } else if (Old->isUsed()) {
3364 // This redeclaration adds an __asm__ label to a declaration that has
3365 // already been ODR-used.
3366 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3367 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3368 }
3369 }
3370
3371 // Re-declaration cannot add abi_tag's.
3372 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3373 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3374 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3375 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3376 Diag(Loc: NewAbiTagAttr->getLocation(),
3377 DiagID: diag::err_new_abi_tag_on_redeclaration)
3378 << NewTag;
3379 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3380 }
3381 }
3382 } else {
3383 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3384 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3385 }
3386 }
3387
3388 // This redeclaration adds a section attribute.
3389 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3390 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3391 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3392 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3393 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3394 }
3395 }
3396 }
3397
3398 // Redeclaration adds code-seg attribute.
3399 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3400 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3401 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3402 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3403 << 0 /*codeseg*/;
3404 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3405 }
3406
3407 if (!Old->hasAttrs())
3408 return;
3409
3410 bool foundAny = New->hasAttrs();
3411
3412 // Ensure that any moving of objects within the allocated map is done before
3413 // we process them.
3414 if (!foundAny) New->setAttrs(AttrVec());
3415
3416 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3417 // Ignore deprecated/unavailable/availability attributes if requested.
3418 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3419 if (isa<DeprecatedAttr>(Val: I) ||
3420 isa<UnavailableAttr>(Val: I) ||
3421 isa<AvailabilityAttr>(Val: I)) {
3422 switch (AMK) {
3423 case AvailabilityMergeKind::None:
3424 continue;
3425
3426 case AvailabilityMergeKind::Redeclaration:
3427 case AvailabilityMergeKind::Override:
3428 case AvailabilityMergeKind::ProtocolImplementation:
3429 case AvailabilityMergeKind::OptionalProtocolImplementation:
3430 LocalAMK = AMK;
3431 break;
3432 }
3433 }
3434
3435 // Already handled.
3436 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3437 continue;
3438
3439 // Don't propagate inferred noreturn or conflicting inline attributes to
3440 // explicit specializations.
3441 if (isa<InferredNoReturnAttr>(Val: I) || isa<AlwaysInlineAttr>(Val: I) ||
3442 isa<NoInlineAttr>(Val: I)) {
3443 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3444 FD &&
3445 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3446 continue;
3447 }
3448
3449 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3450 foundAny = true;
3451 }
3452
3453 if (mergeAlignedAttrs(S&: *this, New, Old))
3454 foundAny = true;
3455
3456 if (!foundAny) New->dropAttrs();
3457}
3458
3459void Sema::CheckAttributesOnDeducedType(Decl *D) {
3460 for (const Attr *A : D->attrs())
3461 checkAttrIsTypeDependent(D, A);
3462}
3463
3464// Returns the number of added attributes.
3465template <class T>
3466static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3467 Sema &S) {
3468 unsigned found = 0;
3469 for (const auto *I : From->specific_attrs<T>()) {
3470 if (!DeclHasAttr(To, I)) {
3471 T *newAttr = cast<T>(I->clone(S.Context));
3472 newAttr->setInherited(true);
3473 To->addAttr(A: newAttr);
3474 ++found;
3475 }
3476 }
3477 return found;
3478}
3479
3480template <class F>
3481static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3482 F &&propagator) {
3483 if (!From->hasAttrs()) {
3484 return;
3485 }
3486
3487 bool foundAny = To->hasAttrs();
3488
3489 // Ensure that any moving of objects within the allocated map is
3490 // done before we process them.
3491 if (!foundAny)
3492 To->setAttrs(AttrVec());
3493
3494 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3495
3496 if (!foundAny)
3497 To->dropAttrs();
3498}
3499
3500/// mergeParamDeclAttributes - Copy attributes from the old parameter
3501/// to the new one.
3502static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3503 const ParmVarDecl *oldDecl, Sema &S) {
3504 propagateAttributes(
3505 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3506 unsigned found = 0;
3507 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3508 // Propagate the lifetimebound attribute from parameters to the
3509 // most recent declaration. Note that this doesn't include the implicit
3510 // 'this' parameter, as the attribute is applied to the function type in
3511 // that case.
3512 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3513 return found;
3514 });
3515}
3516
3517static bool EquivalentArrayTypes(QualType Old, QualType New,
3518 const ASTContext &Ctx) {
3519
3520 auto NoSizeInfo = [&Ctx](QualType Ty) {
3521 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3522 return true;
3523 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3524 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3525 return false;
3526 };
3527
3528 // `type[]` is equivalent to `type *` and `type[*]`.
3529 if (NoSizeInfo(Old) && NoSizeInfo(New))
3530 return true;
3531
3532 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3533 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3534 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3535 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3536 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3537 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3538 return false;
3539 return true;
3540 }
3541
3542 // Only compare size, ignore Size modifiers and CVR.
3543 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3544 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3545 Ctx.getAsConstantArrayType(T: New)->getSize();
3546 }
3547
3548 // Don't try to compare dependent sized array
3549 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3550 return true;
3551 }
3552
3553 return Old == New;
3554}
3555
3556static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3557 const ParmVarDecl *OldParam,
3558 Sema &S) {
3559 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3560 if (auto Newnullability = NewParam->getType()->getNullability()) {
3561 if (*Oldnullability != *Newnullability) {
3562 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3563 << DiagNullabilityKind(
3564 *Newnullability,
3565 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3566 != 0))
3567 << DiagNullabilityKind(
3568 *Oldnullability,
3569 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3570 != 0));
3571 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3572 }
3573 } else {
3574 QualType NewT = NewParam->getType();
3575 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3576 NewParam->setType(NewT);
3577 }
3578 }
3579 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3580 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3581 if (OldParamDT && NewParamDT &&
3582 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3583 QualType OldParamOT = OldParamDT->getOriginalType();
3584 QualType NewParamOT = NewParamDT->getOriginalType();
3585 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3586 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3587 << NewParam << NewParamOT;
3588 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3589 << OldParamOT;
3590 }
3591 }
3592}
3593
3594namespace {
3595
3596/// Used in MergeFunctionDecl to keep track of function parameters in
3597/// C.
3598struct GNUCompatibleParamWarning {
3599 ParmVarDecl *OldParm;
3600 ParmVarDecl *NewParm;
3601 QualType PromotedType;
3602};
3603
3604} // end anonymous namespace
3605
3606// Determine whether the previous declaration was a definition, implicit
3607// declaration, or a declaration.
3608template <typename T>
3609static std::pair<diag::kind, SourceLocation>
3610getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3611 diag::kind PrevDiag;
3612 SourceLocation OldLocation = Old->getLocation();
3613 if (Old->isThisDeclarationADefinition())
3614 PrevDiag = diag::note_previous_definition;
3615 else if (Old->isImplicit()) {
3616 PrevDiag = diag::note_previous_implicit_declaration;
3617 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3618 if (FD->getBuiltinID())
3619 PrevDiag = diag::note_previous_builtin_declaration;
3620 }
3621 if (OldLocation.isInvalid())
3622 OldLocation = New->getLocation();
3623 } else
3624 PrevDiag = diag::note_previous_declaration;
3625 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3626}
3627
3628/// canRedefineFunction - checks if a function can be redefined. Currently,
3629/// only extern inline functions can be redefined, and even then only in
3630/// GNU89 mode.
3631static bool canRedefineFunction(const FunctionDecl *FD,
3632 const LangOptions& LangOpts) {
3633 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3634 !LangOpts.CPlusPlus &&
3635 FD->isInlineSpecified() &&
3636 FD->getStorageClass() == SC_Extern);
3637}
3638
3639const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3640 const AttributedType *AT = T->getAs<AttributedType>();
3641 while (AT && !AT->isCallingConv())
3642 AT = AT->getModifiedType()->getAs<AttributedType>();
3643 return AT;
3644}
3645
3646template <typename T>
3647static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3648 const DeclContext *DC = Old->getDeclContext();
3649 if (DC->isRecord())
3650 return false;
3651
3652 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3653 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3654 return true;
3655 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3656 return true;
3657 return false;
3658}
3659
3660template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3661static bool isExternC(VarTemplateDecl *) { return false; }
3662static bool isExternC(FunctionTemplateDecl *) { return false; }
3663
3664/// Check whether a redeclaration of an entity introduced by a
3665/// using-declaration is valid, given that we know it's not an overload
3666/// (nor a hidden tag declaration).
3667template<typename ExpectedDecl>
3668static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3669 ExpectedDecl *New) {
3670 // C++11 [basic.scope.declarative]p4:
3671 // Given a set of declarations in a single declarative region, each of
3672 // which specifies the same unqualified name,
3673 // -- they shall all refer to the same entity, or all refer to functions
3674 // and function templates; or
3675 // -- exactly one declaration shall declare a class name or enumeration
3676 // name that is not a typedef name and the other declarations shall all
3677 // refer to the same variable or enumerator, or all refer to functions
3678 // and function templates; in this case the class name or enumeration
3679 // name is hidden (3.3.10).
3680
3681 // C++11 [namespace.udecl]p14:
3682 // If a function declaration in namespace scope or block scope has the
3683 // same name and the same parameter-type-list as a function introduced
3684 // by a using-declaration, and the declarations do not declare the same
3685 // function, the program is ill-formed.
3686
3687 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3688 if (Old &&
3689 !Old->getDeclContext()->getRedeclContext()->Equals(
3690 New->getDeclContext()->getRedeclContext()) &&
3691 !(isExternC(Old) && isExternC(New)))
3692 Old = nullptr;
3693
3694 if (!Old) {
3695 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3696 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3697 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3698 return true;
3699 }
3700 return false;
3701}
3702
3703static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3704 const FunctionDecl *B) {
3705 assert(A->getNumParams() == B->getNumParams());
3706
3707 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3708 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3709 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3710 if (AttrA == AttrB)
3711 return true;
3712 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3713 AttrA->isDynamic() == AttrB->isDynamic();
3714 };
3715
3716 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3717}
3718
3719/// If necessary, adjust the semantic declaration context for a qualified
3720/// declaration to name the correct inline namespace within the qualifier.
3721static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3722 DeclaratorDecl *OldD) {
3723 // The only case where we need to update the DeclContext is when
3724 // redeclaration lookup for a qualified name finds a declaration
3725 // in an inline namespace within the context named by the qualifier:
3726 //
3727 // inline namespace N { int f(); }
3728 // int ::f(); // Sema DC needs adjusting from :: to N::.
3729 //
3730 // For unqualified declarations, the semantic context *can* change
3731 // along the redeclaration chain (for local extern declarations,
3732 // extern "C" declarations, and friend declarations in particular).
3733 if (!NewD->getQualifier())
3734 return;
3735
3736 // NewD is probably already in the right context.
3737 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3738 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3739 if (NamedDC->Equals(DC: SemaDC))
3740 return;
3741
3742 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3743 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3744 "unexpected context for redeclaration");
3745
3746 auto *LexDC = NewD->getLexicalDeclContext();
3747 auto FixSemaDC = [=](NamedDecl *D) {
3748 if (!D)
3749 return;
3750 D->setDeclContext(SemaDC);
3751 D->setLexicalDeclContext(LexDC);
3752 };
3753
3754 FixSemaDC(NewD);
3755 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3756 FixSemaDC(FD->getDescribedFunctionTemplate());
3757 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3758 FixSemaDC(VD->getDescribedVarTemplate());
3759}
3760
3761bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3762 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3763 // Verify the old decl was also a function.
3764 FunctionDecl *Old = OldD->getAsFunction();
3765 if (!Old) {
3766 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3767 // We don't need to check the using friend pattern from other module unit
3768 // since we should have diagnosed such cases in its unit already.
3769 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3770 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3771 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3772 DiagID: diag::note_using_decl_target);
3773 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3774 << 0;
3775 return true;
3776 }
3777
3778 // Check whether the two declarations might declare the same function or
3779 // function template.
3780 if (FunctionTemplateDecl *NewTemplate =
3781 New->getDescribedFunctionTemplate()) {
3782 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3783 New: NewTemplate))
3784 return true;
3785 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3786 ->getAsFunction();
3787 } else {
3788 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3789 return true;
3790 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3791 }
3792 } else {
3793 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3794 << New->getDeclName();
3795 notePreviousDefinition(Old: OldD, New: New->getLocation());
3796 return true;
3797 }
3798 }
3799
3800 // If the old declaration was found in an inline namespace and the new
3801 // declaration was qualified, update the DeclContext to match.
3802 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3803
3804 // If the old declaration is invalid, just give up here.
3805 if (Old->isInvalidDecl())
3806 return true;
3807
3808 // Disallow redeclaration of some builtins.
3809 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3810 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3811 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3812 << Old << Old->getType();
3813 return true;
3814 }
3815
3816 diag::kind PrevDiag;
3817 SourceLocation OldLocation;
3818 std::tie(args&: PrevDiag, args&: OldLocation) =
3819 getNoteDiagForInvalidRedeclaration(Old, New);
3820
3821 // Don't complain about this if we're in GNU89 mode and the old function
3822 // is an extern inline function.
3823 // Don't complain about specializations. They are not supposed to have
3824 // storage classes.
3825 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3826 New->getStorageClass() == SC_Static &&
3827 Old->hasExternalFormalLinkage() &&
3828 !New->getTemplateSpecializationInfo() &&
3829 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3830 if (getLangOpts().MicrosoftExt) {
3831 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3832 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3833 } else {
3834 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
3835 << New << /*MixedLinkageUB=*/false;
3836 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3837 return true;
3838 }
3839 }
3840
3841 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3842 if (!Old->hasAttr<InternalLinkageAttr>()) {
3843 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3844 << ILA;
3845 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3846 New->dropAttr<InternalLinkageAttr>();
3847 }
3848
3849 if (auto *EA = New->getAttr<ErrorAttr>()) {
3850 if (!Old->hasAttr<ErrorAttr>()) {
3851 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3852 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3853 New->dropAttr<ErrorAttr>();
3854 }
3855 }
3856
3857 if (CheckRedeclarationInModule(New, Old))
3858 return true;
3859
3860 if (!getLangOpts().CPlusPlus) {
3861 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3862 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3863 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3864 << New << OldOvl;
3865
3866 // Try our best to find a decl that actually has the overloadable
3867 // attribute for the note. In most cases (e.g. programs with only one
3868 // broken declaration/definition), this won't matter.
3869 //
3870 // FIXME: We could do this if we juggled some extra state in
3871 // OverloadableAttr, rather than just removing it.
3872 const Decl *DiagOld = Old;
3873 if (OldOvl) {
3874 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3875 const auto *A = D->getAttr<OverloadableAttr>();
3876 return A && !A->isImplicit();
3877 });
3878 // If we've implicitly added *all* of the overloadable attrs to this
3879 // chain, emitting a "previous redecl" note is pointless.
3880 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3881 }
3882
3883 if (DiagOld)
3884 Diag(Loc: DiagOld->getLocation(),
3885 DiagID: diag::note_attribute_overloadable_prev_overload)
3886 << OldOvl;
3887
3888 if (OldOvl)
3889 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3890 else
3891 New->dropAttr<OverloadableAttr>();
3892 }
3893 }
3894
3895 // It is not permitted to redeclare an SME function with different SME
3896 // attributes.
3897 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3898 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3899 << New->getType() << Old->getType();
3900 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3901 return true;
3902 }
3903
3904 // If a function is first declared with a calling convention, but is later
3905 // declared or defined without one, all following decls assume the calling
3906 // convention of the first.
3907 //
3908 // It's OK if a function is first declared without a calling convention,
3909 // but is later declared or defined with the default calling convention.
3910 //
3911 // To test if either decl has an explicit calling convention, we look for
3912 // AttributedType sugar nodes on the type as written. If they are missing or
3913 // were canonicalized away, we assume the calling convention was implicit.
3914 //
3915 // Note also that we DO NOT return at this point, because we still have
3916 // other tests to run.
3917 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3918 QualType NewQType = Context.getCanonicalType(T: New->getType());
3919 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3920 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3921 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3922 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3923 bool RequiresAdjustment = false;
3924
3925 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3926 FunctionDecl *First = Old->getFirstDecl();
3927 const FunctionType *FT =
3928 First->getType().getCanonicalType()->castAs<FunctionType>();
3929 FunctionType::ExtInfo FI = FT->getExtInfo();
3930 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3931 if (!NewCCExplicit) {
3932 // Inherit the CC from the previous declaration if it was specified
3933 // there but not here.
3934 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3935 RequiresAdjustment = true;
3936 } else if (Old->getBuiltinID()) {
3937 // Builtin attribute isn't propagated to the new one yet at this point,
3938 // so we check if the old one is a builtin.
3939
3940 // Calling Conventions on a Builtin aren't really useful and setting a
3941 // default calling convention and cdecl'ing some builtin redeclarations is
3942 // common, so warn and ignore the calling convention on the redeclaration.
3943 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3944 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3945 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3946 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3947 RequiresAdjustment = true;
3948 } else {
3949 // Calling conventions aren't compatible, so complain.
3950 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3951 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3952 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3953 << !FirstCCExplicit
3954 << (!FirstCCExplicit ? "" :
3955 FunctionType::getNameForCallConv(CC: FI.getCC()));
3956
3957 // Put the note on the first decl, since it is the one that matters.
3958 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3959 return true;
3960 }
3961 }
3962
3963 // FIXME: diagnose the other way around?
3964 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3965 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3966 RequiresAdjustment = true;
3967 }
3968
3969 // If the declaration is marked with cfi_unchecked_callee but the definition
3970 // isn't, the definition is also cfi_unchecked_callee.
3971 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3972 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3973 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3974 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3975
3976 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3977 EPI2.CFIUncheckedCallee = true;
3978 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3979 Args: FPT2->getParamTypes(), EPI: EPI2);
3980 NewType = cast<FunctionType>(Val&: NewQType);
3981 New->setType(NewQType);
3982 }
3983 }
3984 }
3985
3986 // Merge regparm attribute.
3987 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3988 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3989 if (NewTypeInfo.getHasRegParm()) {
3990 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3991 << NewType->getRegParmType()
3992 << OldType->getRegParmType();
3993 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3994 return true;
3995 }
3996
3997 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3998 RequiresAdjustment = true;
3999 }
4000
4001 // Merge ns_returns_retained attribute.
4002 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4003 if (NewTypeInfo.getProducesResult()) {
4004 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
4005 << "'ns_returns_retained'";
4006 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4007 return true;
4008 }
4009
4010 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
4011 RequiresAdjustment = true;
4012 }
4013
4014 if (OldTypeInfo.getNoCallerSavedRegs() !=
4015 NewTypeInfo.getNoCallerSavedRegs()) {
4016 if (NewTypeInfo.getNoCallerSavedRegs()) {
4017 AnyX86NoCallerSavedRegistersAttr *Attr =
4018 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4019 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
4020 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4021 return true;
4022 }
4023
4024 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
4025 RequiresAdjustment = true;
4026 }
4027
4028 if (RequiresAdjustment) {
4029 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4030 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
4031 New->setType(QualType(AdjustedType, 0));
4032 NewQType = Context.getCanonicalType(T: New->getType());
4033 }
4034
4035 // If this redeclaration makes the function inline, we may need to add it to
4036 // UndefinedButUsed.
4037 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4038 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4039 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4040 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4041 y: SourceLocation()));
4042
4043 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4044 // about it.
4045 if (New->hasAttr<GNUInlineAttr>() &&
4046 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4047 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4048 }
4049
4050 // If pass_object_size params don't match up perfectly, this isn't a valid
4051 // redeclaration.
4052 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4053 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4054 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4055 << New->getDeclName();
4056 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4057 return true;
4058 }
4059
4060 QualType OldQTypeForComparison = OldQType;
4061 if (Context.hasAnyFunctionEffects()) {
4062 const auto OldFX = Old->getFunctionEffects();
4063 const auto NewFX = New->getFunctionEffects();
4064 if (OldFX != NewFX) {
4065 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4066 for (const auto &Diff : Diffs) {
4067 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4068 Diag(Loc: New->getLocation(),
4069 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4070 << Diff.effectName();
4071 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4072 }
4073 }
4074 // Following a warning, we could skip merging effects from the previous
4075 // declaration, but that would trigger an additional "conflicting types"
4076 // error.
4077 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4078 FunctionEffectSet::Conflicts MergeErrs;
4079 FunctionEffectSet MergedFX =
4080 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4081 if (!MergeErrs.empty())
4082 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4083 OldLoc: Old->getLocation());
4084
4085 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4086 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4087 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4088 Args: NewFPT->getParamTypes(), EPI);
4089
4090 New->setType(ModQT);
4091 NewQType = New->getType();
4092
4093 // Revise OldQTForComparison to include the merged effects,
4094 // so as not to fail due to differences later.
4095 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4096 EPI = OldFPT->getExtProtoInfo();
4097 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4098 OldQTypeForComparison = Context.getFunctionType(
4099 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4100 }
4101 if (OldFX.empty()) {
4102 // A redeclaration may add the attribute to a previously seen function
4103 // body which needs to be verified.
4104 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4105 }
4106 }
4107 }
4108 }
4109
4110 if (getLangOpts().CPlusPlus) {
4111 OldQType = Context.getCanonicalType(T: Old->getType());
4112 NewQType = Context.getCanonicalType(T: New->getType());
4113
4114 // Go back to the type source info to compare the declared return types,
4115 // per C++1y [dcl.type.auto]p13:
4116 // Redeclarations or specializations of a function or function template
4117 // with a declared return type that uses a placeholder type shall also
4118 // use that placeholder, not a deduced type.
4119 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4120 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4121 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4122 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4123 OldT: OldDeclaredReturnType)) {
4124 QualType ResQT;
4125 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4126 OldDeclaredReturnType->isObjCObjectPointerType())
4127 // FIXME: This does the wrong thing for a deduced return type.
4128 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4129 if (ResQT.isNull()) {
4130 if (New->isCXXClassMember() && New->isOutOfLine())
4131 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4132 << New << New->getReturnTypeSourceRange();
4133 else if (Old->isExternC() && New->isExternC() &&
4134 !Old->hasAttr<OverloadableAttr>() &&
4135 !New->hasAttr<OverloadableAttr>())
4136 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4137 else
4138 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4139 << New->getReturnTypeSourceRange();
4140 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4141 << Old->getReturnTypeSourceRange();
4142 return true;
4143 }
4144 else
4145 NewQType = ResQT;
4146 }
4147
4148 QualType OldReturnType = OldType->getReturnType();
4149 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4150 if (OldReturnType != NewReturnType) {
4151 // If this function has a deduced return type and has already been
4152 // defined, copy the deduced value from the old declaration.
4153 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4154 if (OldAT && OldAT->isDeduced()) {
4155 QualType DT = OldAT->getDeducedType();
4156 if (DT.isNull()) {
4157 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4158 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4159 } else {
4160 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4161 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4162 }
4163 }
4164 }
4165
4166 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4167 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4168 if (OldMethod && NewMethod) {
4169 // Preserve triviality.
4170 NewMethod->setTrivial(OldMethod->isTrivial());
4171
4172 // MSVC allows explicit template specialization at class scope:
4173 // 2 CXXMethodDecls referring to the same function will be injected.
4174 // We don't want a redeclaration error.
4175 bool IsClassScopeExplicitSpecialization =
4176 OldMethod->isFunctionTemplateSpecialization() &&
4177 NewMethod->isFunctionTemplateSpecialization();
4178 bool isFriend = NewMethod->getFriendObjectKind();
4179
4180 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4181 !IsClassScopeExplicitSpecialization) {
4182 // -- Member function declarations with the same name and the
4183 // same parameter types cannot be overloaded if any of them
4184 // is a static member function declaration.
4185 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4186 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4187 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4188 return true;
4189 }
4190
4191 // C++ [class.mem]p1:
4192 // [...] A member shall not be declared twice in the
4193 // member-specification, except that a nested class or member
4194 // class template can be declared and then later defined.
4195 if (!inTemplateInstantiation()) {
4196 unsigned NewDiag;
4197 if (isa<CXXConstructorDecl>(Val: OldMethod))
4198 NewDiag = diag::err_constructor_redeclared;
4199 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4200 NewDiag = diag::err_destructor_redeclared;
4201 else if (isa<CXXConversionDecl>(Val: NewMethod))
4202 NewDiag = diag::err_conv_function_redeclared;
4203 else
4204 NewDiag = diag::err_member_redeclared;
4205
4206 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4207 } else {
4208 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4209 << New << New->getType();
4210 }
4211 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4212 return true;
4213
4214 // Complain if this is an explicit declaration of a special
4215 // member that was initially declared implicitly.
4216 //
4217 // As an exception, it's okay to befriend such methods in order
4218 // to permit the implicit constructor/destructor/operator calls.
4219 } else if (OldMethod->isImplicit()) {
4220 if (isFriend) {
4221 NewMethod->setImplicit();
4222 } else {
4223 Diag(Loc: NewMethod->getLocation(),
4224 DiagID: diag::err_definition_of_implicitly_declared_member)
4225 << New << OldMethod->getSpecialMemberKind();
4226 return true;
4227 }
4228 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4229 Diag(Loc: NewMethod->getLocation(),
4230 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4231 << OldMethod->getSpecialMemberKind();
4232 return true;
4233 }
4234 }
4235
4236 // C++1z [over.load]p2
4237 // Certain function declarations cannot be overloaded:
4238 // -- Function declarations that differ only in the return type,
4239 // the exception specification, or both cannot be overloaded.
4240
4241 // Check the exception specifications match. This may recompute the type of
4242 // both Old and New if it resolved exception specifications, so grab the
4243 // types again after this. Because this updates the type, we do this before
4244 // any of the other checks below, which may update the "de facto" NewQType
4245 // but do not necessarily update the type of New.
4246 if (CheckEquivalentExceptionSpec(Old, New))
4247 return true;
4248
4249 // C++11 [dcl.attr.noreturn]p1:
4250 // The first declaration of a function shall specify the noreturn
4251 // attribute if any declaration of that function specifies the noreturn
4252 // attribute.
4253 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4254 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4255 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4256 << NRA;
4257 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4258 }
4259
4260 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4261 // When a function is declared with SYCL_EXTERNAL, that macro must be
4262 // used on the first declaration of that function in the translation unit.
4263 // Redeclarations of the function in the same translation unit may
4264 // optionally use SYCL_EXTERNAL, but this is not required.
4265 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4266 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4267 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4268 << SEA;
4269 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4270 }
4271
4272 // (C++98 8.3.5p3):
4273 // All declarations for a function shall agree exactly in both the
4274 // return type and the parameter-type-list.
4275 // We also want to respect all the extended bits except noreturn.
4276
4277 // noreturn should now match unless the old type info didn't have it.
4278 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4279 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4280 const FunctionType *OldTypeForComparison
4281 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4282 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4283 assert(OldQTypeForComparison.isCanonical());
4284 }
4285
4286 if (haveIncompatibleLanguageLinkages(Old, New)) {
4287 // As a special case, retain the language linkage from previous
4288 // declarations of a friend function as an extension.
4289 //
4290 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4291 // and is useful because there's otherwise no way to specify language
4292 // linkage within class scope.
4293 //
4294 // Check cautiously as the friend object kind isn't yet complete.
4295 if (New->getFriendObjectKind() != Decl::FOK_None) {
4296 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4297 Diag(Loc: OldLocation, DiagID: PrevDiag);
4298 } else {
4299 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4300 Diag(Loc: OldLocation, DiagID: PrevDiag);
4301 return true;
4302 }
4303 }
4304
4305 // HLSL check parameters for matching ABI specifications.
4306 if (getLangOpts().HLSL) {
4307 if (HLSL().CheckCompatibleParameterABI(New, Old))
4308 return true;
4309
4310 // If no errors are generated when checking parameter ABIs we can check if
4311 // the two declarations have the same type ignoring the ABIs and if so,
4312 // the declarations can be merged. This case for merging is only valid in
4313 // HLSL because there are no valid cases of merging mismatched parameter
4314 // ABIs except the HLSL implicit in and explicit in.
4315 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4316 U: NewQType))
4317 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4318 // Fall through for conflicting redeclarations and redefinitions.
4319 }
4320
4321 // If the function types are compatible, merge the declarations. Ignore the
4322 // exception specifier because it was already checked above in
4323 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4324 // about incompatible types under -fms-compatibility.
4325 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4326 U: NewQType))
4327 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4328
4329 // If the types are imprecise (due to dependent constructs in friends or
4330 // local extern declarations), it's OK if they differ. We'll check again
4331 // during instantiation.
4332 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4333 return false;
4334
4335 // Fall through for conflicting redeclarations and redefinitions.
4336 }
4337
4338 // C: Function types need to be compatible, not identical. This handles
4339 // duplicate function decls like "void f(int); void f(enum X);" properly.
4340 if (!getLangOpts().CPlusPlus) {
4341 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4342 // type is specified by a function definition that contains a (possibly
4343 // empty) identifier list, both shall agree in the number of parameters
4344 // and the type of each parameter shall be compatible with the type that
4345 // results from the application of default argument promotions to the
4346 // type of the corresponding identifier. ...
4347 // This cannot be handled by ASTContext::typesAreCompatible() because that
4348 // doesn't know whether the function type is for a definition or not when
4349 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4350 // we need to cover here is that the number of arguments agree as the
4351 // default argument promotion rules were already checked by
4352 // ASTContext::typesAreCompatible().
4353 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4354 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4355 if (Old->hasInheritedPrototype())
4356 Old = Old->getCanonicalDecl();
4357 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4358 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4359 return true;
4360 }
4361
4362 // If we are merging two functions where only one of them has a prototype,
4363 // we may have enough information to decide to issue a diagnostic that the
4364 // function without a prototype will change behavior in C23. This handles
4365 // cases like:
4366 // void i(); void i(int j);
4367 // void i(int j); void i();
4368 // void i(); void i(int j) {}
4369 // See ActOnFinishFunctionBody() for other cases of the behavior change
4370 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4371 // type without a prototype.
4372 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4373 !New->isImplicit() && !Old->isImplicit()) {
4374 const FunctionDecl *WithProto, *WithoutProto;
4375 if (New->hasWrittenPrototype()) {
4376 WithProto = New;
4377 WithoutProto = Old;
4378 } else {
4379 WithProto = Old;
4380 WithoutProto = New;
4381 }
4382
4383 if (WithProto->getNumParams() != 0) {
4384 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4385 // The one without the prototype will be changing behavior in C23, so
4386 // warn about that one so long as it's a user-visible declaration.
4387 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4388 if (WithoutProto == New)
4389 IsWithoutProtoADef = NewDeclIsDefn;
4390 else
4391 IsWithProtoADef = NewDeclIsDefn;
4392 Diag(Loc: WithoutProto->getLocation(),
4393 DiagID: diag::warn_non_prototype_changes_behavior)
4394 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4395 << (WithoutProto == Old) << IsWithProtoADef;
4396
4397 // The reason the one without the prototype will be changing behavior
4398 // is because of the one with the prototype, so note that so long as
4399 // it's a user-visible declaration. There is one exception to this:
4400 // when the new declaration is a definition without a prototype, the
4401 // old declaration with a prototype is not the cause of the issue,
4402 // and that does not need to be noted because the one with a
4403 // prototype will not change behavior in C23.
4404 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4405 !IsWithoutProtoADef)
4406 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4407 }
4408 }
4409 }
4410
4411 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4412 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4413 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4414 const FunctionProtoType *OldProto = nullptr;
4415 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4416 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4417 // The old declaration provided a function prototype, but the
4418 // new declaration does not. Merge in the prototype.
4419 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4420 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4421 Args: OldProto->getParamTypes(),
4422 EPI: OldProto->getExtProtoInfo());
4423 New->setType(NewQType);
4424 New->setHasInheritedPrototype();
4425
4426 // Synthesize parameters with the same types.
4427 SmallVector<ParmVarDecl *, 16> Params;
4428 for (const auto &ParamType : OldProto->param_types()) {
4429 ParmVarDecl *Param = ParmVarDecl::Create(
4430 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4431 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4432 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4433 Param->setImplicit();
4434 Params.push_back(Elt: Param);
4435 }
4436
4437 New->setParams(Params);
4438 }
4439
4440 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4441 }
4442 }
4443
4444 // Check if the function types are compatible when pointer size address
4445 // spaces are ignored.
4446 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4447 return false;
4448
4449 // GNU C permits a K&R definition to follow a prototype declaration
4450 // if the declared types of the parameters in the K&R definition
4451 // match the types in the prototype declaration, even when the
4452 // promoted types of the parameters from the K&R definition differ
4453 // from the types in the prototype. GCC then keeps the types from
4454 // the prototype.
4455 //
4456 // If a variadic prototype is followed by a non-variadic K&R definition,
4457 // the K&R definition becomes variadic. This is sort of an edge case, but
4458 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4459 // C99 6.9.1p8.
4460 if (!getLangOpts().CPlusPlus &&
4461 Old->hasPrototype() && !New->hasPrototype() &&
4462 New->getType()->getAs<FunctionProtoType>() &&
4463 Old->getNumParams() == New->getNumParams()) {
4464 SmallVector<QualType, 16> ArgTypes;
4465 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4466 const FunctionProtoType *OldProto
4467 = Old->getType()->getAs<FunctionProtoType>();
4468 const FunctionProtoType *NewProto
4469 = New->getType()->getAs<FunctionProtoType>();
4470
4471 // Determine whether this is the GNU C extension.
4472 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4473 NewProto->getReturnType());
4474 bool LooseCompatible = !MergedReturn.isNull();
4475 for (unsigned Idx = 0, End = Old->getNumParams();
4476 LooseCompatible && Idx != End; ++Idx) {
4477 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4478 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4479 if (Context.typesAreCompatible(T1: OldParm->getType(),
4480 T2: NewProto->getParamType(i: Idx))) {
4481 ArgTypes.push_back(Elt: NewParm->getType());
4482 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4483 T2: NewParm->getType(),
4484 /*CompareUnqualified=*/true)) {
4485 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4486 .PromotedType: NewProto->getParamType(i: Idx) };
4487 Warnings.push_back(Elt: Warn);
4488 ArgTypes.push_back(Elt: NewParm->getType());
4489 } else
4490 LooseCompatible = false;
4491 }
4492
4493 if (LooseCompatible) {
4494 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4495 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4496 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4497 << Warnings[Warn].PromotedType
4498 << Warnings[Warn].OldParm->getType();
4499 if (Warnings[Warn].OldParm->getLocation().isValid())
4500 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4501 DiagID: diag::note_previous_declaration);
4502 }
4503
4504 if (MergeTypeWithOld)
4505 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4506 EPI: OldProto->getExtProtoInfo()));
4507 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4508 }
4509
4510 // Fall through to diagnose conflicting types.
4511 }
4512
4513 // A function that has already been declared has been redeclared or
4514 // defined with a different type; show an appropriate diagnostic.
4515
4516 // If the previous declaration was an implicitly-generated builtin
4517 // declaration, then at the very least we should use a specialized note.
4518 unsigned BuiltinID;
4519 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4520 // If it's actually a library-defined builtin function like 'malloc'
4521 // or 'printf', just warn about the incompatible redeclaration.
4522 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4523 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4524 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4525 << Old << Old->getType();
4526 return false;
4527 }
4528
4529 PrevDiag = diag::note_previous_builtin_declaration;
4530 }
4531
4532 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4533 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4534 return true;
4535}
4536
4537bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4538 Scope *S, bool MergeTypeWithOld) {
4539 // Merge the attributes
4540 mergeDeclAttributes(New, Old);
4541
4542 // Merge "pure" flag.
4543 if (Old->isPureVirtual())
4544 New->setIsPureVirtual();
4545
4546 // Merge "used" flag.
4547 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4548 New->setIsUsed();
4549
4550 // Merge attributes from the parameters. These can mismatch with K&R
4551 // declarations.
4552 if (New->getNumParams() == Old->getNumParams())
4553 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4554 ParmVarDecl *NewParam = New->getParamDecl(i);
4555 ParmVarDecl *OldParam = Old->getParamDecl(i);
4556 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4557 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4558 }
4559
4560 if (getLangOpts().CPlusPlus)
4561 return MergeCXXFunctionDecl(New, Old, S);
4562
4563 // Merge the function types so the we get the composite types for the return
4564 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4565 // was visible.
4566 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4567 if (!Merged.isNull() && MergeTypeWithOld)
4568 New->setType(Merged);
4569
4570 return false;
4571}
4572
4573void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4574 ObjCMethodDecl *oldMethod) {
4575 // Merge the attributes, including deprecated/unavailable
4576 AvailabilityMergeKind MergeKind =
4577 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4578 ? (oldMethod->isOptional()
4579 ? AvailabilityMergeKind::OptionalProtocolImplementation
4580 : AvailabilityMergeKind::ProtocolImplementation)
4581 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4582 ? AvailabilityMergeKind::Redeclaration
4583 : AvailabilityMergeKind::Override;
4584
4585 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4586
4587 // Merge attributes from the parameters.
4588 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4589 oe = oldMethod->param_end();
4590 for (ObjCMethodDecl::param_iterator
4591 ni = newMethod->param_begin(), ne = newMethod->param_end();
4592 ni != ne && oi != oe; ++ni, ++oi)
4593 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4594
4595 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4596}
4597
4598static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4599 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4600
4601 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4602 ? diag::err_redefinition_different_type
4603 : diag::err_redeclaration_different_type)
4604 << New->getDeclName() << New->getType() << Old->getType();
4605
4606 diag::kind PrevDiag;
4607 SourceLocation OldLocation;
4608 std::tie(args&: PrevDiag, args&: OldLocation)
4609 = getNoteDiagForInvalidRedeclaration(Old, New);
4610 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4611 New->setInvalidDecl();
4612}
4613
4614void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4615 bool MergeTypeWithOld) {
4616 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4617 return;
4618
4619 QualType MergedT;
4620 if (getLangOpts().CPlusPlus) {
4621 if (New->getType()->isUndeducedType()) {
4622 // We don't know what the new type is until the initializer is attached.
4623 return;
4624 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4625 // These could still be something that needs exception specs checked.
4626 return MergeVarDeclExceptionSpecs(New, Old);
4627 }
4628 // C++ [basic.link]p10:
4629 // [...] the types specified by all declarations referring to a given
4630 // object or function shall be identical, except that declarations for an
4631 // array object can specify array types that differ by the presence or
4632 // absence of a major array bound (8.3.4).
4633 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4634 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4635 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4636
4637 // We are merging a variable declaration New into Old. If it has an array
4638 // bound, and that bound differs from Old's bound, we should diagnose the
4639 // mismatch.
4640 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4641 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4642 PrevVD = PrevVD->getPreviousDecl()) {
4643 QualType PrevVDTy = PrevVD->getType();
4644 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4645 continue;
4646
4647 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4648 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4649 }
4650 }
4651
4652 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4653 if (Context.hasSameType(T1: OldArray->getElementType(),
4654 T2: NewArray->getElementType()))
4655 MergedT = New->getType();
4656 }
4657 // FIXME: Check visibility. New is hidden but has a complete type. If New
4658 // has no array bound, it should not inherit one from Old, if Old is not
4659 // visible.
4660 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4661 if (Context.hasSameType(T1: OldArray->getElementType(),
4662 T2: NewArray->getElementType()))
4663 MergedT = Old->getType();
4664 }
4665 }
4666 else if (New->getType()->isObjCObjectPointerType() &&
4667 Old->getType()->isObjCObjectPointerType()) {
4668 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4669 Old->getType());
4670 }
4671 } else {
4672 // C 6.2.7p2:
4673 // All declarations that refer to the same object or function shall have
4674 // compatible type.
4675 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4676 }
4677 if (MergedT.isNull()) {
4678 // It's OK if we couldn't merge types if either type is dependent, for a
4679 // block-scope variable. In other cases (static data members of class
4680 // templates, variable templates, ...), we require the types to be
4681 // equivalent.
4682 // FIXME: The C++ standard doesn't say anything about this.
4683 if ((New->getType()->isDependentType() ||
4684 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4685 // If the old type was dependent, we can't merge with it, so the new type
4686 // becomes dependent for now. We'll reproduce the original type when we
4687 // instantiate the TypeSourceInfo for the variable.
4688 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4689 New->setType(Context.DependentTy);
4690 return;
4691 }
4692 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4693 }
4694
4695 // Don't actually update the type on the new declaration if the old
4696 // declaration was an extern declaration in a different scope.
4697 if (MergeTypeWithOld)
4698 New->setType(MergedT);
4699}
4700
4701static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4702 LookupResult &Previous) {
4703 // C11 6.2.7p4:
4704 // For an identifier with internal or external linkage declared
4705 // in a scope in which a prior declaration of that identifier is
4706 // visible, if the prior declaration specifies internal or
4707 // external linkage, the type of the identifier at the later
4708 // declaration becomes the composite type.
4709 //
4710 // If the variable isn't visible, we do not merge with its type.
4711 if (Previous.isShadowed())
4712 return false;
4713
4714 if (S.getLangOpts().CPlusPlus) {
4715 // C++11 [dcl.array]p3:
4716 // If there is a preceding declaration of the entity in the same
4717 // scope in which the bound was specified, an omitted array bound
4718 // is taken to be the same as in that earlier declaration.
4719 return NewVD->isPreviousDeclInSameBlockScope() ||
4720 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4721 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4722 } else {
4723 // If the old declaration was function-local, don't merge with its
4724 // type unless we're in the same function.
4725 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4726 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4727 }
4728}
4729
4730void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4731 // If the new decl is already invalid, don't do any other checking.
4732 if (New->isInvalidDecl())
4733 return;
4734
4735 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4736 return;
4737
4738 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4739
4740 // Verify the old decl was also a variable or variable template.
4741 VarDecl *Old = nullptr;
4742 VarTemplateDecl *OldTemplate = nullptr;
4743 if (Previous.isSingleResult()) {
4744 if (NewTemplate) {
4745 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4746 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4747
4748 if (auto *Shadow =
4749 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4750 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4751 return New->setInvalidDecl();
4752 } else {
4753 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4754
4755 if (auto *Shadow =
4756 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4757 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4758 return New->setInvalidDecl();
4759 }
4760 }
4761 if (!Old) {
4762 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4763 << New->getDeclName();
4764 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4765 New: New->getLocation());
4766 return New->setInvalidDecl();
4767 }
4768
4769 // If the old declaration was found in an inline namespace and the new
4770 // declaration was qualified, update the DeclContext to match.
4771 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4772
4773 // Ensure the template parameters are compatible.
4774 if (NewTemplate &&
4775 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4776 Old: OldTemplate->getTemplateParameters(),
4777 /*Complain=*/true, Kind: TPL_TemplateMatch))
4778 return New->setInvalidDecl();
4779
4780 // C++ [class.mem]p1:
4781 // A member shall not be declared twice in the member-specification [...]
4782 //
4783 // Here, we need only consider static data members.
4784 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4785 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4786 << New->getIdentifier();
4787 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4788 New->setInvalidDecl();
4789 }
4790
4791 if (NewTemplate && OldTemplate)
4792 mergeDeclAttributes(New: NewTemplate, Old: OldTemplate);
4793
4794 mergeDeclAttributes(New, Old);
4795
4796 // Warn if an already-defined variable is made a weak_import in a subsequent
4797 // declaration
4798 if (New->hasAttr<WeakImportAttr>())
4799 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4800 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4801 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4802 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4803 // Remove weak_import attribute on new declaration.
4804 New->dropAttr<WeakImportAttr>();
4805 break;
4806 }
4807 }
4808
4809 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4810 if (!Old->hasAttr<InternalLinkageAttr>()) {
4811 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4812 << ILA;
4813 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4814 New->dropAttr<InternalLinkageAttr>();
4815 }
4816
4817 // Merge the types.
4818 VarDecl *MostRecent = Old->getMostRecentDecl();
4819 if (MostRecent != Old) {
4820 MergeVarDeclTypes(New, Old: MostRecent,
4821 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4822 if (New->isInvalidDecl())
4823 return;
4824 }
4825
4826 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4827 if (New->isInvalidDecl())
4828 return;
4829
4830 diag::kind PrevDiag;
4831 SourceLocation OldLocation;
4832 std::tie(args&: PrevDiag, args&: OldLocation) =
4833 getNoteDiagForInvalidRedeclaration(Old, New);
4834
4835 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4836 if (New->getStorageClass() == SC_Static &&
4837 !New->isStaticDataMember() &&
4838 Old->hasExternalFormalLinkage()) {
4839 if (getLangOpts().MicrosoftExt) {
4840 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4841 << New->getDeclName();
4842 Diag(Loc: OldLocation, DiagID: PrevDiag);
4843 } else {
4844 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4845 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4846 // the older C language modes.
4847 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4848 << New->getDeclName()
4849 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4850 Diag(Loc: OldLocation, DiagID: PrevDiag);
4851 return New->setInvalidDecl();
4852 }
4853 }
4854
4855 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4856 // external linkage within a translation unit. Before C2y this was UB
4857 // (C11 6.2.2p7).
4858 //
4859 // In C, a local shadow prevents a block-scope extern from inheriting the
4860 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4861 // external linkage, creating the conflict.
4862 //
4863 // In C++, block-scope extern declarations target the enclosing namespace
4864 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4865 // the extern always inherits internal linkage. No conflict arises.
4866 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4867 New->hasExternalStorage() && Previous.isShadowed() &&
4868 Old->getFormalLinkage() == Linkage::Internal) {
4869 Diag(Loc: New->getLocation(), DiagID: diag::err_internal_extern_mismatch)
4870 << New->getDeclName() << getLangOpts().C2y;
4871 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4872 return New->setInvalidDecl();
4873 }
4874
4875 // C99 6.2.2p4:
4876 // For an identifier declared with the storage-class specifier
4877 // extern in a scope in which a prior declaration of that
4878 // identifier is visible,23) if the prior declaration specifies
4879 // internal or external linkage, the linkage of the identifier at
4880 // the later declaration is the same as the linkage specified at
4881 // the prior declaration. If no prior declaration is visible, or
4882 // if the prior declaration specifies no linkage, then the
4883 // identifier has external linkage.
4884 if (New->hasExternalStorage() && Old->hasLinkage())
4885 /* Okay */;
4886 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4887 !New->isStaticDataMember() &&
4888 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4889 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4890 Diag(Loc: OldLocation, DiagID: PrevDiag);
4891 return New->setInvalidDecl();
4892 }
4893
4894 // Check if extern is followed by non-extern and vice-versa.
4895 if (New->hasExternalStorage() &&
4896 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4897 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4898 Diag(Loc: OldLocation, DiagID: PrevDiag);
4899 return New->setInvalidDecl();
4900 }
4901 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4902 !New->hasExternalStorage()) {
4903 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4904 Diag(Loc: OldLocation, DiagID: PrevDiag);
4905 return New->setInvalidDecl();
4906 }
4907
4908 if (CheckRedeclarationInModule(New, Old))
4909 return;
4910
4911 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4912
4913 // FIXME: The test for external storage here seems wrong? We still
4914 // need to check for mismatches.
4915 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4916 // Don't complain about out-of-line definitions of static members.
4917 !(Old->getLexicalDeclContext()->isRecord() &&
4918 !New->getLexicalDeclContext()->isRecord())) {
4919 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4920 Diag(Loc: OldLocation, DiagID: PrevDiag);
4921 return New->setInvalidDecl();
4922 }
4923
4924 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4925 if (VarDecl *Def = Old->getDefinition()) {
4926 // C++1z [dcl.fcn.spec]p4:
4927 // If the definition of a variable appears in a translation unit before
4928 // its first declaration as inline, the program is ill-formed.
4929 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4930 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4931 }
4932 }
4933
4934 // If this redeclaration makes the variable inline, we may need to add it to
4935 // UndefinedButUsed.
4936 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4937 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4938 !Old->isInAnotherModuleUnit())
4939 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4940 y: SourceLocation()));
4941
4942 if (New->getTLSKind() != Old->getTLSKind()) {
4943 if (!Old->getTLSKind()) {
4944 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4945 Diag(Loc: OldLocation, DiagID: PrevDiag);
4946 } else if (!New->getTLSKind()) {
4947 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4948 Diag(Loc: OldLocation, DiagID: PrevDiag);
4949 } else {
4950 // Do not allow redeclaration to change the variable between requiring
4951 // static and dynamic initialization.
4952 // FIXME: GCC allows this, but uses the TLS keyword on the first
4953 // declaration to determine the kind. Do we need to be compatible here?
4954 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4955 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4956 Diag(Loc: OldLocation, DiagID: PrevDiag);
4957 }
4958 }
4959
4960 // C++ doesn't have tentative definitions, so go right ahead and check here.
4961 if (getLangOpts().CPlusPlus) {
4962 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4963 Old->getCanonicalDecl()->isConstexpr()) {
4964 // This definition won't be a definition any more once it's been merged.
4965 Diag(Loc: New->getLocation(),
4966 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4967 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4968 VarDecl *Def = Old->getDefinition();
4969 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4970 return;
4971 if (Old->isInvalidDecl())
4972 New->setInvalidDecl();
4973 }
4974 } else {
4975 // C++ may not have a tentative definition rule, but it has a different
4976 // rule about what constitutes a definition in the first place. See
4977 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4978 // contains the extern specifier and doesn't have an initializer, it's fine
4979 // in C++.
4980 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4981 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4982 << New;
4983 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4984 }
4985 }
4986
4987 if (haveIncompatibleLanguageLinkages(Old, New)) {
4988 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4989 Diag(Loc: OldLocation, DiagID: PrevDiag);
4990 New->setInvalidDecl();
4991 return;
4992 }
4993
4994 // Merge "used" flag.
4995 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4996 New->setIsUsed();
4997
4998 // Keep a chain of previous declarations.
4999 New->setPreviousDecl(Old);
5000 if (NewTemplate)
5001 NewTemplate->setPreviousDecl(OldTemplate);
5002
5003 // Inherit access appropriately.
5004 New->setAccess(Old->getAccess());
5005 if (NewTemplate)
5006 NewTemplate->setAccess(New->getAccess());
5007
5008 if (Old->isInline())
5009 New->setImplicitlyInline();
5010}
5011
5012void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
5013 SourceManager &SrcMgr = getSourceManager();
5014 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
5015 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
5016 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
5017 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
5018 auto &HSI = PP.getHeaderSearchInfo();
5019 StringRef HdrFilename =
5020 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
5021
5022 auto noteFromModuleOrInclude = [&](Module *Mod,
5023 SourceLocation IncLoc) -> bool {
5024 // Redefinition errors with modules are common with non modular mapped
5025 // headers, example: a non-modular header H in module A that also gets
5026 // included directly in a TU. Pointing twice to the same header/definition
5027 // is confusing, try to get better diagnostics when modules is on.
5028 if (IncLoc.isValid()) {
5029 if (Mod) {
5030 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
5031 << HdrFilename.str() << Mod->getFullModuleName();
5032 if (!Mod->DefinitionLoc.isInvalid())
5033 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
5034 << Mod->getFullModuleName();
5035 } else {
5036 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
5037 << HdrFilename.str();
5038 }
5039 return true;
5040 }
5041
5042 return false;
5043 };
5044
5045 // Is it the same file and same offset? Provide more information on why
5046 // this leads to a redefinition error.
5047 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5048 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
5049 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5050 bool EmittedDiag =
5051 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5052 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5053
5054 // If the header has no guards, emit a note suggesting one.
5055 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5056 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5057
5058 if (EmittedDiag)
5059 return;
5060 }
5061
5062 // Redefinition coming from different files or couldn't do better above.
5063 if (Old->getLocation().isValid())
5064 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5065}
5066
5067bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5068 if ((!hasVisibleDefinition(D: Old) ||
5069 isFromSameSingleIncludeHeader(PrevD: Old, NewLoc: New->getLocation())) &&
5070 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5071 isa<VarTemplateSpecializationDecl>(Val: New) ||
5072 New->getDescribedVarTemplate() ||
5073 !New->getTemplateParameterLists().empty() ||
5074 New->getDeclContext()->isDependentContext() ||
5075 New->hasAttr<SelectAnyAttr>())) {
5076 // The previous definition is hidden, and multiple definitions are
5077 // permitted (in separate TUs). Demote this to a declaration.
5078 New->demoteThisDefinitionToDeclaration();
5079
5080 // Make the canonical definition visible.
5081 if (auto *OldTD = Old->getDescribedVarTemplate())
5082 makeMergedDefinitionVisible(ND: OldTD);
5083 makeMergedDefinitionVisible(ND: Old);
5084 return false;
5085 } else {
5086 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5087 notePreviousDefinition(Old, New: New->getLocation());
5088 New->setInvalidDecl();
5089 return true;
5090 }
5091}
5092
5093Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5094 DeclSpec &DS,
5095 const ParsedAttributesView &DeclAttrs,
5096 RecordDecl *&AnonRecord) {
5097 return ParsedFreeStandingDeclSpec(
5098 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5099}
5100
5101// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5102// disambiguate entities defined in different scopes.
5103// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5104// compatibility.
5105// We will pick our mangling number depending on which version of MSVC is being
5106// targeted.
5107static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5108 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5109 ? S->getMSCurManglingNumber()
5110 : S->getMSLastManglingNumber();
5111}
5112
5113void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5114 if (!Context.getLangOpts().CPlusPlus)
5115 return;
5116
5117 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5118 // If this tag is the direct child of a class, number it if
5119 // it is anonymous.
5120 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5121 return;
5122 MangleNumberingContext &MCtx =
5123 Context.getManglingNumberContext(DC: Tag->getParent());
5124 Context.setManglingNumber(
5125 ND: Tag, Number: MCtx.getManglingNumber(
5126 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5127 return;
5128 }
5129
5130 // If this tag isn't a direct child of a class, number it if it is local.
5131 MangleNumberingContext *MCtx;
5132 Decl *ManglingContextDecl;
5133 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5134 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5135 if (MCtx) {
5136 Context.setManglingNumber(
5137 ND: Tag, Number: MCtx->getManglingNumber(
5138 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5139 }
5140}
5141
5142namespace {
5143struct NonCLikeKind {
5144 enum {
5145 None,
5146 BaseClass,
5147 DefaultMemberInit,
5148 Lambda,
5149 Friend,
5150 OtherMember,
5151 Invalid,
5152 } Kind = None;
5153 SourceRange Range;
5154
5155 explicit operator bool() { return Kind != None; }
5156};
5157}
5158
5159/// Determine whether a class is C-like, according to the rules of C++
5160/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5161static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5162 if (RD->isInvalidDecl())
5163 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5164
5165 // C++ [dcl.typedef]p9: [P1766R1]
5166 // An unnamed class with a typedef name for linkage purposes shall not
5167 //
5168 // -- have any base classes
5169 if (RD->getNumBases())
5170 return {.Kind: NonCLikeKind::BaseClass,
5171 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5172 RD->bases_end()[-1].getEndLoc())};
5173 bool Invalid = false;
5174 for (Decl *D : RD->decls()) {
5175 // Don't complain about things we already diagnosed.
5176 if (D->isInvalidDecl()) {
5177 Invalid = true;
5178 continue;
5179 }
5180
5181 // -- have any [...] default member initializers
5182 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5183 if (FD->hasInClassInitializer()) {
5184 auto *Init = FD->getInClassInitializer();
5185 return {.Kind: NonCLikeKind::DefaultMemberInit,
5186 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5187 }
5188 continue;
5189 }
5190
5191 // FIXME: We don't allow friend declarations. This violates the wording of
5192 // P1766, but not the intent.
5193 if (isa<FriendDecl>(Val: D))
5194 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5195
5196 // -- declare any members other than non-static data members, member
5197 // enumerations, or member classes,
5198 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5199 isa<EnumDecl>(Val: D))
5200 continue;
5201 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5202 if (!MemberRD) {
5203 if (D->isImplicit())
5204 continue;
5205 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5206 }
5207
5208 // -- contain a lambda-expression,
5209 if (MemberRD->isLambda())
5210 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5211
5212 // and all member classes shall also satisfy these requirements
5213 // (recursively).
5214 if (MemberRD->isThisDeclarationADefinition()) {
5215 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5216 return Kind;
5217 }
5218 }
5219
5220 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5221}
5222
5223void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5224 TypedefNameDecl *NewTD) {
5225 if (TagFromDeclSpec->isInvalidDecl())
5226 return;
5227
5228 // Do nothing if the tag already has a name for linkage purposes.
5229 if (TagFromDeclSpec->hasNameForLinkage())
5230 return;
5231
5232 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5233 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5234
5235 // The type must match the tag exactly; no qualifiers allowed.
5236 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5237 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5238 if (getLangOpts().CPlusPlus)
5239 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5240 return;
5241 }
5242
5243 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5244 // An unnamed class with a typedef name for linkage purposes shall [be
5245 // C-like].
5246 //
5247 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5248 // shouldn't happen, but there are constructs that the language rule doesn't
5249 // disallow for which we can't reasonably avoid computing linkage early.
5250 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5251 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5252 : NonCLikeKind();
5253 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5254 if (NonCLike || ChangesLinkage) {
5255 if (NonCLike.Kind == NonCLikeKind::Invalid)
5256 return;
5257
5258 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5259 if (ChangesLinkage) {
5260 // If the linkage changes, we can't accept this as an extension.
5261 if (NonCLike.Kind == NonCLikeKind::None)
5262 DiagID = diag::err_typedef_changes_linkage;
5263 else
5264 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5265 }
5266
5267 SourceLocation FixitLoc =
5268 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5269 llvm::SmallString<40> TextToInsert;
5270 TextToInsert += ' ';
5271 TextToInsert += NewTD->getIdentifier()->getName();
5272
5273 Diag(Loc: FixitLoc, DiagID)
5274 << isa<TypeAliasDecl>(Val: NewTD)
5275 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5276 if (NonCLike.Kind != NonCLikeKind::None) {
5277 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5278 << NonCLike.Kind - 1 << NonCLike.Range;
5279 }
5280 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5281 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5282
5283 if (ChangesLinkage)
5284 return;
5285 }
5286
5287 // Otherwise, set this as the anon-decl typedef for the tag.
5288 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5289
5290 // Now that we have a name for the tag, process API notes again.
5291 ProcessAPINotes(D: TagFromDeclSpec);
5292}
5293
5294static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5295 DeclSpec::TST T = DS.getTypeSpecType();
5296 switch (T) {
5297 case DeclSpec::TST_class:
5298 return 0;
5299 case DeclSpec::TST_struct:
5300 return 1;
5301 case DeclSpec::TST_interface:
5302 return 2;
5303 case DeclSpec::TST_union:
5304 return 3;
5305 case DeclSpec::TST_enum:
5306 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5307 if (ED->isScopedUsingClassTag())
5308 return 5;
5309 if (ED->isScoped())
5310 return 6;
5311 }
5312 return 4;
5313 default:
5314 llvm_unreachable("unexpected type specifier");
5315 }
5316}
5317
5318Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5319 DeclSpec &DS,
5320 const ParsedAttributesView &DeclAttrs,
5321 MultiTemplateParamsArg TemplateParams,
5322 bool IsExplicitInstantiation,
5323 RecordDecl *&AnonRecord,
5324 SourceLocation EllipsisLoc) {
5325 Decl *TagD = nullptr;
5326 TagDecl *Tag = nullptr;
5327 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5328 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5329 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5330 DS.getTypeSpecType() == DeclSpec::TST_union ||
5331 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5332 TagD = DS.getRepAsDecl();
5333
5334 if (!TagD) // We probably had an error
5335 return nullptr;
5336
5337 // Note that the above type specs guarantee that the
5338 // type rep is a Decl, whereas in many of the others
5339 // it's a Type.
5340 if (isa<TagDecl>(Val: TagD))
5341 Tag = cast<TagDecl>(Val: TagD);
5342 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5343 Tag = CTD->getTemplatedDecl();
5344 }
5345
5346 if (Tag) {
5347 handleTagNumbering(Tag, TagScope: S);
5348 Tag->setFreeStanding();
5349 if (Tag->isInvalidDecl())
5350 return Tag;
5351 }
5352
5353 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5354 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5355 // or incomplete types shall not be restrict-qualified."
5356 if (TypeQuals & DeclSpec::TQ_restrict)
5357 Diag(Loc: DS.getRestrictSpecLoc(),
5358 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5359 << DS.getSourceRange();
5360 }
5361
5362 if (DS.isInlineSpecified())
5363 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5364 << getLangOpts().CPlusPlus17;
5365
5366 if (DS.hasConstexprSpecifier()) {
5367 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5368 // and definitions of functions and variables.
5369 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5370 // the declaration of a function or function template
5371 if (Tag)
5372 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5373 << GetDiagnosticTypeSpecifierID(DS)
5374 << static_cast<int>(DS.getConstexprSpecifier());
5375 else if (getLangOpts().C23)
5376 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5377 else
5378 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5379 << static_cast<int>(DS.getConstexprSpecifier());
5380 // Don't emit warnings after this error.
5381 return TagD;
5382 }
5383
5384 DiagnoseFunctionSpecifiers(DS);
5385
5386 if (DS.isFriendSpecified()) {
5387 // If we're dealing with a decl but not a TagDecl, assume that
5388 // whatever routines created it handled the friendship aspect.
5389 if (TagD && !Tag)
5390 return nullptr;
5391 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5392 }
5393
5394 assert(EllipsisLoc.isInvalid() &&
5395 "Friend ellipsis but not friend-specified?");
5396
5397 // Track whether this decl-specifier declares anything.
5398 bool DeclaresAnything = true;
5399
5400 // Handle anonymous struct definitions.
5401 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5402 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5403 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5404 if (getLangOpts().CPlusPlus ||
5405 Record->getDeclContext()->isRecord()) {
5406 // If CurContext is a DeclContext that can contain statements,
5407 // RecursiveASTVisitor won't visit the decls that
5408 // BuildAnonymousStructOrUnion() will put into CurContext.
5409 // Also store them here so that they can be part of the
5410 // DeclStmt that gets created in this case.
5411 // FIXME: Also return the IndirectFieldDecls created by
5412 // BuildAnonymousStructOr union, for the same reason?
5413 if (CurContext->isFunctionOrMethod())
5414 AnonRecord = Record;
5415 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5416 Policy: Context.getPrintingPolicy());
5417 }
5418
5419 DeclaresAnything = false;
5420 }
5421 }
5422
5423 // C11 6.7.2.1p2:
5424 // A struct-declaration that does not declare an anonymous structure or
5425 // anonymous union shall contain a struct-declarator-list.
5426 //
5427 // This rule also existed in C89 and C99; the grammar for struct-declaration
5428 // did not permit a struct-declaration without a struct-declarator-list.
5429 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5430 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5431 // Check for Microsoft C extension: anonymous struct/union member.
5432 // Handle 2 kinds of anonymous struct/union:
5433 // struct STRUCT;
5434 // union UNION;
5435 // and
5436 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5437 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5438 if ((Tag && Tag->getDeclName()) ||
5439 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5440 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5441 : DS.getRepAsType().get()->getAsRecordDecl();
5442 if (Record && getLangOpts().MSAnonymousStructs) {
5443 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5444 << Record->isUnion() << DS.getSourceRange();
5445 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5446 }
5447
5448 DeclaresAnything = false;
5449 }
5450 }
5451
5452 // Skip all the checks below if we have a type error.
5453 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5454 (TagD && TagD->isInvalidDecl()))
5455 return TagD;
5456
5457 if (getLangOpts().CPlusPlus &&
5458 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5459 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5460 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5461 !Enum->isInvalidDecl())
5462 DeclaresAnything = false;
5463
5464 if (!DS.isMissingDeclaratorOk()) {
5465 // Customize diagnostic for a typedef missing a name.
5466 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5467 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5468 << DS.getSourceRange();
5469 else
5470 DeclaresAnything = false;
5471 }
5472
5473 if (DS.isModulePrivateSpecified() &&
5474 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5475 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5476 << Tag->getTagKind()
5477 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5478
5479 ActOnDocumentableDecl(D: TagD);
5480
5481 // C 6.7/2:
5482 // A declaration [...] shall declare at least a declarator [...], a tag,
5483 // or the members of an enumeration.
5484 // C++ [dcl.dcl]p3:
5485 // [If there are no declarators], and except for the declaration of an
5486 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5487 // names into the program, or shall redeclare a name introduced by a
5488 // previous declaration.
5489 if (!DeclaresAnything) {
5490 // In C, we allow this as a (popular) extension / bug. Don't bother
5491 // producing further diagnostics for redundant qualifiers after this.
5492 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5493 ? diag::err_no_declarators
5494 : diag::ext_no_declarators)
5495 << DS.getSourceRange();
5496 return TagD;
5497 }
5498
5499 // C++ [dcl.stc]p1:
5500 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5501 // init-declarator-list of the declaration shall not be empty.
5502 // C++ [dcl.fct.spec]p1:
5503 // If a cv-qualifier appears in a decl-specifier-seq, the
5504 // init-declarator-list of the declaration shall not be empty.
5505 //
5506 // Spurious qualifiers here appear to be valid in C.
5507 unsigned DiagID = diag::warn_standalone_specifier;
5508 if (getLangOpts().CPlusPlus)
5509 DiagID = diag::ext_standalone_specifier;
5510
5511 // Note that a linkage-specification sets a storage class, but
5512 // 'extern "C" struct foo;' is actually valid and not theoretically
5513 // useless.
5514 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5515 if (SCS == DeclSpec::SCS_mutable)
5516 // Since mutable is not a viable storage class specifier in C, there is
5517 // no reason to treat it as an extension. Instead, diagnose as an error.
5518 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5519 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5520 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5521 << DeclSpec::getSpecifierName(S: SCS);
5522 }
5523
5524 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5525 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5526 << DeclSpec::getSpecifierName(S: TSCS);
5527 if (DS.getTypeQualifiers()) {
5528 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5529 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5530 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5531 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5532 // Restrict is covered above.
5533 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5534 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5535 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5536 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5537 }
5538
5539 // Warn about ignored type attributes, for example:
5540 // __attribute__((aligned)) struct A;
5541 // Attributes should be placed after tag to apply to type declaration.
5542 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5543 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5544 if (TypeSpecType == DeclSpec::TST_class ||
5545 TypeSpecType == DeclSpec::TST_struct ||
5546 TypeSpecType == DeclSpec::TST_interface ||
5547 TypeSpecType == DeclSpec::TST_union ||
5548 TypeSpecType == DeclSpec::TST_enum) {
5549
5550 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5551 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5552 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5553 DiagnosticId = diag::warn_attribute_ignored;
5554 else if (AL.isRegularKeywordAttribute())
5555 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5556 else
5557 DiagnosticId = diag::warn_declspec_attribute_ignored;
5558 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5559 << AL << GetDiagnosticTypeSpecifierID(DS);
5560 };
5561
5562 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5563 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5564 }
5565 }
5566
5567 return TagD;
5568}
5569
5570/// We are trying to inject an anonymous member into the given scope;
5571/// check if there's an existing declaration that can't be overloaded.
5572///
5573/// \return true if this is a forbidden redeclaration
5574static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5575 DeclContext *Owner,
5576 DeclarationName Name,
5577 SourceLocation NameLoc, bool IsUnion,
5578 StorageClass SC) {
5579 LookupResult R(SemaRef, Name, NameLoc,
5580 Owner->isRecord() ? Sema::LookupMemberName
5581 : Sema::LookupOrdinaryName,
5582 RedeclarationKind::ForVisibleRedeclaration);
5583 if (!SemaRef.LookupName(R, S)) return false;
5584
5585 // Pick a representative declaration.
5586 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5587 assert(PrevDecl && "Expected a non-null Decl");
5588
5589 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5590 return false;
5591
5592 if (SC == StorageClass::SC_None &&
5593 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5594 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5595 if (!Owner->isRecord())
5596 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5597 return false;
5598 }
5599
5600 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5601 << IsUnion << Name;
5602 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5603
5604 return true;
5605}
5606
5607void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5608 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5609 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5610}
5611
5612void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5613 if (!getLangOpts().CPlusPlus)
5614 return;
5615
5616 // This function can be parsed before we have validated the
5617 // structure as an anonymous struct
5618 if (Record->isAnonymousStructOrUnion())
5619 return;
5620
5621 const NamedDecl *First = 0;
5622 for (const Decl *D : Record->decls()) {
5623 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5624 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5625 continue;
5626 if (!First)
5627 First = ND;
5628 else
5629 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5630 }
5631}
5632
5633/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5634/// anonymous struct or union AnonRecord into the owning context Owner
5635/// and scope S. This routine will be invoked just after we realize
5636/// that an unnamed union or struct is actually an anonymous union or
5637/// struct, e.g.,
5638///
5639/// @code
5640/// union {
5641/// int i;
5642/// float f;
5643/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5644/// // f into the surrounding scope.x
5645/// @endcode
5646///
5647/// This routine is recursive, injecting the names of nested anonymous
5648/// structs/unions into the owning context and scope as well.
5649static bool
5650InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5651 RecordDecl *AnonRecord, AccessSpecifier AS,
5652 StorageClass SC,
5653 SmallVectorImpl<NamedDecl *> &Chaining) {
5654 bool Invalid = false;
5655
5656 // Look every FieldDecl and IndirectFieldDecl with a name.
5657 for (auto *D : AnonRecord->decls()) {
5658 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5659 cast<NamedDecl>(Val: D)->getDeclName()) {
5660 ValueDecl *VD = cast<ValueDecl>(Val: D);
5661 // C++ [class.union]p2:
5662 // The names of the members of an anonymous union shall be
5663 // distinct from the names of any other entity in the
5664 // scope in which the anonymous union is declared.
5665
5666 bool FieldInvalid = CheckAnonMemberRedeclaration(
5667 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5668 IsUnion: AnonRecord->isUnion(), SC);
5669 if (FieldInvalid)
5670 Invalid = true;
5671
5672 // Inject the IndirectFieldDecl even if invalid, because later
5673 // diagnostics may depend on it being present, see findDefaultInitializer.
5674
5675 // C++ [class.union]p2:
5676 // For the purpose of name lookup, after the anonymous union
5677 // definition, the members of the anonymous union are
5678 // considered to have been defined in the scope in which the
5679 // anonymous union is declared.
5680 unsigned OldChainingSize = Chaining.size();
5681 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5682 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5683 else
5684 Chaining.push_back(Elt: VD);
5685
5686 assert(Chaining.size() >= 2);
5687 NamedDecl **NamedChain =
5688 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5689 for (unsigned i = 0; i < Chaining.size(); i++)
5690 NamedChain[i] = Chaining[i];
5691
5692 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5693 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5694 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5695
5696 for (const auto *Attr : VD->attrs())
5697 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5698
5699 IndirectField->setAccess(AS);
5700 IndirectField->setImplicit();
5701 IndirectField->setInvalidDecl(FieldInvalid);
5702 SemaRef.PushOnScopeChains(D: IndirectField, S);
5703
5704 // That includes picking up the appropriate access specifier.
5705 if (AS != AS_none)
5706 IndirectField->setAccess(AS);
5707
5708 Chaining.resize(N: OldChainingSize);
5709 }
5710 }
5711
5712 return Invalid;
5713}
5714
5715/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5716/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5717/// illegal input values are mapped to SC_None.
5718static StorageClass
5719StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5720 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5721 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5722 "Parser allowed 'typedef' as storage class VarDecl.");
5723 switch (StorageClassSpec) {
5724 case DeclSpec::SCS_unspecified: return SC_None;
5725 case DeclSpec::SCS_extern:
5726 if (DS.isExternInLinkageSpec())
5727 return SC_None;
5728 return SC_Extern;
5729 case DeclSpec::SCS_static: return SC_Static;
5730 case DeclSpec::SCS_auto: return SC_Auto;
5731 case DeclSpec::SCS_register: return SC_Register;
5732 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5733 // Illegal SCSs map to None: error reporting is up to the caller.
5734 case DeclSpec::SCS_mutable: // Fall through.
5735 case DeclSpec::SCS_typedef: return SC_None;
5736 }
5737 llvm_unreachable("unknown storage class specifier");
5738}
5739
5740static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5741 assert(Record->hasInClassInitializer());
5742
5743 for (const auto *I : Record->decls()) {
5744 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5745 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5746 FD = IFD->getAnonField();
5747 if (FD && FD->hasInClassInitializer())
5748 return FD->getLocation();
5749 }
5750
5751 llvm_unreachable("couldn't find in-class initializer");
5752}
5753
5754static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5755 SourceLocation DefaultInitLoc) {
5756 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5757 return;
5758
5759 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5760 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5761}
5762
5763static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5764 CXXRecordDecl *AnonUnion) {
5765 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5766 return;
5767
5768 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5769}
5770
5771Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5772 AccessSpecifier AS,
5773 RecordDecl *Record,
5774 const PrintingPolicy &Policy) {
5775 DeclContext *Owner = Record->getDeclContext();
5776
5777 // Diagnose whether this anonymous struct/union is an extension.
5778 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5779 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5780 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5781 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5782 else if (!Record->isUnion() && !getLangOpts().C11)
5783 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5784
5785 // C and C++ require different kinds of checks for anonymous
5786 // structs/unions.
5787 bool Invalid = false;
5788 if (getLangOpts().CPlusPlus) {
5789 const char *PrevSpec = nullptr;
5790 if (Record->isUnion()) {
5791 // C++ [class.union]p6:
5792 // C++17 [class.union.anon]p2:
5793 // Anonymous unions declared in a named namespace or in the
5794 // global namespace shall be declared static.
5795 unsigned DiagID;
5796 DeclContext *OwnerScope = Owner->getRedeclContext();
5797 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5798 (OwnerScope->isTranslationUnit() ||
5799 (OwnerScope->isNamespace() &&
5800 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5801 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5802 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5803
5804 // Recover by adding 'static'.
5805 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5806 PrevSpec, DiagID, Policy);
5807 }
5808 // C++ [class.union]p6:
5809 // A storage class is not allowed in a declaration of an
5810 // anonymous union in a class scope.
5811 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5812 isa<RecordDecl>(Val: Owner)) {
5813 Diag(Loc: DS.getStorageClassSpecLoc(),
5814 DiagID: diag::err_anonymous_union_with_storage_spec)
5815 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5816
5817 // Recover by removing the storage specifier.
5818 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5819 Loc: SourceLocation(),
5820 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5821 }
5822 }
5823
5824 // Ignore const/volatile/restrict qualifiers.
5825 if (DS.getTypeQualifiers()) {
5826 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5827 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5828 << Record->isUnion() << "const"
5829 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5830 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5831 Diag(Loc: DS.getVolatileSpecLoc(),
5832 DiagID: diag::ext_anonymous_struct_union_qualified)
5833 << Record->isUnion() << "volatile"
5834 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5835 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5836 Diag(Loc: DS.getRestrictSpecLoc(),
5837 DiagID: diag::ext_anonymous_struct_union_qualified)
5838 << Record->isUnion() << "restrict"
5839 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5840 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5841 Diag(Loc: DS.getAtomicSpecLoc(),
5842 DiagID: diag::ext_anonymous_struct_union_qualified)
5843 << Record->isUnion() << "_Atomic"
5844 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5845 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5846 Diag(Loc: DS.getUnalignedSpecLoc(),
5847 DiagID: diag::ext_anonymous_struct_union_qualified)
5848 << Record->isUnion() << "__unaligned"
5849 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5850
5851 DS.ClearTypeQualifiers();
5852 }
5853
5854 // C++ [class.union]p2:
5855 // The member-specification of an anonymous union shall only
5856 // define non-static data members. [Note: nested types and
5857 // functions cannot be declared within an anonymous union. ]
5858 for (auto *Mem : Record->decls()) {
5859 // Ignore invalid declarations; we already diagnosed them.
5860 if (Mem->isInvalidDecl())
5861 continue;
5862
5863 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5864 // C++ [class.union]p3:
5865 // An anonymous union shall not have private or protected
5866 // members (clause 11).
5867 assert(FD->getAccess() != AS_none);
5868 if (FD->getAccess() != AS_public) {
5869 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5870 << Record->isUnion() << (FD->getAccess() == AS_protected);
5871 Invalid = true;
5872 }
5873
5874 // C++ [class.union]p1
5875 // An object of a class with a non-trivial constructor, a non-trivial
5876 // copy constructor, a non-trivial destructor, or a non-trivial copy
5877 // assignment operator cannot be a member of a union, nor can an
5878 // array of such objects.
5879 if (CheckNontrivialField(FD))
5880 Invalid = true;
5881 } else if (Mem->isImplicit()) {
5882 // Any implicit members are fine.
5883 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5884 // This is a type that showed up in an
5885 // elaborated-type-specifier inside the anonymous struct or
5886 // union, but which actually declares a type outside of the
5887 // anonymous struct or union. It's okay.
5888 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5889 if (!MemRecord->isAnonymousStructOrUnion() &&
5890 MemRecord->getDeclName()) {
5891 // Visual C++ allows type definition in anonymous struct or union.
5892 if (getLangOpts().MicrosoftExt)
5893 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5894 << Record->isUnion();
5895 else {
5896 // This is a nested type declaration.
5897 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5898 << Record->isUnion();
5899 Invalid = true;
5900 }
5901 } else {
5902 // This is an anonymous type definition within another anonymous type.
5903 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5904 // not part of standard C++.
5905 Diag(Loc: MemRecord->getLocation(),
5906 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5907 << Record->isUnion();
5908 }
5909 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5910 // Any access specifier is fine.
5911 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5912 // In C++1z, static_assert declarations are also fine.
5913 } else {
5914 // We have something that isn't a non-static data
5915 // member. Complain about it.
5916 unsigned DK = diag::err_anonymous_record_bad_member;
5917 if (isa<TypeDecl>(Val: Mem))
5918 DK = diag::err_anonymous_record_with_type;
5919 else if (isa<FunctionDecl>(Val: Mem))
5920 DK = diag::err_anonymous_record_with_function;
5921 else if (isa<VarDecl>(Val: Mem))
5922 DK = diag::err_anonymous_record_with_static;
5923
5924 // Visual C++ allows type definition in anonymous struct or union.
5925 if (getLangOpts().MicrosoftExt &&
5926 DK == diag::err_anonymous_record_with_type)
5927 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5928 << Record->isUnion();
5929 else {
5930 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5931 Invalid = true;
5932 }
5933 }
5934 }
5935
5936 // C++11 [class.union]p8 (DR1460):
5937 // At most one variant member of a union may have a
5938 // brace-or-equal-initializer.
5939 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5940 Owner->isRecord())
5941 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5942 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5943 }
5944
5945 if (!Record->isUnion() && !Owner->isRecord()) {
5946 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5947 << getLangOpts().CPlusPlus;
5948 Invalid = true;
5949 }
5950
5951 // C++ [dcl.dcl]p3:
5952 // [If there are no declarators], and except for the declaration of an
5953 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5954 // names into the program
5955 // C++ [class.mem]p2:
5956 // each such member-declaration shall either declare at least one member
5957 // name of the class or declare at least one unnamed bit-field
5958 //
5959 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5960 if (getLangOpts().CPlusPlus && Record->field_empty())
5961 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5962
5963 // Mock up a declarator.
5964 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5965 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5966 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5967 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5968
5969 // Create a declaration for this anonymous struct/union.
5970 NamedDecl *Anon = nullptr;
5971 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5972 Anon = FieldDecl::Create(
5973 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5974 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5975 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5976 /*InitStyle=*/ICIS_NoInit);
5977 Anon->setAccess(AS);
5978 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5979
5980 if (getLangOpts().CPlusPlus)
5981 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5982 } else {
5983 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5984 if (SCSpec == DeclSpec::SCS_mutable) {
5985 // mutable can only appear on non-static class members, so it's always
5986 // an error here
5987 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5988 Invalid = true;
5989 SC = SC_None;
5990 }
5991
5992 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5993 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5994 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5995 if (Invalid)
5996 Anon->setInvalidDecl();
5997
5998 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5999
6000 // Default-initialize the implicit variable. This initialization will be
6001 // trivial in almost all cases, except if a union member has an in-class
6002 // initializer:
6003 // union { int n = 0; };
6004 ActOnUninitializedDecl(dcl: Anon);
6005 }
6006 Anon->setImplicit();
6007
6008 // Mark this as an anonymous struct/union type.
6009 Record->setAnonymousStructOrUnion(true);
6010
6011 // Add the anonymous struct/union object to the current
6012 // context. We'll be referencing this object when we refer to one of
6013 // its members.
6014 Owner->addDecl(D: Anon);
6015
6016 // Inject the members of the anonymous struct/union into the owning
6017 // context and into the identifier resolver chain for name lookup
6018 // purposes.
6019 SmallVector<NamedDecl*, 2> Chain;
6020 Chain.push_back(Elt: Anon);
6021
6022 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
6023 Chaining&: Chain))
6024 Invalid = true;
6025
6026 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
6027 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6028 MangleNumberingContext *MCtx;
6029 Decl *ManglingContextDecl;
6030 std::tie(args&: MCtx, args&: ManglingContextDecl) =
6031 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
6032 if (MCtx) {
6033 Context.setManglingNumber(
6034 ND: NewVD, Number: MCtx->getManglingNumber(
6035 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
6036 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
6037 }
6038 }
6039 }
6040
6041 if (Invalid)
6042 Anon->setInvalidDecl();
6043
6044 return Anon;
6045}
6046
6047Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
6048 RecordDecl *Record) {
6049 assert(Record && "expected a record!");
6050
6051 // Mock up a declarator.
6052 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6053 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6054 assert(TInfo && "couldn't build declarator info for anonymous struct");
6055
6056 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6057 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6058
6059 // Create a declaration for this anonymous struct.
6060 NamedDecl *Anon =
6061 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6062 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6063 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6064 /*InitStyle=*/ICIS_NoInit);
6065 Anon->setImplicit();
6066
6067 // Add the anonymous struct object to the current context.
6068 CurContext->addDecl(D: Anon);
6069
6070 // Inject the members of the anonymous struct into the current
6071 // context and into the identifier resolver chain for name lookup
6072 // purposes.
6073 SmallVector<NamedDecl*, 2> Chain;
6074 Chain.push_back(Elt: Anon);
6075
6076 RecordDecl *RecordDef = Record->getDefinition();
6077 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6078 DiagID: diag::err_field_incomplete_or_sizeless) ||
6079 InjectAnonymousStructOrUnionMembers(
6080 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6081 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6082 Anon->setInvalidDecl();
6083 ParentDecl->setInvalidDecl();
6084 }
6085
6086 return Anon;
6087}
6088
6089DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6090 return GetNameFromUnqualifiedId(Name: D.getName());
6091}
6092
6093DeclarationNameInfo
6094Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6095 DeclarationNameInfo NameInfo;
6096 NameInfo.setLoc(Name.StartLocation);
6097
6098 switch (Name.getKind()) {
6099
6100 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6101 case UnqualifiedIdKind::IK_Identifier:
6102 NameInfo.setName(Name.Identifier);
6103 return NameInfo;
6104
6105 case UnqualifiedIdKind::IK_DeductionGuideName: {
6106 // C++ [temp.deduct.guide]p3:
6107 // The simple-template-id shall name a class template specialization.
6108 // The template-name shall be the same identifier as the template-name
6109 // of the simple-template-id.
6110 // These together intend to imply that the template-name shall name a
6111 // class template.
6112 // FIXME: template<typename T> struct X {};
6113 // template<typename T> using Y = X<T>;
6114 // Y(int) -> Y<int>;
6115 // satisfies these rules but does not name a class template.
6116 TemplateName TN = Name.TemplateName.get().get();
6117 auto *Template = TN.getAsTemplateDecl();
6118 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6119 Diag(Loc: Name.StartLocation,
6120 DiagID: diag::err_deduction_guide_name_not_class_template)
6121 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6122 if (Template)
6123 NoteTemplateLocation(Decl: *Template);
6124 return DeclarationNameInfo();
6125 }
6126
6127 NameInfo.setName(
6128 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6129 return NameInfo;
6130 }
6131
6132 case UnqualifiedIdKind::IK_OperatorFunctionId:
6133 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6134 Op: Name.OperatorFunctionId.Operator));
6135 NameInfo.setCXXOperatorNameRange(SourceRange(
6136 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6137 return NameInfo;
6138
6139 case UnqualifiedIdKind::IK_LiteralOperatorId:
6140 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6141 II: Name.Identifier));
6142 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6143 return NameInfo;
6144
6145 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6146 TypeSourceInfo *TInfo;
6147 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6148 if (Ty.isNull())
6149 return DeclarationNameInfo();
6150 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6151 Ty: Context.getCanonicalType(T: Ty)));
6152 NameInfo.setNamedTypeInfo(TInfo);
6153 return NameInfo;
6154 }
6155
6156 case UnqualifiedIdKind::IK_ConstructorName: {
6157 TypeSourceInfo *TInfo;
6158 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6159 if (Ty.isNull())
6160 return DeclarationNameInfo();
6161 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6162 Ty: Context.getCanonicalType(T: Ty)));
6163 NameInfo.setNamedTypeInfo(TInfo);
6164 return NameInfo;
6165 }
6166
6167 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6168 // In well-formed code, we can only have a constructor
6169 // template-id that refers to the current context, so go there
6170 // to find the actual type being constructed.
6171 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6172 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6173 return DeclarationNameInfo();
6174
6175 // Determine the type of the class being constructed.
6176 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6177
6178 // FIXME: Check two things: that the template-id names the same type as
6179 // CurClassType, and that the template-id does not occur when the name
6180 // was qualified.
6181
6182 NameInfo.setName(
6183 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6184 // FIXME: should we retrieve TypeSourceInfo?
6185 NameInfo.setNamedTypeInfo(nullptr);
6186 return NameInfo;
6187 }
6188
6189 case UnqualifiedIdKind::IK_DestructorName: {
6190 TypeSourceInfo *TInfo;
6191 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6192 if (Ty.isNull())
6193 return DeclarationNameInfo();
6194 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6195 Ty: Context.getCanonicalType(T: Ty)));
6196 NameInfo.setNamedTypeInfo(TInfo);
6197 return NameInfo;
6198 }
6199
6200 case UnqualifiedIdKind::IK_TemplateId: {
6201 TemplateName TName = Name.TemplateId->Template.get();
6202 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6203 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6204 }
6205
6206 } // switch (Name.getKind())
6207
6208 llvm_unreachable("Unknown name kind");
6209}
6210
6211static QualType getCoreType(QualType Ty) {
6212 do {
6213 if (Ty->isPointerOrReferenceType())
6214 Ty = Ty->getPointeeType();
6215 else if (Ty->isArrayType())
6216 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6217 else
6218 return Ty.withoutLocalFastQualifiers();
6219 } while (true);
6220}
6221
6222/// hasSimilarParameters - Determine whether the C++ functions Declaration
6223/// and Definition have "nearly" matching parameters. This heuristic is
6224/// used to improve diagnostics in the case where an out-of-line function
6225/// definition doesn't match any declaration within the class or namespace.
6226/// Also sets Params to the list of indices to the parameters that differ
6227/// between the declaration and the definition. If hasSimilarParameters
6228/// returns true and Params is empty, then all of the parameters match.
6229static bool hasSimilarParameters(ASTContext &Context,
6230 FunctionDecl *Declaration,
6231 FunctionDecl *Definition,
6232 SmallVectorImpl<unsigned> &Params) {
6233 Params.clear();
6234 if (Declaration->param_size() != Definition->param_size())
6235 return false;
6236 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6237 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6238 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6239
6240 // The parameter types are identical
6241 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6242 continue;
6243
6244 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6245 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6246 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6247 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6248
6249 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6250 (DeclTyName && DeclTyName == DefTyName))
6251 Params.push_back(Elt: Idx);
6252 else // The two parameters aren't even close
6253 return false;
6254 }
6255
6256 return true;
6257}
6258
6259/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6260/// declarator needs to be rebuilt in the current instantiation.
6261/// Any bits of declarator which appear before the name are valid for
6262/// consideration here. That's specifically the type in the decl spec
6263/// and the base type in any member-pointer chunks.
6264static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6265 DeclarationName Name) {
6266 // The types we specifically need to rebuild are:
6267 // - typenames, typeofs, and decltypes
6268 // - types which will become injected class names
6269 // Of course, we also need to rebuild any type referencing such a
6270 // type. It's safest to just say "dependent", but we call out a
6271 // few cases here.
6272
6273 DeclSpec &DS = D.getMutableDeclSpec();
6274 switch (DS.getTypeSpecType()) {
6275 case DeclSpec::TST_typename:
6276 case DeclSpec::TST_typeofType:
6277 case DeclSpec::TST_typeof_unqualType:
6278#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6279#include "clang/Basic/BuiltinTraits.inc"
6280 case DeclSpec::TST_atomic: {
6281 // Grab the type from the parser.
6282 TypeSourceInfo *TSI = nullptr;
6283 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6284 if (T.isNull() || !T->isInstantiationDependentType()) break;
6285
6286 // Make sure there's a type source info. This isn't really much
6287 // of a waste; most dependent types should have type source info
6288 // attached already.
6289 if (!TSI)
6290 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6291
6292 // Rebuild the type in the current instantiation.
6293 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6294 if (!TSI) return true;
6295
6296 // Store the new type back in the decl spec.
6297 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6298 DS.UpdateTypeRep(Rep: LocType);
6299 break;
6300 }
6301
6302 case DeclSpec::TST_decltype:
6303 case DeclSpec::TST_typeof_unqualExpr:
6304 case DeclSpec::TST_typeofExpr: {
6305 Expr *E = DS.getRepAsExpr();
6306 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6307 if (Result.isInvalid()) return true;
6308 DS.UpdateExprRep(Rep: Result.get());
6309 break;
6310 }
6311
6312 default:
6313 // Nothing to do for these decl specs.
6314 break;
6315 }
6316
6317 // It doesn't matter what order we do this in.
6318 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6319 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6320
6321 // The only type information in the declarator which can come
6322 // before the declaration name is the base type of a member
6323 // pointer.
6324 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6325 continue;
6326
6327 // Rebuild the scope specifier in-place.
6328 CXXScopeSpec &SS = Chunk.Mem.Scope();
6329 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6330 return true;
6331 }
6332
6333 return false;
6334}
6335
6336/// Returns true if the declaration is declared in a system header or from a
6337/// system macro.
6338static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6339 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6340 SM.isInSystemMacro(loc: D->getLocation());
6341}
6342
6343void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6344 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6345 // of system decl.
6346 if (D->getPreviousDecl() || D->isImplicit())
6347 return;
6348 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6349 if (Status != ReservedIdentifierStatus::NotReserved &&
6350 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6351 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6352 << D << static_cast<int>(Status);
6353 }
6354}
6355
6356Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6357 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6358
6359 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6360 // declaration only if the `bind_to_declaration` extension is set.
6361 SmallVector<FunctionDecl *, 4> Bases;
6362 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6363 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6364 TP: llvm::omp::TraitProperty::
6365 implementation_extension_bind_to_declaration))
6366 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6367 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6368
6369 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6370
6371 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6372 Dcl && Dcl->getDeclContext()->isFileContext())
6373 Dcl->setTopLevelDeclInObjCContainer();
6374
6375 if (!Bases.empty())
6376 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6377 Bases);
6378
6379 return Dcl;
6380}
6381
6382bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6383 DeclarationNameInfo NameInfo) {
6384 DeclarationName Name = NameInfo.getName();
6385
6386 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6387 while (Record && Record->isAnonymousStructOrUnion())
6388 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6389 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6390 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6391 return true;
6392 }
6393
6394 return false;
6395}
6396
6397bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6398 DeclarationName Name,
6399 SourceLocation Loc,
6400 TemplateIdAnnotation *TemplateId,
6401 bool IsMemberSpecialization) {
6402 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6403 "without nested-name-specifier");
6404 DeclContext *Cur = CurContext;
6405 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6406 Cur = Cur->getParent();
6407
6408 // If the user provided a superfluous scope specifier that refers back to the
6409 // class in which the entity is already declared, diagnose and ignore it.
6410 //
6411 // class X {
6412 // void X::f();
6413 // };
6414 //
6415 // Note, it was once ill-formed to give redundant qualification in all
6416 // contexts, but that rule was removed by DR482.
6417 if (Cur->Equals(DC)) {
6418 if (Cur->isRecord()) {
6419 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6420 : diag::err_member_extra_qualification)
6421 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6422 SS.clear();
6423 } else {
6424 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6425 }
6426 return false;
6427 }
6428
6429 // Check whether the qualifying scope encloses the scope of the original
6430 // declaration. For a template-id, we perform the checks in
6431 // CheckTemplateSpecializationScope.
6432 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6433 Cur = Cur->getEnclosingNonExpansionStatementContext();
6434 if (Cur->isRecord())
6435 Diag(Loc, DiagID: diag::err_member_qualification)
6436 << Name << SS.getRange();
6437 else if (isa<TranslationUnitDecl>(Val: DC))
6438 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6439 << Name << SS.getRange();
6440 else if (isa<FunctionDecl>(Val: Cur))
6441 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6442 << Name << SS.getRange();
6443 else if (isa<BlockDecl>(Val: Cur))
6444 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6445 << Name << SS.getRange();
6446 else if (isa<ExportDecl>(Val: Cur)) {
6447 if (!isa<NamespaceDecl>(Val: DC))
6448 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6449 << Name << SS.getRange();
6450 else
6451 // The cases that DC is not NamespaceDecl should be handled in
6452 // CheckRedeclarationExported.
6453 return false;
6454 } else
6455 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6456 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6457
6458 return true;
6459 }
6460
6461 if (Cur->isRecord()) {
6462 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6463 // An explicit specialization may be declared in any scope in which the
6464 // corresponding primary template may be defined.
6465 if (IsMemberSpecialization)
6466 return false;
6467
6468 // Cannot qualify members within a class.
6469 Diag(Loc, DiagID: diag::err_member_qualification)
6470 << Name << SS.getRange();
6471 SS.clear();
6472
6473 // C++ constructors and destructors with incorrect scopes can break
6474 // our AST invariants by having the wrong underlying types. If
6475 // that's the case, then drop this declaration entirely.
6476 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6477 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6478 !Context.hasSameType(
6479 T1: Name.getCXXNameType(),
6480 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6481 return true;
6482
6483 return false;
6484 }
6485
6486 // C++23 [temp.names]p5:
6487 // The keyword template shall not appear immediately after a declarative
6488 // nested-name-specifier.
6489 //
6490 // First check the template-id (if any), and then check each component of the
6491 // nested-name-specifier in reverse order.
6492 //
6493 // FIXME: nested-name-specifiers in friend declarations are declarative,
6494 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6495 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6496 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6497 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6498
6499 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6500 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6501 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6502 SourceLocation TemplateKeywordLoc;
6503 switch (TL.getTypeLocClass()) {
6504 case TypeLoc::TemplateSpecialization: {
6505 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6506 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6507 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6508 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6509 << TST.getLocalSourceRange();
6510 break;
6511 }
6512 case TypeLoc::Decltype:
6513 case TypeLoc::PackIndexing: {
6514 const Type *T = TL.getTypePtr();
6515 // C++23 [expr.prim.id.qual]p2:
6516 // [...] A declarative nested-name-specifier shall not have a
6517 // computed-type-specifier.
6518 //
6519 // CWG2858 changed this from 'decltype-specifier' to
6520 // 'computed-type-specifier'.
6521 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6522 << T->isDecltypeType() << TL.getSourceRange();
6523 break;
6524 }
6525 case TypeLoc::DependentName:
6526 NextTL =
6527 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6528 break;
6529 default:
6530 break;
6531 }
6532 if (TemplateKeywordLoc.isValid())
6533 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6534 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6535 }
6536
6537 return false;
6538}
6539
6540NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6541 MultiTemplateParamsArg TemplateParamLists) {
6542 // TODO: consider using NameInfo for diagnostic.
6543 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6544 DeclarationName Name = NameInfo.getName();
6545
6546 // All of these full declarators require an identifier. If it doesn't have
6547 // one, the ParsedFreeStandingDeclSpec action should be used.
6548 if (D.isDecompositionDeclarator()) {
6549 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6550 } else if (!Name) {
6551 if (!D.isInvalidType()) // Reject this if we think it is valid.
6552 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6553 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6554 return nullptr;
6555 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6556 return nullptr;
6557
6558 DeclContext *DC = CurContext;
6559 if (D.getCXXScopeSpec().isInvalid())
6560 D.setInvalidType();
6561 else if (D.getCXXScopeSpec().isSet()) {
6562 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6563 UPPC: UPPC_DeclarationQualifier))
6564 return nullptr;
6565
6566 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6567 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6568 if (!DC || isa<EnumDecl>(Val: DC)) {
6569 // If we could not compute the declaration context, it's because the
6570 // declaration context is dependent but does not refer to a class,
6571 // class template, or class template partial specialization. Complain
6572 // and return early, to avoid the coming semantic disaster.
6573 Diag(Loc: D.getIdentifierLoc(),
6574 DiagID: diag::err_template_qualified_declarator_no_match)
6575 << D.getCXXScopeSpec().getScopeRep()
6576 << D.getCXXScopeSpec().getRange();
6577 return nullptr;
6578 }
6579 bool IsDependentContext = DC->isDependentContext();
6580
6581 if (!IsDependentContext &&
6582 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6583 return nullptr;
6584
6585 // If a class is incomplete, do not parse entities inside it.
6586 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6587 Diag(Loc: D.getIdentifierLoc(),
6588 DiagID: diag::err_member_def_undefined_record)
6589 << Name << DC << D.getCXXScopeSpec().getRange();
6590 return nullptr;
6591 }
6592 if (!D.getDeclSpec().isFriendSpecified()) {
6593 TemplateIdAnnotation *TemplateId =
6594 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6595 ? D.getName().TemplateId
6596 : nullptr;
6597 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6598 Loc: D.getIdentifierLoc(), TemplateId,
6599 /*IsMemberSpecialization=*/false)) {
6600 if (DC->isRecord())
6601 return nullptr;
6602
6603 D.setInvalidType();
6604 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6605 D.setInvalidType();
6606 }
6607 }
6608
6609 // Check whether we need to rebuild the type of the given
6610 // declaration in the current instantiation.
6611 if (EnteringContext && IsDependentContext &&
6612 TemplateParamLists.size() != 0) {
6613 ContextRAII SavedContext(*this, DC);
6614 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6615 D.setInvalidType();
6616 }
6617 }
6618
6619 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6620 QualType R = TInfo->getType();
6621
6622 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6623 UPPC: UPPC_DeclarationType))
6624 D.setInvalidType();
6625
6626 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6627 forRedeclarationInCurContext());
6628
6629 // See if this is a redefinition of a variable in the same scope.
6630 if (!D.getCXXScopeSpec().isSet()) {
6631 bool IsLinkageLookup = false;
6632 bool CreateBuiltins = false;
6633
6634 // If the declaration we're planning to build will be a function
6635 // or object with linkage, then look for another declaration with
6636 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6637 //
6638 // If the declaration we're planning to build will be declared with
6639 // external linkage in the translation unit, create any builtin with
6640 // the same name.
6641 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6642 /* Do nothing*/;
6643 else if (CurContext->isFunctionOrMethod() &&
6644 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6645 R->isFunctionType())) {
6646 IsLinkageLookup = true;
6647 CreateBuiltins =
6648 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6649 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6650 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6651 CreateBuiltins = true;
6652
6653 if (IsLinkageLookup) {
6654 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6655 Previous.setRedeclarationKind(
6656 RedeclarationKind::ForExternalRedeclaration);
6657 }
6658
6659 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6660 } else { // Something like "int foo::x;"
6661 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6662
6663 // C++ [dcl.meaning]p1:
6664 // When the declarator-id is qualified, the declaration shall refer to a
6665 // previously declared member of the class or namespace to which the
6666 // qualifier refers (or, in the case of a namespace, of an element of the
6667 // inline namespace set of that namespace (7.3.1)) or to a specialization
6668 // thereof; [...]
6669 //
6670 // Note that we already checked the context above, and that we do not have
6671 // enough information to make sure that Previous contains the declaration
6672 // we want to match. For example, given:
6673 //
6674 // class X {
6675 // void f();
6676 // void f(float);
6677 // };
6678 //
6679 // void X::f(int) { } // ill-formed
6680 //
6681 // In this case, Previous will point to the overload set
6682 // containing the two f's declared in X, but neither of them
6683 // matches.
6684
6685 RemoveUsingDecls(R&: Previous);
6686 }
6687
6688 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6689 TPD && TPD->isTemplateParameter()) {
6690 // Older versions of clang allowed the names of function/variable templates
6691 // to shadow the names of their template parameters. For the compatibility
6692 // purposes we detect such cases and issue a default-to-error warning that
6693 // can be disabled with -Wno-strict-primary-template-shadow.
6694 if (!D.isInvalidType()) {
6695 bool AllowForCompatibility = false;
6696 if (Scope *DeclParent = S->getDeclParent();
6697 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6698 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6699 TemplateParamParent->isDeclScope(D: TPD);
6700 }
6701 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6702 SupportedForCompatibility: AllowForCompatibility);
6703 }
6704
6705 // Just pretend that we didn't see the previous declaration.
6706 Previous.clear();
6707 }
6708
6709 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6710 // Forget that the previous declaration is the injected-class-name.
6711 Previous.clear();
6712
6713 // In C++, the previous declaration we find might be a tag type
6714 // (class or enum). In this case, the new declaration will hide the
6715 // tag type. Note that this applies to functions, function templates, and
6716 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6717 if (Previous.isSingleTagDecl() &&
6718 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6719 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6720 Previous.clear();
6721
6722 // Check that there are no default arguments other than in the parameters
6723 // of a function declaration (C++ only).
6724 if (getLangOpts().CPlusPlus)
6725 CheckExtraCXXDefaultArguments(D);
6726
6727 /// Get the innermost enclosing declaration scope.
6728 S = S->getDeclParent();
6729
6730 NamedDecl *New;
6731
6732 bool AddToScope = true;
6733 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6734 if (TemplateParamLists.size()) {
6735 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6736 return nullptr;
6737 }
6738
6739 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6740 } else if (R->isFunctionType()) {
6741 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6742 TemplateParamLists,
6743 AddToScope);
6744 } else {
6745 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6746 AddToScope);
6747 }
6748
6749 if (!New)
6750 return nullptr;
6751
6752 warnOnCTypeHiddenInCPlusPlus(D: New);
6753
6754 // If this has an identifier and is not a function template specialization,
6755 // add it to the scope stack.
6756 if (New->getDeclName() && AddToScope)
6757 PushOnScopeChains(D: New, S);
6758
6759 if (OpenMP().isInOpenMPDeclareTargetContext())
6760 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6761
6762 return New;
6763}
6764
6765/// Helper method to turn variable array types into constant array
6766/// types in certain situations which would otherwise be errors (for
6767/// GCC compatibility).
6768static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6769 ASTContext &Context,
6770 bool &SizeIsNegative,
6771 llvm::APSInt &Oversized) {
6772 // This method tries to turn a variable array into a constant
6773 // array even when the size isn't an ICE. This is necessary
6774 // for compatibility with code that depends on gcc's buggy
6775 // constant expression folding, like struct {char x[(int)(char*)2];}
6776 SizeIsNegative = false;
6777 Oversized = 0;
6778
6779 if (T->isDependentType())
6780 return QualType();
6781
6782 QualifierCollector Qs;
6783 const Type *Ty = Qs.strip(type: T);
6784
6785 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6786 QualType Pointee = PTy->getPointeeType();
6787 QualType FixedType =
6788 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6789 Oversized);
6790 if (FixedType.isNull()) return FixedType;
6791 FixedType = Context.getPointerType(T: FixedType);
6792 return Qs.apply(Context, QT: FixedType);
6793 }
6794 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6795 QualType Inner = PTy->getInnerType();
6796 QualType FixedType =
6797 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6798 Oversized);
6799 if (FixedType.isNull()) return FixedType;
6800 FixedType = Context.getParenType(NamedType: FixedType);
6801 return Qs.apply(Context, QT: FixedType);
6802 }
6803
6804 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6805 if (!VLATy)
6806 return QualType();
6807
6808 QualType ElemTy = VLATy->getElementType();
6809 if (ElemTy->isVariablyModifiedType()) {
6810 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6811 SizeIsNegative, Oversized);
6812 if (ElemTy.isNull())
6813 return QualType();
6814 }
6815
6816 Expr::EvalResult Result;
6817 if (!VLATy->getSizeExpr() ||
6818 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6819 return QualType();
6820
6821 llvm::APSInt Res = Result.Val.getInt();
6822
6823 // Check whether the array size is negative.
6824 if (Res.isSigned() && Res.isNegative()) {
6825 SizeIsNegative = true;
6826 return QualType();
6827 }
6828
6829 // Check whether the array is too large to be addressed.
6830 unsigned ActiveSizeBits =
6831 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6832 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6833 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6834 : Res.getActiveBits();
6835 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6836 Oversized = std::move(Res);
6837 return QualType();
6838 }
6839
6840 QualType FoldedArrayType = Context.getConstantArrayType(
6841 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6842 return Qs.apply(Context, QT: FoldedArrayType);
6843}
6844
6845static void
6846FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6847 SrcTL = SrcTL.getUnqualifiedLoc();
6848 DstTL = DstTL.getUnqualifiedLoc();
6849 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6850 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6851 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6852 DstTL: DstPTL.getPointeeLoc());
6853 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6854 return;
6855 }
6856 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6857 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6858 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6859 DstTL: DstPTL.getInnerLoc());
6860 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6861 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6862 return;
6863 }
6864 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6865 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6866 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6867 TypeLoc DstElemTL = DstATL.getElementLoc();
6868 if (VariableArrayTypeLoc SrcElemATL =
6869 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6870 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6871 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6872 } else {
6873 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6874 }
6875 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6876 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6877 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6878}
6879
6880/// Helper method to turn variable array types into constant array
6881/// types in certain situations which would otherwise be errors (for
6882/// GCC compatibility).
6883static TypeSourceInfo*
6884TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6885 ASTContext &Context,
6886 bool &SizeIsNegative,
6887 llvm::APSInt &Oversized) {
6888 QualType FixedTy
6889 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6890 SizeIsNegative, Oversized);
6891 if (FixedTy.isNull())
6892 return nullptr;
6893 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6894 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6895 DstTL: FixedTInfo->getTypeLoc());
6896 return FixedTInfo;
6897}
6898
6899bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6900 QualType &T, SourceLocation Loc,
6901 unsigned FailedFoldDiagID) {
6902 bool SizeIsNegative;
6903 llvm::APSInt Oversized;
6904 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6905 TInfo, Context, SizeIsNegative, Oversized);
6906 if (FixedTInfo) {
6907 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6908 TInfo = FixedTInfo;
6909 T = FixedTInfo->getType();
6910 return true;
6911 }
6912
6913 if (SizeIsNegative)
6914 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6915 else if (Oversized.getBoolValue())
6916 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6917 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6918 /*UpperCase=*/false, /*InsertSeparators=*/true);
6919 else if (FailedFoldDiagID)
6920 Diag(Loc, DiagID: FailedFoldDiagID);
6921 return false;
6922}
6923
6924void
6925Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6926 if (!getLangOpts().CPlusPlus &&
6927 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6928 // Don't need to track declarations in the TU in C.
6929 return;
6930
6931 // Note that we have a locally-scoped external with this name.
6932 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6933}
6934
6935NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6936 // FIXME: We can have multiple results via __attribute__((overloadable)).
6937 auto Result = Context.getExternCContextDecl()->lookup(Name);
6938 return Result.empty() ? nullptr : *Result.begin();
6939}
6940
6941void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6942 // FIXME: We should probably indicate the identifier in question to avoid
6943 // confusion for constructs like "virtual int a(), b;"
6944 if (DS.isVirtualSpecified())
6945 Diag(Loc: DS.getVirtualSpecLoc(),
6946 DiagID: diag::err_virtual_non_function);
6947
6948 if (DS.hasExplicitSpecifier())
6949 Diag(Loc: DS.getExplicitSpecLoc(),
6950 DiagID: diag::err_explicit_non_function);
6951
6952 if (DS.isNoreturnSpecified())
6953 Diag(Loc: DS.getNoreturnSpecLoc(),
6954 DiagID: diag::err_noreturn_non_function);
6955}
6956
6957NamedDecl*
6958Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6959 TypeSourceInfo *TInfo, LookupResult &Previous) {
6960 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6961 if (D.getCXXScopeSpec().isSet()) {
6962 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6963 << D.getCXXScopeSpec().getRange();
6964 D.setInvalidType();
6965 // Pretend we didn't see the scope specifier.
6966 DC = CurContext;
6967 Previous.clear();
6968 }
6969
6970 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6971
6972 if (D.getDeclSpec().isInlineSpecified())
6973 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6974 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6975 ? diag::warn_ms_inline_non_function
6976 : diag::err_inline_non_function)
6977 << getLangOpts().CPlusPlus17;
6978 if (D.getDeclSpec().hasConstexprSpecifier())
6979 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6980 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6981
6982 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6983 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6984 Diag(Loc: D.getName().StartLocation,
6985 DiagID: diag::err_deduction_guide_invalid_specifier)
6986 << "typedef";
6987 else
6988 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6989 << D.getName().getSourceRange();
6990 return nullptr;
6991 }
6992
6993 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6994 if (!NewTD) return nullptr;
6995
6996 // Handle attributes prior to checking for duplicates in MergeVarDecl
6997 ProcessDeclAttributes(S, D: NewTD, PD: D);
6998
6999 CheckTypedefForVariablyModifiedType(S, D: NewTD);
7000
7001 bool Redeclaration = D.isRedeclaration();
7002 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
7003 D.setRedeclaration(Redeclaration);
7004 return ND;
7005}
7006
7007void
7008Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
7009 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7010 // then it shall have block scope.
7011 // Note that variably modified types must be fixed before merging the decl so
7012 // that redeclarations will match.
7013 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7014 QualType T = TInfo->getType();
7015 if (T->isVariablyModifiedType()) {
7016 setFunctionHasBranchProtectedScope();
7017
7018 if (S->getFnParent() == nullptr) {
7019 bool SizeIsNegative;
7020 llvm::APSInt Oversized;
7021 TypeSourceInfo *FixedTInfo =
7022 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7023 SizeIsNegative,
7024 Oversized);
7025 if (FixedTInfo) {
7026 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
7027 NewTD->setTypeSourceInfo(FixedTInfo);
7028 } else {
7029 if (SizeIsNegative)
7030 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
7031 else if (T->isVariableArrayType())
7032 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
7033 else if (Oversized.getBoolValue())
7034 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
7035 << toString(I: Oversized, Radix: 10);
7036 else
7037 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
7038 NewTD->setInvalidDecl();
7039 }
7040 }
7041 }
7042}
7043
7044NamedDecl*
7045Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
7046 LookupResult &Previous, bool &Redeclaration) {
7047
7048 // Find the shadowed declaration before filtering for scope.
7049 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
7050
7051 // Merge the decl with the existing one if appropriate. If the decl is
7052 // in an outer scope, it isn't the same thing.
7053 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
7054 /*AllowInlineNamespace*/false);
7055 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
7056 if (!Previous.empty()) {
7057 Redeclaration = true;
7058 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
7059 } else {
7060 inferGslPointerAttribute(TD: NewTD);
7061 }
7062
7063 if (ShadowedDecl && !Redeclaration)
7064 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7065
7066 // If this is the C FILE type, notify the AST context.
7067 if (IdentifierInfo *II = NewTD->getIdentifier())
7068 if (!NewTD->isInvalidDecl() &&
7069 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7070 switch (II->getNotableIdentifierID()) {
7071 case tok::NotableIdentifierKind::FILE:
7072 Context.setFILEDecl(NewTD);
7073 break;
7074 case tok::NotableIdentifierKind::jmp_buf:
7075 Context.setjmp_bufDecl(NewTD);
7076 break;
7077 case tok::NotableIdentifierKind::sigjmp_buf:
7078 Context.setsigjmp_bufDecl(NewTD);
7079 break;
7080 case tok::NotableIdentifierKind::ucontext_t:
7081 Context.setucontext_tDecl(NewTD);
7082 break;
7083 case tok::NotableIdentifierKind::float_t:
7084 case tok::NotableIdentifierKind::double_t:
7085 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7086 break;
7087 default:
7088 break;
7089 }
7090 }
7091
7092 return NewTD;
7093}
7094
7095/// Determines whether the given declaration is an out-of-scope
7096/// previous declaration.
7097///
7098/// This routine should be invoked when name lookup has found a
7099/// previous declaration (PrevDecl) that is not in the scope where a
7100/// new declaration by the same name is being introduced. If the new
7101/// declaration occurs in a local scope, previous declarations with
7102/// linkage may still be considered previous declarations (C99
7103/// 6.2.2p4-5, C++ [basic.link]p6).
7104///
7105/// \param PrevDecl the previous declaration found by name
7106/// lookup
7107///
7108/// \param DC the context in which the new declaration is being
7109/// declared.
7110///
7111/// \returns true if PrevDecl is an out-of-scope previous declaration
7112/// for a new delcaration with the same name.
7113static bool
7114isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7115 ASTContext &Context) {
7116 if (!PrevDecl)
7117 return false;
7118
7119 if (!PrevDecl->hasLinkage())
7120 return false;
7121
7122 if (Context.getLangOpts().CPlusPlus) {
7123 // C++ [basic.link]p6:
7124 // If there is a visible declaration of an entity with linkage
7125 // having the same name and type, ignoring entities declared
7126 // outside the innermost enclosing namespace scope, the block
7127 // scope declaration declares that same entity and receives the
7128 // linkage of the previous declaration.
7129 DeclContext *OuterContext = DC->getRedeclContext();
7130 if (!OuterContext->isFunctionOrMethod())
7131 // This rule only applies to block-scope declarations.
7132 return false;
7133
7134 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7135 if (PrevOuterContext->isRecord())
7136 // We found a member function: ignore it.
7137 return false;
7138
7139 // Find the innermost enclosing namespace for the new and
7140 // previous declarations.
7141 OuterContext = OuterContext->getEnclosingNamespaceContext();
7142 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7143
7144 // The previous declaration is in a different namespace, so it
7145 // isn't the same function.
7146 if (!OuterContext->Equals(DC: PrevOuterContext))
7147 return false;
7148 }
7149
7150 return true;
7151}
7152
7153static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7154 CXXScopeSpec &SS = D.getCXXScopeSpec();
7155 if (!SS.isSet()) return;
7156 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7157}
7158
7159void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7160 LangAS ImplAS = LangAS::opencl_private;
7161 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7162 // __opencl_c_program_scope_global_variables feature, the address space
7163 // for a variable at program scope or a static or extern variable inside
7164 // a function are inferred to be __global.
7165 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7166 Var->hasGlobalStorage())
7167 ImplAS = LangAS::opencl_global;
7168 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7169}
7170
7171static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7172 // 'weak' only applies to declarations with external linkage.
7173 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7174 if (!ND.isExternallyVisible()) {
7175 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7176 ND.dropAttr<WeakAttr>();
7177 }
7178 }
7179}
7180
7181static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7182 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7183 if (ND.isExternallyVisible()) {
7184 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7185 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7186 }
7187 }
7188}
7189
7190static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7191 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7192 if (VD->hasInit()) {
7193 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7194 assert(VD->isThisDeclarationADefinition() &&
7195 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7196 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7197 VD->dropAttr<AliasAttr>();
7198 }
7199 }
7200 }
7201}
7202
7203static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7204 // 'selectany' only applies to externally visible variable declarations.
7205 // It does not apply to functions.
7206 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7207 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7208 S.Diag(Loc: Attr->getLocation(),
7209 DiagID: diag::err_attribute_selectany_non_extern_data);
7210 ND.dropAttr<SelectAnyAttr>();
7211 }
7212 }
7213}
7214
7215static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7216 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7217 if (!ND.isExternallyVisible())
7218 S.Diag(Loc: Attr->getLocation(),
7219 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7220 }
7221}
7222
7223static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7224 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7225 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7226 bool IsAnonymousNS = false;
7227 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7228 if (VD) {
7229 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7230 while (NS && !IsAnonymousNS) {
7231 IsAnonymousNS = NS->isAnonymousNamespace();
7232 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7233 }
7234 }
7235 // dll attributes require external linkage. Static locals may have external
7236 // linkage but still cannot be explicitly imported or exported.
7237 // In Microsoft mode, a variable defined in anonymous namespace must have
7238 // external linkage in order to be exported.
7239 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7240 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7241 (!AnonNSInMicrosoftMode &&
7242 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7243 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7244 << &ND << Attr;
7245 ND.setInvalidDecl();
7246 }
7247 }
7248}
7249
7250static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7251 // Check the attributes on the function type and function params, if any.
7252 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7253 FD = FD->getMostRecentDecl();
7254 // Don't declare this variable in the second operand of the for-statement;
7255 // GCC miscompiles that by ending its lifetime before evaluating the
7256 // third operand. See gcc.gnu.org/PR86769.
7257 AttributedTypeLoc ATL;
7258 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7259 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7260 TL = ATL.getModifiedLoc()) {
7261 // The [[lifetimebound]] attribute can be applied to the implicit object
7262 // parameter of a non-static member function (other than a ctor or dtor)
7263 // by applying it to the function type.
7264 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7265 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7266 int NoImplicitObjectError = -1;
7267 if (!MD)
7268 NoImplicitObjectError = 0;
7269 else if (MD->isStatic())
7270 NoImplicitObjectError = 1;
7271 else if (MD->isExplicitObjectMemberFunction())
7272 NoImplicitObjectError = 2;
7273 if (NoImplicitObjectError != -1) {
7274 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7275 << NoImplicitObjectError << A->getRange();
7276 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7277 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7278 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7279 } else if (MD->getReturnType()->isVoidType()) {
7280 S.Diag(
7281 Loc: MD->getLocation(),
7282 DiagID: diag::
7283 err_lifetimebound_implicit_object_parameter_void_return_type);
7284 }
7285 }
7286 }
7287
7288 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7289 const ParmVarDecl *P = FD->getParamDecl(i: I);
7290
7291 // The [[lifetimebound]] attribute can be applied to a function parameter
7292 // only if the function returns a value.
7293 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7294 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7295 S.Diag(Loc: A->getLocation(),
7296 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7297 }
7298 }
7299 }
7300 }
7301}
7302
7303static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7304 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7305 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7306}
7307
7308static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7309 // Ensure that an auto decl is deduced otherwise the checks below might cache
7310 // the wrong linkage.
7311 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7312
7313 checkWeakAttr(S, ND);
7314 checkWeakRefAttr(S, ND);
7315 checkAliasAttr(S, ND);
7316 checkSelectAnyAttr(S, ND);
7317 checkHybridPatchableAttr(S, ND);
7318 checkInheritableAttr(S, ND);
7319 checkLifetimeBoundAttr(S, ND);
7320}
7321
7322static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7323 NamedDecl *NewDecl,
7324 bool IsSpecialization,
7325 bool IsDefinition) {
7326 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7327 return;
7328
7329 bool IsTemplate = false;
7330 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7331 OldDecl = OldTD->getTemplatedDecl();
7332 IsTemplate = true;
7333 if (!IsSpecialization)
7334 IsDefinition = false;
7335 }
7336 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7337 NewDecl = NewTD->getTemplatedDecl();
7338 IsTemplate = true;
7339 }
7340
7341 if (!OldDecl || !NewDecl)
7342 return;
7343
7344 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7345 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7346 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7347 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7348
7349 // dllimport and dllexport are inheritable attributes so we have to exclude
7350 // inherited attribute instances.
7351 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7352 (NewExportAttr && !NewExportAttr->isInherited());
7353
7354 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7355 // the only exception being explicit specializations.
7356 // Implicitly generated declarations are also excluded for now because there
7357 // is no other way to switch these to use dllimport or dllexport.
7358 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7359
7360 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7361 // Allow with a warning for free functions and global variables.
7362 bool JustWarn = false;
7363 if (!OldDecl->isCXXClassMember()) {
7364 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7365 if (VD && !VD->getDescribedVarTemplate())
7366 JustWarn = true;
7367 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7368 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7369 JustWarn = true;
7370 }
7371
7372 // We cannot change a declaration that's been used because IR has already
7373 // been emitted. Dllimported functions will still work though (modulo
7374 // address equality) as they can use the thunk.
7375 if (OldDecl->isUsed())
7376 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7377 JustWarn = false;
7378
7379 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7380 : diag::err_attribute_dll_redeclaration;
7381 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7382 << NewDecl
7383 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7384 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7385 if (!JustWarn) {
7386 NewDecl->setInvalidDecl();
7387 return;
7388 }
7389 }
7390
7391 // A redeclaration is not allowed to drop a dllimport attribute, the only
7392 // exceptions being inline function definitions (except for function
7393 // templates), local extern declarations, qualified friend declarations or
7394 // special MSVC extension: in the last case, the declaration is treated as if
7395 // it were marked dllexport.
7396 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7397 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7398 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7399 // Ignore static data because out-of-line definitions are diagnosed
7400 // separately.
7401 IsStaticDataMember = VD->isStaticDataMember();
7402 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7403 VarDecl::DeclarationOnly;
7404 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7405 IsInline = FD->isInlined();
7406 IsQualifiedFriend = FD->getQualifier() &&
7407 FD->getFriendObjectKind() == Decl::FOK_Declared;
7408 }
7409
7410 if (OldImportAttr && !HasNewAttr &&
7411 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7412 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7413 if (IsMicrosoftABI && IsDefinition) {
7414 if (IsSpecialization) {
7415 S.Diag(
7416 Loc: NewDecl->getLocation(),
7417 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7418 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7419 NewDecl->dropAttr<DLLImportAttr>();
7420 } else {
7421 S.Diag(Loc: NewDecl->getLocation(),
7422 DiagID: diag::warn_redeclaration_without_import_attribute)
7423 << NewDecl;
7424 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7425 NewDecl->dropAttr<DLLImportAttr>();
7426 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7427 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7428 }
7429 } else if (IsMicrosoftABI && IsSpecialization) {
7430 assert(!IsDefinition);
7431 // MSVC allows this. Keep the inherited attribute.
7432 } else {
7433 S.Diag(Loc: NewDecl->getLocation(),
7434 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7435 << NewDecl << OldImportAttr;
7436 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7437 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7438 OldDecl->dropAttr<DLLImportAttr>();
7439 NewDecl->dropAttr<DLLImportAttr>();
7440 }
7441 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7442 // In MinGW, seeing a function declared inline drops the dllimport
7443 // attribute.
7444 OldDecl->dropAttr<DLLImportAttr>();
7445 NewDecl->dropAttr<DLLImportAttr>();
7446 S.Diag(Loc: NewDecl->getLocation(),
7447 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7448 << NewDecl << OldImportAttr;
7449 }
7450
7451 // A specialization of a class template member function is processed here
7452 // since it's a redeclaration. If the parent class is dllexport, the
7453 // specialization inherits that attribute. This doesn't happen automatically
7454 // since the parent class isn't instantiated until later.
7455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7456 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7457 !NewImportAttr && !NewExportAttr) {
7458 if (const DLLExportAttr *ParentExportAttr =
7459 MD->getParent()->getAttr<DLLExportAttr>()) {
7460 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7461 NewAttr->setInherited(true);
7462 NewDecl->addAttr(A: NewAttr);
7463 }
7464 }
7465 }
7466}
7467
7468/// Given that we are within the definition of the given function,
7469/// will that definition behave like C99's 'inline', where the
7470/// definition is discarded except for optimization purposes?
7471static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7472 // Try to avoid calling GetGVALinkageForFunction.
7473
7474 // All cases of this require the 'inline' keyword.
7475 if (!FD->isInlined()) return false;
7476
7477 // This is only possible in C++ with the gnu_inline attribute.
7478 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7479 return false;
7480
7481 // Okay, go ahead and call the relatively-more-expensive function.
7482 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7483}
7484
7485/// Determine whether a variable is extern "C" prior to attaching
7486/// an initializer. We can't just call isExternC() here, because that
7487/// will also compute and cache whether the declaration is externally
7488/// visible, which might change when we attach the initializer.
7489///
7490/// This can only be used if the declaration is known to not be a
7491/// redeclaration of an internal linkage declaration.
7492///
7493/// For instance:
7494///
7495/// auto x = []{};
7496///
7497/// Attaching the initializer here makes this declaration not externally
7498/// visible, because its type has internal linkage.
7499///
7500/// FIXME: This is a hack.
7501template<typename T>
7502static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7503 if (S.getLangOpts().CPlusPlus) {
7504 // In C++, the overloadable attribute negates the effects of extern "C".
7505 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7506 return false;
7507
7508 // So do CUDA's host/device attributes.
7509 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7510 D->template hasAttr<CUDAHostAttr>()))
7511 return false;
7512 }
7513 return D->isExternC();
7514}
7515
7516static bool shouldConsiderLinkage(const VarDecl *VD) {
7517 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7518 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7519 isa<OMPDeclareMapperDecl>(Val: DC))
7520 return VD->hasExternalStorage();
7521 if (DC->isFileContext())
7522 return true;
7523 if (DC->isRecord())
7524 return false;
7525 if (DC->getDeclKind() == Decl::HLSLBuffer)
7526 return false;
7527
7528 if (isa<RequiresExprBodyDecl, CXXExpansionStmtDecl>(Val: DC))
7529 return false;
7530 llvm_unreachable("Unexpected context");
7531}
7532
7533static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7534 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7535 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7536 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7537 return true;
7538 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(Val: DC))
7539 return false;
7540 llvm_unreachable("Unexpected context");
7541}
7542
7543static bool hasParsedAttr(Scope *S, const Declarator &PD,
7544 ParsedAttr::Kind Kind) {
7545 // Check decl attributes on the DeclSpec.
7546 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7547 return true;
7548
7549 // Walk the declarator structure, checking decl attributes that were in a type
7550 // position to the decl itself.
7551 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7552 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7553 return true;
7554 }
7555
7556 // Finally, check attributes on the decl itself.
7557 return PD.getAttributes().hasAttribute(K: Kind) ||
7558 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7559}
7560
7561bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7562 if (!DC->isFunctionOrMethod())
7563 return false;
7564
7565 // If this is a local extern function or variable declared within a function
7566 // template, don't add it into the enclosing namespace scope until it is
7567 // instantiated; it might have a dependent type right now.
7568 if (DC->isDependentContext())
7569 return true;
7570
7571 // C++11 [basic.link]p7:
7572 // When a block scope declaration of an entity with linkage is not found to
7573 // refer to some other declaration, then that entity is a member of the
7574 // innermost enclosing namespace.
7575 //
7576 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7577 // semantically-enclosing namespace, not a lexically-enclosing one.
7578 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7579 DC = DC->getParent();
7580 return true;
7581}
7582
7583/// Returns true if given declaration has external C language linkage.
7584static bool isDeclExternC(const Decl *D) {
7585 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7586 return FD->isExternC();
7587 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7588 return VD->isExternC();
7589
7590 llvm_unreachable("Unknown type of decl!");
7591}
7592
7593/// Returns true if there hasn't been any invalid type diagnosed.
7594static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7595 DeclContext *DC = NewVD->getDeclContext();
7596 QualType R = NewVD->getType();
7597
7598 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7599 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7600 // argument.
7601 if (R->isImageType() || R->isPipeType()) {
7602 Se.Diag(Loc: NewVD->getLocation(),
7603 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7604 << R;
7605 NewVD->setInvalidDecl();
7606 return false;
7607 }
7608
7609 // OpenCL v1.2 s6.9.r:
7610 // The event type cannot be used to declare a program scope variable.
7611 // OpenCL v2.0 s6.9.q:
7612 // The clk_event_t and reserve_id_t types cannot be declared in program
7613 // scope.
7614 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7615 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7616 Se.Diag(Loc: NewVD->getLocation(),
7617 DiagID: diag::err_invalid_type_for_program_scope_var)
7618 << R;
7619 NewVD->setInvalidDecl();
7620 return false;
7621 }
7622 }
7623
7624 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7625 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7626 LO: Se.getLangOpts())) {
7627 QualType NR = R.getCanonicalType();
7628 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7629 NR->isReferenceType()) {
7630 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7631 NR->isFunctionReferenceType()) {
7632 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7633 << NR->isReferenceType();
7634 NewVD->setInvalidDecl();
7635 return false;
7636 }
7637 NR = NR->getPointeeType();
7638 }
7639 }
7640
7641 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7642 LO: Se.getLangOpts())) {
7643 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7644 // half array type (unless the cl_khr_fp16 extension is enabled).
7645 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7646 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7647 NewVD->setInvalidDecl();
7648 return false;
7649 }
7650 }
7651
7652 // OpenCL v1.2 s6.9.r:
7653 // The event type cannot be used with the __local, __constant and __global
7654 // address space qualifiers.
7655 if (R->isEventT()) {
7656 if (R.getAddressSpace() != LangAS::opencl_private) {
7657 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7658 NewVD->setInvalidDecl();
7659 return false;
7660 }
7661 }
7662
7663 if (R->isSamplerT()) {
7664 // OpenCL v1.2 s6.9.b p4:
7665 // The sampler type cannot be used with the __local and __global address
7666 // space qualifiers.
7667 if (R.getAddressSpace() == LangAS::opencl_local ||
7668 R.getAddressSpace() == LangAS::opencl_global) {
7669 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7670 NewVD->setInvalidDecl();
7671 }
7672
7673 // OpenCL v1.2 s6.12.14.1:
7674 // A global sampler must be declared with either the constant address
7675 // space qualifier or with the const qualifier.
7676 if (DC->isTranslationUnit() &&
7677 !(R.getAddressSpace() == LangAS::opencl_constant ||
7678 R.isConstQualified())) {
7679 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7680 NewVD->setInvalidDecl();
7681 }
7682 if (NewVD->isInvalidDecl())
7683 return false;
7684 }
7685
7686 return true;
7687}
7688
7689template <typename AttrTy>
7690static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7691 const TypedefNameDecl *TND = TT->getDecl();
7692 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7693 AttrTy *Clone = Attribute->clone(S.Context);
7694 Clone->setInherited(true);
7695 D->addAttr(A: Clone);
7696 }
7697}
7698
7699// This function emits warning and a corresponding note based on the
7700// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7701// declarations of an annotated type must be const qualified.
7702static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7703 QualType VarType = VD->getType().getCanonicalType();
7704
7705 // Ignore local declarations (for now) and those with const qualification.
7706 // TODO: Local variables should not be allowed if their type declaration has
7707 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7708 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7709 return;
7710
7711 if (VarType->isArrayType()) {
7712 // Retrieve element type for array declarations.
7713 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7714 }
7715
7716 const RecordDecl *RD = VarType->getAsRecordDecl();
7717
7718 // Check if the record declaration is present and if it has any attributes.
7719 if (RD == nullptr)
7720 return;
7721
7722 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7723 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7724 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7725 return;
7726 }
7727}
7728
7729void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7730 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7731 "NewD is not a function or variable");
7732
7733 if (PendingExportedNames.empty())
7734 return;
7735 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7736 if (getLangOpts().CPlusPlus && !FD->isExternC())
7737 return;
7738 }
7739 IdentifierInfo *IdentName = NewD->getIdentifier();
7740 if (IdentName == nullptr)
7741 return;
7742 auto PendingName = PendingExportedNames.find(Val: IdentName);
7743 if (PendingName != PendingExportedNames.end()) {
7744 auto &Label = PendingName->second;
7745 if (!Label.Used) {
7746 Label.Used = true;
7747 if (NewD->hasExternalFormalLinkage())
7748 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7749 else
7750 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7751 }
7752 }
7753}
7754
7755// Checks if VD is declared at global scope or with C language linkage.
7756static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7757 return Name.getAsIdentifierInfo() &&
7758 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7759 !VD->getDescribedVarTemplate() &&
7760 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7761 VD->isExternC());
7762}
7763
7764void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7765 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7766
7767 // Quickly return if the function does not have an `asm` attribute.
7768 if (E == nullptr)
7769 return;
7770
7771 // The parser guarantees this is a string.
7772 StringLiteral *SE = cast<StringLiteral>(Val: E);
7773 StringRef Label = SE->getString();
7774 QualType R = TInfo->getType();
7775 if (R->isIncompleteType())
7776 return;
7777 if (S->getFnParent() != nullptr) {
7778 switch (SC) {
7779 case SC_None:
7780 case SC_Auto:
7781 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7782 break;
7783 case SC_Register:
7784 // Local Named register
7785 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7786 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7787 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7788 break;
7789 case SC_Static:
7790 case SC_Extern:
7791 case SC_PrivateExtern:
7792 break;
7793 }
7794 } else if (SC == SC_Register) {
7795 // Global Named register
7796 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7797 const auto &TI = Context.getTargetInfo();
7798 bool HasSizeMismatch;
7799
7800 if (!TI.isValidGCCRegisterName(Name: Label))
7801 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7802 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7803 HasSizeMismatch))
7804 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7805 else if (HasSizeMismatch)
7806 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7807 }
7808
7809 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7810 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7811 DiagID: diag::err_asm_unsupported_register_type)
7812 << TInfo->getTypeLoc().getSourceRange();
7813 NewVD->setInvalidDecl(true);
7814 }
7815 }
7816}
7817
7818NamedDecl *Sema::ActOnVariableDeclarator(
7819 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7820 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7821 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7822 QualType R = TInfo->getType();
7823 DeclarationName Name = GetNameForDeclarator(D).getName();
7824
7825 IdentifierInfo *II = Name.getAsIdentifierInfo();
7826 bool IsPlaceholderVariable = false;
7827
7828 if (D.isDecompositionDeclarator()) {
7829 // Take the name of the first declarator as our name for diagnostic
7830 // purposes.
7831 auto &Decomp = D.getDecompositionDeclarator();
7832 if (!Decomp.bindings().empty()) {
7833 II = Decomp.bindings()[0].Name;
7834 Name = II;
7835 }
7836 } else if (!II) {
7837 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7838 return nullptr;
7839 }
7840
7841
7842 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7843 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7844 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7845 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7846
7847 IsPlaceholderVariable = true;
7848
7849 if (!Previous.empty()) {
7850 NamedDecl *PrevDecl = *Previous.begin();
7851 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7852 DC: DC->getRedeclContext());
7853 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7854 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7855 if (IsPlaceholderVariable)
7856 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7857 }
7858 }
7859 }
7860
7861 // dllimport globals without explicit storage class are treated as extern. We
7862 // have to change the storage class this early to get the right DeclContext.
7863 if (SC == SC_None && !DC->isRecord() &&
7864 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7865 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7866 SC = SC_Extern;
7867
7868 DeclContext *OriginalDC = DC;
7869 bool IsLocalExternDecl = SC == SC_Extern &&
7870 adjustContextForLocalExternDecl(DC);
7871
7872 if (SCSpec == DeclSpec::SCS_mutable) {
7873 // mutable can only appear on non-static class members, so it's always
7874 // an error here
7875 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7876 D.setInvalidType();
7877 SC = SC_None;
7878 }
7879
7880 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7881 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7882 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7883 // In C++11, the 'register' storage class specifier is deprecated.
7884 // Suppress the warning in system macros, it's used in macros in some
7885 // popular C system headers, such as in glibc's htonl() macro.
7886 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7887 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7888 : diag::warn_deprecated_register)
7889 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7890 }
7891
7892 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7893
7894 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7895 // C99 6.9p2: The storage-class specifiers auto and register shall not
7896 // appear in the declaration specifiers in an external declaration.
7897 // Global Register+Asm is a GNU extension we support.
7898 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7899 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7900 D.setInvalidType();
7901 }
7902 }
7903
7904 // If this variable has a VLA type and an initializer, try to
7905 // fold to a constant-sized type. This is otherwise invalid.
7906 if (D.hasInitializer() && R->isVariableArrayType())
7907 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7908 /*DiagID=*/FailedFoldDiagID: 0);
7909
7910 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7911 const AutoType *AT = TL.getTypePtr();
7912 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7913 }
7914
7915 bool IsMemberSpecialization = false;
7916 bool IsVariableTemplateSpecialization = false;
7917 bool IsPartialSpecialization = false;
7918 bool IsVariableTemplate = false;
7919 VarDecl *NewVD = nullptr;
7920 VarTemplateDecl *NewTemplate = nullptr;
7921 TemplateParameterList *TemplateParams = nullptr;
7922 if (!getLangOpts().CPlusPlus) {
7923 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7924 Id: II, T: R, TInfo, S: SC);
7925
7926 if (R->getContainedDeducedType())
7927 ParsingInitForAutoVars.insert(Ptr: NewVD);
7928
7929 if (D.isInvalidType())
7930 NewVD->setInvalidDecl();
7931
7932 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7933 NewVD->hasLocalStorage())
7934 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7935 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7936 } else {
7937 bool Invalid = false;
7938 // Match up the template parameter lists with the scope specifier, then
7939 // determine whether we have a template or a template specialization.
7940 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7941 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7942 SS: D.getCXXScopeSpec(),
7943 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7944 ? D.getName().TemplateId
7945 : nullptr,
7946 ParamLists: TemplateParamLists,
7947 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7948
7949 if (TemplateParams) {
7950 if (DC->isDependentContext()) {
7951 ContextRAII SavedContext(*this, DC);
7952 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7953 Invalid = true;
7954 }
7955
7956 if (!TemplateParams->size() &&
7957 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7958 // There is an extraneous 'template<>' for this variable. Complain
7959 // about it, but allow the declaration of the variable.
7960 Diag(Loc: TemplateParams->getTemplateLoc(),
7961 DiagID: diag::err_template_variable_noparams)
7962 << II
7963 << SourceRange(TemplateParams->getTemplateLoc(),
7964 TemplateParams->getRAngleLoc());
7965 TemplateParams = nullptr;
7966 } else {
7967 // Check that we can declare a template here.
7968 if (CheckTemplateDeclScope(S, TemplateParams))
7969 return nullptr;
7970
7971 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7972 // This is an explicit specialization or a partial specialization.
7973 IsVariableTemplateSpecialization = true;
7974 IsPartialSpecialization = TemplateParams->size() > 0;
7975 } else { // if (TemplateParams->size() > 0)
7976 // This is a template declaration.
7977 IsVariableTemplate = true;
7978
7979 // Only C++1y supports variable templates (N3651).
7980 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7981 }
7982 }
7983 } else {
7984 // Check that we can declare a member specialization here.
7985 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7986 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7987 return nullptr;
7988 assert((Invalid ||
7989 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7990 "should have a 'template<>' for this decl");
7991 }
7992
7993 bool IsExplicitSpecialization =
7994 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7995
7996 // C++ [temp.expl.spec]p2:
7997 // The declaration in an explicit-specialization shall not be an
7998 // export-declaration. An explicit specialization shall not use a
7999 // storage-class-specifier other than thread_local.
8000 //
8001 // We use the storage-class-specifier from DeclSpec because we may have
8002 // added implicit 'extern' for declarations with __declspec(dllimport)!
8003 if (SCSpec != DeclSpec::SCS_unspecified &&
8004 (IsExplicitSpecialization || IsMemberSpecialization)) {
8005 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8006 DiagID: diag::ext_explicit_specialization_storage_class)
8007 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8008 }
8009
8010 if (CurContext->isRecord()) {
8011 if (SC == SC_Static) {
8012 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
8013 // Walk up the enclosing DeclContexts to check for any that are
8014 // incompatible with static data members.
8015 const DeclContext *FunctionOrMethod = nullptr;
8016 const CXXRecordDecl *AnonStruct = nullptr;
8017 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8018 if (Ctxt->isFunctionOrMethod()) {
8019 FunctionOrMethod = Ctxt;
8020 break;
8021 }
8022 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
8023 if (ParentDecl && !ParentDecl->getDeclName()) {
8024 AnonStruct = ParentDecl;
8025 break;
8026 }
8027 }
8028 if (FunctionOrMethod) {
8029 // C++ [class.static.data]p5: A local class shall not have static
8030 // data members.
8031 Diag(Loc: D.getIdentifierLoc(),
8032 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
8033 << Name << RD->getDeclName() << RD->getTagKind();
8034 Invalid = true;
8035 } else if (AnonStruct) {
8036 // C++ [class.static.data]p4: Unnamed classes and classes contained
8037 // directly or indirectly within unnamed classes shall not contain
8038 // static data members.
8039 Diag(Loc: D.getIdentifierLoc(),
8040 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
8041 << Name << AnonStruct->getTagKind();
8042 Invalid = true;
8043 } else if (RD->isUnion()) {
8044 // C++98 [class.union]p1: If a union contains a static data member,
8045 // the program is ill-formed. C++11 drops this restriction.
8046 DiagCompat(Loc: D.getIdentifierLoc(),
8047 CompatDiagId: diag_compat::static_data_member_in_union)
8048 << Name;
8049 }
8050 }
8051 } else if (IsVariableTemplate || IsPartialSpecialization) {
8052 // There is no such thing as a member field template.
8053 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
8054 << II << TemplateParams->getSourceRange();
8055 // Recover by pretending this is a static data member template.
8056 SC = SC_Static;
8057 }
8058 } else if (DC->isRecord()) {
8059 // This is an out-of-line definition of a static data member.
8060 switch (SC) {
8061 case SC_None:
8062 break;
8063 case SC_Static:
8064 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8065 DiagID: diag::err_static_out_of_line)
8066 << FixItHint::CreateRemoval(
8067 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8068 break;
8069 case SC_Auto:
8070 case SC_Register:
8071 case SC_Extern:
8072 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8073 // to names of variables declared in a block or to function parameters.
8074 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8075 // of class members
8076
8077 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8078 DiagID: diag::err_storage_class_for_static_member)
8079 << FixItHint::CreateRemoval(
8080 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8081 break;
8082 case SC_PrivateExtern:
8083 llvm_unreachable("C storage class in c++!");
8084 }
8085 }
8086
8087 if (IsVariableTemplateSpecialization) {
8088 SourceLocation TemplateKWLoc =
8089 TemplateParamLists.size() > 0
8090 ? TemplateParamLists[0]->getTemplateLoc()
8091 : SourceLocation();
8092 DeclResult Res = ActOnVarTemplateSpecialization(
8093 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8094 IsPartialSpecialization);
8095 if (Res.isInvalid())
8096 return nullptr;
8097 NewVD = cast<VarDecl>(Val: Res.get());
8098 AddToScope = false;
8099 } else if (D.isDecompositionDeclarator()) {
8100 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8101 LSquareLoc: D.getIdentifierLoc(), RSquareLoc: D.getEndLoc(), T: R,
8102 TInfo, S: SC, Bindings);
8103 } else
8104 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8105 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8106
8107 // If this is supposed to be a variable template, create it as such.
8108 if (IsVariableTemplate) {
8109 NewTemplate =
8110 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8111 Params: TemplateParams, Decl: NewVD);
8112 NewVD->setDescribedVarTemplate(NewTemplate);
8113 }
8114
8115 // If this decl has an auto type in need of deduction, make a note of the
8116 // Decl so we can diagnose uses of it in its own initializer.
8117 if (R->getContainedDeducedType())
8118 ParsingInitForAutoVars.insert(Ptr: NewVD);
8119
8120 if (D.isInvalidType() || Invalid) {
8121 NewVD->setInvalidDecl();
8122 if (NewTemplate)
8123 NewTemplate->setInvalidDecl();
8124 }
8125
8126 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8127
8128 // If we have any template parameter lists that don't directly belong to
8129 // the variable (matching the scope specifier), store them.
8130 // An explicit variable template specialization does not own any template
8131 // parameter lists.
8132 unsigned VDTemplateParamLists =
8133 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8134 if (TemplateParamLists.size() > VDTemplateParamLists)
8135 NewVD->setTemplateParameterListsInfo(
8136 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8137 }
8138
8139 if (D.getDeclSpec().isInlineSpecified()) {
8140 if (!getLangOpts().CPlusPlus) {
8141 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8142 << 0;
8143 } else if (CurContext->isFunctionOrMethod()) {
8144 // 'inline' is not allowed on block scope variable declaration.
8145 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8146 DiagID: diag::err_inline_declaration_block_scope) << Name
8147 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8148 } else {
8149 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8150 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8151 : diag::compat_pre_cxx17_inline_variable);
8152 NewVD->setInlineSpecified();
8153 }
8154 }
8155
8156 // Set the lexical context. If the declarator has a C++ scope specifier, the
8157 // lexical context will be different from the semantic context.
8158 NewVD->setLexicalDeclContext(CurContext);
8159 if (NewTemplate)
8160 NewTemplate->setLexicalDeclContext(CurContext);
8161
8162 if (IsLocalExternDecl) {
8163 if (D.isDecompositionDeclarator())
8164 for (auto *B : Bindings)
8165 B->setLocalExternDecl();
8166 else
8167 NewVD->setLocalExternDecl();
8168 }
8169
8170 bool EmitTLSUnsupportedError = false;
8171 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8172 // C++11 [dcl.stc]p4:
8173 // When thread_local is applied to a variable of block scope the
8174 // storage-class-specifier static is implied if it does not appear
8175 // explicitly.
8176 // Core issue: 'static' is not implied if the variable is declared
8177 // 'extern'.
8178 if (NewVD->hasLocalStorage() &&
8179 (SCSpec != DeclSpec::SCS_unspecified ||
8180 TSCS != DeclSpec::TSCS_thread_local ||
8181 !DC->isFunctionOrMethod()))
8182 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8183 DiagID: diag::err_thread_non_global)
8184 << DeclSpec::getSpecifierName(S: TSCS);
8185 else if (!Context.getTargetInfo().isTLSSupported()) {
8186 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8187 // Postpone error emission until we've collected attributes required to
8188 // figure out whether it's a host or device variable and whether the
8189 // error should be ignored.
8190 EmitTLSUnsupportedError = true;
8191 // We still need to mark the variable as TLS so it shows up in AST with
8192 // proper storage class for other tools to use even if we're not going
8193 // to emit any code for it.
8194 NewVD->setTSCSpec(TSCS);
8195 } else
8196 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8197 DiagID: diag::err_thread_unsupported);
8198 } else
8199 NewVD->setTSCSpec(TSCS);
8200 }
8201
8202 switch (D.getDeclSpec().getConstexprSpecifier()) {
8203 case ConstexprSpecKind::Unspecified:
8204 break;
8205
8206 case ConstexprSpecKind::Consteval:
8207 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8208 DiagID: diag::err_constexpr_wrong_decl_kind)
8209 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8210 [[fallthrough]];
8211
8212 case ConstexprSpecKind::Constexpr:
8213 NewVD->setConstexpr(true);
8214 // C++1z [dcl.spec.constexpr]p1:
8215 // A static data member declared with the constexpr specifier is
8216 // implicitly an inline variable.
8217 if (NewVD->isStaticDataMember() &&
8218 (getLangOpts().CPlusPlus17 ||
8219 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8220 NewVD->setImplicitlyInline();
8221 break;
8222
8223 case ConstexprSpecKind::Constinit:
8224 if (!NewVD->hasGlobalStorage())
8225 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8226 DiagID: diag::err_constinit_local_variable);
8227 else
8228 NewVD->addAttr(
8229 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8230 S: ConstInitAttr::Keyword_constinit));
8231 break;
8232 }
8233
8234 // C99 6.7.4p3
8235 // An inline definition of a function with external linkage shall
8236 // not contain a definition of a modifiable object with static or
8237 // thread storage duration...
8238 // We only apply this when the function is required to be defined
8239 // elsewhere, i.e. when the function is not 'extern inline'. Note
8240 // that a local variable with thread storage duration still has to
8241 // be marked 'static'. Also note that it's possible to get these
8242 // semantics in C++ using __attribute__((gnu_inline)).
8243 if (SC == SC_Static && S->getFnParent() != nullptr &&
8244 !NewVD->getType().isConstQualified()) {
8245 FunctionDecl *CurFD = getCurFunctionDecl();
8246 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8247 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8248 DiagID: diag::warn_static_local_in_extern_inline);
8249 MaybeSuggestAddingStaticToDecl(D: CurFD);
8250 }
8251 }
8252
8253 if (D.getDeclSpec().isModulePrivateSpecified()) {
8254 if (IsVariableTemplateSpecialization)
8255 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8256 << (IsPartialSpecialization ? 1 : 0)
8257 << FixItHint::CreateRemoval(
8258 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8259 else if (IsMemberSpecialization)
8260 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8261 << 2
8262 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8263 else if (NewVD->hasLocalStorage())
8264 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8265 << 0 << NewVD
8266 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8267 << FixItHint::CreateRemoval(
8268 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8269 else {
8270 NewVD->setModulePrivate();
8271 if (NewTemplate)
8272 NewTemplate->setModulePrivate();
8273 for (auto *B : Bindings)
8274 B->setModulePrivate();
8275 }
8276 }
8277
8278 if (getLangOpts().OpenCL) {
8279 deduceOpenCLAddressSpace(Var: NewVD);
8280
8281 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8282 if (TSC != TSCS_unspecified) {
8283 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8284 DiagID: diag::err_opencl_unknown_type_specifier)
8285 << getLangOpts().getOpenCLVersionString()
8286 << DeclSpec::getSpecifierName(S: TSC) << 1;
8287 NewVD->setInvalidDecl();
8288 }
8289 }
8290
8291 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8292 // address space if the table has local storage (semantic checks elsewhere
8293 // will produce an error anyway).
8294 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8295 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8296 !NewVD->hasLocalStorage()) {
8297 QualType Type = Context.getAddrSpaceQualType(
8298 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8299 NewVD->setType(Type);
8300 }
8301 }
8302
8303 LoadExternalExtnameUndeclaredIdentifiers();
8304
8305 if (Expr *E = D.getAsmLabel()) {
8306 // The parser guarantees this is a string.
8307 StringLiteral *SE = cast<StringLiteral>(Val: E);
8308 StringRef Label = SE->getString();
8309
8310 // Insert the asm attribute.
8311 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8312 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8313 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8314 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8315 if (I != ExtnameUndeclaredIdentifiers.end()) {
8316 if (isDeclExternC(D: NewVD)) {
8317 NewVD->addAttr(A: I->second);
8318 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8319 } else if (NewVD->getDeclContext()
8320 ->getRedeclContext()
8321 ->isTranslationUnit())
8322 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8323 << /*Variable*/ 1 << NewVD;
8324 }
8325 }
8326
8327 // Handle attributes prior to checking for duplicates in MergeVarDecl
8328 ProcessDeclAttributes(S, D: NewVD, PD: D);
8329
8330 if (getLangOpts().HLSL)
8331 HLSL().ActOnVariableDeclarator(VD: NewVD);
8332
8333 if (getLangOpts().OpenACC)
8334 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8335
8336 // FIXME: This is probably the wrong location to be doing this and we should
8337 // probably be doing this for more attributes (especially for function
8338 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8339 // the code to copy attributes would be generated by TableGen.
8340 if (R->isFunctionPointerType())
8341 if (const auto *TT = R->getAs<TypedefType>())
8342 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8343
8344 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8345 if (EmitTLSUnsupportedError &&
8346 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8347 (getLangOpts().OpenMPIsTargetDevice &&
8348 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8349 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8350 DiagID: diag::err_thread_unsupported);
8351
8352 if (EmitTLSUnsupportedError &&
8353 (LangOpts.SYCLIsDevice ||
8354 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8355 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8356 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8357 // storage [duration]."
8358 if (SC == SC_None && S->getFnParent() != nullptr &&
8359 (NewVD->hasAttr<CUDASharedAttr>() ||
8360 NewVD->hasAttr<CUDAConstantAttr>())) {
8361 NewVD->setStorageClass(SC_Static);
8362 }
8363 }
8364
8365 // Ensure that dllimport globals without explicit storage class are treated as
8366 // extern. The storage class is set above using parsed attributes. Now we can
8367 // check the VarDecl itself.
8368 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8369 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8370 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8371
8372 // In auto-retain/release, infer strong retension for variables of
8373 // retainable type.
8374 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8375 NewVD->setInvalidDecl();
8376
8377 // Check the ASM label here, as we need to know all other attributes of the
8378 // Decl first. Otherwise, we can't know if the asm label refers to the
8379 // host or device in a CUDA context. The device has other registers than
8380 // host and we must know where the function will be placed.
8381 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8382
8383 // Find the shadowed declaration before filtering for scope.
8384 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8385 ? getShadowedDeclaration(D: NewVD, R: Previous)
8386 : nullptr;
8387
8388 // Don't consider existing declarations that are in a different
8389 // scope and are out-of-semantic-context declarations (if the new
8390 // declaration has linkage).
8391 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8392 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8393 IsMemberSpecialization ||
8394 IsVariableTemplateSpecialization);
8395
8396 // Check whether the previous declaration is in the same block scope. This
8397 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8398 if (getLangOpts().CPlusPlus &&
8399 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8400 NewVD->setPreviousDeclInSameBlockScope(
8401 Previous.isSingleResult() && !Previous.isShadowed() &&
8402 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8403
8404 if (!getLangOpts().CPlusPlus) {
8405 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8406 } else {
8407 // If this is an explicit specialization of a static data member, check it.
8408 if (IsMemberSpecialization && !IsVariableTemplate &&
8409 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8410 CheckMemberSpecialization(Member: NewVD, Previous))
8411 NewVD->setInvalidDecl();
8412
8413 // Merge the decl with the existing one if appropriate.
8414 if (!Previous.empty()) {
8415 if (Previous.isSingleResult() &&
8416 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8417 D.getCXXScopeSpec().isSet()) {
8418 // The user tried to define a non-static data member
8419 // out-of-line (C++ [dcl.meaning]p1).
8420 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8421 << D.getCXXScopeSpec().getRange();
8422 Previous.clear();
8423 NewVD->setInvalidDecl();
8424 }
8425 } else if (D.getCXXScopeSpec().isSet() &&
8426 !IsVariableTemplateSpecialization) {
8427 // No previous declaration in the qualifying scope.
8428 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8429 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8430 << D.getCXXScopeSpec().getRange();
8431 NewVD->setInvalidDecl();
8432
8433 // if this is a member specialization, we don't have any primary template
8434 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8435 // that anything that attempts to refer to this invalid declaration can
8436 // act as if there IS a primary instantiation.
8437 if (NewTemplate && IsMemberSpecialization) {
8438 VarDecl *FakeVD =
8439 VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
8440 Id: II, T: R, TInfo, S: SC);
8441 FakeVD->setInvalidDecl();
8442 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8443 C&: Context, DC, L: D.getIdentifierLoc(), Name, Params: TemplateParams, Decl: FakeVD);
8444 FakeInstantiatedFrom->setInvalidDecl();
8445 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8446 }
8447 }
8448
8449 if (!IsPlaceholderVariable)
8450 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8451
8452 // CheckVariableDeclaration will set NewVD as invalid if something is in
8453 // error like WebAssembly tables being declared as arrays with a non-zero
8454 // size, but then parsing continues and emits further errors on that line.
8455 // To avoid that we check here if it happened and return nullptr.
8456 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8457 return nullptr;
8458
8459 if (NewTemplate) {
8460 VarTemplateDecl *PrevVarTemplate =
8461 NewVD->getPreviousDecl()
8462 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8463 : nullptr;
8464
8465 // Check the template parameter list of this declaration, possibly
8466 // merging in the template parameter list from the previous variable
8467 // template declaration.
8468 if (CheckTemplateParameterList(
8469 NewParams: TemplateParams,
8470 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8471 : nullptr,
8472 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8473 DC->isDependentContext())
8474 ? TPC_ClassTemplateMember
8475 : TPC_Other))
8476 NewVD->setInvalidDecl();
8477 }
8478 }
8479
8480 if (IsMemberSpecialization) {
8481 if (NewTemplate && NewVD->getPreviousDecl()) {
8482 NewTemplate->setMemberSpecialization();
8483 } else if (IsPartialSpecialization) {
8484 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8485 ->setMemberSpecialization();
8486 }
8487 }
8488
8489 // Diagnose shadowed variables iff this isn't a redeclaration.
8490 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8491 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8492
8493 ProcessPragmaWeak(S, D: NewVD);
8494 ProcessPragmaExport(NewD: NewVD);
8495
8496 // If this is the first declaration of an extern C variable, update
8497 // the map of such variables.
8498 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8499 isIncompleteDeclExternC(S&: *this, D: NewVD))
8500 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8501
8502 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8503 MangleNumberingContext *MCtx;
8504 Decl *ManglingContextDecl;
8505 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8506 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8507 if (MCtx) {
8508 Context.setManglingNumber(
8509 ND: NewVD, Number: MCtx->getManglingNumber(
8510 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8511 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8512 }
8513 }
8514
8515 // Special handling of variable named 'main'.
8516 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8517 // C++ [basic.start.main]p3:
8518 // A program that declares
8519 // - a variable main at global scope, or
8520 // - an entity named main with C language linkage (in any namespace)
8521 // is ill-formed
8522 if (getLangOpts().CPlusPlus)
8523 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8524 << NewVD->isExternC();
8525
8526 // In C, and external-linkage variable named main results in undefined
8527 // behavior.
8528 else if (NewVD->hasExternalFormalLinkage())
8529 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8530 }
8531
8532 if (D.isRedeclaration() && !Previous.empty()) {
8533 NamedDecl *Prev = Previous.getRepresentativeDecl();
8534 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8535 IsDefinition: D.isFunctionDefinition());
8536 }
8537
8538 if (NewTemplate) {
8539 if (NewVD->isInvalidDecl())
8540 NewTemplate->setInvalidDecl();
8541 ActOnDocumentableDecl(D: NewTemplate);
8542 return NewTemplate;
8543 }
8544
8545 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8546 CompleteMemberSpecialization(Member: NewVD, Previous);
8547
8548 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8549
8550 return NewVD;
8551}
8552
8553/// Enum describing the %select options in diag::warn_decl_shadow.
8554enum ShadowedDeclKind {
8555 SDK_Local,
8556 SDK_Global,
8557 SDK_StaticMember,
8558 SDK_Field,
8559 SDK_Typedef,
8560 SDK_Using,
8561 SDK_StructuredBinding
8562};
8563
8564/// Determine what kind of declaration we're shadowing.
8565static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8566 const DeclContext *OldDC) {
8567 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8568 return SDK_Using;
8569 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8570 return SDK_Typedef;
8571 else if (isa<BindingDecl>(Val: ShadowedDecl))
8572 return SDK_StructuredBinding;
8573 else if (isa<RecordDecl>(Val: OldDC))
8574 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8575
8576 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8577}
8578
8579/// Return the location of the capture if the given lambda captures the given
8580/// variable \p VD, or an invalid source location otherwise.
8581static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8582 const ValueDecl *VD) {
8583 for (const Capture &Capture : LSI->Captures) {
8584 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8585 return Capture.getLocation();
8586 }
8587 return SourceLocation();
8588}
8589
8590static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8591 const LookupResult &R) {
8592 // Only diagnose if we're shadowing an unambiguous field or variable.
8593 if (R.getResultKind() != LookupResultKind::Found)
8594 return false;
8595
8596 // Return false if warning is ignored.
8597 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8598}
8599
8600NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8601 const LookupResult &R) {
8602 if (!shouldWarnIfShadowedDecl(Diags, R))
8603 return nullptr;
8604
8605 // Don't diagnose declarations at file scope.
8606 if (D->hasGlobalStorage() && !D->isStaticLocal())
8607 return nullptr;
8608
8609 NamedDecl *ShadowedDecl = R.getFoundDecl();
8610 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8611 : nullptr;
8612}
8613
8614NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8615 const LookupResult &R) {
8616 // Don't warn if typedef declaration is part of a class
8617 if (D->getDeclContext()->isRecord())
8618 return nullptr;
8619
8620 if (!shouldWarnIfShadowedDecl(Diags, R))
8621 return nullptr;
8622
8623 NamedDecl *ShadowedDecl = R.getFoundDecl();
8624 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8625}
8626
8627NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8628 const LookupResult &R) {
8629 if (!shouldWarnIfShadowedDecl(Diags, R))
8630 return nullptr;
8631
8632 NamedDecl *ShadowedDecl = R.getFoundDecl();
8633 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8634 : nullptr;
8635}
8636
8637void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8638 const LookupResult &R) {
8639 DeclContext *NewDC = D->getDeclContext();
8640
8641 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8642 DeclContext *FnDC = getFunctionLevelDeclContext();
8643 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDC)) {
8644 // Fields aren't shadowed in C++ static members or in member functions
8645 // with an explicit object parameter.
8646 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8647 return;
8648 } else if (isa<FunctionDecl>(Val: FnDC)) {
8649 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8650 // inline-defined friend function, since that's the only way to
8651 // introduce a non-member function inside a class body. Friends have
8652 // no implicit `this`, so nothing here can shadow a field.
8653 return;
8654 }
8655 // Fields shadowed by constructor parameters are a special case. Usually
8656 // the constructor initializes the field with the parameter.
8657 if (isa<CXXConstructorDecl>(Val: NewDC))
8658 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8659 // Remember that this was shadowed so we can either warn about its
8660 // modification or its existence depending on warning settings.
8661 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8662 return;
8663 }
8664 }
8665
8666 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8667 if (shadowedVar->isExternC()) {
8668 // For shadowing external vars, make sure that we point to the global
8669 // declaration, not a locally scoped extern declaration.
8670 for (auto *I : shadowedVar->redecls())
8671 if (I->isFileVarDecl()) {
8672 ShadowedDecl = I;
8673 break;
8674 }
8675 }
8676
8677 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8678
8679 unsigned WarningDiag = diag::warn_decl_shadow;
8680 SourceLocation CaptureLoc;
8681 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8682 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8683 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8684 // Handle both VarDecl and BindingDecl in lambda contexts
8685 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8686 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8687 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8688 if (RD->getLambdaCaptureDefault() == LCD_None) {
8689 // Try to avoid warnings for lambdas with an explicit capture
8690 // list. Warn only when the lambda captures the shadowed decl
8691 // explicitly.
8692 CaptureLoc = getCaptureLocation(LSI, VD);
8693 if (CaptureLoc.isInvalid())
8694 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8695 } else {
8696 // Remember that this was shadowed so we can avoid the warning if
8697 // the shadowed decl isn't captured and the warning settings allow
8698 // it.
8699 cast<LambdaScopeInfo>(Val: getCurFunction())
8700 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8701 return;
8702 }
8703 }
8704 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8705 // If lambda can capture this, then emit default shadowing warning,
8706 // Otherwise it is not really a shadowing case since field is not
8707 // available in lambda's body.
8708 // At this point we don't know that lambda can capture this, so
8709 // remember that this was shadowed and delay until we know.
8710 cast<LambdaScopeInfo>(Val: getCurFunction())
8711 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8712 return;
8713 }
8714 }
8715 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8716 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8717 bool HasLocalStorage = false;
8718 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8719 HasLocalStorage = VD->hasLocalStorage();
8720 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8721 HasLocalStorage =
8722 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8723
8724 if (HasLocalStorage) {
8725 // A variable can't shadow a local variable or binding in an enclosing
8726 // scope, if they are separated by a non-capturing declaration
8727 // context.
8728 for (DeclContext *ParentDC = NewDC;
8729 ParentDC && !ParentDC->Equals(DC: OldDC);
8730 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8731 // Only block literals, captured statements, and lambda expressions
8732 // can capture; other scopes don't.
8733 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8734 !isLambdaCallOperator(DC: ParentDC))
8735 return;
8736 }
8737 }
8738 }
8739 }
8740 }
8741
8742 // Never warn about shadowing a placeholder variable.
8743 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8744 return;
8745
8746 // Only warn about certain kinds of shadowing for class members.
8747 if (NewDC) {
8748 // In particular, don't warn about shadowing non-class members.
8749 if (NewDC->isRecord() && !OldDC->isRecord())
8750 return;
8751
8752 // Skip shadowing check if we're in a class scope, dealing with an enum
8753 // constant in a different context.
8754 DeclContext *ReDC = NewDC->getRedeclContext();
8755 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8756 return;
8757
8758 // TODO: should we warn about static data members shadowing
8759 // static data members from base classes?
8760
8761 // TODO: don't diagnose for inaccessible shadowed members.
8762 // This is hard to do perfectly because we might friend the
8763 // shadowing context, but that's just a false negative.
8764 }
8765
8766 DeclarationName Name = R.getLookupName();
8767
8768 // Emit warning and note.
8769 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8770 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8771 if (!CaptureLoc.isInvalid())
8772 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8773 << Name << /*explicitly*/ 1;
8774 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8775}
8776
8777void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8778 for (const auto &Shadow : LSI->ShadowingDecls) {
8779 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8780 // Try to avoid the warning when the shadowed decl isn't captured.
8781 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8782 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8783 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8784 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8785 Diag(Loc: Shadow.VD->getLocation(),
8786 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8787 : diag::warn_decl_shadow)
8788 << Shadow.VD->getDeclName()
8789 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8790 if (CaptureLoc.isValid())
8791 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8792 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8793 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8794 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8795 Diag(Loc: Shadow.VD->getLocation(),
8796 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8797 : diag::warn_decl_shadow_uncaptured_local)
8798 << Shadow.VD->getDeclName()
8799 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8800 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8801 }
8802 }
8803}
8804
8805void Sema::CheckShadow(Scope *S, VarDecl *D) {
8806 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8807 return;
8808
8809 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8810 Sema::LookupOrdinaryName,
8811 RedeclarationKind::ForVisibleRedeclaration);
8812 LookupName(R, S);
8813 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8814 CheckShadow(D, ShadowedDecl, R);
8815}
8816
8817/// Check if 'E', which is an expression that is about to be modified, refers
8818/// to a constructor parameter that shadows a field.
8819void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8820 // Quickly ignore expressions that can't be shadowing ctor parameters.
8821 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8822 return;
8823 E = E->IgnoreParenImpCasts();
8824 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8825 if (!DRE)
8826 return;
8827 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8828 auto I = ShadowingDecls.find(Val: D);
8829 if (I == ShadowingDecls.end())
8830 return;
8831 const NamedDecl *ShadowedDecl = I->second;
8832 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8833 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8834 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8835 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8836
8837 // Avoid issuing multiple warnings about the same decl.
8838 ShadowingDecls.erase(I);
8839}
8840
8841/// Check for conflict between this global or extern "C" declaration and
8842/// previous global or extern "C" declarations. This is only used in C++.
8843template<typename T>
8844static bool checkGlobalOrExternCConflict(
8845 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8846 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8847 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8848
8849 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8850 // The common case: this global doesn't conflict with any extern "C"
8851 // declaration.
8852 return false;
8853 }
8854
8855 if (Prev) {
8856 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8857 // Both the old and new declarations have C language linkage. This is a
8858 // redeclaration.
8859 Previous.clear();
8860 Previous.addDecl(D: Prev);
8861 return true;
8862 }
8863
8864 // This is a global, non-extern "C" declaration, and there is a previous
8865 // non-global extern "C" declaration. Diagnose if this is a variable
8866 // declaration.
8867 if (!isa<VarDecl>(ND))
8868 return false;
8869 } else {
8870 // The declaration is extern "C". Check for any declaration in the
8871 // translation unit which might conflict.
8872 if (IsGlobal) {
8873 // We have already performed the lookup into the translation unit.
8874 IsGlobal = false;
8875 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8876 I != E; ++I) {
8877 if (isa<VarDecl>(Val: *I)) {
8878 Prev = *I;
8879 break;
8880 }
8881 }
8882 } else {
8883 DeclContext::lookup_result R =
8884 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8885 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8886 I != E; ++I) {
8887 if (isa<VarDecl>(Val: *I)) {
8888 Prev = *I;
8889 break;
8890 }
8891 // FIXME: If we have any other entity with this name in global scope,
8892 // the declaration is ill-formed, but that is a defect: it breaks the
8893 // 'stat' hack, for instance. Only variables can have mangled name
8894 // clashes with extern "C" declarations, so only they deserve a
8895 // diagnostic.
8896 }
8897 }
8898
8899 if (!Prev)
8900 return false;
8901 }
8902
8903 // Use the first declaration's location to ensure we point at something which
8904 // is lexically inside an extern "C" linkage-spec.
8905 assert(Prev && "should have found a previous declaration to diagnose");
8906 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8907 Prev = FD->getFirstDecl();
8908 else
8909 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8910
8911 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8912 << IsGlobal << ND;
8913 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8914 << IsGlobal;
8915 return false;
8916}
8917
8918/// Apply special rules for handling extern "C" declarations. Returns \c true
8919/// if we have found that this is a redeclaration of some prior entity.
8920///
8921/// Per C++ [dcl.link]p6:
8922/// Two declarations [for a function or variable] with C language linkage
8923/// with the same name that appear in different scopes refer to the same
8924/// [entity]. An entity with C language linkage shall not be declared with
8925/// the same name as an entity in global scope.
8926template<typename T>
8927static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8928 LookupResult &Previous) {
8929 if (!S.getLangOpts().CPlusPlus) {
8930 // In C, when declaring a global variable, look for a corresponding 'extern'
8931 // variable declared in function scope. We don't need this in C++, because
8932 // we find local extern decls in the surrounding file-scope DeclContext.
8933 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8934 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8935 Previous.clear();
8936 Previous.addDecl(D: Prev);
8937 return true;
8938 }
8939 }
8940 return false;
8941 }
8942
8943 // A declaration in the translation unit can conflict with an extern "C"
8944 // declaration.
8945 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8946 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8947
8948 // An extern "C" declaration can conflict with a declaration in the
8949 // translation unit or can be a redeclaration of an extern "C" declaration
8950 // in another scope.
8951 if (isIncompleteDeclExternC(S,ND))
8952 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8953
8954 // Neither global nor extern "C": nothing to do.
8955 return false;
8956}
8957
8958static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8959 QualType T) {
8960 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8961 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8962 // any of its members, even recursively, shall not have an atomic type, or a
8963 // variably modified type, or a type that is volatile or restrict qualified.
8964 if (CanonT->isVariablyModifiedType()) {
8965 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8966 return true;
8967 }
8968
8969 // Arrays are qualified by their element type, so get the base type (this
8970 // works on non-arrays as well).
8971 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8972
8973 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8974 CanonT.isRestrictQualified()) {
8975 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8976 return true;
8977 }
8978
8979 if (CanonT->isRecordType()) {
8980 const RecordDecl *RD = CanonT->getAsRecordDecl();
8981 if (!RD->isInvalidDecl() &&
8982 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8983 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8984 }))
8985 return true;
8986 }
8987
8988 return false;
8989}
8990
8991static bool isSYCLAddressSpace(LangAS AS) {
8992 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
8993}
8994
8995void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8996 // If the decl is already known invalid, don't check it.
8997 if (NewVD->isInvalidDecl())
8998 return;
8999
9000 QualType T = NewVD->getType();
9001
9002 // Defer checking an 'auto' type until its initializer is attached.
9003 if (T->isUndeducedType())
9004 return;
9005
9006 if (NewVD->hasAttrs())
9007 CheckAlignasUnderalignment(D: NewVD);
9008
9009 if (T->isObjCObjectType()) {
9010 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
9011 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
9012 T = Context.getObjCObjectPointerType(OIT: T);
9013 NewVD->setType(T);
9014 }
9015
9016 // The top-level type of a variable declaration cannot have a SYCL address
9017 // space qualifier.
9018 if (getLangOpts().isSYCL()) {
9019 LangAS AS = Context.getBaseElementType(QT: T).getAddressSpace();
9020 if (isSYCLAddressSpace(AS)) {
9021 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sycl_address_space_qualified_object)
9022 << Qualifiers::getAddrSpaceAsString(AS);
9023 NewVD->setInvalidDecl();
9024 return;
9025 }
9026 }
9027
9028 // Emit an error if an address space was applied to decl with local storage.
9029 // This includes arrays of objects with address space qualifiers, but not
9030 // automatic variables that point to other address spaces.
9031 // ISO/IEC TR 18037 S5.1.2
9032 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9033 T.getAddressSpace() != LangAS::Default) {
9034 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
9035 NewVD->setInvalidDecl();
9036 return;
9037 }
9038
9039 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9040 // scope.
9041 if (getLangOpts().OpenCLVersion == 120 &&
9042 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
9043 LO: getLangOpts()) &&
9044 NewVD->isStaticLocal()) {
9045 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
9046 NewVD->setInvalidDecl();
9047 return;
9048 }
9049
9050 if (getLangOpts().OpenCL) {
9051 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
9052 return;
9053
9054 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9055 if (NewVD->hasAttr<BlocksAttr>()) {
9056 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
9057 return;
9058 }
9059
9060 if (T->isBlockPointerType()) {
9061 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9062 // can't use 'extern' storage class.
9063 if (!T.isConstQualified()) {
9064 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
9065 << 0 /*const*/;
9066 NewVD->setInvalidDecl();
9067 return;
9068 }
9069 if (NewVD->hasExternalStorage()) {
9070 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
9071 NewVD->setInvalidDecl();
9072 return;
9073 }
9074 }
9075
9076 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9077 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9078 NewVD->hasExternalStorage()) {
9079 if (!T->isSamplerT() && !T->isDependentType() &&
9080 !(T.getAddressSpace() == LangAS::opencl_constant ||
9081 (T.getAddressSpace() == LangAS::opencl_global &&
9082 getOpenCLOptions().areProgramScopeVariablesSupported(
9083 Opts: getLangOpts())))) {
9084 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9085 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
9086 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9087 << Scope << "global or constant";
9088 else
9089 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9090 << Scope << "constant";
9091 NewVD->setInvalidDecl();
9092 return;
9093 }
9094 } else {
9095 if (T.getAddressSpace() == LangAS::opencl_global) {
9096 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9097 << 1 /*is any function*/ << "global";
9098 NewVD->setInvalidDecl();
9099 return;
9100 }
9101 // When this extension is enabled, 'local' variables are permitted in
9102 // non-kernel functions and within nested scopes of kernel functions,
9103 // bypassing standard OpenCL address space restrictions.
9104 bool AllowFunctionScopeLocalVariables =
9105 T.getAddressSpace() == LangAS::opencl_local &&
9106 getOpenCLOptions().isAvailableOption(
9107 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9108 if (AllowFunctionScopeLocalVariables) {
9109 // Direct pass: No further diagnostics needed for this specific case.
9110 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9111 T.getAddressSpace() == LangAS::opencl_local) {
9112 FunctionDecl *FD = getCurFunctionDecl();
9113 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9114 // in functions.
9115 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9116 if (T.getAddressSpace() == LangAS::opencl_constant)
9117 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9118 << 0 /*non-kernel only*/ << "constant";
9119 else
9120 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9121 << 0 /*non-kernel only*/ << "local";
9122 NewVD->setInvalidDecl();
9123 return;
9124 }
9125 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9126 // in the outermost scope of a kernel function.
9127 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9128 if (!getCurScope()->isFunctionScope()) {
9129 if (T.getAddressSpace() == LangAS::opencl_constant)
9130 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9131 << "constant";
9132 else
9133 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9134 << "local";
9135 NewVD->setInvalidDecl();
9136 return;
9137 }
9138 }
9139 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9140 // If we are parsing a template we didn't deduce an addr
9141 // space yet.
9142 T.getAddressSpace() != LangAS::Default) {
9143 // Do not allow other address spaces on automatic variable.
9144 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9145 NewVD->setInvalidDecl();
9146 return;
9147 }
9148 }
9149 }
9150
9151 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9152 && !NewVD->hasAttr<BlocksAttr>()) {
9153 if (getLangOpts().getGC() != LangOptions::NonGC)
9154 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9155 else {
9156 assert(!getLangOpts().ObjCAutoRefCount);
9157 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9158 }
9159 }
9160
9161 // WebAssembly tables must be static with a zero length and can't be
9162 // declared within functions.
9163 if (T->isWebAssemblyTableType()) {
9164 if (getCurScope()->getParent()) { // Parent is null at top-level
9165 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9166 NewVD->setInvalidDecl();
9167 return;
9168 }
9169 if (NewVD->getStorageClass() != SC_Static) {
9170 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9171 NewVD->setInvalidDecl();
9172 return;
9173 }
9174 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9175 if (!ATy || ATy->getZExtSize() != 0) {
9176 Diag(Loc: NewVD->getLocation(),
9177 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9178 NewVD->setInvalidDecl();
9179 return;
9180 }
9181 }
9182
9183 // zero sized static arrays are not allowed in HIP device functions
9184 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9185 if (FunctionDecl *FD = getCurFunctionDecl();
9186 FD &&
9187 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9188 if (const ConstantArrayType *ArrayT =
9189 getASTContext().getAsConstantArrayType(T);
9190 ArrayT && ArrayT->isZeroSize()) {
9191 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9192 }
9193 }
9194 }
9195
9196 bool isVM = T->isVariablyModifiedType();
9197 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9198 NewVD->hasAttr<BlocksAttr>())
9199 setFunctionHasBranchProtectedScope();
9200
9201 if ((isVM && NewVD->hasLinkage()) ||
9202 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9203 bool SizeIsNegative;
9204 llvm::APSInt Oversized;
9205 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9206 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9207 QualType FixedT;
9208 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9209 FixedT = FixedTInfo->getType();
9210 else if (FixedTInfo) {
9211 // Type and type-as-written are canonically different. We need to fix up
9212 // both types separately.
9213 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9214 Oversized);
9215 }
9216 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9217 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9218 // FIXME: This won't give the correct result for
9219 // int a[10][n];
9220 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9221
9222 if (NewVD->isFileVarDecl())
9223 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9224 << SizeRange;
9225 else if (NewVD->isStaticLocal())
9226 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9227 << SizeRange;
9228 else
9229 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9230 << SizeRange;
9231 NewVD->setInvalidDecl();
9232 return;
9233 }
9234
9235 if (!FixedTInfo) {
9236 if (NewVD->isFileVarDecl())
9237 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9238 else
9239 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9240 NewVD->setInvalidDecl();
9241 return;
9242 }
9243
9244 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9245 NewVD->setType(FixedT);
9246 NewVD->setTypeSourceInfo(FixedTInfo);
9247 }
9248
9249 if (T->isVoidType()) {
9250 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9251 // of objects and functions.
9252 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9253 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9254 << T;
9255 NewVD->setInvalidDecl();
9256 return;
9257 }
9258 }
9259
9260 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9261 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9262 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9263 NewVD->setInvalidDecl();
9264 return;
9265 }
9266
9267 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9268 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9269 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9270 NewVD->setInvalidDecl();
9271 return;
9272 }
9273
9274 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9275 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9276 NewVD->setInvalidDecl();
9277 return;
9278 }
9279
9280 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9281 !T->isDependentType() &&
9282 RequireLiteralType(Loc: NewVD->getLocation(), T,
9283 DiagID: diag::err_constexpr_var_non_literal)) {
9284 NewVD->setInvalidDecl();
9285 return;
9286 }
9287
9288 // PPC MMA non-pointer types are not allowed as non-local variable types.
9289 if (Context.getTargetInfo().getTriple().isPPC64() &&
9290 !NewVD->isLocalVarDecl() &&
9291 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9292 NewVD->setInvalidDecl();
9293 return;
9294 }
9295
9296 // Check that SVE types are only used in functions with SVE available.
9297 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9298 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9299 llvm::StringMap<bool> CallerFeatureMap;
9300 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9301 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9302 FeatureMap: CallerFeatureMap)) {
9303 NewVD->setInvalidDecl();
9304 return;
9305 }
9306 }
9307
9308 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9309 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9310 llvm::StringMap<bool> CallerFeatureMap;
9311 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9312 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9313 FeatureMap: CallerFeatureMap);
9314 }
9315
9316 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9317 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewVD->getLocation())) {
9318 NewVD->setInvalidDecl();
9319 return;
9320 }
9321 }
9322
9323 if (T.hasAddressSpace() &&
9324 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9325 NewVD->setInvalidDecl();
9326 return;
9327 }
9328}
9329
9330bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9331 CheckVariableDeclarationType(NewVD);
9332
9333 // If the decl is already known invalid, don't check it.
9334 if (NewVD->isInvalidDecl())
9335 return false;
9336
9337 // If we did not find anything by this name, look for a non-visible
9338 // extern "C" declaration with the same name.
9339 if (Previous.empty() &&
9340 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9341 Previous.setShadowed();
9342
9343 if (!Previous.empty()) {
9344 MergeVarDecl(New: NewVD, Previous);
9345 return true;
9346 }
9347 return false;
9348}
9349
9350bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9351 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9352
9353 // Look for methods in base classes that this method might override.
9354 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9355 /*DetectVirtual=*/false);
9356 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9357 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9358 DeclarationName Name = MD->getDeclName();
9359
9360 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9361 // We really want to find the base class destructor here.
9362 Name = Context.DeclarationNames.getCXXDestructorName(
9363 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9364 }
9365
9366 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9367 CXXMethodDecl *BaseMD =
9368 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9369 if (!BaseMD || !BaseMD->isVirtual() ||
9370 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9371 /*ConsiderCudaAttrs=*/true))
9372 continue;
9373 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9374 continue;
9375 if (Overridden.insert(Ptr: BaseMD).second) {
9376 MD->addOverriddenMethod(MD: BaseMD);
9377 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9378 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9379 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9380 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9381 }
9382
9383 // A method can only override one function from each base class. We
9384 // don't track indirectly overridden methods from bases of bases.
9385 return true;
9386 }
9387
9388 return false;
9389 };
9390
9391 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9392 return !Overridden.empty();
9393}
9394
9395namespace {
9396 // Struct for holding all of the extra arguments needed by
9397 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9398 struct ActOnFDArgs {
9399 Scope *S;
9400 Declarator &D;
9401 MultiTemplateParamsArg TemplateParamLists;
9402 bool AddToScope;
9403 };
9404} // end anonymous namespace
9405
9406namespace {
9407
9408// Callback to only accept typo corrections that have a non-zero edit distance.
9409// Also only accept corrections that have the same parent decl.
9410class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9411 public:
9412 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9413 CXXRecordDecl *Parent)
9414 : Context(Context), OriginalFD(TypoFD),
9415 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9416
9417 bool ValidateCandidate(const TypoCorrection &candidate) override {
9418 if (candidate.getEditDistance() == 0)
9419 return false;
9420
9421 SmallVector<unsigned, 1> MismatchedParams;
9422 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9423 CDeclEnd = candidate.end();
9424 CDecl != CDeclEnd; ++CDecl) {
9425 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9426
9427 if (FD && !FD->hasBody() &&
9428 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9429 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9430 CXXRecordDecl *Parent = MD->getParent();
9431 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9432 return true;
9433 } else if (!ExpectedParent) {
9434 return true;
9435 }
9436 }
9437 }
9438
9439 return false;
9440 }
9441
9442 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9443 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9444 }
9445
9446 private:
9447 ASTContext &Context;
9448 FunctionDecl *OriginalFD;
9449 CXXRecordDecl *ExpectedParent;
9450};
9451
9452} // end anonymous namespace
9453
9454void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9455 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9456}
9457
9458/// Generate diagnostics for an invalid function redeclaration.
9459///
9460/// This routine handles generating the diagnostic messages for an invalid
9461/// function redeclaration, including finding possible similar declarations
9462/// or performing typo correction if there are no previous declarations with
9463/// the same name.
9464///
9465/// Returns a NamedDecl iff typo correction was performed and substituting in
9466/// the new declaration name does not cause new errors.
9467static NamedDecl *DiagnoseInvalidRedeclaration(
9468 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9469 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9470 DeclarationName Name = NewFD->getDeclName();
9471 DeclContext *NewDC = NewFD->getDeclContext();
9472 SmallVector<unsigned, 1> MismatchedParams;
9473 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9474 TypoCorrection Correction;
9475 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9476 unsigned DiagMsg =
9477 IsLocalFriend ? diag::err_no_matching_local_friend :
9478 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9479 diag::err_member_decl_does_not_match;
9480 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9481 IsLocalFriend ? Sema::LookupLocalFriendName
9482 : Sema::LookupOrdinaryName,
9483 RedeclarationKind::ForVisibleRedeclaration);
9484
9485 NewFD->setInvalidDecl();
9486 if (IsLocalFriend)
9487 SemaRef.LookupName(R&: Prev, S);
9488 else
9489 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9490 assert(!Prev.isAmbiguous() &&
9491 "Cannot have an ambiguity in previous-declaration lookup");
9492 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9493 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9494 MD ? MD->getParent() : nullptr);
9495 if (!Prev.empty()) {
9496 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9497 Func != FuncEnd; ++Func) {
9498 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9499 if (FD &&
9500 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9501 // Add 1 to the index so that 0 can mean the mismatch didn't
9502 // involve a parameter
9503 unsigned ParamNum =
9504 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9505 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9506 }
9507 }
9508 // If the qualified name lookup yielded nothing, try typo correction
9509 } else if ((Correction = SemaRef.CorrectTypo(
9510 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9511 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9512 Mode: CorrectTypoKind::ErrorRecovery,
9513 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9514 // Set up everything for the call to ActOnFunctionDeclarator
9515 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9516 IdLoc: ExtraArgs.D.getIdentifierLoc());
9517 Previous.clear();
9518 Previous.setLookupName(Correction.getCorrection());
9519 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9520 CDeclEnd = Correction.end();
9521 CDecl != CDeclEnd; ++CDecl) {
9522 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9523 if (FD && !FD->hasBody() &&
9524 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9525 Previous.addDecl(D: FD);
9526 }
9527 }
9528 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9529
9530 NamedDecl *Result;
9531 // Retry building the function declaration with the new previous
9532 // declarations, and with errors suppressed.
9533 {
9534 // Trap errors.
9535 Sema::SFINAETrap Trap(SemaRef);
9536
9537 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9538 // pieces need to verify the typo-corrected C++ declaration and hopefully
9539 // eliminate the need for the parameter pack ExtraArgs.
9540 Result = SemaRef.ActOnFunctionDeclarator(
9541 S: ExtraArgs.S, D&: ExtraArgs.D,
9542 DC: Correction.getCorrectionDecl()->getDeclContext(),
9543 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9544 AddToScope&: ExtraArgs.AddToScope);
9545
9546 if (Trap.hasErrorOccurred())
9547 Result = nullptr;
9548 }
9549
9550 if (Result) {
9551 // Determine which correction we picked.
9552 Decl *Canonical = Result->getCanonicalDecl();
9553 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9554 I != E; ++I)
9555 if ((*I)->getCanonicalDecl() == Canonical)
9556 Correction.setCorrectionDecl(*I);
9557
9558 // Let Sema know about the correction.
9559 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9560 SemaRef.diagnoseTypo(
9561 Correction,
9562 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9563 ? diag::err_no_matching_local_friend_suggest
9564 : diag::err_member_decl_does_not_match_suggest)
9565 << Name << NewDC << IsDefinition);
9566 return Result;
9567 }
9568
9569 // Pretend the typo correction never occurred
9570 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9571 IdLoc: ExtraArgs.D.getIdentifierLoc());
9572 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9573 Previous.clear();
9574 Previous.setLookupName(Name);
9575 }
9576
9577 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9578 << Name << NewDC << IsDefinition << NewFD->getLocation();
9579
9580 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9581 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9582 CXXRecordDecl *RD = NewMD->getParent();
9583 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9584 << RD->getName() << RD->getLocation();
9585 }
9586
9587 bool NewFDisConst = NewMD && NewMD->isConst();
9588
9589 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9590 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9591 NearMatch != NearMatchEnd; ++NearMatch) {
9592 FunctionDecl *FD = NearMatch->first;
9593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9594 bool FDisConst = MD && MD->isConst();
9595 bool IsMember = MD || !IsLocalFriend;
9596
9597 // FIXME: These notes are poorly worded for the local friend case.
9598 if (unsigned Idx = NearMatch->second) {
9599 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9600 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9601 if (Loc.isInvalid()) Loc = FD->getLocation();
9602 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9603 : diag::note_local_decl_close_param_match)
9604 << Idx << FDParam->getType()
9605 << NewFD->getParamDecl(i: Idx - 1)->getType();
9606 } else if (FDisConst != NewFDisConst) {
9607 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9608 DiagID: diag::note_member_def_close_const_match)
9609 << NewFDisConst << FD->getSourceRange().getEnd();
9610 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9611 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9612 Code: " const");
9613 else if (FTI.hasMethodTypeQualifiers() &&
9614 FTI.getConstQualifierLoc().isValid())
9615 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9616 } else {
9617 SemaRef.Diag(Loc: FD->getLocation(),
9618 DiagID: IsMember ? diag::note_member_def_close_match
9619 : diag::note_local_decl_close_match);
9620 }
9621 }
9622 return nullptr;
9623}
9624
9625static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9626 switch (D.getDeclSpec().getStorageClassSpec()) {
9627 default: llvm_unreachable("Unknown storage class!");
9628 case DeclSpec::SCS_auto:
9629 case DeclSpec::SCS_register:
9630 case DeclSpec::SCS_mutable:
9631 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9632 DiagID: diag::err_typecheck_sclass_func);
9633 D.getMutableDeclSpec().ClearStorageClassSpecs();
9634 D.setInvalidType();
9635 break;
9636 case DeclSpec::SCS_unspecified: break;
9637 case DeclSpec::SCS_extern:
9638 if (D.getDeclSpec().isExternInLinkageSpec())
9639 return SC_None;
9640 return SC_Extern;
9641 case DeclSpec::SCS_static: {
9642 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9643 // C99 6.7.1p5:
9644 // The declaration of an identifier for a function that has
9645 // block scope shall have no explicit storage-class specifier
9646 // other than extern
9647 // See also (C++ [dcl.stc]p4).
9648 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9649 DiagID: diag::err_static_block_func);
9650 break;
9651 } else
9652 return SC_Static;
9653 }
9654 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9655 }
9656
9657 // No explicit storage class has already been returned
9658 return SC_None;
9659}
9660
9661static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9662 DeclContext *DC, QualType &R,
9663 TypeSourceInfo *TInfo,
9664 StorageClass SC,
9665 bool &IsVirtualOkay) {
9666 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9667 DeclarationName Name = NameInfo.getName();
9668
9669 FunctionDecl *NewFD = nullptr;
9670 bool isInline = D.getDeclSpec().isInlineSpecified();
9671
9672 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9673 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9674 (SemaRef.getLangOpts().C23 &&
9675 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9676
9677 if (SemaRef.getLangOpts().C23)
9678 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9679 DiagID: diag::err_c23_constexpr_not_variable);
9680 else
9681 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9682 DiagID: diag::err_constexpr_wrong_decl_kind)
9683 << static_cast<int>(ConstexprKind);
9684 ConstexprKind = ConstexprSpecKind::Unspecified;
9685 D.getMutableDeclSpec().ClearConstexprSpec();
9686 }
9687
9688 if (!SemaRef.getLangOpts().CPlusPlus) {
9689 // Determine whether the function was written with a prototype. This is
9690 // true when:
9691 // - there is a prototype in the declarator, or
9692 // - the type R of the function is some kind of typedef or other non-
9693 // attributed reference to a type name (which eventually refers to a
9694 // function type). Note, we can't always look at the adjusted type to
9695 // check this case because attributes may cause a non-function
9696 // declarator to still have a function type. e.g.,
9697 // typedef void func(int a);
9698 // __attribute__((noreturn)) func other_func; // This has a prototype
9699 bool HasPrototype =
9700 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9701 (D.getDeclSpec().isTypeRep() &&
9702 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9703 ->isFunctionProtoType()) ||
9704 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9705 assert(
9706 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9707 "Strict prototypes are required");
9708
9709 NewFD = FunctionDecl::Create(
9710 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9711 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9712 ConstexprKind: ConstexprSpecKind::Unspecified,
9713 /*TrailingRequiresClause=*/{});
9714 if (D.isInvalidType())
9715 NewFD->setInvalidDecl();
9716
9717 return NewFD;
9718 }
9719
9720 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9721 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9722
9723 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9724
9725 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9726 // This is a C++ constructor declaration.
9727 assert(DC->isRecord() &&
9728 "Constructors can only be declared in a member context");
9729
9730 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9731 return CXXConstructorDecl::Create(
9732 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9733 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9734 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9735 Inherited: InheritedConstructor(), TrailingRequiresClause);
9736
9737 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9738 // This is a C++ destructor declaration.
9739 if (DC->isRecord()) {
9740 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9741 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9742 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9743 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9744 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9745 /*isImplicitlyDeclared=*/false, ConstexprKind,
9746 TrailingRequiresClause);
9747 // User defined destructors start as not selected if the class definition is still
9748 // not done.
9749 if (Record->isBeingDefined())
9750 NewDD->setIneligibleOrNotSelected(true);
9751
9752 // If the destructor needs an implicit exception specification, set it
9753 // now. FIXME: It'd be nice to be able to create the right type to start
9754 // with, but the type needs to reference the destructor declaration.
9755 if (SemaRef.getLangOpts().CPlusPlus11)
9756 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9757
9758 IsVirtualOkay = true;
9759 return NewDD;
9760
9761 } else {
9762 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9763 D.setInvalidType();
9764
9765 // Create a FunctionDecl to satisfy the function definition parsing
9766 // code path.
9767 return FunctionDecl::Create(
9768 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9769 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9770 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9771 }
9772
9773 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9774 if (!DC->isRecord()) {
9775 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9776 DiagID: diag::err_conv_function_not_member);
9777 return nullptr;
9778 }
9779
9780 SemaRef.CheckConversionDeclarator(D, R, SC);
9781 if (D.isInvalidType())
9782 return nullptr;
9783
9784 IsVirtualOkay = true;
9785 return CXXConversionDecl::Create(
9786 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9787 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9788 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9789 TrailingRequiresClause);
9790
9791 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9792 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9793 return nullptr;
9794 return CXXDeductionGuideDecl::Create(
9795 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9796 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9797 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9798 } else if (DC->isRecord()) {
9799 // If the name of the function is the same as the name of the record,
9800 // then this must be an invalid constructor that has a return type.
9801 // (The parser checks for a return type and makes the declarator a
9802 // constructor if it has no return type).
9803 if (Name.getAsIdentifierInfo() &&
9804 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9805 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9806 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9807 << SourceRange(D.getIdentifierLoc());
9808 return nullptr;
9809 }
9810
9811 // This is a C++ method declaration.
9812 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9813 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9814 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9815 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9816 IsVirtualOkay = !Ret->isStatic();
9817 return Ret;
9818 } else {
9819 bool isFriend =
9820 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9821 if (!isFriend && SemaRef.CurContext->isRecord())
9822 return nullptr;
9823
9824 // Determine whether the function was written with a
9825 // prototype. This true when:
9826 // - we're in C++ (where every function has a prototype),
9827 return FunctionDecl::Create(
9828 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9829 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9830 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9831 }
9832}
9833
9834enum OpenCLParamType {
9835 ValidKernelParam,
9836 PtrPtrKernelParam,
9837 PtrKernelParam,
9838 InvalidAddrSpacePtrKernelParam,
9839 InvalidKernelParam,
9840 RecordKernelParam
9841};
9842
9843static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9844 // Size dependent types are just typedefs to normal integer types
9845 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9846 // integers other than by their names.
9847 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9848
9849 // Remove typedefs one by one until we reach a typedef
9850 // for a size dependent type.
9851 QualType DesugaredTy = Ty;
9852 do {
9853 ArrayRef<StringRef> Names(SizeTypeNames);
9854 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9855 if (Names.end() != Match)
9856 return true;
9857
9858 Ty = DesugaredTy;
9859 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9860 } while (DesugaredTy != Ty);
9861
9862 return false;
9863}
9864
9865static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9866 if (PT->isDependentType())
9867 return InvalidKernelParam;
9868
9869 if (PT->isPointerOrReferenceType()) {
9870 QualType PointeeType = PT->getPointeeType();
9871 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9872 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9873 PointeeType.getAddressSpace() == LangAS::Default)
9874 return InvalidAddrSpacePtrKernelParam;
9875
9876 if (PointeeType->isPointerType()) {
9877 // This is a pointer to pointer parameter.
9878 // Recursively check inner type.
9879 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9880 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9881 ParamKind == InvalidKernelParam)
9882 return ParamKind;
9883
9884 // OpenCL v3.0 s6.11.a:
9885 // A restriction to pass pointers to pointers only applies to OpenCL C
9886 // v1.2 or below.
9887 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9888 return ValidKernelParam;
9889
9890 return PtrPtrKernelParam;
9891 }
9892
9893 // C++ for OpenCL v1.0 s2.4:
9894 // Moreover the types used in parameters of the kernel functions must be:
9895 // Standard layout types for pointer parameters. The same applies to
9896 // reference if an implementation supports them in kernel parameters.
9897 if (S.getLangOpts().OpenCLCPlusPlus &&
9898 !S.getOpenCLOptions().isAvailableOption(
9899 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9900 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9901 bool IsStandardLayoutType = true;
9902 if (CXXRec) {
9903 // If template type is not ODR-used its definition is only available
9904 // in the template definition not its instantiation.
9905 // FIXME: This logic doesn't work for types that depend on template
9906 // parameter (PR58590).
9907 if (!CXXRec->hasDefinition())
9908 CXXRec = CXXRec->getTemplateInstantiationPattern();
9909 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9910 IsStandardLayoutType = false;
9911 }
9912 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9913 !IsStandardLayoutType)
9914 return InvalidKernelParam;
9915 }
9916
9917 // OpenCL v1.2 s6.9.p:
9918 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9919 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9920 return ValidKernelParam;
9921
9922 return PtrKernelParam;
9923 }
9924
9925 // OpenCL v1.2 s6.9.k:
9926 // Arguments to kernel functions in a program cannot be declared with the
9927 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9928 // uintptr_t or a struct and/or union that contain fields declared to be one
9929 // of these built-in scalar types.
9930 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9931 return InvalidKernelParam;
9932
9933 if (PT->isImageType())
9934 return PtrKernelParam;
9935
9936 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9937 return InvalidKernelParam;
9938
9939 // OpenCL extension spec v1.2 s9.5:
9940 // This extension adds support for half scalar and vector types as built-in
9941 // types that can be used for arithmetic operations, conversions etc.
9942 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9943 PT->isHalfType())
9944 return InvalidKernelParam;
9945
9946 // Look into an array argument to check if it has a forbidden type.
9947 if (PT->isArrayType()) {
9948 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9949 // Call ourself to check an underlying type of an array. Since the
9950 // getPointeeOrArrayElementType returns an innermost type which is not an
9951 // array, this recursive call only happens once.
9952 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9953 }
9954
9955 // C++ for OpenCL v1.0 s2.4:
9956 // Moreover the types used in parameters of the kernel functions must be:
9957 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9958 // types) for parameters passed by value;
9959 if (S.getLangOpts().OpenCLCPlusPlus &&
9960 !S.getOpenCLOptions().isAvailableOption(
9961 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9962 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9963 return InvalidKernelParam;
9964
9965 if (PT->isRecordType())
9966 return RecordKernelParam;
9967
9968 return ValidKernelParam;
9969}
9970
9971static void checkIsValidOpenCLKernelParameter(
9972 Sema &S,
9973 Declarator &D,
9974 ParmVarDecl *Param,
9975 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9976 QualType PT = Param->getType();
9977
9978 // Cache the valid types we encounter to avoid rechecking structs that are
9979 // used again
9980 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9981 return;
9982
9983 switch (getOpenCLKernelParameterType(S, PT)) {
9984 case PtrPtrKernelParam:
9985 // OpenCL v3.0 s6.11.a:
9986 // A kernel function argument cannot be declared as a pointer to a pointer
9987 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9988 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9989 D.setInvalidType();
9990 return;
9991
9992 case InvalidAddrSpacePtrKernelParam:
9993 // OpenCL v1.0 s6.5:
9994 // __kernel function arguments declared to be a pointer of a type can point
9995 // to one of the following address spaces only : __global, __local or
9996 // __constant.
9997 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9998 D.setInvalidType();
9999 return;
10000
10001 // OpenCL v1.2 s6.9.k:
10002 // Arguments to kernel functions in a program cannot be declared with the
10003 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10004 // uintptr_t or a struct and/or union that contain fields declared to be
10005 // one of these built-in scalar types.
10006
10007 case InvalidKernelParam:
10008 // OpenCL v1.2 s6.8 n:
10009 // A kernel function argument cannot be declared
10010 // of event_t type.
10011 // Do not diagnose half type since it is diagnosed as invalid argument
10012 // type for any function elsewhere.
10013 if (!PT->isHalfType()) {
10014 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10015
10016 // Explain what typedefs are involved.
10017 const TypedefType *Typedef = nullptr;
10018 while ((Typedef = PT->getAs<TypedefType>())) {
10019 SourceLocation Loc = Typedef->getDecl()->getLocation();
10020 // SourceLocation may be invalid for a built-in type.
10021 if (Loc.isValid())
10022 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
10023 PT = Typedef->desugar();
10024 }
10025 }
10026
10027 D.setInvalidType();
10028 return;
10029
10030 case PtrKernelParam:
10031 case ValidKernelParam:
10032 ValidTypes.insert(Ptr: PT.getTypePtr());
10033 return;
10034
10035 case RecordKernelParam:
10036 break;
10037 }
10038
10039 // Track nested structs we will inspect
10040 SmallVector<const Decl *, 4> VisitStack;
10041
10042 // Track where we are in the nested structs. Items will migrate from
10043 // VisitStack to HistoryStack as we do the DFS for bad field.
10044 SmallVector<const FieldDecl *, 4> HistoryStack;
10045 HistoryStack.push_back(Elt: nullptr);
10046
10047 // At this point we already handled everything except of a RecordType.
10048 assert(PT->isRecordType() && "Unexpected type.");
10049 const auto *PD = PT->castAsRecordDecl();
10050 VisitStack.push_back(Elt: PD);
10051 assert(VisitStack.back() && "First decl null?");
10052
10053 do {
10054 const Decl *Next = VisitStack.pop_back_val();
10055 if (!Next) {
10056 assert(!HistoryStack.empty());
10057 // Found a marker, we have gone up a level
10058 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10059 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
10060
10061 continue;
10062 }
10063
10064 // Adds everything except the original parameter declaration (which is not a
10065 // field itself) to the history stack.
10066 const RecordDecl *RD;
10067 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
10068 HistoryStack.push_back(Elt: Field);
10069
10070 QualType FieldTy = Field->getType();
10071 // Other field types (known to be valid or invalid) are handled while we
10072 // walk around RecordDecl::fields().
10073 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10074 "Unexpected type.");
10075 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10076
10077 RD = FieldRecTy->castAsRecordDecl();
10078 } else {
10079 RD = cast<RecordDecl>(Val: Next);
10080 }
10081
10082 // Add a null marker so we know when we've gone back up a level
10083 VisitStack.push_back(Elt: nullptr);
10084
10085 for (const auto *FD : RD->fields()) {
10086 QualType QT = FD->getType();
10087
10088 if (ValidTypes.count(Ptr: QT.getTypePtr()))
10089 continue;
10090
10091 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
10092 if (ParamType == ValidKernelParam)
10093 continue;
10094
10095 if (ParamType == RecordKernelParam) {
10096 VisitStack.push_back(Elt: FD);
10097 continue;
10098 }
10099
10100 // OpenCL v1.2 s6.9.p:
10101 // Arguments to kernel functions that are declared to be a struct or union
10102 // do not allow OpenCL objects to be passed as elements of the struct or
10103 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10104 // of SVM.
10105 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10106 ParamType == InvalidAddrSpacePtrKernelParam) {
10107 S.Diag(Loc: Param->getLocation(),
10108 DiagID: diag::err_record_with_pointers_kernel_param)
10109 << PT->isUnionType()
10110 << PT;
10111 } else {
10112 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10113 }
10114
10115 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10116 << PD->getDeclName();
10117
10118 // We have an error, now let's go back up through history and show where
10119 // the offending field came from
10120 for (ArrayRef<const FieldDecl *>::const_iterator
10121 I = HistoryStack.begin() + 1,
10122 E = HistoryStack.end();
10123 I != E; ++I) {
10124 const FieldDecl *OuterField = *I;
10125 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10126 << OuterField->getType();
10127 }
10128
10129 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10130 << QT->isPointerType()
10131 << QT;
10132 D.setInvalidType();
10133 return;
10134 }
10135 } while (!VisitStack.empty());
10136}
10137
10138/// Find the DeclContext in which a tag is implicitly declared if we see an
10139/// elaborated type specifier in the specified context, and lookup finds
10140/// nothing.
10141static DeclContext *getTagInjectionContext(DeclContext *DC) {
10142 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10143 DC = DC->getParent();
10144 return DC;
10145}
10146
10147/// Find the Scope in which a tag is implicitly declared if we see an
10148/// elaborated type specifier in the specified context, and lookup finds
10149/// nothing.
10150static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10151 while (S->isClassScope() ||
10152 (LangOpts.CPlusPlus &&
10153 S->isFunctionPrototypeScope()) ||
10154 ((S->getFlags() & Scope::DeclScope) == 0) ||
10155 (S->getEntity() && S->getEntity()->isTransparentContext()))
10156 S = S->getParent();
10157 return S;
10158}
10159
10160/// Determine whether a declaration matches a known function in namespace std.
10161static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10162 unsigned BuiltinID) {
10163 switch (BuiltinID) {
10164 case Builtin::BI__GetExceptionInfo:
10165 // No type checking whatsoever.
10166 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10167
10168 case Builtin::BIaddressof:
10169 case Builtin::BI__addressof:
10170 case Builtin::BIforward:
10171 case Builtin::BIforward_like:
10172 case Builtin::BImove:
10173 case Builtin::BImove_if_noexcept:
10174 case Builtin::BIas_const: {
10175 // Ensure that we don't treat the algorithm
10176 // OutputIt std::move(InputIt, InputIt, OutputIt)
10177 // as the builtin std::move.
10178 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10179 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10180 }
10181
10182 default:
10183 return false;
10184 }
10185}
10186
10187void Sema::addImplicitCallingConvAbiTag(FunctionDecl *FD) {
10188 const auto *FT = FD->getType()->getAs<FunctionType>();
10189 if (!FT)
10190 return;
10191
10192 StringRef Tag;
10193 switch (FT->getCallConv()) {
10194#define CC_VLS_CASE(ABI_VLEN) \
10195 case CC_RISCVVLSCall_##ABI_VLEN: \
10196 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10197 break;
10198 CC_VLS_CASE(32)
10199 CC_VLS_CASE(64)
10200 CC_VLS_CASE(128)
10201 CC_VLS_CASE(256)
10202 CC_VLS_CASE(512)
10203 CC_VLS_CASE(1024)
10204 CC_VLS_CASE(2048)
10205 CC_VLS_CASE(4096)
10206 CC_VLS_CASE(8192)
10207 CC_VLS_CASE(16384)
10208 CC_VLS_CASE(32768)
10209 CC_VLS_CASE(65536)
10210#undef CC_VLS_CASE
10211 default:
10212 return;
10213 }
10214
10215 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10216 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10217
10218 SmallVector<StringRef, 4> Tags;
10219 if (Old)
10220 llvm::append_range(C&: Tags, R: Old->tags());
10221 if (llvm::is_contained(Range&: Tags, Element: Tag))
10222 return;
10223 Tags.push_back(Elt: Tag);
10224
10225 AbiTagAttr *Merged =
10226 Old ? AbiTagAttr::Create(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(), CommonInfo: *Old)
10227 : AbiTagAttr::CreateImplicit(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(),
10228 Range: FD->getLocation());
10229 FD->dropAttr<AbiTagAttr>();
10230 FD->addAttr(A: Merged);
10231 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10232 FD->addAttr(A: Existing[I]);
10233}
10234
10235NamedDecl*
10236Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10237 TypeSourceInfo *TInfo, LookupResult &Previous,
10238 MultiTemplateParamsArg TemplateParamListsRef,
10239 bool &AddToScope) {
10240 QualType R = TInfo->getType();
10241
10242 assert(R->isFunctionType());
10243 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10244 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10245
10246 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10247 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10248 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10249 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10250 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10251 TemplateParamLists.back() = Invented;
10252 else
10253 TemplateParamLists.push_back(Elt: Invented);
10254 }
10255
10256 // TODO: consider using NameInfo for diagnostic.
10257 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10258 DeclarationName Name = NameInfo.getName();
10259 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10260
10261 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10262 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10263 DiagID: diag::err_invalid_thread)
10264 << DeclSpec::getSpecifierName(S: TSCS);
10265
10266 if (D.isFirstDeclarationOfMember())
10267 adjustMemberFunctionCC(
10268 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10269 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10270
10271 bool isFriend = false;
10272 FunctionTemplateDecl *FunctionTemplate = nullptr;
10273 bool isMemberSpecialization = false;
10274 bool isFunctionTemplateSpecialization = false;
10275
10276 bool HasExplicitTemplateArgs = false;
10277 TemplateArgumentListInfo TemplateArgs;
10278
10279 bool isVirtualOkay = false;
10280
10281 DeclContext *OriginalDC = DC;
10282 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10283
10284 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10285 IsVirtualOkay&: isVirtualOkay);
10286 if (!NewFD) return nullptr;
10287
10288 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10289 NewFD->setTopLevelDeclInObjCContainer();
10290
10291 // Set the lexical context. If this is a function-scope declaration, or has a
10292 // C++ scope specifier, or is the object of a friend declaration, the lexical
10293 // context will be different from the semantic context.
10294 NewFD->setLexicalDeclContext(CurContext);
10295
10296 if (IsLocalExternDecl)
10297 NewFD->setLocalExternDecl();
10298
10299 if (getLangOpts().CPlusPlus) {
10300 // The rules for implicit inlines changed in C++20 for methods and friends
10301 // with an in-class definition (when such a definition is not attached to
10302 // the global module). This does not affect declarations that are already
10303 // inline (whether explicitly or implicitly by being declared constexpr,
10304 // consteval, etc).
10305 // FIXME: We need a better way to separate C++ standard and clang modules.
10306 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10307 !NewFD->getOwningModule() ||
10308 NewFD->isFromGlobalModule() ||
10309 NewFD->getOwningModule()->isHeaderLikeModule();
10310 bool isInline = D.getDeclSpec().isInlineSpecified();
10311 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10312 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10313 isFriend = D.getDeclSpec().isFriendSpecified();
10314 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10315 // Pre-C++20 [class.friend]p5
10316 // A function can be defined in a friend declaration of a
10317 // class . . . . Such a function is implicitly inline.
10318 // Post C++20 [class.friend]p7
10319 // Such a function is implicitly an inline function if it is attached
10320 // to the global module.
10321 NewFD->setImplicitlyInline();
10322 }
10323
10324 // If this is a method defined in an __interface, and is not a constructor
10325 // or an overloaded operator, then set the pure flag (isVirtual will already
10326 // return true).
10327 if (const CXXRecordDecl *Parent =
10328 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10329 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10330 NewFD->setIsPureVirtual(true);
10331
10332 // C++ [class.union]p2
10333 // A union can have member functions, but not virtual functions.
10334 if (isVirtual && Parent->isUnion()) {
10335 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10336 NewFD->setInvalidDecl();
10337 }
10338 if ((Parent->isClass() || Parent->isStruct()) &&
10339 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10340 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10341 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10342 if (auto *Def = Parent->getDefinition())
10343 Def->setInitMethod(true);
10344 }
10345 }
10346
10347 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10348 isMemberSpecialization = false;
10349 isFunctionTemplateSpecialization = false;
10350 if (D.isInvalidType())
10351 NewFD->setInvalidDecl();
10352
10353 // Match up the template parameter lists with the scope specifier, then
10354 // determine whether we have a template or a template specialization.
10355 bool Invalid = false;
10356 TemplateIdAnnotation *TemplateId =
10357 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10358 ? D.getName().TemplateId
10359 : nullptr;
10360 TemplateParameterList *TemplateParams =
10361 MatchTemplateParametersToScopeSpecifier(
10362 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10363 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10364 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10365 if (TemplateParams) {
10366 // Check that we can declare a template here.
10367 if (CheckTemplateDeclScope(S, TemplateParams))
10368 NewFD->setInvalidDecl();
10369
10370 if (TemplateParams->size() > 0) {
10371 // This is a function template
10372
10373 // A destructor cannot be a template.
10374 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10375 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10376 NewFD->setInvalidDecl();
10377 // Function template with explicit template arguments.
10378 } else if (TemplateId) {
10379 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10380 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10381 NewFD->setInvalidDecl();
10382 }
10383
10384 // If we're adding a template to a dependent context, we may need to
10385 // rebuilding some of the types used within the template parameter list,
10386 // now that we know what the current instantiation is.
10387 if (DC->isDependentContext()) {
10388 ContextRAII SavedContext(*this, DC);
10389 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10390 Invalid = true;
10391 }
10392
10393 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10394 L: NewFD->getLocation(),
10395 Name, Params: TemplateParams,
10396 Decl: NewFD);
10397 FunctionTemplate->setLexicalDeclContext(CurContext);
10398 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10399
10400 // For source fidelity, store the other template param lists.
10401 if (TemplateParamLists.size() > 1) {
10402 NewFD->setTemplateParameterListsInfo(Context,
10403 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10404 .drop_back(N: 1));
10405 }
10406 } else {
10407 // This is a function template specialization.
10408 isFunctionTemplateSpecialization = true;
10409 // For source fidelity, store all the template param lists.
10410 if (TemplateParamLists.size() > 0)
10411 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10412
10413 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10414 if (isFriend) {
10415 // We want to remove the "template<>", found here.
10416 SourceRange RemoveRange = TemplateParams->getSourceRange();
10417
10418 // If we remove the template<> and the name is not a
10419 // template-id, we're actually silently creating a problem:
10420 // the friend declaration will refer to an untemplated decl,
10421 // and clearly the user wants a template specialization. So
10422 // we need to insert '<>' after the name.
10423 SourceLocation InsertLoc;
10424 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10425 InsertLoc = D.getName().getSourceRange().getEnd();
10426 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10427 }
10428
10429 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10430 << Name << RemoveRange
10431 << FixItHint::CreateRemoval(RemoveRange)
10432 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10433 Invalid = true;
10434
10435 // Recover by faking up an empty template argument list.
10436 HasExplicitTemplateArgs = true;
10437 TemplateArgs.setLAngleLoc(InsertLoc);
10438 TemplateArgs.setRAngleLoc(InsertLoc);
10439 }
10440 }
10441 } else {
10442 // Check that we can declare a template here.
10443 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10444 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10445 NewFD->setInvalidDecl();
10446
10447 // All template param lists were matched against the scope specifier:
10448 // this is NOT (an explicit specialization of) a template.
10449 if (TemplateParamLists.size() > 0)
10450 // For source fidelity, store all the template param lists.
10451 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10452
10453 // "friend void foo<>(int);" is an implicit specialization decl.
10454 if (isFriend && TemplateId)
10455 isFunctionTemplateSpecialization = true;
10456 }
10457
10458 // If this is a function template specialization and the unqualified-id of
10459 // the declarator-id is a template-id, convert the template argument list
10460 // into our AST format and check for unexpanded packs.
10461 if (isFunctionTemplateSpecialization && TemplateId) {
10462 HasExplicitTemplateArgs = true;
10463
10464 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10465 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10466 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10467 TemplateId->NumArgs);
10468 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10469
10470 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10471 // declaration of a function template partial specialization? Should we
10472 // consider the unexpanded pack context to be a partial specialization?
10473 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10474 if (DiagnoseUnexpandedParameterPack(
10475 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10476 : UPPC_ExplicitSpecialization))
10477 NewFD->setInvalidDecl();
10478 }
10479 }
10480
10481 if (Invalid) {
10482 NewFD->setInvalidDecl();
10483 if (FunctionTemplate)
10484 FunctionTemplate->setInvalidDecl();
10485 }
10486
10487 // C++ [dcl.fct.spec]p5:
10488 // The virtual specifier shall only be used in declarations of
10489 // nonstatic class member functions that appear within a
10490 // member-specification of a class declaration; see 10.3.
10491 //
10492 if (isVirtual && !NewFD->isInvalidDecl()) {
10493 if (!isVirtualOkay) {
10494 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10495 DiagID: diag::err_virtual_non_function);
10496 } else if (!CurContext->isRecord()) {
10497 // 'virtual' was specified outside of the class.
10498 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10499 DiagID: diag::err_virtual_out_of_class)
10500 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10501 } else if (NewFD->getDescribedFunctionTemplate()) {
10502 // C++ [temp.mem]p3:
10503 // A member function template shall not be virtual.
10504 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10505 DiagID: diag::err_virtual_member_function_template)
10506 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10507 } else {
10508 // Okay: Add virtual to the method.
10509 NewFD->setVirtualAsWritten(true);
10510 }
10511
10512 if (getLangOpts().CPlusPlus14 &&
10513 NewFD->getReturnType()->isUndeducedType())
10514 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10515 }
10516
10517 // C++ [dcl.fct.spec]p3:
10518 // The inline specifier shall not appear on a block scope function
10519 // declaration.
10520 if (isInline && !NewFD->isInvalidDecl()) {
10521 if (CurContext->isFunctionOrMethod()) {
10522 // 'inline' is not allowed on block scope function declaration.
10523 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10524 DiagID: diag::err_inline_declaration_block_scope) << Name
10525 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10526 }
10527 }
10528
10529 // C++ [dcl.fct.spec]p6:
10530 // The explicit specifier shall be used only in the declaration of a
10531 // constructor or conversion function within its class definition;
10532 // see 12.3.1 and 12.3.2.
10533 if (hasExplicit && !NewFD->isInvalidDecl() &&
10534 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10535 if (!CurContext->isRecord()) {
10536 // 'explicit' was specified outside of the class.
10537 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10538 DiagID: diag::err_explicit_out_of_class)
10539 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10540 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10541 !isa<CXXConversionDecl>(Val: NewFD)) {
10542 // 'explicit' was specified on a function that wasn't a constructor
10543 // or conversion function.
10544 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10545 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10546 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10547 }
10548 }
10549
10550 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10551 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10552 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10553 // are implicitly inline.
10554 NewFD->setImplicitlyInline();
10555
10556 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10557 // be either constructors or to return a literal type. Therefore,
10558 // destructors cannot be declared constexpr.
10559 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10560 (!getLangOpts().CPlusPlus20 ||
10561 ConstexprKind == ConstexprSpecKind::Consteval)) {
10562 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10563 << static_cast<int>(ConstexprKind);
10564 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10565 ? ConstexprSpecKind::Unspecified
10566 : ConstexprSpecKind::Constexpr);
10567 }
10568 // C++20 [dcl.constexpr]p2: An allocation function, or a
10569 // deallocation function shall not be declared with the consteval
10570 // specifier.
10571 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10572 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10573 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10574 DiagID: diag::err_invalid_consteval_decl_kind)
10575 << NewFD;
10576 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10577 }
10578 }
10579
10580 // If __module_private__ was specified, mark the function accordingly.
10581 if (D.getDeclSpec().isModulePrivateSpecified()) {
10582 if (isFunctionTemplateSpecialization) {
10583 SourceLocation ModulePrivateLoc
10584 = D.getDeclSpec().getModulePrivateSpecLoc();
10585 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10586 << 0
10587 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10588 } else {
10589 NewFD->setModulePrivate();
10590 if (FunctionTemplate)
10591 FunctionTemplate->setModulePrivate();
10592 }
10593 }
10594
10595 if (isFriend) {
10596 if (FunctionTemplate) {
10597 FunctionTemplate->setObjectOfFriendDecl();
10598 FunctionTemplate->setAccess(AS_public);
10599 }
10600 NewFD->setObjectOfFriendDecl();
10601 NewFD->setAccess(AS_public);
10602 }
10603
10604 // If a function is defined as defaulted or deleted, mark it as such now.
10605 // We'll do the relevant checks on defaulted / deleted functions later.
10606 switch (D.getFunctionDefinitionKind()) {
10607 case FunctionDefinitionKind::Declaration:
10608 case FunctionDefinitionKind::Definition:
10609 break;
10610
10611 case FunctionDefinitionKind::Defaulted:
10612 NewFD->setDefaulted();
10613 break;
10614
10615 case FunctionDefinitionKind::Deleted:
10616 NewFD->setDeletedAsWritten();
10617 break;
10618 }
10619
10620 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10621 D.isFunctionDefinition()) {
10622 // Pre C++20 [class.mfct]p2:
10623 // A member function may be defined (8.4) in its class definition, in
10624 // which case it is an inline member function (7.1.2)
10625 // Post C++20 [class.mfct]p1:
10626 // If a member function is attached to the global module and is defined
10627 // in its class definition, it is inline.
10628 NewFD->setImplicitlyInline();
10629 }
10630
10631 if (!isFriend && SC != SC_None) {
10632 // C++ [temp.expl.spec]p2:
10633 // The declaration in an explicit-specialization shall not be an
10634 // export-declaration. An explicit specialization shall not use a
10635 // storage-class-specifier other than thread_local.
10636 //
10637 // We diagnose friend declarations with storage-class-specifiers
10638 // elsewhere.
10639 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10640 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10641 DiagID: diag::ext_explicit_specialization_storage_class)
10642 << FixItHint::CreateRemoval(
10643 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10644 }
10645
10646 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10647 assert(isa<CXXMethodDecl>(NewFD) &&
10648 "Out-of-line member function should be a CXXMethodDecl");
10649 // C++ [class.static]p1:
10650 // A data or function member of a class may be declared static
10651 // in a class definition, in which case it is a static member of
10652 // the class.
10653
10654 // Complain about the 'static' specifier if it's on an out-of-line
10655 // member function definition.
10656
10657 // MSVC permits the use of a 'static' storage specifier on an
10658 // out-of-line member function template declaration and class member
10659 // template declaration (MSVC versions before 2015), warn about this.
10660 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10661 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10662 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10663 (getLangOpts().MSVCCompat &&
10664 NewFD->getDescribedFunctionTemplate()))
10665 ? diag::ext_static_out_of_line
10666 : diag::err_static_out_of_line)
10667 << FixItHint::CreateRemoval(
10668 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10669 }
10670 }
10671
10672 // C++11 [except.spec]p15:
10673 // A deallocation function with no exception-specification is treated
10674 // as if it were specified with noexcept(true).
10675 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10676 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10677 !FPT->hasExceptionSpec())
10678 NewFD->setType(Context.getFunctionType(
10679 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10680 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10681
10682 // C++20 [dcl.inline]/7
10683 // If an inline function or variable that is attached to a named module
10684 // is declared in a definition domain, it shall be defined in that
10685 // domain.
10686 // So, if the current declaration does not have a definition, we must
10687 // check at the end of the TU (or when the PMF starts) to see that we
10688 // have a definition at that point.
10689 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10690 NewFD->isInNamedModule()) {
10691 PendingInlineFuncDecls.insert(Ptr: NewFD);
10692 }
10693 }
10694
10695 // Filter out previous declarations that don't match the scope.
10696 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10697 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10698 isMemberSpecialization ||
10699 isFunctionTemplateSpecialization);
10700
10701 LoadExternalExtnameUndeclaredIdentifiers();
10702
10703 // Handle GNU asm-label extension (encoded as an attribute).
10704 if (Expr *E = D.getAsmLabel()) {
10705 // The parser guarantees this is a string.
10706 StringLiteral *SE = cast<StringLiteral>(Val: E);
10707 NewFD->addAttr(
10708 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10709 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10710 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10711 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10712 if (I != ExtnameUndeclaredIdentifiers.end()) {
10713 if (isDeclExternC(D: NewFD)) {
10714 NewFD->addAttr(A: I->second);
10715 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10716 } else if (NewFD->getDeclContext()
10717 ->getRedeclContext()
10718 ->isTranslationUnit())
10719 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10720 << /*Variable*/0 << NewFD;
10721 }
10722 }
10723
10724 // Copy the parameter declarations from the declarator D to the function
10725 // declaration NewFD, if they are available. First scavenge them into Params.
10726 SmallVector<ParmVarDecl*, 16> Params;
10727 unsigned FTIIdx;
10728 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10729 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10730
10731 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10732 // function that takes no arguments, not a function that takes a
10733 // single void argument.
10734 // We let through "const void" here because Sema::GetTypeForDeclarator
10735 // already checks for that case.
10736 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10737 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10738 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10739 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10740 Param->setDeclContext(NewFD);
10741 Params.push_back(Elt: Param);
10742
10743 if (Param->isInvalidDecl())
10744 NewFD->setInvalidDecl();
10745 }
10746 }
10747
10748 if (!getLangOpts().CPlusPlus) {
10749 // In C, find all the tag declarations from the prototype and move them
10750 // into the function DeclContext. Remove them from the surrounding tag
10751 // injection context of the function, which is typically but not always
10752 // the TU.
10753 DeclContext *PrototypeTagContext =
10754 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10755 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10756 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10757
10758 // We don't want to reparent enumerators. Look at their parent enum
10759 // instead.
10760 if (!TD) {
10761 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10762 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10763 }
10764 if (!TD)
10765 continue;
10766 DeclContext *TagDC = TD->getLexicalDeclContext();
10767 if (!TagDC->containsDecl(D: TD))
10768 continue;
10769 TagDC->removeDecl(D: TD);
10770 TD->setDeclContext(NewFD);
10771 NewFD->addDecl(D: TD);
10772
10773 // Preserve the lexical DeclContext if it is not the surrounding tag
10774 // injection context of the FD. In this example, the semantic context of
10775 // E will be f and the lexical context will be S, while both the
10776 // semantic and lexical contexts of S will be f:
10777 // void f(struct S { enum E { a } f; } s);
10778 if (TagDC != PrototypeTagContext)
10779 TD->setLexicalDeclContext(TagDC);
10780 }
10781 }
10782 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10783 // When we're declaring a function with a typedef, typeof, etc as in the
10784 // following example, we'll need to synthesize (unnamed)
10785 // parameters for use in the declaration.
10786 //
10787 // @code
10788 // typedef void fn(int);
10789 // fn f;
10790 // @endcode
10791
10792 // Synthesize a parameter for each argument type.
10793 for (const auto &AI : FT->param_types()) {
10794 ParmVarDecl *Param =
10795 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10796 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10797 Params.push_back(Elt: Param);
10798 }
10799 } else {
10800 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10801 "Should not need args for typedef of non-prototype fn");
10802 }
10803
10804 // Finally, we know we have the right number of parameters, install them.
10805 NewFD->setParams(Params);
10806
10807 // If this declarator is a declaration and not a definition, its parameters
10808 // will not be pushed onto a scope chain. That means we will not issue any
10809 // reserved identifier warnings for the declaration, but we will for the
10810 // definition. Handle those here.
10811 if (!D.isFunctionDefinition()) {
10812 for (const ParmVarDecl *PVD : Params)
10813 warnOnReservedIdentifier(D: PVD);
10814 }
10815
10816 if (D.getDeclSpec().isNoreturnSpecified())
10817 NewFD->addAttr(
10818 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10819
10820 // Functions returning a variably modified type violate C99 6.7.5.2p2
10821 // because all functions have linkage.
10822 if (!NewFD->isInvalidDecl() &&
10823 NewFD->getReturnType()->isVariablyModifiedType()) {
10824 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10825 NewFD->setInvalidDecl();
10826 }
10827
10828 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10829 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10830 !NewFD->hasAttr<SectionAttr>())
10831 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10832 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10833 Range: PragmaClangTextSection.PragmaLocation));
10834
10835 // Apply an implicit SectionAttr if #pragma code_seg is active.
10836 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10837 !NewFD->hasAttr<SectionAttr>()) {
10838 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10839 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10840 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10841 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10842 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10843 ASTContext::PSF_Read,
10844 TheDecl: NewFD))
10845 NewFD->dropAttr<SectionAttr>();
10846 }
10847
10848 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10849 // active.
10850 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10851 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10852 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10853 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10854
10855 // Apply an implicit CodeSegAttr from class declspec or
10856 // apply an implicit SectionAttr from #pragma code_seg if active.
10857 if (!NewFD->hasAttr<CodeSegAttr>()) {
10858 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10859 IsDefinition: D.isFunctionDefinition())) {
10860 NewFD->addAttr(A: SAttr);
10861 }
10862 }
10863
10864 // Handle attributes.
10865 ProcessDeclAttributes(S, D: NewFD, PD: D);
10866 addImplicitCallingConvAbiTag(FD: NewFD);
10867 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10868 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10869 !NewTVA->isDefaultVersion() &&
10870 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10871 // Don't add to scope fmv functions declarations if fmv disabled
10872 AddToScope = false;
10873 return NewFD;
10874 }
10875
10876 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10877 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10878 // type.
10879 //
10880 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10881 // type declaration will generate a compilation error.
10882 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10883 if (AddressSpace != LangAS::Default) {
10884 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10885 NewFD->setInvalidDecl();
10886 }
10887 }
10888
10889 if (!getLangOpts().CPlusPlus) {
10890 // Perform semantic checking on the function declaration.
10891 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10892 CheckMain(FD: NewFD, D: D.getDeclSpec());
10893
10894 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10895 CheckMSVCRTEntryPoint(FD: NewFD);
10896
10897 if (!NewFD->isInvalidDecl())
10898 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10899 IsMemberSpecialization: isMemberSpecialization,
10900 DeclIsDefn: D.isFunctionDefinition()));
10901 else if (!Previous.empty())
10902 // Recover gracefully from an invalid redeclaration.
10903 D.setRedeclaration(true);
10904 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10905 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10906 "previous declaration set still overloaded");
10907
10908 // Diagnose no-prototype function declarations with calling conventions that
10909 // don't support variadic calls. Only do this in C and do it after merging
10910 // possibly prototyped redeclarations.
10911 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10912 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10913 CallingConv CC = FT->getExtInfo().getCC();
10914 if (!supportsVariadicCall(CC)) {
10915 // Windows system headers sometimes accidentally use stdcall without
10916 // (void) parameters, so we relax this to a warning.
10917 int DiagID =
10918 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10919 Diag(Loc: NewFD->getLocation(), DiagID)
10920 << FunctionType::getNameForCallConv(CC);
10921 }
10922 }
10923
10924 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10925 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10926 checkNonTrivialCUnion(
10927 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10928 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10929 } else {
10930 // C++11 [replacement.functions]p3:
10931 // The program's definitions shall not be specified as inline.
10932 //
10933 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10934 //
10935 // Suppress the diagnostic if the function is __attribute__((used)), since
10936 // that forces an external definition to be emitted.
10937 if (D.getDeclSpec().isInlineSpecified() &&
10938 NewFD->isReplaceableGlobalAllocationFunction() &&
10939 !NewFD->hasAttr<UsedAttr>())
10940 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10941 DiagID: diag::ext_operator_new_delete_declared_inline)
10942 << NewFD->getDeclName();
10943
10944 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10945 // C++20 [dcl.decl.general]p4:
10946 // The optional requires-clause in an init-declarator or
10947 // member-declarator shall be present only if the declarator declares a
10948 // templated function.
10949 //
10950 // C++20 [temp.pre]p8:
10951 // An entity is templated if it is
10952 // - a template,
10953 // - an entity defined or created in a templated entity,
10954 // - a member of a templated entity,
10955 // - an enumerator for an enumeration that is a templated entity, or
10956 // - the closure type of a lambda-expression appearing in the
10957 // declaration of a templated entity.
10958 //
10959 // [Note 6: A local class, a local or block variable, or a friend
10960 // function defined in a templated entity is a templated entity.
10961 // — end note]
10962 //
10963 // A templated function is a function template or a function that is
10964 // templated. A templated class is a class template or a class that is
10965 // templated. A templated variable is a variable template or a variable
10966 // that is templated.
10967 if (!FunctionTemplate) {
10968 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10969 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10970 // An explicit specialization shall not have a trailing
10971 // requires-clause unless it declares a function template.
10972 //
10973 // Since a friend function template specialization cannot be
10974 // definition, and since a non-template friend declaration with a
10975 // trailing requires-clause must be a definition, we diagnose
10976 // friend function template specializations with trailing
10977 // requires-clauses on the same path as explicit specializations
10978 // even though they aren't necessarily prohibited by the same
10979 // language rule.
10980 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10981 << isFriend;
10982 } else if (isFriend && NewFD->isTemplated() &&
10983 !D.isFunctionDefinition()) {
10984 // C++ [temp.friend]p9:
10985 // A non-template friend declaration with a requires-clause shall be
10986 // a definition.
10987 Diag(Loc: NewFD->getBeginLoc(),
10988 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10989 NewFD->setInvalidDecl();
10990 } else if (!NewFD->isTemplated() ||
10991 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10992 Diag(Loc: TRC->getBeginLoc(),
10993 DiagID: diag::err_constrained_non_templated_function);
10994 }
10995 }
10996 }
10997
10998 // We do not add HD attributes to specializations here because
10999 // they may have different constexpr-ness compared to their
11000 // templates and, after maybeAddHostDeviceAttrs() is applied,
11001 // may end up with different effective targets. Instead, a
11002 // specialization inherits its target attributes from its template
11003 // in the CheckFunctionTemplateSpecialization() call below.
11004 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11005 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
11006
11007 // Handle explicit specializations of function templates
11008 // and friend function declarations with an explicit
11009 // template argument list.
11010 if (isFunctionTemplateSpecialization) {
11011 bool isDependentSpecialization = false;
11012 if (isFriend) {
11013 // For friend function specializations, this is a dependent
11014 // specialization if its semantic context is dependent, its
11015 // qualifier is dependent, its type is dependent, or its template-id is
11016 // dependent.
11017 isDependentSpecialization =
11018 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11019 NewFD->getType()->isDependentType() ||
11020 (HasExplicitTemplateArgs &&
11021 TemplateSpecializationType::
11022 anyInstantiationDependentTemplateArguments(
11023 Args: TemplateArgs.arguments()));
11024 assert((!isDependentSpecialization ||
11025 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11026 "dependent friend function specialization without template "
11027 "args");
11028 } else {
11029 // For class-scope explicit specializations of function templates,
11030 // if the lexical context is dependent, then the specialization
11031 // is dependent.
11032 isDependentSpecialization =
11033 CurContext->isRecord() && CurContext->isDependentContext();
11034 }
11035
11036 TemplateArgumentListInfo *ExplicitTemplateArgs =
11037 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11038 if (isDependentSpecialization) {
11039 // If it's a dependent specialization, it may not be possible
11040 // to determine the primary template (for explicit specializations)
11041 // or befriended declaration (for friends) until the enclosing
11042 // template is instantiated. In such cases, we store the declarations
11043 // found by name lookup and defer resolution until instantiation.
11044 if (CheckDependentFunctionTemplateSpecialization(
11045 FD: NewFD, ExplicitTemplateArgs, Previous))
11046 NewFD->setInvalidDecl();
11047 } else if (!NewFD->isInvalidDecl()) {
11048 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
11049 Previous))
11050 NewFD->setInvalidDecl();
11051 }
11052 } else if (isMemberSpecialization && !FunctionTemplate) {
11053 if (CheckMemberSpecialization(Member: NewFD, Previous))
11054 NewFD->setInvalidDecl();
11055 }
11056
11057 // Perform semantic checking on the function declaration.
11058 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11059 CheckMain(FD: NewFD, D: D.getDeclSpec());
11060
11061 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11062 CheckMSVCRTEntryPoint(FD: NewFD);
11063
11064 if (!NewFD->isInvalidDecl())
11065 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
11066 IsMemberSpecialization: isMemberSpecialization,
11067 DeclIsDefn: D.isFunctionDefinition()));
11068 else if (!Previous.empty())
11069 // Recover gracefully from an invalid redeclaration.
11070 D.setRedeclaration(true);
11071
11072 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11073 !D.isRedeclaration() ||
11074 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11075 "previous declaration set still overloaded");
11076
11077 NamedDecl *PrincipalDecl = (FunctionTemplate
11078 ? cast<NamedDecl>(Val: FunctionTemplate)
11079 : NewFD);
11080
11081 if (isFriend && NewFD->getPreviousDecl()) {
11082 AccessSpecifier Access = AS_public;
11083 if (!NewFD->isInvalidDecl())
11084 Access = NewFD->getPreviousDecl()->getAccess();
11085
11086 NewFD->setAccess(Access);
11087 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11088 }
11089
11090 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11091 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
11092 PrincipalDecl->setNonMemberOperator();
11093
11094 // If we have a function template, check the template parameter
11095 // list. This will check and merge default template arguments.
11096 if (FunctionTemplate) {
11097 FunctionTemplateDecl *PrevTemplate =
11098 FunctionTemplate->getPreviousDecl();
11099 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
11100 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
11101 : nullptr,
11102 TPC: D.getDeclSpec().isFriendSpecified()
11103 ? (D.isFunctionDefinition()
11104 ? TPC_FriendFunctionTemplateDefinition
11105 : TPC_FriendFunctionTemplate)
11106 : (D.getCXXScopeSpec().isSet() &&
11107 DC && DC->isRecord() &&
11108 DC->isDependentContext())
11109 ? TPC_ClassTemplateMember
11110 : TPC_FunctionTemplate);
11111 }
11112
11113 if (NewFD->isInvalidDecl()) {
11114 // Ignore all the rest of this.
11115 } else if (!D.isRedeclaration()) {
11116 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
11117 .AddToScope: AddToScope };
11118 // Fake up an access specifier if it's supposed to be a class member.
11119 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
11120 NewFD->setAccess(AS_public);
11121
11122 // Qualified decls generally require a previous declaration.
11123 if (D.getCXXScopeSpec().isSet()) {
11124 // ...with the major exception of templated-scope or
11125 // dependent-scope friend declarations.
11126
11127 // TODO: we currently also suppress this check in dependent
11128 // contexts because (1) the parameter depth will be off when
11129 // matching friend templates and (2) we might actually be
11130 // selecting a friend based on a dependent factor. But there
11131 // are situations where these conditions don't apply and we
11132 // can actually do this check immediately.
11133 //
11134 // Unless the scope is dependent, it's always an error if qualified
11135 // redeclaration lookup found nothing at all. Diagnose that now;
11136 // nothing will diagnose that error later.
11137 if (isFriend &&
11138 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
11139 (!Previous.empty() && CurContext->isDependentContext()))) {
11140 // ignore these
11141 } else if (NewFD->isCPUDispatchMultiVersion() ||
11142 NewFD->isCPUSpecificMultiVersion()) {
11143 // ignore this, we allow the redeclaration behavior here to create new
11144 // versions of the function.
11145 } else {
11146 // The user tried to provide an out-of-line definition for a
11147 // function that is a member of a class or namespace, but there
11148 // was no such member function declared (C++ [class.mfct]p2,
11149 // C++ [namespace.memdef]p2). For example:
11150 //
11151 // class X {
11152 // void f() const;
11153 // };
11154 //
11155 // void X::f() { } // ill-formed
11156 //
11157 // Complain about this problem, and attempt to suggest close
11158 // matches (e.g., those that differ only in cv-qualifiers and
11159 // whether the parameter types are references).
11160
11161 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11162 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11163 AddToScope = ExtraArgs.AddToScope;
11164 return Result;
11165 }
11166 }
11167
11168 // Unqualified local friend declarations are required to resolve
11169 // to something.
11170 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11171 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11172 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11173 AddToScope = ExtraArgs.AddToScope;
11174 return Result;
11175 }
11176 }
11177 } else if (!D.isFunctionDefinition() &&
11178 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11179 !isFriend && !isFunctionTemplateSpecialization &&
11180 !isMemberSpecialization) {
11181 // An out-of-line member function declaration must also be a
11182 // definition (C++ [class.mfct]p2).
11183 // Note that this is not the case for explicit specializations of
11184 // function templates or member functions of class templates, per
11185 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11186 // extension for compatibility with old SWIG code which likes to
11187 // generate them.
11188 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11189 << D.getCXXScopeSpec().getRange();
11190 }
11191 }
11192
11193 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11194 // Any top level function could potentially be specified as an entry.
11195 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11196 HLSL().ActOnTopLevelFunction(FD: NewFD);
11197
11198 if (NewFD->hasAttr<HLSLShaderAttr>())
11199 HLSL().CheckEntryPoint(FD: NewFD);
11200
11201 // Resources cannot be passed to functions that are not inlined.
11202 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11203 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11204 QualType ParamTy = PVD->getType().getNonReferenceType();
11205 QualType EltTy = Context.getBaseElementType(QT: ParamTy);
11206 // `isCompleteType` forces completion of the element type without
11207 // reporting an error (diagnosed elsewhere) so the resource parameter
11208 // check is valid.
11209 if (!EltTy->isDependentType() &&
11210 isCompleteType(Loc: PVD->getLocation(), T: EltTy) &&
11211 ParamTy->isHLSLIntangibleType()) {
11212 Diag(Loc: PVD->getLocation(),
11213 DiagID: diag::err_hlsl_resource_param_in_noinline_function)
11214 << ParamTy;
11215 Diag(Loc: NoInline->getLocation(), DiagID: diag::note_attribute);
11216 }
11217 }
11218 }
11219 }
11220
11221 // If this is the first declaration of a library builtin function, add
11222 // attributes as appropriate.
11223 if (!D.isRedeclaration()) {
11224 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11225 if (unsigned BuiltinID = II->getBuiltinID()) {
11226 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11227 if (!InStdNamespace &&
11228 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11229 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11230 // Validate the type matches unless this builtin is specified as
11231 // matching regardless of its declared type.
11232 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11233 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11234 } else {
11235 ASTContext::GetBuiltinTypeError Error;
11236 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11237 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11238
11239 if (!Error && !BuiltinType.isNull() &&
11240 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11241 T: NewFD->getType(), U: BuiltinType))
11242 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11243 }
11244 }
11245 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11246 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11247 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11248 }
11249 }
11250 }
11251 }
11252
11253 ProcessPragmaWeak(S, D: NewFD);
11254 ProcessPragmaExport(NewD: NewFD);
11255 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11256
11257 AddKnownFunctionAttributes(FD: NewFD);
11258 // The above can add the format attribute for known builtin/library functions
11259 // which is required by the modular_format attribute, thus
11260 // validate modular_format now after those attributes have been added.
11261 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11262
11263 if (NewFD->hasAttr<OverloadableAttr>() &&
11264 !NewFD->getType()->getAs<FunctionProtoType>()) {
11265 Diag(Loc: NewFD->getLocation(),
11266 DiagID: diag::err_attribute_overloadable_no_prototype)
11267 << NewFD;
11268 NewFD->dropAttr<OverloadableAttr>();
11269 }
11270
11271 // If there's a #pragma GCC visibility in scope, and this isn't a class
11272 // member, set the visibility of this function.
11273 if (!DC->isRecord() && NewFD->isExternallyVisible())
11274 AddPushedVisibilityAttribute(RD: NewFD);
11275
11276 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11277 // marking the function.
11278 ObjC().AddCFAuditedAttribute(D: NewFD);
11279
11280 // If this is a function definition, check if we have to apply any
11281 // attributes (i.e. optnone and no_builtin) due to a pragma.
11282 if (D.isFunctionDefinition()) {
11283 AddRangeBasedOptnone(FD: NewFD);
11284 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11285 AddSectionMSAllocText(FD: NewFD);
11286 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11287 }
11288
11289 // If this is the first declaration of an extern C variable, update
11290 // the map of such variables.
11291 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11292 isIncompleteDeclExternC(S&: *this, D: NewFD))
11293 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11294
11295 // Set this FunctionDecl's range up to the right paren.
11296 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11297
11298 if (D.isRedeclaration() && !Previous.empty()) {
11299 NamedDecl *Prev = Previous.getRepresentativeDecl();
11300 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11301 IsSpecialization: isMemberSpecialization ||
11302 isFunctionTemplateSpecialization,
11303 IsDefinition: D.isFunctionDefinition());
11304 }
11305
11306 if (getLangOpts().CUDA) {
11307 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11308 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11309 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11310 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11311 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11312 << CUDA().getConfigureFuncName();
11313 Context.setcudaConfigureCallDecl(NewFD);
11314 }
11315 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11316 !NewFD->isInvalidDecl() &&
11317 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11318 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11319 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11320 << CUDA().getConfigureFuncName();
11321 Context.setcudaGetParameterBufferDecl(NewFD);
11322 }
11323 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11324 !NewFD->isInvalidDecl() &&
11325 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11326 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11327 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11328 << CUDA().getConfigureFuncName();
11329 Context.setcudaLaunchDeviceDecl(NewFD);
11330 }
11331 }
11332 }
11333
11334 MarkUnusedFileScopedDecl(D: NewFD);
11335
11336 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11337 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11338 if (SC == SC_Static) {
11339 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11340 D.setInvalidType();
11341 }
11342
11343 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11344 if (!NewFD->getReturnType()->isVoidType()) {
11345 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11346 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11347 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11348 : FixItHint());
11349 D.setInvalidType();
11350 }
11351
11352 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11353 for (auto *Param : NewFD->parameters())
11354 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11355
11356 if (getLangOpts().OpenCLCPlusPlus) {
11357 if (DC->isRecord()) {
11358 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11359 D.setInvalidType();
11360 }
11361 if (FunctionTemplate) {
11362 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11363 D.setInvalidType();
11364 }
11365 }
11366 }
11367
11368 if (getLangOpts().CPlusPlus) {
11369 // Precalculate whether this is a friend function template with a constraint
11370 // that depends on an enclosing template, per [temp.friend]p9.
11371 if (isFriend && FunctionTemplate &&
11372 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11373 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11374
11375 // C++ [temp.friend]p9:
11376 // A friend function template with a constraint that depends on a
11377 // template parameter from an enclosing template shall be a definition.
11378 if (!D.isFunctionDefinition()) {
11379 Diag(Loc: NewFD->getBeginLoc(),
11380 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11381 NewFD->setInvalidDecl();
11382 }
11383 }
11384
11385 if (FunctionTemplate) {
11386 if (NewFD->isInvalidDecl())
11387 FunctionTemplate->setInvalidDecl();
11388 return FunctionTemplate;
11389 }
11390
11391 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11392 CompleteMemberSpecialization(Member: NewFD, Previous);
11393 }
11394
11395 for (const ParmVarDecl *Param : NewFD->parameters()) {
11396 QualType PT = Param->getType();
11397
11398 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11399 // types.
11400 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11401 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11402 QualType ElemTy = PipeTy->getElementType();
11403 if (ElemTy->isPointerOrReferenceType()) {
11404 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11405 D.setInvalidType();
11406 }
11407 }
11408 }
11409 // WebAssembly tables can't be used as function parameters.
11410 if (Context.getTargetInfo().getTriple().isWasm()) {
11411 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11412 Diag(Loc: Param->getTypeSpecStartLoc(),
11413 DiagID: diag::err_wasm_table_as_function_parameter);
11414 D.setInvalidType();
11415 }
11416 }
11417 }
11418
11419 // Diagnose availability attributes. Availability cannot be used on functions
11420 // that are run during load/unload.
11421 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11422 if (NewFD->hasAttr<ConstructorAttr>()) {
11423 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11424 << 1;
11425 NewFD->dropAttr<AvailabilityAttr>();
11426 }
11427 if (NewFD->hasAttr<DestructorAttr>()) {
11428 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11429 << 2;
11430 NewFD->dropAttr<AvailabilityAttr>();
11431 }
11432 }
11433
11434 // Diagnose no_builtin attribute on function declaration that are not a
11435 // definition.
11436 // FIXME: We should really be doing this in
11437 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11438 // the FunctionDecl and at this point of the code
11439 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11440 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11441 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11442 switch (D.getFunctionDefinitionKind()) {
11443 case FunctionDefinitionKind::Defaulted:
11444 case FunctionDefinitionKind::Deleted:
11445 Diag(Loc: NBA->getLocation(),
11446 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11447 << NBA->getSpelling();
11448 break;
11449 case FunctionDefinitionKind::Declaration:
11450 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11451 << NBA->getSpelling();
11452 break;
11453 case FunctionDefinitionKind::Definition:
11454 break;
11455 }
11456
11457 // Similar to no_builtin logic above, at this point of the code
11458 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11459 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11460 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11461 !NewFD->isInvalidDecl() &&
11462 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11463 ExternalDeclarations.push_back(Elt: NewFD);
11464
11465 // Used for a warning on the 'next' declaration when used with a
11466 // `routine(name)`.
11467 if (getLangOpts().OpenACC)
11468 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11469
11470 return NewFD;
11471}
11472
11473/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11474/// when __declspec(code_seg) "is applied to a class, all member functions of
11475/// the class and nested classes -- this includes compiler-generated special
11476/// member functions -- are put in the specified segment."
11477/// The actual behavior is a little more complicated. The Microsoft compiler
11478/// won't check outer classes if there is an active value from #pragma code_seg.
11479/// The CodeSeg is always applied from the direct parent but only from outer
11480/// classes when the #pragma code_seg stack is empty. See:
11481/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11482/// available since MS has removed the page.
11483static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11484 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11485 if (!Method)
11486 return nullptr;
11487 const CXXRecordDecl *Parent = Method->getParent();
11488 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11489 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11490 NewAttr->setImplicit(true);
11491 return NewAttr;
11492 }
11493
11494 // The Microsoft compiler won't check outer classes for the CodeSeg
11495 // when the #pragma code_seg stack is active.
11496 if (S.CodeSegStack.CurrentValue)
11497 return nullptr;
11498
11499 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11500 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11501 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11502 NewAttr->setImplicit(true);
11503 return NewAttr;
11504 }
11505 }
11506 return nullptr;
11507}
11508
11509Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11510 bool IsDefinition) {
11511 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11512 return A;
11513 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11514 CodeSegStack.CurrentValue)
11515 return SectionAttr::CreateImplicit(
11516 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11517 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11518 return nullptr;
11519}
11520
11521bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11522 QualType NewT, QualType OldT) {
11523 if (!NewD->getLexicalDeclContext()->isDependentContext())
11524 return true;
11525
11526 // For dependently-typed local extern declarations and friends, we can't
11527 // perform a correct type check in general until instantiation:
11528 //
11529 // int f();
11530 // template<typename T> void g() { T f(); }
11531 //
11532 // (valid if g() is only instantiated with T = int).
11533 if (NewT->isDependentType() &&
11534 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11535 return false;
11536
11537 // Similarly, if the previous declaration was a dependent local extern
11538 // declaration, we don't really know its type yet.
11539 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11540 return false;
11541
11542 return true;
11543}
11544
11545bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11546 if (!D->getLexicalDeclContext()->isDependentContext())
11547 return true;
11548
11549 // Don't chain dependent friend function definitions until instantiation, to
11550 // permit cases like
11551 //
11552 // void func();
11553 // template<typename T> class C1 { friend void func() {} };
11554 // template<typename T> class C2 { friend void func() {} };
11555 //
11556 // ... which is valid if only one of C1 and C2 is ever instantiated.
11557 //
11558 // FIXME: This need only apply to function definitions. For now, we proxy
11559 // this by checking for a file-scope function. We do not want this to apply
11560 // to friend declarations nominating member functions, because that gets in
11561 // the way of access checks.
11562 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11563 return false;
11564
11565 auto *VD = dyn_cast<ValueDecl>(Val: D);
11566 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11567 return !VD || !PrevVD ||
11568 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11569 OldT: PrevVD->getType());
11570}
11571
11572/// Check the target or target_version attribute of the function for
11573/// MultiVersion validity.
11574///
11575/// Returns true if there was an error, false otherwise.
11576static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11577 const auto *TA = FD->getAttr<TargetAttr>();
11578 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11579
11580 assert((TA || TVA) && "Expecting target or target_version attribute");
11581
11582 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11583 enum ErrType { Feature = 0, Architecture = 1 };
11584
11585 if (TA) {
11586 ParsedTargetAttr ParseInfo =
11587 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11588 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11589 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11590 << Architecture << ParseInfo.CPU;
11591 return true;
11592 }
11593 for (const auto &Feat : ParseInfo.Features) {
11594 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11595 if (Feat[0] == '-') {
11596 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11597 << Feature << ("no-" + BareFeat);
11598 return true;
11599 }
11600
11601 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11602 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11603 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11604 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11605 << Feature << BareFeat;
11606 return true;
11607 }
11608 }
11609 }
11610
11611 if (TVA) {
11612 llvm::SmallVector<StringRef, 8> Feats;
11613 ParsedTargetAttr ParseInfo;
11614 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11615 ParseInfo =
11616 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11617 for (auto &Feat : ParseInfo.Features)
11618 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11619 } else {
11620 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11621 TVA->getFeatures(Out&: Feats);
11622 }
11623 for (const auto &Feat : Feats) {
11624 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11625 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11626 << Feature << Feat;
11627 return true;
11628 }
11629 }
11630 }
11631 return false;
11632}
11633
11634// Provide a white-list of attributes that are allowed to be combined with
11635// multiversion functions.
11636static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11637 MultiVersionKind MVKind) {
11638 // Note: this list/diagnosis must match the list in
11639 // checkMultiversionAttributesAllSame.
11640 switch (Kind) {
11641 default:
11642 return false;
11643 case attr::ArmLocallyStreaming:
11644 return MVKind == MultiVersionKind::TargetVersion ||
11645 MVKind == MultiVersionKind::TargetClones;
11646 case attr::Used:
11647 return MVKind == MultiVersionKind::Target;
11648 case attr::NonNull:
11649 case attr::NoThrow:
11650 return true;
11651 }
11652}
11653
11654static bool checkNonMultiVersionCompatAttributes(Sema &S,
11655 const FunctionDecl *FD,
11656 const FunctionDecl *CausedFD,
11657 MultiVersionKind MVKind) {
11658 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11659 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11660 << static_cast<unsigned>(MVKind) << A;
11661 if (CausedFD)
11662 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11663 return true;
11664 };
11665
11666 for (const Attr *A : FD->attrs()) {
11667 switch (A->getKind()) {
11668 case attr::CPUDispatch:
11669 case attr::CPUSpecific:
11670 if (MVKind != MultiVersionKind::CPUDispatch &&
11671 MVKind != MultiVersionKind::CPUSpecific)
11672 return Diagnose(S, A);
11673 break;
11674 case attr::Target:
11675 if (MVKind != MultiVersionKind::Target)
11676 return Diagnose(S, A);
11677 break;
11678 case attr::TargetVersion:
11679 if (MVKind != MultiVersionKind::TargetVersion &&
11680 MVKind != MultiVersionKind::TargetClones)
11681 return Diagnose(S, A);
11682 break;
11683 case attr::TargetClones:
11684 if (MVKind != MultiVersionKind::TargetClones &&
11685 MVKind != MultiVersionKind::TargetVersion)
11686 return Diagnose(S, A);
11687 break;
11688 default:
11689 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11690 return Diagnose(S, A);
11691 break;
11692 }
11693 }
11694 return false;
11695}
11696
11697bool Sema::areMultiversionVariantFunctionsCompatible(
11698 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11699 const PartialDiagnostic &NoProtoDiagID,
11700 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11701 const PartialDiagnosticAt &NoSupportDiagIDAt,
11702 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11703 bool ConstexprSupported, bool CLinkageMayDiffer) {
11704 enum DoesntSupport {
11705 FuncTemplates = 0,
11706 VirtFuncs = 1,
11707 DeducedReturn = 2,
11708 Constructors = 3,
11709 Destructors = 4,
11710 DeletedFuncs = 5,
11711 DefaultedFuncs = 6,
11712 ConstexprFuncs = 7,
11713 ConstevalFuncs = 8,
11714 Lambda = 9,
11715 };
11716 enum Different {
11717 CallingConv = 0,
11718 ReturnType = 1,
11719 ConstexprSpec = 2,
11720 InlineSpec = 3,
11721 Linkage = 4,
11722 LanguageLinkage = 5,
11723 };
11724
11725 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11726 !OldFD->getType()->getAs<FunctionProtoType>()) {
11727 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11728 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11729 return true;
11730 }
11731
11732 if (NoProtoDiagID.getDiagID() != 0 &&
11733 !NewFD->getType()->getAs<FunctionProtoType>())
11734 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11735
11736 if (!TemplatesSupported &&
11737 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11738 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11739 << FuncTemplates;
11740
11741 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11742 if (NewCXXFD->isVirtual())
11743 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11744 << VirtFuncs;
11745
11746 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11747 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11748 << Constructors;
11749
11750 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11751 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11752 << Destructors;
11753 }
11754
11755 if (NewFD->isDeleted())
11756 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11757 << DeletedFuncs;
11758
11759 if (NewFD->isDefaulted())
11760 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11761 << DefaultedFuncs;
11762
11763 if (!ConstexprSupported && NewFD->isConstexpr())
11764 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11765 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11766
11767 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11768 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11769 QualType NewReturnType = NewType->getReturnType();
11770
11771 if (NewReturnType->isUndeducedType())
11772 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11773 << DeducedReturn;
11774
11775 // Ensure the return type is identical.
11776 if (OldFD) {
11777 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11778 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11779 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11780 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11781
11782 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11783 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11784
11785 bool ArmStreamingCCMismatched = false;
11786 if (OldFPT && NewFPT) {
11787 unsigned Diff =
11788 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11789 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11790 // cannot be mixed.
11791 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11792 FunctionType::SME_PStateSMCompatibleMask))
11793 ArmStreamingCCMismatched = true;
11794 }
11795
11796 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11797 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11798
11799 QualType OldReturnType = OldType->getReturnType();
11800
11801 if (OldReturnType != NewReturnType)
11802 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11803
11804 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11805 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11806
11807 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11808 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11809
11810 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11811 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11812
11813 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11814 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11815
11816 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11817 NewLoc: NewFD->getLocation()))
11818 return true;
11819 }
11820 return false;
11821}
11822
11823static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11824 const FunctionDecl *NewFD,
11825 bool CausesMV,
11826 MultiVersionKind MVKind) {
11827 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11828 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11829 if (OldFD)
11830 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11831 return true;
11832 }
11833
11834 bool IsCPUSpecificCPUDispatchMVKind =
11835 MVKind == MultiVersionKind::CPUDispatch ||
11836 MVKind == MultiVersionKind::CPUSpecific;
11837
11838 if (CausesMV && OldFD &&
11839 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11840 return true;
11841
11842 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11843 return true;
11844
11845 // Only allow transition to MultiVersion if it hasn't been used.
11846 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11847 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11848 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11849 return true;
11850 }
11851
11852 return S.areMultiversionVariantFunctionsCompatible(
11853 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11854 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11855 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11856 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11857 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11858 << static_cast<unsigned>(MVKind)),
11859 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11860 S.PDiag(DiagID: diag::err_multiversion_diff)),
11861 /*TemplatesSupported=*/false,
11862 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11863 /*CLinkageMayDiffer=*/false);
11864}
11865
11866/// Check the validity of a multiversion function declaration that is the
11867/// first of its kind. Also sets the multiversion'ness' of the function itself.
11868///
11869/// This sets NewFD->isInvalidDecl() to true if there was an error.
11870///
11871/// Returns true if there was an error, false otherwise.
11872static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11873 MultiVersionKind MVKind = FD->getMultiVersionKind();
11874 assert(MVKind != MultiVersionKind::None &&
11875 "Function lacks multiversion attribute");
11876 const auto *TA = FD->getAttr<TargetAttr>();
11877 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11878 // The target attribute only causes MV if this declaration is the default,
11879 // otherwise it is treated as a normal function.
11880 if (TA && !TA->isDefaultVersion())
11881 return false;
11882
11883 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11884 FD->setInvalidDecl();
11885 return true;
11886 }
11887
11888 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11889 FD->setInvalidDecl();
11890 return true;
11891 }
11892
11893 FD->setIsMultiVersion();
11894 return false;
11895}
11896
11897static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11898 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11899 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11900 return true;
11901 }
11902
11903 return false;
11904}
11905
11906static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11907 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11908 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11909 return;
11910
11911 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11912 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11913
11914 if (MVKindTo == MultiVersionKind::None &&
11915 (MVKindFrom == MultiVersionKind::TargetVersion ||
11916 MVKindFrom == MultiVersionKind::TargetClones))
11917 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11918 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11919}
11920
11921static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11922 FunctionDecl *NewFD,
11923 bool &Redeclaration,
11924 NamedDecl *&OldDecl,
11925 LookupResult &Previous) {
11926 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11927
11928 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11929 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11930 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11931 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11932
11933 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11934
11935 // The definitions should be allowed in any order. If we have discovered
11936 // a new target version and the preceeding was the default, then add the
11937 // corresponding attribute to it.
11938 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11939
11940 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11941 // to change, this is a simple redeclaration.
11942 if (NewTA && !NewTA->isDefaultVersion() &&
11943 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11944 return false;
11945
11946 // Otherwise, this decl causes MultiVersioning.
11947 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11948 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11949 : MultiVersionKind::Target)) {
11950 NewFD->setInvalidDecl();
11951 return true;
11952 }
11953
11954 if (CheckMultiVersionValue(S, FD: NewFD)) {
11955 NewFD->setInvalidDecl();
11956 return true;
11957 }
11958
11959 // If this is 'default', permit the forward declaration.
11960 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11961 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11962 Redeclaration = true;
11963 OldDecl = OldFD;
11964 OldFD->setIsMultiVersion();
11965 NewFD->setIsMultiVersion();
11966 return false;
11967 }
11968
11969 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11970 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11971 NewFD->setInvalidDecl();
11972 return true;
11973 }
11974
11975 if (NewTA) {
11976 ParsedTargetAttr OldParsed =
11977 S.getASTContext().getTargetInfo().parseTargetAttr(
11978 Str: OldTA->getFeaturesStr());
11979 llvm::sort(C&: OldParsed.Features);
11980 ParsedTargetAttr NewParsed =
11981 S.getASTContext().getTargetInfo().parseTargetAttr(
11982 Str: NewTA->getFeaturesStr());
11983 // Sort order doesn't matter, it just needs to be consistent.
11984 llvm::sort(C&: NewParsed.Features);
11985 if (OldParsed == NewParsed) {
11986 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11987 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11988 NewFD->setInvalidDecl();
11989 return true;
11990 }
11991 }
11992
11993 for (const auto *FD : OldFD->redecls()) {
11994 const auto *CurTA = FD->getAttr<TargetAttr>();
11995 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11996 // We allow forward declarations before ANY multiversioning attributes, but
11997 // nothing after the fact.
11998 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11999 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12000 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12001 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12002 << (NewTA ? 0 : 2);
12003 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
12004 NewFD->setInvalidDecl();
12005 return true;
12006 }
12007 }
12008
12009 OldFD->setIsMultiVersion();
12010 NewFD->setIsMultiVersion();
12011 Redeclaration = false;
12012 OldDecl = nullptr;
12013 Previous.clear();
12014 return false;
12015}
12016
12017static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
12018 MultiVersionKind OldKind = Old->getMultiVersionKind();
12019 MultiVersionKind NewKind = New->getMultiVersionKind();
12020
12021 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12022 NewKind == MultiVersionKind::None)
12023 return true;
12024
12025 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12026 switch (OldKind) {
12027 case MultiVersionKind::TargetVersion:
12028 return NewKind == MultiVersionKind::TargetClones;
12029 case MultiVersionKind::TargetClones:
12030 return NewKind == MultiVersionKind::TargetVersion;
12031 default:
12032 return false;
12033 }
12034 } else {
12035 switch (OldKind) {
12036 case MultiVersionKind::CPUDispatch:
12037 return NewKind == MultiVersionKind::CPUSpecific;
12038 case MultiVersionKind::CPUSpecific:
12039 return NewKind == MultiVersionKind::CPUDispatch;
12040 default:
12041 return false;
12042 }
12043 }
12044}
12045
12046/// Check the validity of a new function declaration being added to an existing
12047/// multiversioned declaration collection.
12048static bool CheckMultiVersionAdditionalDecl(
12049 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12050 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12051 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12052 LookupResult &Previous) {
12053
12054 // Disallow mixing of multiversioning types.
12055 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
12056 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
12057 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12058 NewFD->setInvalidDecl();
12059 return true;
12060 }
12061
12062 // Add the default target_version attribute if it's missing.
12063 patchDefaultTargetVersion(From: OldFD, To: NewFD);
12064 patchDefaultTargetVersion(From: NewFD, To: OldFD);
12065
12066 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12067 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12068 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12069 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12070
12071 ParsedTargetAttr NewParsed;
12072 if (NewTA) {
12073 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
12074 Str: NewTA->getFeaturesStr());
12075 llvm::sort(C&: NewParsed.Features);
12076 }
12077 llvm::SmallVector<StringRef, 8> NewFeats;
12078 if (NewTVA) {
12079 NewTVA->getFeatures(Out&: NewFeats);
12080 llvm::sort(C&: NewFeats);
12081 }
12082
12083 bool UseMemberUsingDeclRules =
12084 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12085
12086 bool MayNeedOverloadableChecks =
12087 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
12088
12089 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12090 // of a previous member of the MultiVersion set.
12091 for (NamedDecl *ND : Previous) {
12092 FunctionDecl *CurFD = ND->getAsFunction();
12093 if (!CurFD || CurFD->isInvalidDecl())
12094 continue;
12095 if (MayNeedOverloadableChecks &&
12096 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
12097 continue;
12098
12099 switch (NewMVKind) {
12100 case MultiVersionKind::None:
12101 assert(OldMVKind == MultiVersionKind::TargetClones &&
12102 "Only target_clones can be omitted in subsequent declarations");
12103 break;
12104 case MultiVersionKind::Target: {
12105 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12106 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12107 NewFD->setIsMultiVersion();
12108 Redeclaration = true;
12109 OldDecl = ND;
12110 return false;
12111 }
12112
12113 ParsedTargetAttr CurParsed =
12114 S.getASTContext().getTargetInfo().parseTargetAttr(
12115 Str: CurTA->getFeaturesStr());
12116 llvm::sort(C&: CurParsed.Features);
12117 if (CurParsed == NewParsed) {
12118 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12119 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12120 NewFD->setInvalidDecl();
12121 return true;
12122 }
12123 break;
12124 }
12125 case MultiVersionKind::TargetVersion: {
12126 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12127 if (CurTVA->getName() == NewTVA->getName()) {
12128 NewFD->setIsMultiVersion();
12129 Redeclaration = true;
12130 OldDecl = ND;
12131 return false;
12132 }
12133 llvm::SmallVector<StringRef, 8> CurFeats;
12134 CurTVA->getFeatures(Out&: CurFeats);
12135 llvm::sort(C&: CurFeats);
12136
12137 if (CurFeats == NewFeats) {
12138 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12139 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12140 NewFD->setInvalidDecl();
12141 return true;
12142 }
12143 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12144 // Default
12145 if (NewFeats.empty())
12146 break;
12147
12148 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12149 llvm::SmallVector<StringRef, 8> CurFeats;
12150 CurClones->getFeatures(Out&: CurFeats, Index: I);
12151 llvm::sort(C&: CurFeats);
12152
12153 if (CurFeats == NewFeats) {
12154 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12155 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12156 NewFD->setInvalidDecl();
12157 return true;
12158 }
12159 }
12160 }
12161 break;
12162 }
12163 case MultiVersionKind::TargetClones: {
12164 assert(NewClones && "MultiVersionKind does not match attribute type");
12165 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12166 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12167 !std::equal(first1: CurClones->featuresStrs_begin(),
12168 last1: CurClones->featuresStrs_end(),
12169 first2: NewClones->featuresStrs_begin())) {
12170 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
12171 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12172 NewFD->setInvalidDecl();
12173 return true;
12174 }
12175 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12176 llvm::SmallVector<StringRef, 8> CurFeats;
12177 CurTVA->getFeatures(Out&: CurFeats);
12178 llvm::sort(C&: CurFeats);
12179
12180 // Default
12181 if (CurFeats.empty())
12182 break;
12183
12184 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12185 NewFeats.clear();
12186 NewClones->getFeatures(Out&: NewFeats, Index: I);
12187 llvm::sort(C&: NewFeats);
12188
12189 if (CurFeats == NewFeats) {
12190 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12191 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12192 NewFD->setInvalidDecl();
12193 return true;
12194 }
12195 }
12196 break;
12197 }
12198 Redeclaration = true;
12199 OldDecl = CurFD;
12200 NewFD->setIsMultiVersion();
12201 return false;
12202 }
12203 case MultiVersionKind::CPUSpecific:
12204 case MultiVersionKind::CPUDispatch: {
12205 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12206 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12207 // Handle CPUDispatch/CPUSpecific versions.
12208 // Only 1 CPUDispatch function is allowed, this will make it go through
12209 // the redeclaration errors.
12210 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12211 CurFD->hasAttr<CPUDispatchAttr>()) {
12212 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12213 std::equal(
12214 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12215 first2: NewCPUDisp->cpus_begin(),
12216 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12217 return Cur->getName() == New->getName();
12218 })) {
12219 NewFD->setIsMultiVersion();
12220 Redeclaration = true;
12221 OldDecl = ND;
12222 return false;
12223 }
12224
12225 // If the declarations don't match, this is an error condition.
12226 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12227 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12228 NewFD->setInvalidDecl();
12229 return true;
12230 }
12231 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12232 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12233 std::equal(
12234 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12235 first2: NewCPUSpec->cpus_begin(),
12236 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12237 return Cur->getName() == New->getName();
12238 })) {
12239 NewFD->setIsMultiVersion();
12240 Redeclaration = true;
12241 OldDecl = ND;
12242 return false;
12243 }
12244
12245 // Only 1 version of CPUSpecific is allowed for each CPU.
12246 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12247 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12248 if (CurII == NewII) {
12249 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12250 << NewII;
12251 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12252 NewFD->setInvalidDecl();
12253 return true;
12254 }
12255 }
12256 }
12257 }
12258 break;
12259 }
12260 }
12261 }
12262
12263 // Redeclarations of a target_clones function may omit the attribute, in which
12264 // case it will be inherited during declaration merging.
12265 if (NewMVKind == MultiVersionKind::None &&
12266 OldMVKind == MultiVersionKind::TargetClones) {
12267 NewFD->setIsMultiVersion();
12268 Redeclaration = true;
12269 OldDecl = OldFD;
12270 return false;
12271 }
12272
12273 // Else, this is simply a non-redecl case. Checking the 'value' is only
12274 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12275 // handled in the attribute adding step.
12276 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12277 NewFD->setInvalidDecl();
12278 return true;
12279 }
12280
12281 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12282 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12283 NewFD->setInvalidDecl();
12284 return true;
12285 }
12286
12287 // Permit forward declarations in the case where these two are compatible.
12288 if (!OldFD->isMultiVersion()) {
12289 OldFD->setIsMultiVersion();
12290 NewFD->setIsMultiVersion();
12291 Redeclaration = true;
12292 OldDecl = OldFD;
12293 return false;
12294 }
12295
12296 NewFD->setIsMultiVersion();
12297 Redeclaration = false;
12298 OldDecl = nullptr;
12299 Previous.clear();
12300 return false;
12301}
12302
12303/// Check the validity of a mulitversion function declaration.
12304/// Also sets the multiversion'ness' of the function itself.
12305///
12306/// This sets NewFD->isInvalidDecl() to true if there was an error.
12307///
12308/// Returns true if there was an error, false otherwise.
12309static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12310 bool &Redeclaration, NamedDecl *&OldDecl,
12311 LookupResult &Previous) {
12312 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12313
12314 // Check if FMV is disabled.
12315 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12316 return false;
12317
12318 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12319 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12320 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12321 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12322 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12323 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12324
12325 // Main isn't allowed to become a multiversion function, however it IS
12326 // permitted to have 'main' be marked with the 'target' optimization hint,
12327 // for 'target_version' only default is allowed.
12328 if (NewFD->isMain()) {
12329 if (MVKind != MultiVersionKind::None &&
12330 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12331 !(MVKind == MultiVersionKind::TargetVersion &&
12332 NewTVA->isDefaultVersion())) {
12333 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12334 NewFD->setInvalidDecl();
12335 return true;
12336 }
12337 return false;
12338 }
12339
12340 // Target attribute on AArch64 is not used for multiversioning
12341 if (NewTA && TI.getTriple().isAArch64())
12342 return false;
12343
12344 // Target attribute on RISCV is not used for multiversioning
12345 if (NewTA && TI.getTriple().isRISCV())
12346 return false;
12347
12348 if (!OldDecl || !OldDecl->getAsFunction() ||
12349 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12350 DC: NewFD->getDeclContext()->getRedeclContext())) {
12351 // If there's no previous declaration, AND this isn't attempting to cause
12352 // multiversioning, this isn't an error condition.
12353 if (MVKind == MultiVersionKind::None)
12354 return false;
12355 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12356 }
12357
12358 FunctionDecl *OldFD = OldDecl->getAsFunction();
12359
12360 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12361 return false;
12362
12363 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12364 // for target_clones and target_version.
12365 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12366 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12367 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12368 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12369 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12370 NewFD->setInvalidDecl();
12371 return true;
12372 }
12373
12374 if (!OldFD->isMultiVersion()) {
12375 switch (MVKind) {
12376 case MultiVersionKind::Target:
12377 case MultiVersionKind::TargetVersion:
12378 return CheckDeclarationCausesMultiVersioning(
12379 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12380 case MultiVersionKind::TargetClones:
12381 if (OldFD->isUsed(CheckUsedAttr: false)) {
12382 NewFD->setInvalidDecl();
12383 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12384 }
12385 OldFD->setIsMultiVersion();
12386 break;
12387
12388 case MultiVersionKind::CPUDispatch:
12389 case MultiVersionKind::CPUSpecific:
12390 case MultiVersionKind::None:
12391 break;
12392 }
12393 }
12394
12395 // At this point, we have a multiversion function decl (in OldFD) AND an
12396 // appropriate attribute in the current function decl (unless it's allowed to
12397 // omit the attribute). Resolve that these are still compatible with previous
12398 // declarations.
12399 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12400 NewCPUSpec, NewClones, Redeclaration,
12401 OldDecl, Previous);
12402}
12403
12404static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12405 bool IsPure = NewFD->hasAttr<PureAttr>();
12406 bool IsConst = NewFD->hasAttr<ConstAttr>();
12407
12408 // If there are no pure or const attributes, there's nothing to check.
12409 if (!IsPure && !IsConst)
12410 return;
12411
12412 // If the function is marked both pure and const, we retain the const
12413 // attribute because it makes stronger guarantees than the pure attribute, and
12414 // we drop the pure attribute explicitly to prevent later confusion about
12415 // semantics.
12416 if (IsPure && IsConst) {
12417 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12418 NewFD->dropAttrs<PureAttr>();
12419 }
12420
12421 // Constructors and destructors are functions which return void, so are
12422 // handled here as well.
12423 if (NewFD->getReturnType()->isVoidType()) {
12424 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12425 << IsConst;
12426 NewFD->dropAttrs<PureAttr, ConstAttr>();
12427 }
12428}
12429
12430bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12431 LookupResult &Previous,
12432 bool IsMemberSpecialization,
12433 bool DeclIsDefn) {
12434 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12435 "Variably modified return types are not handled here");
12436
12437 // Determine whether the type of this function should be merged with
12438 // a previous visible declaration. This never happens for functions in C++,
12439 // and always happens in C if the previous declaration was visible.
12440 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12441 !Previous.isShadowed();
12442
12443 bool Redeclaration = false;
12444 NamedDecl *OldDecl = nullptr;
12445 bool MayNeedOverloadableChecks = false;
12446
12447 inferLifetimeCaptureByAttribute(FD: NewFD);
12448 // Merge or overload the declaration with an existing declaration of
12449 // the same name, if appropriate.
12450 if (!Previous.empty()) {
12451 // Determine whether NewFD is an overload of PrevDecl or
12452 // a declaration that requires merging. If it's an overload,
12453 // there's no more work to do here; we'll just add the new
12454 // function to the scope.
12455 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12456 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12457 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12458 Redeclaration = true;
12459 OldDecl = Candidate;
12460 }
12461 } else {
12462 MayNeedOverloadableChecks = true;
12463 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12464 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12465 case OverloadKind::Match:
12466 Redeclaration = true;
12467 break;
12468
12469 case OverloadKind::NonFunction:
12470 Redeclaration = true;
12471 break;
12472
12473 case OverloadKind::Overload:
12474 Redeclaration = false;
12475 break;
12476 }
12477 }
12478 }
12479
12480 // Check for a previous extern "C" declaration with this name.
12481 if (!Redeclaration &&
12482 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12483 if (!Previous.empty()) {
12484 // This is an extern "C" declaration with the same name as a previous
12485 // declaration, and thus redeclares that entity...
12486 Redeclaration = true;
12487 OldDecl = Previous.getFoundDecl();
12488 MergeTypeWithPrevious = false;
12489
12490 // ... except in the presence of __attribute__((overloadable)).
12491 if (OldDecl->hasAttr<OverloadableAttr>() ||
12492 NewFD->hasAttr<OverloadableAttr>()) {
12493 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12494 MayNeedOverloadableChecks = true;
12495 Redeclaration = false;
12496 OldDecl = nullptr;
12497 }
12498 }
12499 }
12500 }
12501
12502 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12503 return Redeclaration;
12504
12505 // PPC MMA non-pointer types are not allowed as function return types.
12506 if (Context.getTargetInfo().getTriple().isPPC64() &&
12507 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12508 NewFD->setInvalidDecl();
12509 }
12510
12511 CheckConstPureAttributesUsage(S&: *this, NewFD);
12512
12513 // C++ [dcl.spec.auto.general]p12:
12514 // Return type deduction for a templated function with a placeholder in its
12515 // declared type occurs when the definition is instantiated even if the
12516 // function body contains a return statement with a non-type-dependent
12517 // operand.
12518 //
12519 // C++ [temp.dep.expr]p3:
12520 // An id-expression is type-dependent if it is a template-id that is not a
12521 // concept-id and is dependent; or if its terminal name is:
12522 // - [...]
12523 // - associated by name lookup with one or more declarations of member
12524 // functions of a class that is the current instantiation declared with a
12525 // return type that contains a placeholder type,
12526 // - [...]
12527 //
12528 // If this is a templated function with a placeholder in its return type,
12529 // make the placeholder type dependent since it won't be deduced until the
12530 // definition is instantiated. We do this here because it needs to happen
12531 // for implicitly instantiated member functions/member function templates.
12532 if (getLangOpts().CPlusPlus14 &&
12533 (NewFD->isDependentContext() &&
12534 NewFD->getReturnType()->isUndeducedType())) {
12535 const FunctionProtoType *FPT =
12536 NewFD->getType()->castAs<FunctionProtoType>();
12537 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12538 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12539 EPI: FPT->getExtProtoInfo()));
12540 }
12541
12542 // C++11 [dcl.constexpr]p8:
12543 // A constexpr specifier for a non-static member function that is not
12544 // a constructor declares that member function to be const.
12545 //
12546 // This needs to be delayed until we know whether this is an out-of-line
12547 // definition of a static member function.
12548 //
12549 // This rule is not present in C++1y, so we produce a backwards
12550 // compatibility warning whenever it happens in C++11.
12551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12552 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12553 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12554 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12555 CXXMethodDecl *OldMD = nullptr;
12556 if (OldDecl)
12557 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12558 if (!OldMD || !OldMD->isStatic()) {
12559 const FunctionProtoType *FPT =
12560 MD->getType()->castAs<FunctionProtoType>();
12561 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12562 EPI.TypeQuals.addConst();
12563 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12564 Args: FPT->getParamTypes(), EPI));
12565
12566 // Warn that we did this, if we're not performing template instantiation.
12567 // In that case, we'll have warned already when the template was defined.
12568 if (!inTemplateInstantiation()) {
12569 SourceLocation AddConstLoc;
12570 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12571 .IgnoreParens().getAs<FunctionTypeLoc>())
12572 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12573
12574 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12575 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12576 }
12577 }
12578 }
12579
12580 if (Redeclaration) {
12581 // NewFD and OldDecl represent declarations that need to be
12582 // merged.
12583 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12584 NewDeclIsDefn: DeclIsDefn)) {
12585 NewFD->setInvalidDecl();
12586 return Redeclaration;
12587 }
12588
12589 Previous.clear();
12590 Previous.addDecl(D: OldDecl);
12591
12592 if (FunctionTemplateDecl *OldTemplateDecl =
12593 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12594 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12595 FunctionTemplateDecl *NewTemplateDecl
12596 = NewFD->getDescribedFunctionTemplate();
12597 assert(NewTemplateDecl && "Template/non-template mismatch");
12598
12599 // The call to MergeFunctionDecl above may have created some state in
12600 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12601 // can add it as a redeclaration.
12602 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12603
12604 NewFD->setPreviousDeclaration(OldFD);
12605 if (NewFD->isCXXClassMember()) {
12606 NewFD->setAccess(OldTemplateDecl->getAccess());
12607 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12608 }
12609
12610 // If this is an explicit specialization of a member that is a function
12611 // template, mark it as a member specialization.
12612 if (IsMemberSpecialization &&
12613 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12614 NewTemplateDecl->setMemberSpecialization();
12615 assert(OldTemplateDecl->isMemberSpecialization());
12616 // Explicit specializations of a member template do not inherit deleted
12617 // status from the parent member template that they are specializing.
12618 if (OldFD->isDeleted()) {
12619 // FIXME: This assert will not hold in the presence of modules.
12620 assert(OldFD->getCanonicalDecl() == OldFD);
12621 // FIXME: We need an update record for this AST mutation.
12622 OldFD->setDeletedAsWritten(D: false);
12623 }
12624 }
12625
12626 } else {
12627 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12628 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12629 // This needs to happen first so that 'inline' propagates.
12630 NewFD->setPreviousDeclaration(OldFD);
12631 if (NewFD->isCXXClassMember())
12632 NewFD->setAccess(OldFD->getAccess());
12633 }
12634 }
12635 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12636 !NewFD->getAttr<OverloadableAttr>()) {
12637 assert((Previous.empty() ||
12638 llvm::any_of(Previous,
12639 [](const NamedDecl *ND) {
12640 return ND->hasAttr<OverloadableAttr>();
12641 })) &&
12642 "Non-redecls shouldn't happen without overloadable present");
12643
12644 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12645 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12646 return FD && !FD->hasAttr<OverloadableAttr>();
12647 });
12648
12649 if (OtherUnmarkedIter != Previous.end()) {
12650 Diag(Loc: NewFD->getLocation(),
12651 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12652 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12653 DiagID: diag::note_attribute_overloadable_prev_overload)
12654 << false;
12655
12656 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12657 }
12658 }
12659
12660 if (LangOpts.OpenMP)
12661 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12662
12663 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12664 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12665
12666 if (NewFD->hasAttr<SYCLExternalAttr>())
12667 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12668
12669 // Semantic checking for this function declaration (in isolation).
12670
12671 if (getLangOpts().CPlusPlus) {
12672 // C++-specific checks.
12673 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12674 CheckConstructor(Constructor);
12675 } else if (CXXDestructorDecl *Destructor =
12676 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12677 // We check here for invalid destructor names.
12678 // If we have a friend destructor declaration that is dependent, we can't
12679 // diagnose right away because cases like this are still valid:
12680 // template <class T> struct A { friend T::X::~Y(); };
12681 // struct B { struct Y { ~Y(); }; using X = Y; };
12682 // template struct A<B>;
12683 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12684 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12685 !Destructor->getDeclName().isDependentName())) {
12686 CanQualType ClassType =
12687 Context.getCanonicalTagType(TD: Destructor->getParent());
12688
12689 DeclarationName Name =
12690 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12691 if (NewFD->getDeclName() != Name) {
12692 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12693 NewFD->setInvalidDecl();
12694 return Redeclaration;
12695 }
12696 }
12697 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12698 if (auto *TD = Guide->getDescribedFunctionTemplate())
12699 CheckDeductionGuideTemplate(TD);
12700
12701 // A deduction guide is not on the list of entities that can be
12702 // explicitly specialized.
12703 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12704 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12705 << /*explicit specialization*/ 1;
12706 }
12707
12708 // Find any virtual functions that this function overrides.
12709 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12710 if (!Method->isFunctionTemplateSpecialization() &&
12711 !Method->getDescribedFunctionTemplate() &&
12712 Method->isCanonicalDecl()) {
12713 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12714 }
12715 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12716 // C++2a [class.virtual]p6
12717 // A virtual method shall not have a requires-clause.
12718 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12719 DiagID: diag::err_constrained_virtual_method);
12720
12721 if (Method->isStatic())
12722 checkThisInStaticMemberFunctionType(Method);
12723 }
12724
12725 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12726 ActOnConversionDeclarator(Conversion);
12727
12728 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12729 if (NewFD->isOverloadedOperator() &&
12730 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12731 NewFD->setInvalidDecl();
12732 return Redeclaration;
12733 }
12734
12735 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12736 if (NewFD->getLiteralIdentifier() &&
12737 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12738 NewFD->setInvalidDecl();
12739 return Redeclaration;
12740 }
12741
12742 // In C++, check default arguments now that we have merged decls. Unless
12743 // the lexical context is the class, because in this case this is done
12744 // during delayed parsing anyway.
12745 if (!CurContext->isRecord())
12746 CheckCXXDefaultArguments(FD: NewFD);
12747
12748 // If this function is declared as being extern "C", then check to see if
12749 // the function returns a UDT (class, struct, or union type) that is not C
12750 // compatible, and if it does, warn the user.
12751 // But, issue any diagnostic on the first declaration only.
12752 if (Previous.empty() && NewFD->isExternC()) {
12753 QualType R = NewFD->getReturnType();
12754 if (R->isIncompleteType() && !R->isVoidType())
12755 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12756 << NewFD << R;
12757 else if (!R.isPODType(Context) && !R->isVoidType() &&
12758 !R->isObjCObjectPointerType())
12759 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12760 }
12761
12762 // C++1z [dcl.fct]p6:
12763 // [...] whether the function has a non-throwing exception-specification
12764 // [is] part of the function type
12765 //
12766 // This results in an ABI break between C++14 and C++17 for functions whose
12767 // declared type includes an exception-specification in a parameter or
12768 // return type. (Exception specifications on the function itself are OK in
12769 // most cases, and exception specifications are not permitted in most other
12770 // contexts where they could make it into a mangling.)
12771 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12772 auto HasNoexcept = [&](QualType T) -> bool {
12773 // Strip off declarator chunks that could be between us and a function
12774 // type. We don't need to look far, exception specifications are very
12775 // restricted prior to C++17.
12776 if (auto *RT = T->getAs<ReferenceType>())
12777 T = RT->getPointeeType();
12778 else if (T->isAnyPointerType())
12779 T = T->getPointeeType();
12780 else if (auto *MPT = T->getAs<MemberPointerType>())
12781 T = MPT->getPointeeType();
12782 if (auto *FPT = T->getAs<FunctionProtoType>())
12783 if (FPT->isNothrow())
12784 return true;
12785 return false;
12786 };
12787
12788 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12789 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12790 for (QualType T : FPT->param_types())
12791 AnyNoexcept |= HasNoexcept(T);
12792 if (AnyNoexcept)
12793 Diag(Loc: NewFD->getLocation(),
12794 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12795 << NewFD;
12796 }
12797
12798 if (!Redeclaration && LangOpts.CUDA) {
12799 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12800 for (auto *Parm : NewFD->parameters()) {
12801 if (!Parm->getType()->isDependentType() &&
12802 Parm->hasAttr<CUDAGridConstantAttr>() &&
12803 !(IsKernel && Parm->getType().isConstQualified()))
12804 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12805 DiagID: diag::err_cuda_grid_constant_not_allowed);
12806 }
12807 CUDA().checkTargetOverload(NewFD, Previous);
12808 }
12809 }
12810
12811 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12812 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12813
12814 return Redeclaration;
12815}
12816
12817void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12818 // [basic.start.main]p3
12819 // The main function shall not be declared with C linkage-specification.
12820 if (FD->isExternCContext())
12821 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12822
12823 // C++11 [basic.start.main]p3:
12824 // A program that [...] declares main to be inline, static or
12825 // constexpr is ill-formed.
12826 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12827 // appear in a declaration of main.
12828 // static main is not an error under C99, but we should warn about it.
12829 // We accept _Noreturn main as an extension.
12830 if (FD->getStorageClass() == SC_Static)
12831 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12832 ? diag::err_static_main : diag::warn_static_main)
12833 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12834 if (FD->isInlineSpecified())
12835 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12836 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12837 if (DS.isNoreturnSpecified()) {
12838 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12839 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12840 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12841 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12842 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12843 }
12844 if (FD->isConstexpr()) {
12845 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12846 << FD->isConsteval()
12847 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12848 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12849 }
12850
12851 if (getLangOpts().OpenCL) {
12852 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12853 << FD->hasAttr<DeviceKernelAttr>();
12854 FD->setInvalidDecl();
12855 return;
12856 }
12857
12858 if (FD->hasAttr<SYCLExternalAttr>()) {
12859 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12860 << FD->getAttr<SYCLExternalAttr>();
12861 FD->setInvalidDecl();
12862 return;
12863 }
12864
12865 // Functions named main in hlsl are default entries, but don't have specific
12866 // signatures they are required to conform to.
12867 if (getLangOpts().HLSL)
12868 return;
12869
12870 QualType T = FD->getType();
12871 assert(T->isFunctionType() && "function decl is not of function type");
12872 const FunctionType* FT = T->castAs<FunctionType>();
12873
12874 // Set default calling convention for main()
12875 if (FT->getCallConv() != CC_C) {
12876 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12877 FD->setType(QualType(FT, 0));
12878 T = Context.getCanonicalType(T: FD->getType());
12879 }
12880
12881 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12882 // In C with GNU extensions we allow main() to have non-integer return
12883 // type, but we should warn about the extension, and we disable the
12884 // implicit-return-zero rule.
12885
12886 // GCC in C mode accepts qualified 'int'.
12887 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12888 FD->setHasImplicitReturnZero(true);
12889 else {
12890 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12891 SourceRange RTRange = FD->getReturnTypeSourceRange();
12892 if (RTRange.isValid())
12893 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12894 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12895 }
12896 } else {
12897 // In C and C++, main magically returns 0 if you fall off the end;
12898 // set the flag which tells us that.
12899 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12900
12901 // All the standards say that main() should return 'int'.
12902 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12903 FD->setHasImplicitReturnZero(true);
12904 else {
12905 // Otherwise, this is just a flat-out error.
12906 SourceRange RTRange = FD->getReturnTypeSourceRange();
12907 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12908 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12909 : FixItHint());
12910 FD->setInvalidDecl(true);
12911 }
12912
12913 // [basic.start.main]p3:
12914 // A program that declares a function main that belongs to the global scope
12915 // and is attached to a named module is ill-formed.
12916 if (FD->isInNamedModule()) {
12917 const SourceLocation start = FD->getTypeSpecStartLoc();
12918 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12919 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12920 }
12921 }
12922
12923 // Treat protoless main() as nullary.
12924 if (isa<FunctionNoProtoType>(Val: FT)) return;
12925
12926 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12927 unsigned nparams = FTP->getNumParams();
12928 assert(FD->getNumParams() == nparams);
12929
12930 bool HasExtraParameters = (nparams > 3);
12931
12932 if (FTP->isVariadic()) {
12933 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12934 // FIXME: if we had information about the location of the ellipsis, we
12935 // could add a FixIt hint to remove it as a parameter.
12936 }
12937
12938 // Darwin passes an undocumented fourth argument of type char**. If
12939 // other platforms start sprouting these, the logic below will start
12940 // getting shifty.
12941 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12942 HasExtraParameters = false;
12943
12944 if (HasExtraParameters) {
12945 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12946 FD->setInvalidDecl(true);
12947 nparams = 3;
12948 }
12949
12950 // FIXME: a lot of the following diagnostics would be improved
12951 // if we had some location information about types.
12952
12953 QualType CharPP =
12954 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12955 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12956
12957 for (unsigned i = 0; i < nparams; ++i) {
12958 QualType AT = FTP->getParamType(i);
12959
12960 bool mismatch = true;
12961
12962 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12963 mismatch = false;
12964 else if (Expected[i] == CharPP) {
12965 // As an extension, the following forms are okay:
12966 // char const **
12967 // char const * const *
12968 // char * const *
12969
12970 QualifierCollector qs;
12971 const PointerType* PT;
12972 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12973 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12974 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12975 T2: Context.CharTy)) {
12976 qs.removeConst();
12977 mismatch = !qs.empty();
12978 }
12979 }
12980
12981 if (mismatch) {
12982 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12983 // TODO: suggest replacing given type with expected type
12984 FD->setInvalidDecl(true);
12985 }
12986 }
12987
12988 if (nparams == 1 && !FD->isInvalidDecl()) {
12989 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12990 }
12991
12992 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12993 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12994 FD->setInvalidDecl();
12995 }
12996}
12997
12998static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12999
13000 // Default calling convention for main and wmain is __cdecl
13001 if (FD->getName() == "main" || FD->getName() == "wmain")
13002 return false;
13003
13004 // Default calling convention for MinGW and Cygwin is __cdecl
13005 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13006 if (T.isOSCygMing())
13007 return false;
13008
13009 // Default calling convention for WinMain, wWinMain and DllMain
13010 // is __stdcall on 32 bit Windows
13011 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13012 return true;
13013
13014 return false;
13015}
13016
13017void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
13018 QualType T = FD->getType();
13019 assert(T->isFunctionType() && "function decl is not of function type");
13020 const FunctionType *FT = T->castAs<FunctionType>();
13021
13022 // Set an implicit return of 'zero' if the function can return some integral,
13023 // enumeration, pointer or nullptr type.
13024 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
13025 FT->getReturnType()->isAnyPointerType() ||
13026 FT->getReturnType()->isNullPtrType())
13027 // DllMain is exempt because a return value of zero means it failed.
13028 if (FD->getName() != "DllMain")
13029 FD->setHasImplicitReturnZero(true);
13030
13031 // Explicitly specified calling conventions are applied to MSVC entry points
13032 if (!hasExplicitCallingConv(T)) {
13033 if (isDefaultStdCall(FD, S&: *this)) {
13034 if (FT->getCallConv() != CC_X86StdCall) {
13035 FT = Context.adjustFunctionType(
13036 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
13037 FD->setType(QualType(FT, 0));
13038 }
13039 } else if (FT->getCallConv() != CC_C) {
13040 FT = Context.adjustFunctionType(Fn: FT,
13041 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
13042 FD->setType(QualType(FT, 0));
13043 }
13044 }
13045
13046 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13047 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13048 FD->setInvalidDecl();
13049 }
13050}
13051
13052bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
13053 // FIXME: Need strict checking. In C89, we need to check for
13054 // any assignment, increment, decrement, function-calls, or
13055 // commas outside of a sizeof. In C99, it's the same list,
13056 // except that the aforementioned are allowed in unevaluated
13057 // expressions. Everything else falls under the
13058 // "may accept other forms of constant expressions" exception.
13059 //
13060 // Regular C++ code will not end up here (exceptions: language extensions,
13061 // OpenCL C++ etc), so the constant expression rules there don't matter.
13062 if (Init->isValueDependent()) {
13063 assert(Init->containsErrors() &&
13064 "Dependent code should only occur in error-recovery path.");
13065 return true;
13066 }
13067 const Expr *Culprit;
13068 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
13069 return false;
13070
13071 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13072 // casts and parentheses that it does not look through: under ARC an
13073 // object-pointer initializer is an `ImplicitCastExpr
13074 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13075 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13076 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13077 // the ObjC-specific classification and per-element reporting below can see
13078 // the underlying literal regardless of how it is wrapped.
13079 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13080
13081 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13082 if (getLangOpts().ObjCConstantLiterals &&
13083 isa<ObjCObjectLiteral>(Val: CulpritLiteral)) {
13084
13085 // For collection literals, iterate the elements to point at the specific
13086 // offender. These per-element checks mirror the constant-initializer rules
13087 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13088 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13089 // constant object literal, and dictionary keys must additionally be string
13090 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13091 // `id`, so the isa<> classification is done on the unwrapped expression.
13092 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(Val: CulpritLiteral)) {
13093 for (const Expr *Elm : ALE->elements()) {
13094 if (!isa<ObjCObjectLiteral>(Val: Elm->IgnoreImpCasts()) ||
13095 !Elm->isConstantInitializer(Ctx&: Context)) {
13096 Diag(Loc: Elm->getExprLoc(),
13097 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13098 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
13099 return true;
13100 }
13101 }
13102 }
13103
13104 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(Val: CulpritLiteral)) {
13105 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13106 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
13107
13108 // Keys must be constant string literals.
13109 if (!isa<ObjCStringLiteral>(Val: Elm.Key->IgnoreImpCasts()) ||
13110 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
13111 Diag(Loc: Elm.Key->getExprLoc(),
13112 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13113 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
13114 return true;
13115 }
13116
13117 // Values must be constant object literals.
13118 if (!isa<ObjCObjectLiteral>(Val: Elm.Value->IgnoreImpCasts()) ||
13119 !Elm.Value->isConstantInitializer(Ctx&: Context)) {
13120 Diag(Loc: Elm.Value->getExprLoc(),
13121 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13122 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
13123 return true;
13124 }
13125 }
13126 }
13127
13128 Diag(Loc: CulpritLiteral->getExprLoc(),
13129 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13130 << ObjC().CheckLiteralKind(FromE: Init) << CulpritLiteral->getSourceRange();
13131 return true;
13132 }
13133
13134 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13135 return true;
13136}
13137
13138namespace {
13139 // Visits an initialization expression to see if OrigDecl is evaluated in
13140 // its own initialization and throws a warning if it does.
13141 class SelfReferenceChecker
13142 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13143 Sema &S;
13144 Decl *OrigDecl;
13145 bool isRecordType;
13146 bool isPODType;
13147 bool isReferenceType;
13148 bool isInCXXOperatorCall;
13149
13150 bool isInitList;
13151 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13152
13153 public:
13154 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
13155
13156 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13157 S(S), OrigDecl(OrigDecl) {
13158 isPODType = false;
13159 isRecordType = false;
13160 isReferenceType = false;
13161 isInCXXOperatorCall = false;
13162 isInitList = false;
13163 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
13164 isPODType = VD->getType().isPODType(Context: S.Context);
13165 isRecordType = VD->getType()->isRecordType();
13166 isReferenceType = VD->getType()->isReferenceType();
13167 }
13168 }
13169
13170 // For most expressions, just call the visitor. For initializer lists,
13171 // track the index of the field being initialized since fields are
13172 // initialized in order allowing use of previously initialized fields.
13173 void CheckExpr(Expr *E) {
13174 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
13175 if (!InitList) {
13176 Visit(S: E);
13177 return;
13178 }
13179
13180 // Track and increment the index here.
13181 isInitList = true;
13182 InitFieldIndex.push_back(Elt: 0);
13183 for (auto *Child : InitList->children()) {
13184 CheckExpr(E: cast<Expr>(Val: Child));
13185 ++InitFieldIndex.back();
13186 }
13187 InitFieldIndex.pop_back();
13188 }
13189
13190 // Returns true if MemberExpr is checked and no further checking is needed.
13191 // Returns false if additional checking is required.
13192 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13193 llvm::SmallVector<FieldDecl*, 4> Fields;
13194 Expr *Base = E;
13195 bool ReferenceField = false;
13196
13197 // Get the field members used.
13198 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13199 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13200 if (!FD)
13201 return false;
13202 Fields.push_back(Elt: FD);
13203 if (FD->getType()->isReferenceType())
13204 ReferenceField = true;
13205 Base = ME->getBase()->IgnoreParenImpCasts();
13206 }
13207
13208 // Keep checking only if the base Decl is the same.
13209 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13210 if (!DRE || DRE->getDecl() != OrigDecl)
13211 return false;
13212
13213 // A reference field can be bound to an unininitialized field.
13214 if (CheckReference && !ReferenceField)
13215 return true;
13216
13217 // Convert FieldDecls to their index number.
13218 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13219 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13220 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13221
13222 // See if a warning is needed by checking the first difference in index
13223 // numbers. If field being used has index less than the field being
13224 // initialized, then the use is safe.
13225 for (auto UsedIter = UsedFieldIndex.begin(),
13226 UsedEnd = UsedFieldIndex.end(),
13227 OrigIter = InitFieldIndex.begin(),
13228 OrigEnd = InitFieldIndex.end();
13229 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13230 if (*UsedIter < *OrigIter)
13231 return true;
13232 if (*UsedIter > *OrigIter)
13233 break;
13234 }
13235
13236 // TODO: Add a different warning which will print the field names.
13237 HandleDeclRefExpr(DRE);
13238 return true;
13239 }
13240
13241 // For most expressions, the cast is directly above the DeclRefExpr.
13242 // For conditional operators, the cast can be outside the conditional
13243 // operator if both expressions are DeclRefExpr's.
13244 void HandleValue(Expr *E) {
13245 E = E->IgnoreParens();
13246 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13247 HandleDeclRefExpr(DRE);
13248 return;
13249 }
13250
13251 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13252 Visit(S: CO->getCond());
13253 HandleValue(E: CO->getTrueExpr());
13254 HandleValue(E: CO->getFalseExpr());
13255 return;
13256 }
13257
13258 if (BinaryConditionalOperator *BCO =
13259 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13260 Visit(S: BCO->getCond());
13261 HandleValue(E: BCO->getFalseExpr());
13262 return;
13263 }
13264
13265 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13266 if (Expr *SE = OVE->getSourceExpr())
13267 HandleValue(E: SE);
13268 return;
13269 }
13270
13271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13272 if (BO->getOpcode() == BO_Comma) {
13273 Visit(S: BO->getLHS());
13274 HandleValue(E: BO->getRHS());
13275 return;
13276 }
13277 }
13278
13279 if (isa<MemberExpr>(Val: E)) {
13280 if (isInitList) {
13281 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13282 CheckReference: false /*CheckReference*/))
13283 return;
13284 }
13285
13286 Expr *Base = E->IgnoreParenImpCasts();
13287 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13288 // Check for static member variables and don't warn on them.
13289 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13290 return;
13291 Base = ME->getBase()->IgnoreParenImpCasts();
13292 }
13293 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13294 HandleDeclRefExpr(DRE);
13295 return;
13296 }
13297
13298 Visit(S: E);
13299 }
13300
13301 // Reference types not handled in HandleValue are handled here since all
13302 // uses of references are bad, not just r-value uses.
13303 void VisitDeclRefExpr(DeclRefExpr *E) {
13304 if (isReferenceType)
13305 HandleDeclRefExpr(DRE: E);
13306 }
13307
13308 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13309 if (E->getCastKind() == CK_LValueToRValue) {
13310 HandleValue(E: E->getSubExpr());
13311 return;
13312 }
13313
13314 Inherited::VisitImplicitCastExpr(S: E);
13315 }
13316
13317 void VisitMemberExpr(MemberExpr *E) {
13318 if (isInitList) {
13319 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13320 return;
13321 }
13322
13323 // Don't warn on arrays since they can be treated as pointers.
13324 if (E->getType()->canDecayToPointerType()) return;
13325
13326 // Warn when a non-static method call is followed by non-static member
13327 // field accesses, which is followed by a DeclRefExpr.
13328 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13329 bool Warn = (MD && !MD->isStatic());
13330 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13331 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13332 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13333 Warn = false;
13334 Base = ME->getBase()->IgnoreParenImpCasts();
13335 }
13336
13337 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13338 if (Warn)
13339 HandleDeclRefExpr(DRE);
13340 return;
13341 }
13342
13343 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13344 // Visit that expression.
13345 Visit(S: Base);
13346 }
13347
13348 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13349 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13350 Expr *Callee = E->getCallee();
13351
13352 if (isa<UnresolvedLookupExpr>(Val: Callee))
13353 return Inherited::VisitCXXOperatorCallExpr(S: E);
13354
13355 Visit(S: Callee);
13356 for (auto Arg: E->arguments())
13357 HandleValue(E: Arg->IgnoreParenImpCasts());
13358 }
13359
13360 void VisitLambdaExpr(LambdaExpr *E) {
13361 if (!isInCXXOperatorCall) {
13362 Inherited::VisitLambdaExpr(LE: E);
13363 return;
13364 }
13365
13366 for (Expr *Init : E->capture_inits())
13367 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13368 HandleDeclRefExpr(DRE);
13369 else if (Init)
13370 Visit(S: Init);
13371 }
13372
13373 void VisitUnaryOperator(UnaryOperator *E) {
13374 // For POD record types, addresses of its own members are well-defined.
13375 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13376 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13377 if (!isPODType)
13378 HandleValue(E: E->getSubExpr());
13379 return;
13380 }
13381
13382 if (E->isIncrementDecrementOp()) {
13383 HandleValue(E: E->getSubExpr());
13384 return;
13385 }
13386
13387 Inherited::VisitUnaryOperator(S: E);
13388 }
13389
13390 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13391
13392 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13393 if (E->getConstructor()->isCopyConstructor()) {
13394 Expr *ArgExpr = E->getArg(Arg: 0);
13395 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13396 if (ILE->getNumInits() == 1)
13397 ArgExpr = ILE->getInit(Init: 0);
13398 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13399 if (ICE->getCastKind() == CK_NoOp)
13400 ArgExpr = ICE->getSubExpr();
13401 HandleValue(E: ArgExpr);
13402 return;
13403 }
13404 Inherited::VisitCXXConstructExpr(S: E);
13405 }
13406
13407 void VisitCallExpr(CallExpr *E) {
13408 // Treat std::move as a use.
13409 if (E->isCallToStdMove()) {
13410 HandleValue(E: E->getArg(Arg: 0));
13411 return;
13412 }
13413
13414 Inherited::VisitCallExpr(CE: E);
13415 }
13416
13417 void VisitBinaryOperator(BinaryOperator *E) {
13418 if (E->isCompoundAssignmentOp()) {
13419 HandleValue(E: E->getLHS());
13420 Visit(S: E->getRHS());
13421 return;
13422 }
13423
13424 Inherited::VisitBinaryOperator(S: E);
13425 }
13426
13427 // A custom visitor for BinaryConditionalOperator is needed because the
13428 // regular visitor would check the condition and true expression separately
13429 // but both point to the same place giving duplicate diagnostics.
13430 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13431 Visit(S: E->getCond());
13432 Visit(S: E->getFalseExpr());
13433 }
13434
13435 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13436 Decl* ReferenceDecl = DRE->getDecl();
13437 if (OrigDecl != ReferenceDecl) return;
13438 unsigned diag;
13439 if (isReferenceType) {
13440 diag = diag::warn_uninit_self_reference_in_reference_init;
13441 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13442 diag = diag::warn_static_self_reference_in_init;
13443 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13444 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13445 DRE->getDecl()->getType()->isRecordType()) {
13446 diag = diag::warn_uninit_self_reference_in_init;
13447 } else {
13448 // Local variables will be handled by the CFG analysis.
13449 return;
13450 }
13451
13452 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13453 PD: S.PDiag(DiagID: diag)
13454 << DRE->getDecl() << OrigDecl->getLocation()
13455 << DRE->getSourceRange());
13456 }
13457 };
13458
13459 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13460 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13461 bool DirectInit) {
13462 // Parameters arguments are occassionially constructed with itself,
13463 // for instance, in recursive functions. Skip them.
13464 if (isa<ParmVarDecl>(Val: OrigDecl))
13465 return;
13466
13467 // Skip checking for file-scope constexpr variables - constant evaluation
13468 // will produce appropriate errors without needing runtime diagnostics.
13469 // Local constexpr should still emit runtime warnings.
13470 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13471 VD && VD->isConstexpr() && VD->isFileVarDecl())
13472 return;
13473
13474 E = E->IgnoreParens();
13475
13476 // Skip checking T a = a where T is not a record or reference type.
13477 // Doing so is a way to silence uninitialized warnings.
13478 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13479 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13480 if (ICE->getCastKind() == CK_LValueToRValue)
13481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13482 if (DRE->getDecl() == OrigDecl)
13483 return;
13484
13485 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13486 }
13487} // end anonymous namespace
13488
13489namespace {
13490 // Simple wrapper to add the name of a variable or (if no variable is
13491 // available) a DeclarationName into a diagnostic.
13492 struct VarDeclOrName {
13493 VarDecl *VDecl;
13494 DeclarationName Name;
13495
13496 friend const Sema::SemaDiagnosticBuilder &
13497 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13498 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13499 }
13500 };
13501} // end anonymous namespace
13502
13503QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13504 DeclarationName Name, QualType Type,
13505 TypeSourceInfo *TSI,
13506 SourceRange Range, bool DirectInit,
13507 Expr *Init) {
13508 bool IsInitCapture = !VDecl;
13509 assert((!VDecl || !VDecl->isInitCapture()) &&
13510 "init captures are expected to be deduced prior to initialization");
13511
13512 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13513
13514 DeducedType *Deduced = Type->getContainedDeducedType();
13515 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13516
13517 // Diagnose auto array declarations in C23, unless it's a supported extension.
13518 if (getLangOpts().C23 && Type->isArrayType() &&
13519 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13520 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13521 << (int)Deduced->getContainedAutoType()->getKeyword()
13522 << /*in array decl*/ 23 << Range;
13523 return QualType();
13524 }
13525
13526 // C++11 [dcl.spec.auto]p3
13527 if (!Init) {
13528 assert(VDecl && "no init for init capture deduction?");
13529
13530 // Except for class argument deduction, and then for an initializing
13531 // declaration only, i.e. no static at class scope or extern.
13532 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13533 VDecl->hasExternalStorage() ||
13534 VDecl->isStaticDataMember()) {
13535 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13536 << VDecl->getDeclName() << Type;
13537 return QualType();
13538 }
13539 }
13540
13541 ArrayRef<Expr*> DeduceInits;
13542 if (Init)
13543 DeduceInits = Init;
13544
13545 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13546 if (DirectInit && PL)
13547 DeduceInits = PL->exprs();
13548
13549 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13550 assert(VDecl && "non-auto type for init capture deduction?");
13551 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13552 InitializationKind Kind = InitializationKind::CreateForInit(
13553 Loc: VDecl->getLocation(), DirectInit, Init);
13554 // FIXME: Initialization should not be taking a mutable list of inits.
13555 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13556 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13557 Init: InitsCopy);
13558 }
13559
13560 if (DirectInit) {
13561 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13562 DeduceInits = IL->inits();
13563 }
13564
13565 // Deduction only works if we have exactly one source expression.
13566 if (DeduceInits.empty()) {
13567 // It isn't possible to write this directly, but it is possible to
13568 // end up in this situation with "auto x(some_pack...);"
13569 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13570 ? diag::err_init_capture_no_expression
13571 : diag::err_auto_var_init_no_expression)
13572 << VN << Type << Range;
13573 return QualType();
13574 }
13575
13576 if (DeduceInits.size() > 1) {
13577 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13578 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13579 : diag::err_auto_var_init_multiple_expressions)
13580 << VN << Type << Range;
13581 return QualType();
13582 }
13583
13584 Expr *DeduceInit = DeduceInits[0];
13585 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13586 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13587 ? diag::err_init_capture_paren_braces
13588 : diag::err_auto_var_init_paren_braces)
13589 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13590 return QualType();
13591 }
13592
13593 // Expressions default to 'id' when we're in a debugger.
13594 bool DefaultedAnyToId = false;
13595 if (getLangOpts().DebuggerCastResultToId &&
13596 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13597 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13598 if (Result.isInvalid()) {
13599 return QualType();
13600 }
13601 Init = Result.get();
13602 DefaultedAnyToId = true;
13603 }
13604
13605 // C++ [dcl.decomp]p1:
13606 // If the assignment-expression [...] has array type A and no ref-qualifier
13607 // is present, e has type cv A
13608 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13609 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13610 DeduceInit->getType()->isConstantArrayType())
13611 return Context.getQualifiedType(T: DeduceInit->getType(),
13612 Qs: Type.getQualifiers());
13613
13614 QualType DeducedType;
13615 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13616 TemplateDeductionResult Result =
13617 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13618 if (Result != TemplateDeductionResult::Success &&
13619 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13620 if (!IsInitCapture)
13621 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13622 else if (isa<InitListExpr>(Val: Init))
13623 Diag(Loc: Range.getBegin(),
13624 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13625 << VN
13626 << (DeduceInit->getType().isNull() ? TSI->getType()
13627 : DeduceInit->getType())
13628 << DeduceInit->getSourceRange();
13629 else
13630 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13631 << VN << TSI->getType()
13632 << (DeduceInit->getType().isNull() ? TSI->getType()
13633 : DeduceInit->getType())
13634 << DeduceInit->getSourceRange();
13635 }
13636
13637 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13638 // 'id' instead of a specific object type prevents most of our usual
13639 // checks.
13640 // We only want to warn outside of template instantiations, though:
13641 // inside a template, the 'id' could have come from a parameter.
13642 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13643 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13644 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13645 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13646 }
13647
13648 return DeducedType;
13649}
13650
13651bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13652 Expr *Init) {
13653 assert(!Init || !Init->containsErrors());
13654 QualType DeducedType = deduceVarTypeFromInitializer(
13655 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13656 Range: VDecl->getSourceRange(), DirectInit, Init);
13657 if (DeducedType.isNull()) {
13658 VDecl->setInvalidDecl();
13659 return true;
13660 }
13661
13662 VDecl->setType(DeducedType);
13663 assert(VDecl->isLinkageValid());
13664
13665 // In ARC, infer lifetime.
13666 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13667 VDecl->setInvalidDecl();
13668
13669 if (getLangOpts().OpenCL)
13670 deduceOpenCLAddressSpace(Var: VDecl);
13671
13672 if (getLangOpts().HLSL)
13673 HLSL().deduceAddressSpace(Decl: VDecl);
13674
13675 // If this is a redeclaration, check that the type we just deduced matches
13676 // the previously declared type.
13677 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13678 // We never need to merge the type, because we cannot form an incomplete
13679 // array of auto, nor deduce such a type.
13680 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13681 }
13682
13683 // Check the deduced type is valid for a variable declaration.
13684 CheckVariableDeclarationType(NewVD: VDecl);
13685 return VDecl->isInvalidDecl();
13686}
13687
13688void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13689 SourceLocation Loc) {
13690 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13691 Init = EWC->getSubExpr();
13692
13693 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13694 Init = CE->getSubExpr();
13695
13696 QualType InitType = Init->getType();
13697 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13698 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13699 "shouldn't be called if type doesn't have a non-trivial C struct");
13700 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13701 for (auto *I : ILE->inits()) {
13702 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13703 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13704 continue;
13705 SourceLocation SL = I->getExprLoc();
13706 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13707 }
13708 return;
13709 }
13710
13711 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13712 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13713 checkNonTrivialCUnion(QT: InitType, Loc,
13714 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13715 NonTrivialKind: NTCUK_Init);
13716 } else {
13717 // Assume all other explicit initializers involving copying some existing
13718 // object.
13719 // TODO: ignore any explicit initializers where we can guarantee
13720 // copy-elision.
13721 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13722 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13723 NonTrivialKind: NTCUK_Copy);
13724 }
13725}
13726
13727namespace {
13728
13729bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13730 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13731 // in the source code or implicitly by the compiler if it is in a union
13732 // defined in a system header and has non-trivial ObjC ownership
13733 // qualifications. We don't want those fields to participate in determining
13734 // whether the containing union is non-trivial.
13735 return FD->hasAttr<UnavailableAttr>();
13736}
13737
13738struct DiagNonTrivalCUnionDefaultInitializeVisitor
13739 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13740 void> {
13741 using Super =
13742 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13743 void>;
13744
13745 DiagNonTrivalCUnionDefaultInitializeVisitor(
13746 QualType OrigTy, SourceLocation OrigLoc,
13747 NonTrivialCUnionContext UseContext, Sema &S)
13748 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13749
13750 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13751 const FieldDecl *FD, bool InNonTrivialUnion) {
13752 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13753 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13754 Args&: InNonTrivialUnion);
13755 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13756 }
13757
13758 void visitARCStrong(QualType QT, const FieldDecl *FD,
13759 bool InNonTrivialUnion) {
13760 if (InNonTrivialUnion)
13761 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13762 << 1 << 0 << QT << FD->getName();
13763 }
13764
13765 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13766 if (InNonTrivialUnion)
13767 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13768 << 1 << 0 << QT << FD->getName();
13769 }
13770
13771 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13772 const auto *RD = QT->castAsRecordDecl();
13773 if (RD->isUnion()) {
13774 if (OrigLoc.isValid()) {
13775 bool IsUnion = false;
13776 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13777 IsUnion = OrigRD->isUnion();
13778 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13779 << 0 << OrigTy << IsUnion << UseContext;
13780 // Reset OrigLoc so that this diagnostic is emitted only once.
13781 OrigLoc = SourceLocation();
13782 }
13783 InNonTrivialUnion = true;
13784 }
13785
13786 if (InNonTrivialUnion)
13787 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13788 << 0 << 0 << QT.getUnqualifiedType() << "";
13789
13790 for (const FieldDecl *FD : RD->fields())
13791 if (!shouldIgnoreForRecordTriviality(FD))
13792 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13793 }
13794
13795 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13796
13797 // The non-trivial C union type or the struct/union type that contains a
13798 // non-trivial C union.
13799 QualType OrigTy;
13800 SourceLocation OrigLoc;
13801 NonTrivialCUnionContext UseContext;
13802 Sema &S;
13803};
13804
13805struct DiagNonTrivalCUnionDestructedTypeVisitor
13806 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13807 using Super =
13808 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13809
13810 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13811 SourceLocation OrigLoc,
13812 NonTrivialCUnionContext UseContext,
13813 Sema &S)
13814 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13815
13816 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13817 const FieldDecl *FD, bool InNonTrivialUnion) {
13818 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13819 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13820 Args&: InNonTrivialUnion);
13821 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13822 }
13823
13824 void visitARCStrong(QualType QT, const FieldDecl *FD,
13825 bool InNonTrivialUnion) {
13826 if (InNonTrivialUnion)
13827 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13828 << 1 << 1 << QT << FD->getName();
13829 }
13830
13831 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13832 if (InNonTrivialUnion)
13833 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13834 << 1 << 1 << QT << FD->getName();
13835 }
13836
13837 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13838 const auto *RD = QT->castAsRecordDecl();
13839 if (RD->isUnion()) {
13840 if (OrigLoc.isValid()) {
13841 bool IsUnion = false;
13842 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13843 IsUnion = OrigRD->isUnion();
13844 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13845 << 1 << OrigTy << IsUnion << UseContext;
13846 // Reset OrigLoc so that this diagnostic is emitted only once.
13847 OrigLoc = SourceLocation();
13848 }
13849 InNonTrivialUnion = true;
13850 }
13851
13852 if (InNonTrivialUnion)
13853 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13854 << 0 << 1 << QT.getUnqualifiedType() << "";
13855
13856 for (const FieldDecl *FD : RD->fields())
13857 if (!shouldIgnoreForRecordTriviality(FD))
13858 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13859 }
13860
13861 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13862 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13863 bool InNonTrivialUnion) {}
13864
13865 // The non-trivial C union type or the struct/union type that contains a
13866 // non-trivial C union.
13867 QualType OrigTy;
13868 SourceLocation OrigLoc;
13869 NonTrivialCUnionContext UseContext;
13870 Sema &S;
13871};
13872
13873struct DiagNonTrivalCUnionCopyVisitor
13874 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13875 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13876
13877 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13878 NonTrivialCUnionContext UseContext, Sema &S)
13879 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13880
13881 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13882 const FieldDecl *FD, bool InNonTrivialUnion) {
13883 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13884 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13885 Args&: InNonTrivialUnion);
13886 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13887 }
13888
13889 void visitARCStrong(QualType QT, const FieldDecl *FD,
13890 bool InNonTrivialUnion) {
13891 if (InNonTrivialUnion)
13892 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13893 << 1 << 2 << QT << FD->getName();
13894 }
13895
13896 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13897 if (InNonTrivialUnion)
13898 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13899 << 1 << 2 << QT << FD->getName();
13900 }
13901
13902 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13903 const auto *RD = QT->castAsRecordDecl();
13904 if (RD->isUnion()) {
13905 if (OrigLoc.isValid()) {
13906 bool IsUnion = false;
13907 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13908 IsUnion = OrigRD->isUnion();
13909 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13910 << 2 << OrigTy << IsUnion << UseContext;
13911 // Reset OrigLoc so that this diagnostic is emitted only once.
13912 OrigLoc = SourceLocation();
13913 }
13914 InNonTrivialUnion = true;
13915 }
13916
13917 if (InNonTrivialUnion)
13918 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13919 << 0 << 2 << QT.getUnqualifiedType() << "";
13920
13921 for (const FieldDecl *FD : RD->fields())
13922 if (!shouldIgnoreForRecordTriviality(FD))
13923 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13924 }
13925
13926 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13927 if (InNonTrivialUnion)
13928 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13929 << 1 << 2 << QT << FD->getName();
13930 }
13931
13932 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13933 const FieldDecl *FD, bool InNonTrivialUnion) {}
13934 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13935 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13936 bool InNonTrivialUnion) {}
13937
13938 // The non-trivial C union type or the struct/union type that contains a
13939 // non-trivial C union.
13940 QualType OrigTy;
13941 SourceLocation OrigLoc;
13942 NonTrivialCUnionContext UseContext;
13943 Sema &S;
13944};
13945
13946} // namespace
13947
13948void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13949 NonTrivialCUnionContext UseContext,
13950 unsigned NonTrivialKind) {
13951 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13952 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13953 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13954 "shouldn't be called if type doesn't have a non-trivial C union");
13955
13956 if ((NonTrivialKind & NTCUK_Init) &&
13957 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13958 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13959 .visit(FT: QT, Args: nullptr, Args: false);
13960 if ((NonTrivialKind & NTCUK_Destruct) &&
13961 QT.hasNonTrivialToPrimitiveDestructCUnion())
13962 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13963 .visit(FT: QT, Args: nullptr, Args: false);
13964 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13965 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13966 .visit(FT: QT, Args: nullptr, Args: false);
13967}
13968
13969bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13970 const VarDecl *Dcl) {
13971 if (!getLangOpts().CPlusPlus)
13972 return false;
13973
13974 // We only need to warn if the definition is in a header file, so wait to
13975 // diagnose until we've seen the definition.
13976 if (!Dcl->isThisDeclarationADefinition())
13977 return false;
13978
13979 // If an object is defined in a source file, its definition can't get
13980 // duplicated since it will never appear in more than one TU.
13981 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13982 return false;
13983
13984 // If the variable we're looking at is a static local, then we actually care
13985 // about the properties of the function containing it.
13986 const ValueDecl *Target = Dcl;
13987 // VarDecls and FunctionDecls have different functions for checking
13988 // inline-ness, and whether they were originally templated, so we have to
13989 // call the appropriate functions manually.
13990 bool TargetIsInline = Dcl->isInline();
13991 bool TargetWasTemplated =
13992 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13993
13994 // Update the Target and TargetIsInline property if necessary
13995 if (Dcl->isStaticLocal()) {
13996 const DeclContext *Ctx = Dcl->getDeclContext();
13997 if (!Ctx)
13998 return false;
13999
14000 const FunctionDecl *FunDcl =
14001 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
14002 if (!FunDcl)
14003 return false;
14004
14005 Target = FunDcl;
14006 // IsInlined() checks for the C++ inline property
14007 TargetIsInline = FunDcl->isInlined();
14008 TargetWasTemplated =
14009 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
14010 }
14011
14012 // Non-inline functions/variables can only legally appear in one TU
14013 // unless they were part of a template. Unfortunately, making complex
14014 // template instantiations visible is infeasible in practice, since
14015 // everything the template depends on also has to be visible. To avoid
14016 // giving impractical-to-fix warnings, don't warn if we're inside
14017 // something that was templated, even on inline stuff.
14018 if (!TargetIsInline || TargetWasTemplated)
14019 return false;
14020
14021 // If the object isn't hidden, the dynamic linker will prevent duplication.
14022 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14023
14024 // The target is "hidden" (from the dynamic linker) if:
14025 // 1. On posix, it has hidden visibility, or
14026 // 2. On windows, it has no import/export annotation, and neither does the
14027 // class which directly contains it.
14028 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14029 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14030 return false;
14031
14032 // If the variable isn't directly annotated, check to see if it's a member
14033 // of an annotated class.
14034 const CXXRecordDecl *Ctx =
14035 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
14036 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14037 return false;
14038
14039 } else if (Lnk.getVisibility() != HiddenVisibility) {
14040 // Posix case
14041 return false;
14042 }
14043
14044 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14045 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
14046 return false;
14047
14048 return true;
14049}
14050
14051// Determine whether the object seems mutable for the purpose of diagnosing
14052// possible unique object duplication, i.e. non-const-qualified, and
14053// not an always-constant type like a function.
14054// Not perfect: doesn't account for mutable members, for example, or
14055// elements of container types.
14056// For nested pointers, any individual level being non-const is sufficient.
14057static bool looksMutable(QualType T, const ASTContext &Ctx) {
14058 T = T.getNonReferenceType();
14059 if (T->isFunctionType())
14060 return false;
14061 if (!T.isConstant(Ctx))
14062 return true;
14063 if (T->isPointerType())
14064 return looksMutable(T: T->getPointeeType(), Ctx);
14065 return false;
14066}
14067
14068void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
14069 // If this object has external linkage and hidden visibility, it might be
14070 // duplicated when built into a shared library, which causes problems if it's
14071 // mutable (since the copies won't be in sync) or its initialization has side
14072 // effects (since it will run once per copy instead of once globally).
14073
14074 // Don't diagnose if we're inside a template, because it's not practical to
14075 // fix the warning in most cases.
14076 if (!VD->isTemplated() &&
14077 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
14078
14079 QualType Type = VD->getType();
14080 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
14081 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
14082 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14083 }
14084
14085 // To keep false positives low, only warn if we're certain that the
14086 // initializer has side effects. Don't warn on operator new, since a mutable
14087 // pointer will trigger the previous warning, and an immutable pointer
14088 // getting duplicated just results in a little extra memory usage.
14089 const Expr *Init = VD->getAnyInitializer();
14090 if (Init &&
14091 Init->HasSideEffects(Ctx: VD->getASTContext(),
14092 /*IncludePossibleEffects=*/false) &&
14093 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
14094 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
14095 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14096 }
14097 }
14098}
14099
14100void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
14101 llvm::scope_exit ResetDeclForInitializer([this]() {
14102 if (!this->ExprEvalContexts.empty())
14103 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14104 });
14105
14106 // If there is no declaration, there was an error parsing it. Just ignore
14107 // the initializer.
14108 if (!RealDecl) {
14109 return;
14110 }
14111
14112 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
14113 if (!Method->isInvalidDecl()) {
14114 // Pure-specifiers are handled in ActOnPureSpecifier.
14115 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
14116 << Method->getDeclName() << Init->getSourceRange();
14117 Method->setInvalidDecl();
14118 }
14119 return;
14120 }
14121
14122 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
14123 if (!VDecl) {
14124 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14125 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
14126 RealDecl->setInvalidDecl();
14127 return;
14128 }
14129
14130 if (VDecl->isInvalidDecl()) {
14131 ExprResult Recovery =
14132 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
14133 if (Expr *E = Recovery.get())
14134 VDecl->setInit(E);
14135 return;
14136 }
14137
14138 // __amdgpu_feature_predicate_t cannot be initialised
14139 if (VDecl->getType().getDesugaredType(Context) ==
14140 Context.AMDGPUFeaturePredicateTy) {
14141 Diag(Loc: VDecl->getLocation(),
14142 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14143 << VDecl;
14144 VDecl->setInvalidDecl();
14145 return;
14146 }
14147
14148 // WebAssembly tables can't be used to initialise a variable.
14149 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14150 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
14151 VDecl->setInvalidDecl();
14152 return;
14153 }
14154
14155 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14156 if (VDecl->getType()->isUndeducedType()) {
14157 if (Init->containsErrors()) {
14158 // Invalidate the decl as we don't know the type for recovery-expr yet.
14159 RealDecl->setInvalidDecl();
14160 VDecl->setInit(Init);
14161 return;
14162 }
14163
14164 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
14165 assert(VDecl->isInvalidDecl() &&
14166 "decl should be invalidated when deduce fails");
14167 if (auto *RecoveryExpr =
14168 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
14169 .get())
14170 VDecl->setInit(RecoveryExpr);
14171 return;
14172 }
14173 }
14174
14175 this->CheckAttributesOnDeducedType(D: RealDecl);
14176
14177 // we don't initialize groupshared variables so warn and return
14178 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14179 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
14180 return;
14181 }
14182
14183 // dllimport cannot be used on variable definitions.
14184 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14185 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
14186 VDecl->setInvalidDecl();
14187 return;
14188 }
14189
14190 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14191 // the identifier has external or internal linkage, the declaration shall
14192 // have no initializer for the identifier.
14193 // C++14 [dcl.init]p5 is the same restriction for C++.
14194 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14195 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14196 VDecl->setInvalidDecl();
14197 return;
14198 }
14199
14200 if (!VDecl->getType()->isDependentType()) {
14201 // A definition must end up with a complete type, which means it must be
14202 // complete with the restriction that an array type might be completed by
14203 // the initializer; note that later code assumes this restriction.
14204 QualType BaseDeclType = VDecl->getType();
14205 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14206 BaseDeclType = Array->getElementType();
14207 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14208 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14209 RealDecl->setInvalidDecl();
14210 return;
14211 }
14212
14213 // The variable can not have an abstract class type.
14214 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14215 DiagID: diag::err_abstract_type_in_decl,
14216 Args: AbstractVariableType))
14217 VDecl->setInvalidDecl();
14218 }
14219
14220 // C++ [module.import/6]
14221 // ...
14222 // A header unit shall not contain a definition of a non-inline function or
14223 // variable whose name has external linkage.
14224 //
14225 // We choose to allow weak & selectany definitions, as they are common in
14226 // headers, and have semantics similar to inline definitions which are allowed
14227 // in header units.
14228 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14229 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14230 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14231 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14232 !VDecl->getInstantiatedFromStaticDataMember() &&
14233 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14234 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14235 VDecl->setInvalidDecl();
14236 }
14237
14238 // If adding the initializer will turn this declaration into a definition,
14239 // and we already have a definition for this variable, diagnose or otherwise
14240 // handle the situation.
14241 if (VarDecl *Def = VDecl->getDefinition())
14242 if (Def != VDecl &&
14243 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14244 !VDecl->isThisDeclarationADemotedDefinition() &&
14245 checkVarDeclRedefinition(Old: Def, New: VDecl))
14246 return;
14247
14248 if (getLangOpts().CPlusPlus) {
14249 // C++ [class.static.data]p4
14250 // If a static data member is of const integral or const
14251 // enumeration type, its declaration in the class definition can
14252 // specify a constant-initializer which shall be an integral
14253 // constant expression (5.19). In that case, the member can appear
14254 // in integral constant expressions. The member shall still be
14255 // defined in a namespace scope if it is used in the program and the
14256 // namespace scope definition shall not contain an initializer.
14257 //
14258 // We already performed a redefinition check above, but for static
14259 // data members we also need to check whether there was an in-class
14260 // declaration with an initializer.
14261 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14262 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14263 << VDecl->getDeclName();
14264 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14265 DiagID: diag::note_previous_initializer)
14266 << 0;
14267 return;
14268 }
14269
14270 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14271 VDecl->setInvalidDecl();
14272 return;
14273 }
14274 }
14275
14276 // If the variable has an initializer and local storage, check whether
14277 // anything jumps over the initialization.
14278 if (VDecl->hasLocalStorage())
14279 setFunctionHasBranchProtectedScope();
14280
14281 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14282 // a kernel function cannot be initialized."
14283 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14284 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14285 VDecl->setInvalidDecl();
14286 return;
14287 }
14288
14289 // The LoaderUninitialized attribute acts as a definition (of undef).
14290 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14291 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14292 VDecl->setInvalidDecl();
14293 return;
14294 }
14295
14296 if (getLangOpts().HLSL)
14297 if (!HLSL().handleInitialization(VDecl, Init))
14298 return;
14299
14300 // Get the decls type and save a reference for later, since
14301 // CheckInitializerTypes may change it.
14302 QualType DclT = VDecl->getType(), SavT = DclT;
14303
14304 // Expressions default to 'id' when we're in a debugger
14305 // and we are assigning it to a variable of Objective-C pointer type.
14306 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14307 Init->getType() == Context.UnknownAnyTy) {
14308 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14309 if (!Result.isUsable()) {
14310 VDecl->setInvalidDecl();
14311 return;
14312 }
14313 Init = Result.get();
14314 }
14315
14316 // Perform the initialization.
14317 bool InitializedFromParenListExpr = false;
14318 bool IsParenListInit = false;
14319 if (!VDecl->isInvalidDecl()) {
14320 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14321 InitializationKind Kind = InitializationKind::CreateForInit(
14322 Loc: VDecl->getLocation(), DirectInit, Init);
14323
14324 MultiExprArg Args = Init;
14325 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14326 Args =
14327 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14328 InitializedFromParenListExpr = true;
14329 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14330 Args = CXXDirectInit->getInitExprs();
14331 InitializedFromParenListExpr = true;
14332 }
14333
14334 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14335 /*TopLevelOfInitList=*/false,
14336 /*TreatUnavailableAsInvalid=*/false);
14337 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14338 if (!Result.isUsable()) {
14339 // If the provided initializer fails to initialize the var decl,
14340 // we attach a recovery expr for better recovery.
14341 auto RecoveryExpr =
14342 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14343 if (RecoveryExpr.get())
14344 VDecl->setInit(RecoveryExpr.get());
14345 // In general, for error recovery purposes, the initializer doesn't play
14346 // part in the valid bit of the declaration. There are a few exceptions:
14347 // 1) if the var decl has a deduced auto type, and the type cannot be
14348 // deduced by an invalid initializer;
14349 // 2) if the var decl is a decomposition decl with a non-deduced type,
14350 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14351 // Case 1) was already handled elsewhere.
14352 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14353 VDecl->setInvalidDecl();
14354 return;
14355 }
14356
14357 Init = Result.getAs<Expr>();
14358 IsParenListInit = !InitSeq.steps().empty() &&
14359 InitSeq.step_begin()->Kind ==
14360 InitializationSequence::SK_ParenthesizedListInit;
14361 QualType VDeclType = VDecl->getType();
14362 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14363 !VDeclType->isDependentType() &&
14364 Context.getAsIncompleteArrayType(T: VDeclType) &&
14365 Context.getAsIncompleteArrayType(T: Init->getType())) {
14366 // Bail out if it is not possible to deduce array size from the
14367 // initializer.
14368 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14369 << VDeclType;
14370 VDecl->setInvalidDecl();
14371 return;
14372 }
14373 }
14374
14375 // Check for self-references within variable initializers.
14376 // Variables declared within a function/method body (except for references)
14377 // are handled by a dataflow analysis.
14378 // This is undefined behavior in C++, but valid in C.
14379 if (getLangOpts().CPlusPlus)
14380 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14381 VDecl->getType()->isReferenceType())
14382 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14383
14384 // If the type changed, it means we had an incomplete type that was
14385 // completed by the initializer. For example:
14386 // int ary[] = { 1, 3, 5 };
14387 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14388 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14389 VDecl->setType(DclT);
14390
14391 if (!VDecl->isInvalidDecl()) {
14392 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14393
14394 if (VDecl->hasAttr<BlocksAttr>())
14395 ObjC().checkRetainCycles(Var: VDecl, Init);
14396
14397 // It is safe to assign a weak reference into a strong variable.
14398 // Although this code can still have problems:
14399 // id x = self.weakProp;
14400 // id y = self.weakProp;
14401 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14402 // paths through the function. This should be revisited if
14403 // -Wrepeated-use-of-weak is made flow-sensitive.
14404 if (FunctionScopeInfo *FSI = getCurFunction())
14405 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14406 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14407 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14408 Loc: Init->getBeginLoc()))
14409 FSI->markSafeWeakUse(E: Init);
14410 }
14411
14412 // The initialization is usually a full-expression.
14413 //
14414 // FIXME: If this is a braced initialization of an aggregate, it is not
14415 // an expression, and each individual field initializer is a separate
14416 // full-expression. For instance, in:
14417 //
14418 // struct Temp { ~Temp(); };
14419 // struct S { S(Temp); };
14420 // struct T { S a, b; } t = { Temp(), Temp() }
14421 //
14422 // we should destroy the first Temp before constructing the second.
14423
14424 // Set context flag for OverflowBehaviorType initialization analysis
14425 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14426 true);
14427 ExprResult Result =
14428 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14429 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14430 if (!Result.isUsable()) {
14431 VDecl->setInvalidDecl();
14432 return;
14433 }
14434 Init = Result.get();
14435
14436 // Attach the initializer to the decl.
14437 VDecl->setInit(Init);
14438
14439 if (VDecl->isLocalVarDecl()) {
14440 // Don't check the initializer if the declaration is malformed.
14441 if (VDecl->isInvalidDecl()) {
14442 // do nothing
14443
14444 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14445 // This is true even in C++ for OpenCL.
14446 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14447 CheckForConstantInitializer(Init);
14448
14449 // Otherwise, C++ does not restrict the initializer.
14450 } else if (getLangOpts().CPlusPlus) {
14451 // do nothing
14452
14453 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14454 // static storage duration shall be constant expressions or string literals.
14455 } else if (VDecl->getStorageClass() == SC_Static) {
14456 // Avoid evaluating the initializer twice for constexpr variables. It will
14457 // be evaluated later.
14458 if (!VDecl->isConstexpr())
14459 CheckForConstantInitializer(Init);
14460
14461 // C89 is stricter than C99 for aggregate initializers.
14462 // C89 6.5.7p3: All the expressions [...] in an initializer list
14463 // for an object that has aggregate or union type shall be
14464 // constant expressions.
14465 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14466 isa<InitListExpr>(Val: Init)) {
14467 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14468 }
14469
14470 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14471 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14472 if (VDecl->hasLocalStorage())
14473 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14474 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14475 VDecl->getLexicalDeclContext()->isRecord()) {
14476 // This is an in-class initialization for a static data member, e.g.,
14477 //
14478 // struct S {
14479 // static const int value = 17;
14480 // };
14481
14482 // C++ [class.mem]p4:
14483 // A member-declarator can contain a constant-initializer only
14484 // if it declares a static member (9.4) of const integral or
14485 // const enumeration type, see 9.4.2.
14486 //
14487 // C++11 [class.static.data]p3:
14488 // If a non-volatile non-inline const static data member is of integral
14489 // or enumeration type, its declaration in the class definition can
14490 // specify a brace-or-equal-initializer in which every initializer-clause
14491 // that is an assignment-expression is a constant expression. A static
14492 // data member of literal type can be declared in the class definition
14493 // with the constexpr specifier; if so, its declaration shall specify a
14494 // brace-or-equal-initializer in which every initializer-clause that is
14495 // an assignment-expression is a constant expression.
14496
14497 // Do nothing on dependent types.
14498 if (DclT->isDependentType()) {
14499
14500 // Allow any 'static constexpr' members, whether or not they are of literal
14501 // type. We separately check that every constexpr variable is of literal
14502 // type.
14503 } else if (VDecl->isConstexpr()) {
14504
14505 // Require constness.
14506 } else if (!DclT.isConstQualified()) {
14507 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14508 << Init->getSourceRange();
14509 VDecl->setInvalidDecl();
14510
14511 // We allow integer constant expressions in all cases.
14512 } else if (DclT->isIntegralOrEnumerationType()) {
14513 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14514 // In C++11, a non-constexpr const static data member with an
14515 // in-class initializer cannot be volatile.
14516 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14517
14518 // We allow foldable floating-point constants as an extension.
14519 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14520 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14521 // it anyway and provide a fixit to add the 'constexpr'.
14522 if (getLangOpts().CPlusPlus11) {
14523 Diag(Loc: VDecl->getLocation(),
14524 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14525 << DclT << Init->getSourceRange();
14526 Diag(Loc: VDecl->getBeginLoc(),
14527 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14528 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14529 } else {
14530 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14531 << DclT << Init->getSourceRange();
14532
14533 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14534 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14535 << Init->getSourceRange();
14536 VDecl->setInvalidDecl();
14537 }
14538 }
14539
14540 // Suggest adding 'constexpr' in C++11 for literal types.
14541 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14542 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14543 << DclT << Init->getSourceRange()
14544 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14545 VDecl->setConstexpr(true);
14546
14547 } else {
14548 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14549 << DclT << Init->getSourceRange();
14550 VDecl->setInvalidDecl();
14551 }
14552 } else if (VDecl->isFileVarDecl()) {
14553 // In C, extern is typically used to avoid tentative definitions when
14554 // declaring variables in headers, but adding an initializer makes it a
14555 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14556 // In C++, extern is often used to give implicitly static const variables
14557 // external linkage, so don't warn in that case. If selectany is present,
14558 // this might be header code intended for C and C++ inclusion, so apply the
14559 // C++ rules.
14560 if (VDecl->getStorageClass() == SC_Extern &&
14561 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14562 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14563 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14564 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14565 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14566
14567 // In Microsoft C++ mode, a const variable defined in namespace scope has
14568 // external linkage by default if the variable is declared with
14569 // __declspec(dllexport).
14570 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14571 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14572 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14573 VDecl->setStorageClass(SC_Extern);
14574
14575 // C99 6.7.8p4. All file scoped initializers need to be constant.
14576 // Avoid duplicate diagnostics for constexpr variables.
14577 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14578 !VDecl->isConstexpr())
14579 CheckForConstantInitializer(Init);
14580 }
14581
14582 QualType InitType = Init->getType();
14583 if (!InitType.isNull() &&
14584 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14585 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14586 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14587
14588 // We will represent direct-initialization similarly to copy-initialization:
14589 // int x(1); -as-> int x = 1;
14590 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14591 //
14592 // Clients that want to distinguish between the two forms, can check for
14593 // direct initializer using VarDecl::getInitStyle().
14594 // A major benefit is that clients that don't particularly care about which
14595 // exactly form was it (like the CodeGen) can handle both cases without
14596 // special case code.
14597
14598 // C++ 8.5p11:
14599 // The form of initialization (using parentheses or '=') matters
14600 // when the entity being initialized has class type.
14601 if (InitializedFromParenListExpr) {
14602 assert(DirectInit && "Call-style initializer must be direct init.");
14603 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14604 : VarDecl::CallInit);
14605 } else if (DirectInit) {
14606 // This must be list-initialization. No other way is direct-initialization.
14607 VDecl->setInitStyle(VarDecl::ListInit);
14608 }
14609
14610 if (LangOpts.OpenMP &&
14611 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14612 VDecl->isFileVarDecl())
14613 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14614 CheckCompleteVariableDeclaration(VD: VDecl);
14615
14616 if (LangOpts.OpenACC && !InitType.isNull())
14617 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14618}
14619
14620void Sema::ActOnInitializerError(Decl *D) {
14621 // Our main concern here is re-establishing invariants like "a
14622 // variable's type is either dependent or complete".
14623 if (!D || D->isInvalidDecl()) return;
14624
14625 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14626 if (!VD) return;
14627
14628 // Bindings are not usable if we can't make sense of the initializer.
14629 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14630 for (auto *BD : DD->bindings())
14631 BD->setInvalidDecl();
14632
14633 // Auto types are meaningless if we can't make sense of the initializer.
14634 if (VD->getType()->isUndeducedType()) {
14635 D->setInvalidDecl();
14636 return;
14637 }
14638
14639 QualType Ty = VD->getType();
14640 if (Ty->isDependentType()) return;
14641
14642 // Require a complete type.
14643 if (RequireCompleteType(Loc: VD->getLocation(),
14644 T: Context.getBaseElementType(QT: Ty),
14645 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14646 VD->setInvalidDecl();
14647 return;
14648 }
14649
14650 // Require a non-abstract type.
14651 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14652 DiagID: diag::err_abstract_type_in_decl,
14653 Args: AbstractVariableType)) {
14654 VD->setInvalidDecl();
14655 return;
14656 }
14657
14658 // Don't bother complaining about constructors or destructors,
14659 // though.
14660}
14661
14662void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14663 // If there is no declaration, there was an error parsing it. Just ignore it.
14664 if (!RealDecl)
14665 return;
14666
14667 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14668 QualType Type = Var->getType();
14669
14670 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14671 Diag(Loc: Var->getLocation(),
14672 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14673 << Var;
14674 Var->setInvalidDecl();
14675 return;
14676 }
14677 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14678 if (isa<DecompositionDecl>(Val: RealDecl)) {
14679 // Point the caret to the token immediately after the closing bracket if
14680 // it can be found; otherwise fall back to the declaration's location.
14681 SourceLocation Loc = Var->getLocation();
14682 SourceLocation RSquareLoc =
14683 dyn_cast<DecompositionDecl>(Val: RealDecl)->getRSquareLoc();
14684 if (std::optional<Token> Next = Lexer::findNextToken(
14685 Loc: RSquareLoc, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()))
14686 Loc = Next->getLocation();
14687 Diag(Loc, DiagID: diag::err_decomp_decl_requires_init) << Var;
14688 Var->setInvalidDecl();
14689 return;
14690 }
14691
14692 if (Type->isUndeducedType() &&
14693 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14694 return;
14695
14696 this->CheckAttributesOnDeducedType(D: RealDecl);
14697
14698 // C++11 [class.static.data]p3: A static data member can be declared with
14699 // the constexpr specifier; if so, its declaration shall specify
14700 // a brace-or-equal-initializer.
14701 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14702 // the definition of a variable [...] or the declaration of a static data
14703 // member.
14704 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14705 !Var->isThisDeclarationADemotedDefinition()) {
14706 if (Var->isStaticDataMember()) {
14707 // C++1z removes the relevant rule; the in-class declaration is always
14708 // a definition there.
14709 if (!getLangOpts().CPlusPlus17 &&
14710 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14711 Diag(Loc: Var->getLocation(),
14712 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14713 << Var;
14714 Var->setInvalidDecl();
14715 return;
14716 }
14717 } else {
14718 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14719 Var->setInvalidDecl();
14720 return;
14721 }
14722 }
14723
14724 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14725 // be initialized.
14726 if (!Var->isInvalidDecl() &&
14727 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14728 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14729 bool HasConstExprDefaultConstructor = false;
14730 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14731 for (auto *Ctor : RD->ctors()) {
14732 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14733 Ctor->getMethodQualifiers().getAddressSpace() ==
14734 LangAS::opencl_constant) {
14735 HasConstExprDefaultConstructor = true;
14736 }
14737 }
14738 }
14739 if (!HasConstExprDefaultConstructor) {
14740 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14741 Var->setInvalidDecl();
14742 return;
14743 }
14744 }
14745
14746 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14747 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14748 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14749 Var->setInvalidDecl();
14750 return;
14751 }
14752
14753 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14754 if (Var->getStorageClass() == SC_Extern) {
14755 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14756 << Var;
14757 Var->setInvalidDecl();
14758 return;
14759 }
14760 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14761 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14762 Var->setInvalidDecl();
14763 return;
14764 }
14765 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14766 if (!RD->hasTrivialDefaultConstructor()) {
14767 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14768 Var->setInvalidDecl();
14769 return;
14770 }
14771 }
14772 // The declaration is uninitialized, no need for further checks.
14773 return;
14774 }
14775
14776 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14777 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14778 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14779 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14780 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14781 NonTrivialKind: NTCUK_Init);
14782
14783 switch (DefKind) {
14784 case VarDecl::Definition:
14785 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14786 break;
14787
14788 // We have an out-of-line definition of a static data member
14789 // that has an in-class initializer, so we type-check this like
14790 // a declaration.
14791 //
14792 [[fallthrough]];
14793
14794 case VarDecl::DeclarationOnly:
14795 // It's only a declaration.
14796
14797 // Block scope. C99 6.7p7: If an identifier for an object is
14798 // declared with no linkage (C99 6.2.2p6), the type for the
14799 // object shall be complete.
14800 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14801 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14802 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14803 DiagID: diag::err_typecheck_decl_incomplete_type))
14804 Var->setInvalidDecl();
14805
14806 // Make sure that the type is not abstract.
14807 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14808 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14809 DiagID: diag::err_abstract_type_in_decl,
14810 Args: AbstractVariableType))
14811 Var->setInvalidDecl();
14812 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14813 Var->getStorageClass() == SC_PrivateExtern) {
14814 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14815 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14816 }
14817
14818 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14819 !Var->isInvalidDecl())
14820 ExternalDeclarations.push_back(Elt: Var);
14821
14822 return;
14823
14824 case VarDecl::TentativeDefinition:
14825 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14826 // object that has file scope without an initializer, and without a
14827 // storage-class specifier or with the storage-class specifier "static",
14828 // constitutes a tentative definition. Note: A tentative definition with
14829 // external linkage is valid (C99 6.2.2p5).
14830 if (!Var->isInvalidDecl()) {
14831 if (const IncompleteArrayType *ArrayT
14832 = Context.getAsIncompleteArrayType(T: Type)) {
14833 if (RequireCompleteSizedType(
14834 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14835 DiagID: diag::err_array_incomplete_or_sizeless_type))
14836 Var->setInvalidDecl();
14837 }
14838 if (Var->getStorageClass() == SC_Static) {
14839 // C99 6.9.2p3: If the declaration of an identifier for an object is
14840 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14841 // declared type shall not be an incomplete type.
14842 // NOTE: code such as the following
14843 // static struct s;
14844 // struct s { int a; };
14845 // is accepted by gcc. Hence here we issue a warning instead of
14846 // an error and we do not invalidate the static declaration.
14847 // NOTE: to avoid multiple warnings, only check the first declaration.
14848 if (Var->isFirstDecl())
14849 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14850 DiagID: diag::ext_typecheck_decl_incomplete_type,
14851 Args: Type->isArrayType());
14852 }
14853 }
14854
14855 // Record the tentative definition; we're done.
14856 if (!Var->isInvalidDecl())
14857 TentativeDefinitions.push_back(LocalValue: Var);
14858 return;
14859 }
14860
14861 // Provide a specific diagnostic for uninitialized variable definitions
14862 // with incomplete array type, unless it is a global unbounded HLSL resource
14863 // array.
14864 if (Type->isIncompleteArrayType() &&
14865 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14866 Type->isHLSLResourceRecordArray())) {
14867 if (Var->isConstexpr())
14868 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14869 << Var;
14870 else
14871 Diag(Loc: Var->getLocation(),
14872 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14873 Var->setInvalidDecl();
14874 return;
14875 }
14876
14877 // Provide a specific diagnostic for uninitialized variable
14878 // definitions with reference type.
14879 if (Type->isReferenceType()) {
14880 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14881 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14882 return;
14883 }
14884
14885 // Do not attempt to type-check the default initializer for a
14886 // variable with dependent type.
14887 if (Type->isDependentType())
14888 return;
14889
14890 if (Var->isInvalidDecl())
14891 return;
14892
14893 if (!Var->hasAttr<AliasAttr>()) {
14894 if (RequireCompleteType(Loc: Var->getLocation(),
14895 T: Context.getBaseElementType(QT: Type),
14896 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14897 Var->setInvalidDecl();
14898 return;
14899 }
14900 } else {
14901 return;
14902 }
14903
14904 // The variable can not have an abstract class type.
14905 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14906 DiagID: diag::err_abstract_type_in_decl,
14907 Args: AbstractVariableType)) {
14908 Var->setInvalidDecl();
14909 return;
14910 }
14911
14912 // In C, if the definition is const-qualified and has no initializer, it
14913 // is left uninitialized unless it has static or thread storage duration.
14914 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14915 unsigned DiagID = diag::warn_default_init_const_unsafe;
14916 if (Var->getStorageDuration() == SD_Static ||
14917 Var->getStorageDuration() == SD_Thread)
14918 DiagID = diag::warn_default_init_const;
14919
14920 bool EmitCppCompat = !Diags.isIgnored(
14921 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14922 Loc: Var->getLocation());
14923
14924 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14925 }
14926
14927 // Check for jumps past the implicit initializer. C++0x
14928 // clarifies that this applies to a "variable with automatic
14929 // storage duration", not a "local variable".
14930 // C++11 [stmt.dcl]p3
14931 // A program that jumps from a point where a variable with automatic
14932 // storage duration is not in scope to a point where it is in scope is
14933 // ill-formed unless the variable has scalar type, class type with a
14934 // trivial default constructor and a trivial destructor, a cv-qualified
14935 // version of one of these types, or an array of one of the preceding
14936 // types and is declared without an initializer.
14937 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14938 if (const auto *CXXRecord =
14939 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14940 // Mark the function (if we're in one) for further checking even if the
14941 // looser rules of C++11 do not require such checks, so that we can
14942 // diagnose incompatibilities with C++98.
14943 if (!CXXRecord->isPOD())
14944 setFunctionHasBranchProtectedScope();
14945 }
14946 }
14947 // In OpenCL, we can't initialize objects in the __local address space,
14948 // even implicitly, so don't synthesize an implicit initializer.
14949 if (getLangOpts().OpenCL &&
14950 Var->getType().getAddressSpace() == LangAS::opencl_local)
14951 return;
14952
14953 // Handle HLSL uninitialized decls
14954 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14955 return;
14956
14957 // HLSL input & push-constant variables are expected to be externally
14958 // initialized, even when marked `static`.
14959 if (getLangOpts().HLSL &&
14960 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14961 return;
14962
14963 // C++03 [dcl.init]p9:
14964 // If no initializer is specified for an object, and the
14965 // object is of (possibly cv-qualified) non-POD class type (or
14966 // array thereof), the object shall be default-initialized; if
14967 // the object is of const-qualified type, the underlying class
14968 // type shall have a user-declared default
14969 // constructor. Otherwise, if no initializer is specified for
14970 // a non- static object, the object and its subobjects, if
14971 // any, have an indeterminate initial value); if the object
14972 // or any of its subobjects are of const-qualified type, the
14973 // program is ill-formed.
14974 // C++0x [dcl.init]p11:
14975 // If no initializer is specified for an object, the object is
14976 // default-initialized; [...].
14977 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14978 InitializationKind Kind
14979 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14980
14981 InitializationSequence InitSeq(*this, Entity, Kind, {});
14982 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14983
14984 if (Init.get()) {
14985 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14986 // This is important for template substitution.
14987 Var->setInitStyle(VarDecl::CallInit);
14988 } else if (Init.isInvalid()) {
14989 // If default-init fails, attach a recovery-expr initializer to track
14990 // that initialization was attempted and failed.
14991 auto RecoveryExpr =
14992 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14993 if (RecoveryExpr.get())
14994 Var->setInit(RecoveryExpr.get());
14995 }
14996
14997 CheckCompleteVariableDeclaration(VD: Var);
14998 }
14999}
15000
15001void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15002 // If there is no declaration, there was an error parsing it. Ignore it.
15003 if (!D)
15004 return;
15005
15006 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
15007 if (!VD) {
15008 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var)
15009 << InExpansionStmt;
15010 D->setInvalidDecl();
15011 return;
15012 }
15013
15014 VD->setCXXForRangeDecl(true);
15015
15016 // for-range-declaration cannot be given a storage class specifier.
15017 int Error = -1;
15018 switch (VD->getStorageClass()) {
15019 case SC_None:
15020 break;
15021 case SC_Extern:
15022 Error = 0;
15023 break;
15024 case SC_Static:
15025 Error = 1;
15026 break;
15027 case SC_PrivateExtern:
15028 Error = 2;
15029 break;
15030 case SC_Auto:
15031 Error = 3;
15032 break;
15033 case SC_Register:
15034 Error = 4;
15035 break;
15036 }
15037
15038 // for-range-declaration cannot be given a storage class specifier con't.
15039 switch (VD->getTSCSpec()) {
15040 case TSCS_thread_local:
15041 Error = 6;
15042 break;
15043 case TSCS___thread:
15044 case TSCS__Thread_local:
15045 case TSCS_unspecified:
15046 break;
15047 }
15048
15049 if (Error != -1) {
15050 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
15051 << InExpansionStmt << VD << Error;
15052 D->setInvalidDecl();
15053 }
15054}
15055
15056StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
15057 IdentifierInfo *Ident,
15058 ParsedAttributes &Attrs) {
15059 // C++1y [stmt.iter]p1:
15060 // A range-based for statement of the form
15061 // for ( for-range-identifier : for-range-initializer ) statement
15062 // is equivalent to
15063 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15064 DeclSpec DS(Attrs.getPool().getFactory());
15065
15066 const char *PrevSpec;
15067 unsigned DiagID;
15068 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
15069 Policy: getPrintingPolicy());
15070
15071 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
15072 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
15073 D.takeAttributesAppending(attrs&: Attrs);
15074
15075 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
15076 EndLoc: IdentLoc);
15077 Decl *Var = ActOnDeclarator(S, D);
15078 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
15079 FinalizeDeclaration(D: Var);
15080 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
15081 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15082 : IdentLoc);
15083}
15084
15085void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
15086 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
15087 return;
15088 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
15089 QualType MethodType = MD->getType();
15090 QualType AttributedType =
15091 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
15092 TypeLocBuilder TLB;
15093 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
15094 TLB.pushFullCopy(L: TSI->getTypeLoc());
15095 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
15096 TyLoc.setAttr(Attr);
15097 MD->setType(AttributedType);
15098 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
15099}
15100
15101void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
15102 if (var->isInvalidDecl()) return;
15103
15104 CUDA().MaybeAddConstantAttr(VD: var);
15105
15106 if (getLangOpts().OpenCL) {
15107 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15108 // initialiser
15109 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15110 !var->hasInit()) {
15111 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
15112 << 1 /*Init*/;
15113 var->setInvalidDecl();
15114 return;
15115 }
15116 }
15117
15118 // In Objective-C, don't allow jumps past the implicit initialization of a
15119 // local retaining variable.
15120 if (getLangOpts().ObjC &&
15121 var->hasLocalStorage()) {
15122 switch (var->getType().getObjCLifetime()) {
15123 case Qualifiers::OCL_None:
15124 case Qualifiers::OCL_ExplicitNone:
15125 case Qualifiers::OCL_Autoreleasing:
15126 break;
15127
15128 case Qualifiers::OCL_Weak:
15129 case Qualifiers::OCL_Strong:
15130 setFunctionHasBranchProtectedScope();
15131 break;
15132 }
15133 }
15134
15135 if (var->hasLocalStorage() &&
15136 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15137 setFunctionHasBranchProtectedScope();
15138
15139 // Warn about externally-visible variables being defined without a
15140 // prior declaration. We only want to do this for global
15141 // declarations, but we also specifically need to avoid doing it for
15142 // class members because the linkage of an anonymous class can
15143 // change if it's later given a typedef name.
15144 if (var->isThisDeclarationADefinition() &&
15145 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15146 var->isExternallyVisible() && var->hasLinkage() &&
15147 !var->isInline() && !var->getDescribedVarTemplate() &&
15148 var->getStorageClass() != SC_Register &&
15149 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
15150 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
15151 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
15152 Loc: var->getLocation())) {
15153 // Find a previous declaration that's not a definition.
15154 VarDecl *prev = var->getPreviousDecl();
15155 while (prev && prev->isThisDeclarationADefinition())
15156 prev = prev->getPreviousDecl();
15157
15158 if (!prev) {
15159 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
15160 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
15161 << /* variable */ 0;
15162 }
15163 }
15164
15165 // Cache the result of checking for constant initialization.
15166 std::optional<bool> CacheHasConstInit;
15167 const Expr *CacheCulprit = nullptr;
15168 auto checkConstInit = [&]() mutable {
15169 const Expr *Init = var->getInit();
15170 if (Init->isInstantiationDependent())
15171 return true;
15172
15173 if (!CacheHasConstInit)
15174 CacheHasConstInit = var->getInit()->isConstantInitializer(
15175 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
15176 return *CacheHasConstInit;
15177 };
15178
15179 if (var->getTLSKind() == VarDecl::TLS_Static) {
15180 if (var->getType().isDestructedType()) {
15181 // GNU C++98 edits for __thread, [basic.start.term]p3:
15182 // The type of an object with thread storage duration shall not
15183 // have a non-trivial destructor.
15184 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
15185 if (getLangOpts().CPlusPlus11)
15186 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15187 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15188 if (!checkConstInit()) {
15189 // GNU C++98 edits for __thread, [basic.start.init]p4:
15190 // An object of thread storage duration shall not require dynamic
15191 // initialization.
15192 // FIXME: Need strict checking here.
15193 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
15194 << CacheCulprit->getSourceRange();
15195 if (getLangOpts().CPlusPlus11)
15196 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15197 }
15198 }
15199 }
15200
15201
15202 if (!var->getType()->isStructureType() && var->hasInit() &&
15203 isa<InitListExpr>(Val: var->getInit())) {
15204 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15205 unsigned NumInits = ILE->getNumInits();
15206 if (NumInits > 2)
15207 for (unsigned I = 0; I < NumInits; ++I) {
15208 const auto *Init = ILE->getInit(Init: I);
15209 if (!Init)
15210 break;
15211 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15212 if (!SL)
15213 break;
15214
15215 unsigned NumConcat = SL->getNumConcatenated();
15216 // Diagnose missing comma in string array initialization.
15217 // Do not warn when all the elements in the initializer are concatenated
15218 // together. Do not warn for macros too.
15219 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15220 bool OnlyOneMissingComma = true;
15221 for (unsigned J = I + 1; J < NumInits; ++J) {
15222 const auto *Init = ILE->getInit(Init: J);
15223 if (!Init)
15224 break;
15225 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15226 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15227 OnlyOneMissingComma = false;
15228 break;
15229 }
15230 }
15231
15232 if (OnlyOneMissingComma) {
15233 SmallVector<FixItHint, 1> Hints;
15234 for (unsigned i = 0; i < NumConcat - 1; ++i)
15235 Hints.push_back(Elt: FixItHint::CreateInsertion(
15236 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15237
15238 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15239 DiagID: diag::warn_concatenated_literal_array_init)
15240 << Hints;
15241 Diag(Loc: SL->getBeginLoc(),
15242 DiagID: diag::note_concatenated_string_literal_silence);
15243 }
15244 // In any case, stop now.
15245 break;
15246 }
15247 }
15248 }
15249
15250
15251 QualType type = var->getType();
15252
15253 if (var->hasAttr<BlocksAttr>())
15254 getCurFunction()->addByrefBlockVar(VD: var);
15255
15256 Expr *Init = var->getInit();
15257 bool GlobalStorage = var->hasGlobalStorage();
15258 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15259 QualType baseType = Context.getBaseElementType(QT: type);
15260 bool HasConstInit = true;
15261
15262 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15263 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15264 << var;
15265
15266 // Check whether the initializer is sufficiently constant.
15267 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15268 !type->isDependentType() && Init && !Init->isValueDependent() &&
15269 (GlobalStorage || var->isConstexpr() ||
15270 var->mightBeUsableInConstantExpressions(C: Context))) {
15271 // If this variable might have a constant initializer or might be usable in
15272 // constant expressions, check whether or not it actually is now. We can't
15273 // do this lazily, because the result might depend on things that change
15274 // later, such as which constexpr functions happen to be defined.
15275 SmallVector<PartialDiagnosticAt, 8> Notes;
15276 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15277 // Prior to C++11, in contexts where a constant initializer is required,
15278 // the set of valid constant initializers is described by syntactic rules
15279 // in [expr.const]p2-6.
15280 // FIXME: Stricter checking for these rules would be useful for constinit /
15281 // -Wglobal-constructors.
15282 HasConstInit = checkConstInit();
15283
15284 // Compute and cache the constant value, and remember that we have a
15285 // constant initializer.
15286 if (HasConstInit) {
15287 if (var->isStaticDataMember() && !var->isInline() &&
15288 var->getLexicalDeclContext()->isRecord() &&
15289 type->isIntegralOrEnumerationType()) {
15290 // In C++98, in-class initialization for a static data member must
15291 // be an integer constant expression.
15292 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15293 Diag(Loc: Init->getExprLoc(),
15294 DiagID: diag::ext_in_class_initializer_non_constant)
15295 << Init->getSourceRange();
15296 }
15297 }
15298 (void)var->checkForConstantInitialization(Notes);
15299 Notes.clear();
15300 } else if (CacheCulprit) {
15301 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15302 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15303 Notes.back().second << CacheCulprit->getSourceRange();
15304 }
15305 } else {
15306 // Evaluate the initializer to see if it's a constant initializer.
15307 HasConstInit = var->checkForConstantInitialization(Notes);
15308 }
15309
15310 if (HasConstInit) {
15311 // FIXME: Consider replacing the initializer with a ConstantExpr.
15312 } else if (var->isConstexpr()) {
15313 SourceLocation DiagLoc = var->getLocation();
15314 // If the note doesn't add any useful information other than a source
15315 // location, fold it into the primary diagnostic.
15316 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15317 diag::note_invalid_subexpr_in_const_expr) {
15318 DiagLoc = Notes[0].first;
15319 Notes.clear();
15320 }
15321 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15322 << var << Init->getSourceRange();
15323 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15324 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15325 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15326 auto *Attr = var->getAttr<ConstInitAttr>();
15327 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15328 << Init->getSourceRange();
15329 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15330 << Attr->getRange() << Attr->isConstinit();
15331 for (auto &it : Notes)
15332 Diag(Loc: it.first, PD: it.second);
15333 } else if (var->isStaticDataMember() && !var->isInline() &&
15334 var->getLexicalDeclContext()->isRecord()) {
15335 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15336 << Init->getSourceRange();
15337 for (auto &it : Notes)
15338 Diag(Loc: it.first, PD: it.second);
15339 var->setInvalidDecl();
15340 } else if (IsGlobal &&
15341 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15342 Loc: var->getLocation())) {
15343 // Warn about globals which don't have a constant initializer. Don't
15344 // warn about globals with a non-trivial destructor because we already
15345 // warned about them.
15346 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15347 if (!(RD && !RD->hasTrivialDestructor())) {
15348 // checkConstInit() here permits trivial default initialization even in
15349 // C++11 onwards, where such an initializer is not a constant initializer
15350 // but nonetheless doesn't require a global constructor.
15351 if (!checkConstInit())
15352 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15353 << Init->getSourceRange();
15354 }
15355 }
15356 }
15357
15358 // Apply section attributes and pragmas to global variables.
15359 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15360 !inTemplateInstantiation()) {
15361 PragmaStack<StringLiteral *> *Stack = nullptr;
15362 int SectionFlags = ASTContext::PSF_Read;
15363 bool MSVCEnv =
15364 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15365 std::optional<QualType::NonConstantStorageReason> Reason;
15366 if (HasConstInit &&
15367 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15368 Stack = &ConstSegStack;
15369 } else {
15370 SectionFlags |= ASTContext::PSF_Write;
15371 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15372 }
15373 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15374 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15375 SectionFlags |= ASTContext::PSF_Implicit;
15376 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15377 } else if (Stack->CurrentValue) {
15378 if (Stack != &ConstSegStack && MSVCEnv &&
15379 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15380 var->getType().isConstQualified()) {
15381 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15382 NonConstNonReferenceType) &&
15383 "This case should've already been handled elsewhere");
15384 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15385 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15386 ? QualType::NonConstantStorageReason::NonTrivialCtor
15387 : *Reason);
15388 }
15389 SectionFlags |= ASTContext::PSF_Implicit;
15390 auto SectionName = Stack->CurrentValue->getString();
15391 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15392 Range: Stack->CurrentPragmaLocation,
15393 S: SectionAttr::Declspec_allocate));
15394 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15395 var->dropAttr<SectionAttr>();
15396 }
15397
15398 // Apply the init_seg attribute if this has an initializer. If the
15399 // initializer turns out to not be dynamic, we'll end up ignoring this
15400 // attribute.
15401 if (CurInitSeg && var->getInit())
15402 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15403 Range: CurInitSegLoc));
15404 }
15405
15406 // All the following checks are C++ only.
15407 if (!getLangOpts().CPlusPlus) {
15408 // If this variable must be emitted, add it as an initializer for the
15409 // current module.
15410 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15411 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15412 return;
15413 }
15414
15415 DiagnoseUniqueObjectDuplication(VD: var);
15416
15417 // Require the destructor.
15418 if (!type->isDependentType())
15419 if (auto *RD = baseType->getAsCXXRecordDecl())
15420 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15421
15422 // If this variable must be emitted, add it as an initializer for the current
15423 // module. For named modules, discardable inline variables may be deferred
15424 // until they are odr-used. Non-inline variables that must be emitted,
15425 // including those with side-effecting initialization, must still be emitted
15426 // even if they have internal linkage.
15427 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) {
15428 GVALinkage Linkage = Context.GetGVALinkageForVariable(VD: var);
15429 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15430 !isDiscardableGVALinkage(L: Linkage) ||
15431 (Linkage == GVA_Internal && !var->isInline()))
15432 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15433 }
15434
15435 // Build the bindings if this is a structured binding declaration.
15436 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15437 CheckCompleteDecompositionDeclaration(DD);
15438}
15439
15440void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15441 assert(VD->isStaticLocal());
15442
15443 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15444
15445 // Find outermost function when VD is in lambda function.
15446 while (FD && !getDLLAttr(D: FD) &&
15447 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15448 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15449 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15450 }
15451
15452 if (!FD)
15453 return;
15454
15455 // Static locals inherit dll attributes from their function.
15456 if (Attr *A = getDLLAttr(D: FD)) {
15457 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15458 NewAttr->setInherited(true);
15459 VD->addAttr(A: NewAttr);
15460 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15461 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15462 NewAttr->setInherited(true);
15463 VD->addAttr(A: NewAttr);
15464
15465 // Export this function to enforce exporting this static variable even
15466 // if it is not used in this compilation unit.
15467 if (!FD->hasAttr<DLLExportAttr>())
15468 FD->addAttr(A: NewAttr);
15469
15470 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15471 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15472 NewAttr->setInherited(true);
15473 VD->addAttr(A: NewAttr);
15474 }
15475}
15476
15477void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15478 assert(VD->getTLSKind());
15479
15480 // Perform TLS alignment check here after attributes attached to the variable
15481 // which may affect the alignment have been processed. Only perform the check
15482 // if the target has a maximum TLS alignment (zero means no constraints).
15483 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15484 // Protect the check so that it's not performed on dependent types and
15485 // dependent alignments (we can't determine the alignment in that case).
15486 if (!VD->hasDependentAlignment()) {
15487 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15488 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15489 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15490 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15491 << (unsigned)MaxAlignChars.getQuantity();
15492 }
15493 }
15494 }
15495}
15496
15497void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15498 // Note that we are no longer parsing the initializer for this declaration.
15499 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15500
15501 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15502 if (!VD)
15503 return;
15504
15505 // Emit any deferred warnings for the variable's initializer, even if the
15506 // variable is invalid
15507 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15508
15509 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15510 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15511 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15512 if (PragmaClangBSSSection.Valid)
15513 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15514 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15515 Range: PragmaClangBSSSection.PragmaLocation));
15516 if (PragmaClangDataSection.Valid)
15517 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15518 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15519 Range: PragmaClangDataSection.PragmaLocation));
15520 if (PragmaClangRodataSection.Valid)
15521 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15522 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15523 Range: PragmaClangRodataSection.PragmaLocation));
15524 if (PragmaClangRelroSection.Valid)
15525 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15526 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15527 Range: PragmaClangRelroSection.PragmaLocation));
15528 }
15529
15530 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15531 for (auto *BD : DD->bindings()) {
15532 FinalizeDeclaration(ThisDecl: BD);
15533 }
15534 }
15535
15536 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15537 K: BuiltinCountedByRefKind::Initializer);
15538
15539 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15540
15541 if (VD->isStaticLocal())
15542 CheckStaticLocalForDllExport(VD);
15543
15544 if (VD->getTLSKind())
15545 CheckThreadLocalForLargeAlignment(VD);
15546
15547 // Perform check for initializers of device-side global variables.
15548 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15549 // 7.5). We must also apply the same checks to all __shared__
15550 // variables whether they are local or not. CUDA also allows
15551 // constant initializers for __constant__ and __device__ variables.
15552 if (getLangOpts().CUDA)
15553 CUDA().checkAllowedInitializer(VD);
15554
15555 // Grab the dllimport or dllexport attribute off of the VarDecl.
15556 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15557
15558 // Imported static data members cannot be defined out-of-line.
15559 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15560 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15561 VD->isThisDeclarationADefinition()) {
15562 // We allow definitions of dllimport class template static data members
15563 // with a warning.
15564 CXXRecordDecl *Context =
15565 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15566 bool IsClassTemplateMember =
15567 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15568 Context->getDescribedClassTemplate();
15569
15570 Diag(Loc: VD->getLocation(),
15571 DiagID: IsClassTemplateMember
15572 ? diag::warn_attribute_dllimport_static_field_definition
15573 : diag::err_attribute_dllimport_static_field_definition);
15574 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15575 if (!IsClassTemplateMember)
15576 VD->setInvalidDecl();
15577 }
15578 }
15579
15580 // dllimport/dllexport variables cannot be thread local, their TLS index
15581 // isn't exported with the variable.
15582 if (DLLAttr && VD->getTLSKind()) {
15583 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15584 if (F && getDLLAttr(D: F)) {
15585 assert(VD->isStaticLocal());
15586 // But if this is a static local in a dlimport/dllexport function, the
15587 // function will never be inlined, which means the var would never be
15588 // imported, so having it marked import/export is safe.
15589 } else {
15590 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15591 << DLLAttr;
15592 VD->setInvalidDecl();
15593 }
15594 }
15595
15596 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15597 if (!Attr->isInherited() && !Attr->isImplicit() &&
15598 !VD->isThisDeclarationADefinition()) {
15599 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15600 << Attr;
15601 VD->dropAttr<UsedAttr>();
15602 }
15603 }
15604 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15605 if (!Attr->isInherited() && !Attr->isImplicit() &&
15606 !VD->isThisDeclarationADefinition()) {
15607 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15608 << Attr;
15609 VD->dropAttr<RetainAttr>();
15610 }
15611 }
15612
15613 const DeclContext *DC = VD->getDeclContext();
15614 // If there's a #pragma GCC visibility in scope, and this isn't a class
15615 // member, set the visibility of this variable.
15616 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15617 AddPushedVisibilityAttribute(RD: VD);
15618
15619 // FIXME: Warn on unused var template partial specializations.
15620 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15621 MarkUnusedFileScopedDecl(D: VD);
15622
15623 // Now we have parsed the initializer and can update the table of magic
15624 // tag values.
15625 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15626 !VD->getType()->isIntegralOrEnumerationType())
15627 return;
15628
15629 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15630 const Expr *MagicValueExpr = VD->getInit();
15631 if (!MagicValueExpr) {
15632 continue;
15633 }
15634 std::optional<llvm::APSInt> MagicValueInt;
15635 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15636 Diag(Loc: I->getRange().getBegin(),
15637 DiagID: diag::err_type_tag_for_datatype_not_ice)
15638 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15639 continue;
15640 }
15641 if (MagicValueInt->getActiveBits() > 64) {
15642 Diag(Loc: I->getRange().getBegin(),
15643 DiagID: diag::err_type_tag_for_datatype_too_large)
15644 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15645 continue;
15646 }
15647 uint64_t MagicValue = MagicValueInt->getZExtValue();
15648 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15649 MagicValue,
15650 Type: I->getMatchingCType(),
15651 LayoutCompatible: I->getLayoutCompatible(),
15652 MustBeNull: I->getMustBeNull());
15653 }
15654}
15655
15656static bool hasDeducedAuto(DeclaratorDecl *DD) {
15657 auto *VD = dyn_cast<VarDecl>(Val: DD);
15658 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15659}
15660
15661Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15662 ArrayRef<Decl *> Group) {
15663 SmallVector<Decl*, 8> Decls;
15664
15665 if (DS.isTypeSpecOwned())
15666 Decls.push_back(Elt: DS.getRepAsDecl());
15667
15668 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15669 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15670 bool DiagnosedMultipleDecomps = false;
15671 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15672 bool DiagnosedNonDeducedAuto = false;
15673
15674 for (Decl *D : Group) {
15675 if (!D)
15676 continue;
15677 // Check if the Decl has been declared in '#pragma omp declare target'
15678 // directive and has static storage duration.
15679 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15680 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15681 VD->hasGlobalStorage())
15682 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15683 // For declarators, there are some additional syntactic-ish checks we need
15684 // to perform.
15685 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15686 if (!FirstDeclaratorInGroup)
15687 FirstDeclaratorInGroup = DD;
15688 if (!FirstDecompDeclaratorInGroup)
15689 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15690 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15691 !hasDeducedAuto(DD))
15692 FirstNonDeducedAutoInGroup = DD;
15693
15694 if (FirstDeclaratorInGroup != DD) {
15695 // A decomposition declaration cannot be combined with any other
15696 // declaration in the same group.
15697 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15698 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15699 DiagID: diag::err_decomp_decl_not_alone)
15700 << FirstDeclaratorInGroup->getSourceRange()
15701 << DD->getSourceRange();
15702 DiagnosedMultipleDecomps = true;
15703 }
15704
15705 // A declarator that uses 'auto' in any way other than to declare a
15706 // variable with a deduced type cannot be combined with any other
15707 // declarator in the same group.
15708 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15709 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15710 DiagID: diag::err_auto_non_deduced_not_alone)
15711 << FirstNonDeducedAutoInGroup->getType()
15712 ->hasAutoForTrailingReturnType()
15713 << FirstDeclaratorInGroup->getSourceRange()
15714 << DD->getSourceRange();
15715 DiagnosedNonDeducedAuto = true;
15716 }
15717 }
15718 }
15719
15720 Decls.push_back(Elt: D);
15721 }
15722
15723 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15724 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15725 handleTagNumbering(Tag, TagScope: S);
15726 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15727 getLangOpts().CPlusPlus)
15728 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15729 }
15730 }
15731
15732 return BuildDeclaratorGroup(Group: Decls);
15733}
15734
15735Sema::DeclGroupPtrTy
15736Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15737 // C++14 [dcl.spec.auto]p7: (DR1347)
15738 // If the type that replaces the placeholder type is not the same in each
15739 // deduction, the program is ill-formed.
15740 if (Group.size() > 1) {
15741 QualType Deduced;
15742 VarDecl *DeducedDecl = nullptr;
15743 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15744 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15745 if (!D || D->isInvalidDecl())
15746 break;
15747 DeducedType *DT = D->getType()->getContainedDeducedType();
15748 if (!DT || DT->getDeducedType().isNull())
15749 continue;
15750 if (Deduced.isNull()) {
15751 Deduced = DT->getDeducedType();
15752 DeducedDecl = D;
15753 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15754 auto *AT = dyn_cast<AutoType>(Val: DT);
15755 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15756 DiagID: diag::err_auto_different_deductions)
15757 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15758 << DeducedDecl->getDeclName() << DT->getDeducedType()
15759 << D->getDeclName();
15760 if (DeducedDecl->hasInit())
15761 Dia << DeducedDecl->getInit()->getSourceRange();
15762 if (D->getInit())
15763 Dia << D->getInit()->getSourceRange();
15764 D->setInvalidDecl();
15765 break;
15766 }
15767 }
15768 }
15769
15770 ActOnDocumentableDecls(Group);
15771
15772 return DeclGroupPtrTy::make(
15773 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15774}
15775
15776void Sema::ActOnDocumentableDecl(Decl *D) {
15777 ActOnDocumentableDecls(Group: D);
15778}
15779
15780void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15781 // Don't parse the comment if Doxygen diagnostics are ignored.
15782 if (Group.empty() || !Group[0])
15783 return;
15784
15785 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15786 Loc: Group[0]->getLocation()) &&
15787 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15788 Loc: Group[0]->getLocation()))
15789 return;
15790
15791 if (Group.size() >= 2) {
15792 // This is a decl group. Normally it will contain only declarations
15793 // produced from declarator list. But in case we have any definitions or
15794 // additional declaration references:
15795 // 'typedef struct S {} S;'
15796 // 'typedef struct S *S;'
15797 // 'struct S *pS;'
15798 // FinalizeDeclaratorGroup adds these as separate declarations.
15799 Decl *MaybeTagDecl = Group[0];
15800 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15801 Group = Group.slice(N: 1);
15802 }
15803 }
15804
15805 // FIXME: We assume every Decl in the group is in the same file.
15806 // This is false when preprocessor constructs the group from decls in
15807 // different files (e. g. macros or #include).
15808 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15809}
15810
15811void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15812 // Check that there are no default arguments inside the type of this
15813 // parameter.
15814 if (getLangOpts().CPlusPlus)
15815 CheckExtraCXXDefaultArguments(D);
15816
15817 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15818 if (D.getCXXScopeSpec().isSet()) {
15819 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15820 << D.getCXXScopeSpec().getRange();
15821 }
15822
15823 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15824 // simple identifier except [...irrelevant cases...].
15825 switch (D.getName().getKind()) {
15826 case UnqualifiedIdKind::IK_Identifier:
15827 break;
15828
15829 case UnqualifiedIdKind::IK_OperatorFunctionId:
15830 case UnqualifiedIdKind::IK_ConversionFunctionId:
15831 case UnqualifiedIdKind::IK_LiteralOperatorId:
15832 case UnqualifiedIdKind::IK_ConstructorName:
15833 case UnqualifiedIdKind::IK_DestructorName:
15834 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15835 case UnqualifiedIdKind::IK_DeductionGuideName:
15836 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15837 << GetNameForDeclarator(D).getName();
15838 break;
15839
15840 case UnqualifiedIdKind::IK_TemplateId:
15841 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15842 // GetNameForDeclarator would not produce a useful name in this case.
15843 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15844 break;
15845 }
15846}
15847
15848void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15849 // This only matters in C.
15850 if (getLangOpts().CPlusPlus)
15851 return;
15852
15853 // This only matters if the declaration has a type.
15854 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15855 if (!VD)
15856 return;
15857
15858 // Get the type, this only matters for tag types.
15859 QualType QT = VD->getType();
15860 const auto *TD = QT->getAsTagDecl();
15861 if (!TD)
15862 return;
15863
15864 // Check if the tag declaration is lexically declared somewhere different
15865 // from the lexical declaration of the given object, then it will be hidden
15866 // in C++ and we should warn on it.
15867 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15868 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15869 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15870 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15871 }
15872}
15873
15874static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15875 SourceLocation ExplicitThisLoc) {
15876 if (!ExplicitThisLoc.isValid())
15877 return;
15878 assert(S.getLangOpts().CPlusPlus &&
15879 "explicit parameter in non-cplusplus mode");
15880 if (!S.getLangOpts().CPlusPlus23)
15881 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15882 << P->getSourceRange();
15883
15884 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15885 // parameter pack.
15886 if (P->isParameterPack()) {
15887 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15888 << P->getSourceRange();
15889 return;
15890 }
15891 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15892 if (LambdaScopeInfo *LSI = S.getCurLambda())
15893 LSI->ExplicitObjectParameter = P;
15894}
15895
15896Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15897 SourceLocation ExplicitThisLoc) {
15898 const DeclSpec &DS = D.getDeclSpec();
15899
15900 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15901 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15902 // except for the special case of a single unnamed parameter of type void
15903 // with no storage class specifier, no type qualifier, and no following
15904 // ellipsis terminator.
15905 // Clang applies the C2y rules for 'register void' in all C language modes,
15906 // same as GCC, because it's questionable what that could possibly mean.
15907
15908 // C++03 [dcl.stc]p2 also permits 'auto'.
15909 StorageClass SC = SC_None;
15910 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15911 SC = SC_Register;
15912 // In C++11, the 'register' storage class specifier is deprecated.
15913 // In C++17, it is not allowed, but we tolerate it as an extension.
15914 if (getLangOpts().CPlusPlus11) {
15915 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15916 ? diag::ext_register_storage_class
15917 : diag::warn_deprecated_register)
15918 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15919 } else if (!getLangOpts().CPlusPlus &&
15920 DS.getTypeSpecType() == DeclSpec::TST_void &&
15921 D.getNumTypeObjects() == 0) {
15922 Diag(Loc: DS.getStorageClassSpecLoc(),
15923 DiagID: diag::err_invalid_storage_class_in_func_decl)
15924 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15925 D.getMutableDeclSpec().ClearStorageClassSpecs();
15926 }
15927 } else if (getLangOpts().CPlusPlus &&
15928 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15929 SC = SC_Auto;
15930 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15931 Diag(Loc: DS.getStorageClassSpecLoc(),
15932 DiagID: diag::err_invalid_storage_class_in_func_decl);
15933 D.getMutableDeclSpec().ClearStorageClassSpecs();
15934 }
15935
15936 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15937 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15938 << DeclSpec::getSpecifierName(S: TSCS);
15939 if (DS.isInlineSpecified())
15940 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15941 << getLangOpts().CPlusPlus17;
15942 if (DS.hasConstexprSpecifier())
15943 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15944 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15945
15946 DiagnoseFunctionSpecifiers(DS);
15947
15948 CheckFunctionOrTemplateParamDeclarator(S, D);
15949
15950 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15951 QualType parmDeclType = TInfo->getType();
15952
15953 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15954 const IdentifierInfo *II = D.getIdentifier();
15955 if (II) {
15956 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15957 RedeclarationKind::ForVisibleRedeclaration);
15958 LookupName(R, S);
15959 if (!R.empty()) {
15960 NamedDecl *PrevDecl = *R.begin();
15961 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15962 // Maybe we will complain about the shadowed template parameter.
15963 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15964 // Just pretend that we didn't see the previous declaration.
15965 PrevDecl = nullptr;
15966 }
15967 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15968 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15969 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15970 // Recover by removing the name
15971 II = nullptr;
15972 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15973 D.setInvalidType(true);
15974 }
15975 }
15976 }
15977
15978 // Incomplete resource arrays are not allowed as function parameters in HLSL
15979 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15980 QualType EltTy = Context.getBaseElementType(QT: parmDeclType);
15981 // `isCompleteType` forces completion of the element type so the resource
15982 // check is valid.
15983 if (!EltTy->isDependentType() &&
15984 isCompleteType(Loc: D.getIdentifierLoc(), T: EltTy) &&
15985 parmDeclType->isHLSLResourceRecordArray()) {
15986 Diag(Loc: D.getIdentifierLoc(),
15987 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15988 D.setInvalidType(true);
15989 }
15990 }
15991
15992 // Temporarily put parameter variables in the translation unit, not
15993 // the enclosing context. This prevents them from accidentally
15994 // looking like class members in C++.
15995 ParmVarDecl *New =
15996 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15997 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15998
15999 if (D.isInvalidType())
16000 New->setInvalidDecl();
16001
16002 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
16003
16004 assert(S->isFunctionPrototypeScope());
16005 assert(S->getFunctionPrototypeDepth() >= 1);
16006 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
16007 parameterIndex: S->getNextFunctionPrototypeIndex());
16008
16009 warnOnCTypeHiddenInCPlusPlus(D: New);
16010
16011 // Add the parameter declaration into this scope.
16012 S->AddDecl(D: New);
16013 if (II)
16014 IdResolver.AddDecl(D: New);
16015
16016 ProcessDeclAttributes(S, D: New, PD: D);
16017
16018 if (D.getDeclSpec().isModulePrivateSpecified())
16019 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
16020 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16021 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
16022
16023 if (New->hasAttr<BlocksAttr>())
16024 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
16025 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16026
16027 New->deduceParmAddressSpace(Ctxt: Context);
16028
16029 return New;
16030}
16031
16032ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
16033 SourceLocation Loc,
16034 QualType T) {
16035 /* FIXME: setting StartLoc == Loc.
16036 Would it be worth to modify callers so as to provide proper source
16037 location for the unnamed parameters, embedding the parameter's type? */
16038 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
16039 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
16040 S: SC_None, DefArg: nullptr);
16041 Param->setImplicit();
16042 return Param;
16043}
16044
16045void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
16046 // Don't diagnose unused-parameter errors in template instantiations; we
16047 // will already have done so in the template itself.
16048 if (inTemplateInstantiation())
16049 return;
16050
16051 for (const ParmVarDecl *Parameter : Parameters) {
16052 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16053 !Parameter->hasAttr<UnusedAttr>() &&
16054 !Parameter->getIdentifier()->isPlaceholder()) {
16055 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
16056 << Parameter->getDeclName();
16057 }
16058 }
16059}
16060
16061void Sema::DiagnoseSizeOfParametersAndReturnValue(
16062 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16063 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16064 return;
16065
16066 // Warn if the return value is pass-by-value and larger than the specified
16067 // threshold.
16068 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16069 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
16070 if (Size > LangOpts.NumLargeByValueCopy)
16071 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
16072 }
16073
16074 // Warn if any parameter is pass-by-value and larger than the specified
16075 // threshold.
16076 for (const ParmVarDecl *Parameter : Parameters) {
16077 QualType T = Parameter->getType();
16078 if (T->isDependentType() || !T.isPODType(Context))
16079 continue;
16080 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16081 if (Size > LangOpts.NumLargeByValueCopy)
16082 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
16083 << Parameter << Size;
16084 }
16085}
16086
16087ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
16088 SourceLocation NameLoc,
16089 const IdentifierInfo *Name, QualType T,
16090 TypeSourceInfo *TSInfo, StorageClass SC) {
16091 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16092 if (getLangOpts().ObjCAutoRefCount &&
16093 T.getObjCLifetime() == Qualifiers::OCL_None &&
16094 T->isObjCLifetimeType()) {
16095
16096 Qualifiers::ObjCLifetime lifetime;
16097
16098 // Special cases for arrays:
16099 // - if it's const, use __unsafe_unretained
16100 // - otherwise, it's an error
16101 if (T->isArrayType()) {
16102 if (!T.isConstQualified()) {
16103 if (DelayedDiagnostics.shouldDelayDiagnostics())
16104 DelayedDiagnostics.add(
16105 diag: sema::DelayedDiagnostic::makeForbiddenType(
16106 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
16107 else
16108 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
16109 << TSInfo->getTypeLoc().getSourceRange();
16110 }
16111 lifetime = Qualifiers::OCL_ExplicitNone;
16112 } else {
16113 lifetime = T->getObjCARCImplicitLifetime();
16114 }
16115 T = Context.getLifetimeQualifiedType(type: T, lifetime);
16116 }
16117
16118 if (getLangOpts().OpenCL) {
16119 assert(!isa<DecayedType>(T));
16120 if (T->isArrayType() && !T.hasAddressSpace()) {
16121 QualType ET = Context.getAsArrayType(T)->getElementType();
16122 if (!ET.hasAddressSpace()) {
16123 // Add the private address space to the contents of the pointer when a
16124 // pointer parameter is declared as an array and not declared.
16125 LangAS ImplAS = LangAS::opencl_private;
16126 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
16127 T = QualType(Context.getAsArrayType(T), 0);
16128 }
16129 }
16130 }
16131
16132 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
16133 T: Context.getAdjustedParameterType(T),
16134 TInfo: TSInfo, S: SC, DefArg: nullptr);
16135
16136 // Make a note if we created a new pack in the scope of a lambda, so that
16137 // we know that references to that pack must also be expanded within the
16138 // lambda scope.
16139 if (New->isParameterPack())
16140 if (auto *CSI = getEnclosingLambdaOrBlock())
16141 CSI->LocalPacks.push_back(Elt: New);
16142
16143 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16144 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16145 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
16146 UseContext: NonTrivialCUnionContext::FunctionParam,
16147 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16148
16149 // Parameter declarators cannot be interface types. All ObjC objects are
16150 // passed by reference.
16151 if (T->isObjCObjectType()) {
16152 SourceLocation TypeEndLoc =
16153 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
16154 Diag(Loc: NameLoc,
16155 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16156 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
16157 T = Context.getObjCObjectPointerType(OIT: T);
16158 New->setType(T);
16159 }
16160
16161 // __ptrauth is forbidden on parameters.
16162 if (T.getPointerAuth()) {
16163 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
16164 New->setInvalidDecl();
16165 }
16166
16167 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16168 // duration shall not be qualified by an address-space qualifier."
16169 // Since all parameters have automatic store duration, they can not have
16170 // an address space.
16171 if (T.getAddressSpace() != LangAS::Default &&
16172 // OpenCL allows function arguments declared to be an array of a type
16173 // to be qualified with an address space.
16174 !(getLangOpts().OpenCL &&
16175 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16176 // WebAssembly allows reference types as parameters. Funcref in particular
16177 // lives in a different address space.
16178 !(T->isFunctionPointerType() &&
16179 T.getAddressSpace() == LangAS::wasm_funcref) &&
16180 // HLSL allows function arguments to be qualified with an address space
16181 // if the groupshared annotation is used.
16182 !(getLangOpts().HLSL &&
16183 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16184 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
16185 New->setInvalidDecl();
16186 }
16187
16188 // PPC MMA non-pointer types are not allowed as function argument types.
16189 if (Context.getTargetInfo().getTriple().isPPC64() &&
16190 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
16191 New->setInvalidDecl();
16192 }
16193
16194 return New;
16195}
16196
16197void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
16198 SourceLocation LocAfterDecls) {
16199 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
16200
16201 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16202 // in the declaration list shall have at least one declarator, those
16203 // declarators shall only declare identifiers from the identifier list, and
16204 // every identifier in the identifier list shall be declared.
16205 //
16206 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16207 // identifiers it names shall be declared in the declaration list."
16208 //
16209 // This is why we only diagnose in C99 and later. Note, the other conditions
16210 // listed are checked elsewhere.
16211 if (!FTI.hasPrototype) {
16212 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16213 --i;
16214 if (FTI.Params[i].Param == nullptr) {
16215 if (getLangOpts().C99) {
16216 SmallString<256> Code;
16217 llvm::raw_svector_ostream(Code)
16218 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16219 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16220 << FTI.Params[i].Ident
16221 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16222 }
16223
16224 // Implicitly declare the argument as type 'int' for lack of a better
16225 // type.
16226 AttributeFactory attrs;
16227 DeclSpec DS(attrs);
16228 const char* PrevSpec; // unused
16229 unsigned DiagID; // unused
16230 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16231 DiagID, Policy: Context.getPrintingPolicy());
16232 // Use the identifier location for the type source range.
16233 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16234 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16235 Declarator ParamD(DS, ParsedAttributesView::none(),
16236 DeclaratorContext::KNRTypeList);
16237 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16238 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16239 }
16240 }
16241 }
16242}
16243
16244Decl *
16245Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16246 MultiTemplateParamsArg TemplateParameterLists,
16247 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16248 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16249 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16250 Scope *ParentScope = FnBodyScope->getParent();
16251
16252 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16253 // we define a non-templated function definition, we will create a declaration
16254 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16255 // The base function declaration will have the equivalent of an `omp declare
16256 // variant` annotation which specifies the mangled definition as a
16257 // specialization function under the OpenMP context defined as part of the
16258 // `omp begin declare variant`.
16259 SmallVector<FunctionDecl *, 4> Bases;
16260 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16261 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16262 S: ParentScope, D, TemplateParameterLists, Bases);
16263
16264 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16265 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16266 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16267
16268 if (!Bases.empty())
16269 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16270 Bases);
16271
16272 return Dcl;
16273}
16274
16275void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16276 Consumer.HandleInlineFunctionDefinition(D);
16277}
16278
16279static bool FindPossiblePrototype(const FunctionDecl *FD,
16280 const FunctionDecl *&PossiblePrototype) {
16281 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16282 Prev = Prev->getPreviousDecl()) {
16283 // Ignore any declarations that occur in function or method
16284 // scope, because they aren't visible from the header.
16285 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16286 continue;
16287
16288 PossiblePrototype = Prev;
16289 return Prev->getType()->isFunctionProtoType();
16290 }
16291 return false;
16292}
16293
16294static bool
16295ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16296 const FunctionDecl *&PossiblePrototype) {
16297 // Don't warn about invalid declarations.
16298 if (FD->isInvalidDecl())
16299 return false;
16300
16301 // Or declarations that aren't global.
16302 if (!FD->isGlobal())
16303 return false;
16304
16305 // Don't warn about C++ member functions.
16306 if (isa<CXXMethodDecl>(Val: FD))
16307 return false;
16308
16309 // Don't warn about 'main'.
16310 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16311 if (IdentifierInfo *II = FD->getIdentifier())
16312 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16313 return false;
16314
16315 if (FD->isMSVCRTEntryPoint())
16316 return false;
16317
16318 // Don't warn about inline functions.
16319 if (FD->isInlined())
16320 return false;
16321
16322 // Don't warn about function templates.
16323 if (FD->getDescribedFunctionTemplate())
16324 return false;
16325
16326 // Don't warn about function template specializations.
16327 if (FD->isFunctionTemplateSpecialization())
16328 return false;
16329
16330 // Don't warn for OpenCL kernels.
16331 if (FD->hasAttr<DeviceKernelAttr>())
16332 return false;
16333
16334 // Don't warn on explicitly deleted functions.
16335 if (FD->isDeleted())
16336 return false;
16337
16338 // Don't warn on implicitly local functions (such as having local-typed
16339 // parameters).
16340 if (!FD->isExternallyVisible())
16341 return false;
16342
16343 // If we were able to find a potential prototype, don't warn.
16344 if (FindPossiblePrototype(FD, PossiblePrototype))
16345 return false;
16346
16347 return true;
16348}
16349
16350void
16351Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16352 const FunctionDecl *EffectiveDefinition,
16353 SkipBodyInfo *SkipBody) {
16354 const FunctionDecl *Definition = EffectiveDefinition;
16355 if (!Definition &&
16356 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16357 return;
16358
16359 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16360 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16361 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16362 // A merged copy of the same function, instantiated as a member of
16363 // the same class, is OK.
16364 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16365 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16366 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16367 return;
16368 }
16369 }
16370 }
16371
16372 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16373 return;
16374
16375 // Don't emit an error when this is redefinition of a typo-corrected
16376 // definition.
16377 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16378 return;
16379
16380 bool DefinitionVisible = false;
16381 if (SkipBody &&
16382 isRedefinitionAllowedFor(D: Definition, NewLoc: FD->getLocation(),
16383 Visible&: DefinitionVisible) &&
16384 (Definition->getFormalLinkage() == Linkage::Internal ||
16385 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16386 !Definition->getTemplateParameterLists().empty())) {
16387 SkipBody->ShouldSkip = true;
16388 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16389 if (!DefinitionVisible) {
16390 if (auto *TD = Definition->getDescribedFunctionTemplate())
16391 makeMergedDefinitionVisible(ND: TD);
16392 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16393 }
16394 return;
16395 }
16396
16397 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16398 Definition->getStorageClass() == SC_Extern)
16399 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16400 << FD << getLangOpts().CPlusPlus;
16401 else
16402 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16403
16404 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16405 FD->setInvalidDecl();
16406}
16407
16408LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16409 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16410
16411 LambdaScopeInfo *LSI = PushLambdaScope();
16412 LSI->CallOperator = CallOperator;
16413 LSI->Lambda = LambdaClass;
16414 LSI->ReturnType = CallOperator->getReturnType();
16415 // When this function is called in situation where the context of the call
16416 // operator is not entered, we set AfterParameterList to false, so that
16417 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16418 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16419 // where we would set the CurContext to the lambda operator before
16420 // substituting into it. In this case the flag needs to be true such that
16421 // tryCaptureVariable can correctly handle potential captures thereof.
16422 LSI->AfterParameterList = CurContext == CallOperator;
16423 LSI->BeforeCompoundStatement = false;
16424
16425 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16426 // used at the point of dealing with potential captures.
16427 //
16428 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16429 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16430 // associated. (Technically, we could recover that list from their
16431 // instantiation patterns, but for now, the GLTemplateParameterList seems
16432 // unnecessary in these cases.)
16433 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16434 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16435 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16436
16437 if (LCD == LCD_None)
16438 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16439 else if (LCD == LCD_ByCopy)
16440 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16441 else if (LCD == LCD_ByRef)
16442 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16443 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16444
16445 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16446 LSI->Mutable = !CallOperator->isConst();
16447 if (CallOperator->isExplicitObjectMemberFunction())
16448 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16449
16450 // Add the captures to the LSI so they can be noted as already
16451 // captured within tryCaptureVar.
16452 auto I = LambdaClass->field_begin();
16453 for (const auto &C : LambdaClass->captures()) {
16454 if (C.capturesVariable()) {
16455 ValueDecl *VD = C.getCapturedVar();
16456 if (VD->isInitCapture())
16457 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16458 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16459 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16460 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16461 /*EllipsisLoc*/C.isPackExpansion()
16462 ? C.getEllipsisLoc() : SourceLocation(),
16463 CaptureType: I->getType(), /*Invalid*/false);
16464
16465 } else if (C.capturesThis()) {
16466 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16467 ByCopy: C.getCaptureKind() == LCK_StarThis);
16468 } else {
16469 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16470 CaptureType: I->getType());
16471 }
16472 ++I;
16473 }
16474 return LSI;
16475}
16476
16477Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16478 SkipBodyInfo *SkipBody,
16479 FnBodyKind BodyKind) {
16480 if (!D) {
16481 // Parsing the function declaration failed in some way. Push on a fake scope
16482 // anyway so we can try to parse the function body.
16483 PushFunctionScope();
16484 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16485 return D;
16486 }
16487
16488 FunctionDecl *FD = nullptr;
16489
16490 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16491 FD = FunTmpl->getTemplatedDecl();
16492 else
16493 FD = cast<FunctionDecl>(Val: D);
16494
16495 // Do not push if it is a lambda because one is already pushed when building
16496 // the lambda in ActOnStartOfLambdaDefinition().
16497 if (!isLambdaCallOperator(DC: FD))
16498 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16499 FD);
16500
16501 // Check for defining attributes before the check for redefinition.
16502 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16503 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16504 FD->dropAttr<AliasAttr>();
16505 FD->setInvalidDecl();
16506 }
16507 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16508 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16509 FD->dropAttr<IFuncAttr>();
16510 FD->setInvalidDecl();
16511 }
16512 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16513 if (Context.getTargetInfo().getTriple().isAArch64() &&
16514 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16515 !Attr->isDefaultVersion()) {
16516 // If function multi versioning disabled skip parsing function body
16517 // defined with non-default target_version attribute
16518 if (SkipBody)
16519 SkipBody->ShouldSkip = true;
16520 return nullptr;
16521 }
16522 }
16523
16524 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16525 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16526 Ctor->isDefaultConstructor() &&
16527 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16528 // If this is an MS ABI dllexport default constructor, instantiate any
16529 // default arguments.
16530 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16531 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
16532 }
16533 }
16534
16535 // See if this is a redefinition. If 'will have body' (or similar) is already
16536 // set, then these checks were already performed when it was set.
16537 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16538 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16539 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16540
16541 // If we're skipping the body, we're done. Don't enter the scope.
16542 if (SkipBody && SkipBody->ShouldSkip)
16543 return D;
16544 }
16545
16546 // Mark this function as "will have a body eventually". This lets users to
16547 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16548 // this function.
16549 FD->setWillHaveBody();
16550
16551 // If we are instantiating a generic lambda call operator, push
16552 // a LambdaScopeInfo onto the function stack. But use the information
16553 // that's already been calculated (ActOnLambdaExpr) to prime the current
16554 // LambdaScopeInfo.
16555 // When the template operator is being specialized, the LambdaScopeInfo,
16556 // has to be properly restored so that tryCaptureVariable doesn't try
16557 // and capture any new variables. In addition when calculating potential
16558 // captures during transformation of nested lambdas, it is necessary to
16559 // have the LSI properly restored.
16560 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16561 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16562 // specialized.
16563 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16564 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16565 << /*specialization*/ 0;
16566 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16567 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16568
16569 FD->setInvalidDecl();
16570 PushFunctionScope();
16571 } else {
16572 assert(inTemplateInstantiation() &&
16573 "There should be an active template instantiation on the stack "
16574 "when instantiating a generic lambda!");
16575 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16576 }
16577 } else {
16578 // Enter a new function scope
16579 PushFunctionScope();
16580 }
16581
16582 // Builtin functions cannot be defined.
16583 if (unsigned BuiltinID = FD->getBuiltinID()) {
16584 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16585 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16586 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16587 FD->setInvalidDecl();
16588 }
16589 }
16590
16591 // The return type of a function definition must be complete (C99 6.9.1p3).
16592 // C++23 [dcl.fct.def.general]/p2
16593 // The type of [...] the return for a function definition
16594 // shall not be a (possibly cv-qualified) class type that is incomplete
16595 // or abstract within the function body unless the function is deleted.
16596 QualType ResultType = FD->getReturnType();
16597 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16598 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16599 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16600 DiagID: diag::err_func_def_incomplete_result) ||
16601 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16602 DiagID: diag::err_abstract_type_in_decl,
16603 Args: AbstractReturnType)))
16604 FD->setInvalidDecl();
16605
16606 if (FnBodyScope)
16607 PushDeclContext(S: FnBodyScope, DC: FD);
16608
16609 // Check the validity of our function parameters
16610 if (BodyKind != FnBodyKind::Delete)
16611 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16612 /*CheckParameterNames=*/true);
16613
16614 // Add non-parameter declarations already in the function to the current
16615 // scope.
16616 if (FnBodyScope) {
16617 for (Decl *NPD : FD->decls()) {
16618 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16619 if (!NonParmDecl)
16620 continue;
16621 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16622 "parameters should not be in newly created FD yet");
16623
16624 // If the decl has a name, make it accessible in the current scope.
16625 if (NonParmDecl->getDeclName())
16626 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16627
16628 // Similarly, dive into enums and fish their constants out, making them
16629 // accessible in this scope.
16630 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16631 for (auto *EI : ED->enumerators())
16632 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16633 }
16634 }
16635 }
16636
16637 // Introduce our parameters into the function scope
16638 for (auto *Param : FD->parameters()) {
16639 Param->setOwningFunction(FD);
16640
16641 // If this has an identifier, add it to the scope stack.
16642 if (Param->getIdentifier() && FnBodyScope) {
16643 CheckShadow(S: FnBodyScope, D: Param);
16644
16645 PushOnScopeChains(D: Param, S: FnBodyScope);
16646 }
16647 }
16648
16649 // C++ [module.import/6]
16650 // ...
16651 // A header unit shall not contain a definition of a non-inline function or
16652 // variable whose name has external linkage.
16653 //
16654 // Deleted and Defaulted functions are implicitly inline (but the
16655 // inline state is not set at this point, so check the BodyKind explicitly).
16656 // We choose to allow weak & selectany definitions, as they are common in
16657 // headers, and have semantics similar to inline definitions which are allowed
16658 // in header units.
16659 // FIXME: Consider an alternate location for the test where the inlined()
16660 // state is complete.
16661 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16662 !FD->isInvalidDecl() && !FD->isInlined() &&
16663 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16664 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16665 !FD->isTemplateInstantiation() &&
16666 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16667 assert(FD->isThisDeclarationADefinition());
16668 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16669 FD->setInvalidDecl();
16670 }
16671
16672 // Ensure that the function's exception specification is instantiated.
16673 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16674 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16675
16676 // dllimport cannot be applied to non-inline function definitions.
16677 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16678 !FD->isTemplateInstantiation()) {
16679 assert(!FD->hasAttr<DLLExportAttr>());
16680 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16681 FD->setInvalidDecl();
16682 return D;
16683 }
16684
16685 // Some function attributes (like OptimizeNoneAttr) need actions before
16686 // parsing body started.
16687 applyFunctionAttributesBeforeParsingBody(FD: D);
16688
16689 // We want to attach documentation to original Decl (which might be
16690 // a function template).
16691 ActOnDocumentableDecl(D);
16692 if (getCurLexicalContext()->isObjCContainer() &&
16693 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16694 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16695 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16696
16697 maybeAddDeclWithEffects(D: FD);
16698
16699 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16700 FnBodyScope) {
16701 // An implicit call expression is synthesized for functions declared with
16702 // the sycl_kernel_entry_point attribute. The call may resolve to a
16703 // function template, a member function template, or a call operator
16704 // of a variable template depending on the results of unqualified lookup
16705 // for 'sycl_kernel_launch' from the beginning of the function body.
16706 // Performing that lookup requires the stack of parsing scopes active
16707 // when the definition is parsed and is thus done here; the result is
16708 // cached in FunctionScopeInfo and used to synthesize the (possibly
16709 // unresolved) call expression after the function body has been parsed.
16710 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16711 if (!SKEPAttr->isInvalidAttr()) {
16712 ExprResult LaunchIdExpr =
16713 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16714 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16715 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16716 // treated as an error in the definition of 'FD'; treating it as an error
16717 // of the declaration would affect overload resolution which would
16718 // potentially result in additional errors. If construction of
16719 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16720 // a null pointer value below; that is expected.
16721 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16722 }
16723 }
16724
16725 return D;
16726}
16727
16728void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16729 if (!FD || FD->isInvalidDecl())
16730 return;
16731 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16732 FD = TD->getTemplatedDecl();
16733 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16734 FPOptionsOverride FPO;
16735 FPO.setDisallowOptimizations();
16736 CurFPFeatures.applyChanges(FPO);
16737 FpPragmaStack.CurrentValue =
16738 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16739 }
16740}
16741
16742void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16743 ReturnStmt **Returns = Scope->Returns.data();
16744
16745 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16746 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16747 if (!NRVOCandidate->isNRVOVariable()) {
16748 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16749 DiagID: diag::warn_not_eliding_copy_on_return);
16750 Returns[I]->setNRVOCandidate(nullptr);
16751 }
16752 }
16753 }
16754}
16755
16756bool Sema::canDelayFunctionBody(const Declarator &D) {
16757 // We can't delay parsing the body of a constexpr function template (yet).
16758 if (D.getDeclSpec().hasConstexprSpecifier())
16759 return false;
16760
16761 // We can't delay parsing the body of a function template with a deduced
16762 // return type (yet).
16763 if (D.getDeclSpec().hasAutoTypeSpec()) {
16764 // If the placeholder introduces a non-deduced trailing return type,
16765 // we can still delay parsing it.
16766 if (D.getNumTypeObjects()) {
16767 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16768 if (Outer.Kind == DeclaratorChunk::Function &&
16769 Outer.Fun.hasTrailingReturnType()) {
16770 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16771 return Ty.isNull() || !Ty->isUndeducedType();
16772 }
16773 }
16774 return false;
16775 }
16776
16777 return true;
16778}
16779
16780bool Sema::canSkipFunctionBody(Decl *D) {
16781 // We cannot skip the body of a function (or function template) which is
16782 // constexpr, since we may need to evaluate its body in order to parse the
16783 // rest of the file.
16784 // We cannot skip the body of a function with an undeduced return type,
16785 // because any callers of that function need to know the type.
16786 if (const FunctionDecl *FD = D->getAsFunction()) {
16787 if (FD->isConstexpr())
16788 return false;
16789 // We can't simply call Type::isUndeducedType here, because inside template
16790 // auto can be deduced to a dependent type, which is not considered
16791 // "undeduced".
16792 if (FD->getReturnType()->getContainedDeducedType())
16793 return false;
16794 }
16795 return Consumer.shouldSkipFunctionBody(D);
16796}
16797
16798Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16799 if (!Decl)
16800 return nullptr;
16801 if (FunctionDecl *FD = Decl->getAsFunction())
16802 FD->setHasSkippedBody();
16803 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16804 MD->setHasSkippedBody();
16805 return Decl;
16806}
16807
16808/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16809/// body.
16810class ExitFunctionBodyRAII {
16811public:
16812 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16813 ~ExitFunctionBodyRAII() {
16814 if (!IsLambda)
16815 S.PopExpressionEvaluationContext();
16816 }
16817
16818private:
16819 Sema &S;
16820 bool IsLambda = false;
16821};
16822
16823static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16824 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16825
16826 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16827 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16828 if (!Inserted)
16829 return It->second;
16830
16831 bool R = false;
16832 const BlockDecl *CurBD = BD;
16833
16834 do {
16835 R = !CurBD->doesNotEscape();
16836 if (R)
16837 break;
16838 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16839 } while (CurBD);
16840
16841 return It->second = R;
16842 };
16843
16844 // If the location where 'self' is implicitly retained is inside a escaping
16845 // block, emit a diagnostic.
16846 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16847 S.ImplicitlyRetainedSelfLocs)
16848 if (IsOrNestedInEscapingBlock(P.second))
16849 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16850 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16851}
16852
16853static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16854 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16855 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16856}
16857
16858bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16859 return methodHasName(FD, Name: "get_return_object");
16860}
16861
16862bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16863 return FD->isStatic() &&
16864 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16865}
16866
16867void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16868 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16869 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16870 return;
16871 // Allow some_promise_type::get_return_object().
16872 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16873 return;
16874 if (!FD->hasAttr<CoroWrapperAttr>())
16875 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16876}
16877
16878Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16879 bool RetainFunctionScopeInfo) {
16880 FunctionScopeInfo *FSI = getCurFunction();
16881 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16882
16883 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16884 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16885
16886 SourceLocation AnalysisLoc;
16887 if (Body)
16888 AnalysisLoc = Body->getEndLoc();
16889 else if (FD)
16890 AnalysisLoc = FD->getEndLoc();
16891 sema::AnalysisBasedWarnings::Policy WP =
16892 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16893 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16894
16895 // If we skip function body, we can't tell if a function is a coroutine.
16896 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16897 if (FSI->isCoroutine())
16898 CheckCompletedCoroutineBody(FD, Body);
16899 else
16900 CheckCoroutineWrapper(FD);
16901 }
16902
16903 // Diagnose invalid SYCL kernel entry point function declarations
16904 // and build SYCLKernelCallStmts for valid ones.
16905 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16906 SYCLKernelEntryPointAttr *SKEPAttr =
16907 FD->getAttr<SYCLKernelEntryPointAttr>();
16908 if (FD->isDefaulted()) {
16909 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16910 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16911 SKEPAttr->setInvalidAttr();
16912 } else if (FD->isDeleted()) {
16913 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16914 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16915 SKEPAttr->setInvalidAttr();
16916 } else if (FSI->isCoroutine()) {
16917 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16918 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16919 SKEPAttr->setInvalidAttr();
16920 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16921 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16922 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16923 SKEPAttr->setInvalidAttr();
16924 }
16925
16926 // Build an unresolved SYCL kernel call statement for a function template,
16927 // validate that a SYCL kernel call statement was instantiated for an
16928 // (implicit or explicit) instantiation of a function template, or otherwise
16929 // build a (resolved) SYCL kernel call statement for a non-templated
16930 // function or an explicit specialization.
16931 if (Body && !SKEPAttr->isInvalidAttr()) {
16932 StmtResult SR;
16933 if (FD->isTemplateInstantiation()) {
16934 // The function body should already be a SYCLKernelCallStmt in this
16935 // case, but might not be if there were previous errors.
16936 SR = Body;
16937 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16938 // If name lookup for a template named sycl_kernel_launch failed
16939 // earlier, don't try to build a SYCL kernel call statement as that
16940 // would cause additional errors to be issued; just proceed with the
16941 // original function body.
16942 SR = Body;
16943 } else if (FD->isTemplated()) {
16944 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16945 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16946 } else {
16947 SR = SYCL().BuildSYCLKernelCallStmt(
16948 FD, Body: cast<CompoundStmt>(Val: Body),
16949 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16950 }
16951 // If construction of the replacement body fails, just continue with the
16952 // original function body. An early error return here is not valid; the
16953 // current declaration context and function scopes must be popped before
16954 // returning.
16955 if (SR.isUsable())
16956 Body = SR.get();
16957 }
16958 }
16959
16960 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16961 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16962 if (FD->isDeletedAsWritten())
16963 Diag(Loc: SEAttr->getLocation(),
16964 DiagID: diag::err_sycl_external_invalid_deleted_function)
16965 << SEAttr;
16966 }
16967
16968 {
16969 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16970 // one is already popped when finishing the lambda in BuildLambdaExpr().
16971 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16972 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16973 if (FD) {
16974 // The function body and the DefaultedOrDeletedInfo, if present, use
16975 // the same storage; don't overwrite the latter if the former is null
16976 // (the body is initialised to null anyway, so even if the latter isn't
16977 // present, this would still be a no-op).
16978 if (Body)
16979 FD->setBody(Body);
16980 FD->setWillHaveBody(false);
16981
16982 if (getLangOpts().CPlusPlus14) {
16983 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16984 FD->getReturnType()->isUndeducedType()) {
16985 // For a function with a deduced result type to return void,
16986 // the result type as written must be 'auto' or 'decltype(auto)',
16987 // possibly cv-qualified or constrained, but not ref-qualified.
16988 if (!FD->getReturnType()->getAs<AutoType>()) {
16989 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16990 << FD->getReturnType();
16991 FD->setInvalidDecl();
16992 } else {
16993 // Falling off the end of the function is the same as 'return;'.
16994 Expr *Dummy = nullptr;
16995 if (DeduceFunctionTypeFromReturnExpr(
16996 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16997 AT: FD->getReturnType()->getAs<AutoType>()))
16998 FD->setInvalidDecl();
16999 }
17000 }
17001 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
17002 // In C++11, we don't use 'auto' deduction rules for lambda call
17003 // operators because we don't support return type deduction.
17004 auto *LSI = getCurLambda();
17005 if (LSI->HasImplicitReturnType) {
17006 deduceClosureReturnType(CSI&: *LSI);
17007
17008 // C++11 [expr.prim.lambda]p4:
17009 // [...] if there are no return statements in the compound-statement
17010 // [the deduced type is] the type void
17011 QualType RetType =
17012 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17013
17014 // Update the return type to the deduced type.
17015 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17016 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
17017 EPI: Proto->getExtProtoInfo()));
17018 }
17019 }
17020
17021 // If the function implicitly returns zero (like 'main') or is naked,
17022 // don't complain about missing return statements.
17023 // Clang implicitly returns 0 in C89 mode, but that's considered an
17024 // extension. The check is necessary to ensure the expected extension
17025 // warning is emitted in C89 mode.
17026 if ((FD->hasImplicitReturnZero() &&
17027 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17028 FD->hasAttr<NakedAttr>())
17029 WP.disableCheckFallThrough();
17030
17031 // MSVC permits the use of pure specifier (=0) on function definition,
17032 // defined at class scope, warn about this non-standard construct.
17033 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17034 !FD->isOutOfLine())
17035 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
17036
17037 if (!FD->isInvalidDecl()) {
17038 // Don't diagnose unused parameters of defaulted, deleted or naked
17039 // functions.
17040 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17041 !FD->hasAttr<NakedAttr>())
17042 DiagnoseUnusedParameters(Parameters: FD->parameters());
17043 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
17044 ReturnTy: FD->getReturnType(), D: FD);
17045
17046 // If this is a structor, we need a vtable.
17047 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
17048 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
17049 else if (CXXDestructorDecl *Destructor =
17050 dyn_cast<CXXDestructorDecl>(Val: FD))
17051 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
17052
17053 // Try to apply the named return value optimization. We have to check
17054 // if we can do this here because lambdas keep return statements around
17055 // to deduce an implicit return type.
17056 if (FD->getReturnType()->isRecordType() &&
17057 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
17058 computeNRVO(Body, Scope: FSI);
17059 }
17060
17061 // GNU warning -Wmissing-prototypes:
17062 // Warn if a global function is defined without a previous
17063 // prototype declaration. This warning is issued even if the
17064 // definition itself provides a prototype. The aim is to detect
17065 // global functions that fail to be declared in header files.
17066 const FunctionDecl *PossiblePrototype = nullptr;
17067 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17068 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
17069
17070 if (PossiblePrototype) {
17071 // We found a declaration that is not a prototype,
17072 // but that could be a zero-parameter prototype
17073 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17074 TypeLoc TL = TI->getTypeLoc();
17075 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
17076 Diag(Loc: PossiblePrototype->getLocation(),
17077 DiagID: diag::note_declaration_not_a_prototype)
17078 << (FD->getNumParams() != 0)
17079 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
17080 InsertionLoc: FTL.getRParenLoc(), Code: "void")
17081 : FixItHint{});
17082 }
17083 } else {
17084 // Returns true if the token beginning at this Loc is `const`.
17085 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17086 const LangOptions &LangOpts) {
17087 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17088 if (LocInfo.first.isInvalid())
17089 return false;
17090
17091 bool Invalid = false;
17092 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
17093 if (Invalid)
17094 return false;
17095
17096 if (LocInfo.second > Buffer.size())
17097 return false;
17098
17099 const char *LexStart = Buffer.data() + LocInfo.second;
17100 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17101
17102 return StartTok.consume_front(Prefix: "const") &&
17103 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
17104 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
17105 };
17106
17107 auto findBeginLoc = [&]() {
17108 // If the return type has `const` qualifier, we want to insert
17109 // `static` before `const` (and not before the typename).
17110 if ((FD->getReturnType()->isAnyPointerType() &&
17111 FD->getReturnType()->getPointeeType().isConstQualified()) ||
17112 FD->getReturnType().isConstQualified()) {
17113 // But only do this if we can determine where the `const` is.
17114
17115 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17116 getLangOpts()))
17117
17118 return FD->getBeginLoc();
17119 }
17120 return FD->getTypeSpecStartLoc();
17121 };
17122 Diag(Loc: FD->getTypeSpecStartLoc(),
17123 DiagID: diag::note_static_for_internal_linkage)
17124 << /* function */ 1
17125 << (FD->getStorageClass() == SC_None
17126 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
17127 : FixItHint{});
17128 }
17129 }
17130
17131 // We might not have found a prototype because we didn't wish to warn on
17132 // the lack of a missing prototype. Try again without the checks for
17133 // whether we want to warn on the missing prototype.
17134 if (!PossiblePrototype)
17135 (void)FindPossiblePrototype(FD, PossiblePrototype);
17136
17137 // If the function being defined does not have a prototype, then we may
17138 // need to diagnose it as changing behavior in C23 because we now know
17139 // whether the function accepts arguments or not. This only handles the
17140 // case where the definition has no prototype but does have parameters
17141 // and either there is no previous potential prototype, or the previous
17142 // potential prototype also has no actual prototype. This handles cases
17143 // like:
17144 // void f(); void f(a) int a; {}
17145 // void g(a) int a; {}
17146 // See MergeFunctionDecl() for other cases of the behavior change
17147 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17148 // type without a prototype.
17149 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17150 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17151 !PossiblePrototype->isImplicit()))) {
17152 // The function definition has parameters, so this will change behavior
17153 // in C23. If there is a possible prototype, it comes before the
17154 // function definition.
17155 // FIXME: The declaration may have already been diagnosed as being
17156 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17157 // there's no way to test for the "changes behavior" condition in
17158 // SemaType.cpp when forming the declaration's function type. So, we do
17159 // this awkward dance instead.
17160 //
17161 // If we have a possible prototype and it declares a function with a
17162 // prototype, we don't want to diagnose it; if we have a possible
17163 // prototype and it has no prototype, it may have already been
17164 // diagnosed in SemaType.cpp as deprecated depending on whether
17165 // -Wstrict-prototypes is enabled. If we already warned about it being
17166 // deprecated, add a note that it also changes behavior. If we didn't
17167 // warn about it being deprecated (because the diagnostic is not
17168 // enabled), warn now that it is deprecated and changes behavior.
17169
17170 // This K&R C function definition definitely changes behavior in C23,
17171 // so diagnose it.
17172 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
17173 << /*definition*/ 1 << /* not supported in C23 */ 0;
17174
17175 // If we have a possible prototype for the function which is a user-
17176 // visible declaration, we already tested that it has no prototype.
17177 // This will change behavior in C23. This gets a warning rather than a
17178 // note because it's the same behavior-changing problem as with the
17179 // definition.
17180 if (PossiblePrototype)
17181 Diag(Loc: PossiblePrototype->getLocation(),
17182 DiagID: diag::warn_non_prototype_changes_behavior)
17183 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17184 << /*definition*/ 1;
17185 }
17186
17187 // Warn on CPUDispatch with an actual body.
17188 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17189 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
17190 if (!CmpndBody->body_empty())
17191 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
17192 DiagID: diag::warn_dispatch_body_ignored);
17193
17194 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
17195 const CXXMethodDecl *KeyFunction;
17196 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17197 MD->isVirtual() &&
17198 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
17199 MD == KeyFunction->getCanonicalDecl()) {
17200 // Update the key-function state if necessary for this ABI.
17201 if (FD->isInlined() &&
17202 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17203 Context.setNonKeyFunction(MD);
17204
17205 // If the newly-chosen key function is already defined, then we
17206 // need to mark the vtable as used retroactively.
17207 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
17208 const FunctionDecl *Definition;
17209 if (KeyFunction && KeyFunction->isDefined(Definition))
17210 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17211 } else {
17212 // We just defined they key function; mark the vtable as used.
17213 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17214 }
17215 }
17216 }
17217
17218 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17219 "Function parsing confused");
17220 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
17221 assert(MD == getCurMethodDecl() && "Method parsing confused");
17222 MD->setBody(Body);
17223 if (!MD->isInvalidDecl()) {
17224 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17225 ReturnTy: MD->getReturnType(), D: MD);
17226
17227 if (Body)
17228 computeNRVO(Body, Scope: FSI);
17229 }
17230 if (FSI->ObjCShouldCallSuper) {
17231 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17232 << MD->getSelector().getAsString();
17233 FSI->ObjCShouldCallSuper = false;
17234 }
17235 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17236 const ObjCMethodDecl *InitMethod = nullptr;
17237 bool isDesignated =
17238 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17239 assert(isDesignated && InitMethod);
17240 (void)isDesignated;
17241
17242 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17243 auto IFace = MD->getClassInterface();
17244 if (!IFace)
17245 return false;
17246 auto SuperD = IFace->getSuperClass();
17247 if (!SuperD)
17248 return false;
17249 return SuperD->getIdentifier() ==
17250 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17251 };
17252 // Don't issue this warning for unavailable inits or direct subclasses
17253 // of NSObject.
17254 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17255 Diag(Loc: MD->getLocation(),
17256 DiagID: diag::warn_objc_designated_init_missing_super_call);
17257 Diag(Loc: InitMethod->getLocation(),
17258 DiagID: diag::note_objc_designated_init_marked_here);
17259 }
17260 FSI->ObjCWarnForNoDesignatedInitChain = false;
17261 }
17262 if (FSI->ObjCWarnForNoInitDelegation) {
17263 // Don't issue this warning for unavailable inits.
17264 if (!MD->isUnavailable())
17265 Diag(Loc: MD->getLocation(),
17266 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17267 FSI->ObjCWarnForNoInitDelegation = false;
17268 }
17269
17270 diagnoseImplicitlyRetainedSelf(S&: *this);
17271 } else {
17272 // Parsing the function declaration failed in some way. Pop the fake scope
17273 // we pushed on.
17274 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17275 return nullptr;
17276 }
17277
17278 if (Body) {
17279 if (FSI->HasPotentialAvailabilityViolations)
17280 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17281 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17282 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17283 }
17284
17285 assert(!FSI->ObjCShouldCallSuper &&
17286 "This should only be set for ObjC methods, which should have been "
17287 "handled in the block above.");
17288
17289 // Verify and clean out per-function state.
17290 if (Body && (!FD || !FD->isDefaulted())) {
17291 // C++ constructors that have function-try-blocks can't have return
17292 // statements in the handlers of that block. (C++ [except.handle]p14)
17293 // Verify this.
17294 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17295 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17296
17297 // Verify that gotos and switch cases don't jump into scopes illegally.
17298 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17299 DiagnoseInvalidJumps(Body);
17300
17301 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17302 if (!Destructor->getParent()->isDependentType())
17303 CheckDestructor(Destructor);
17304
17305 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17306 Record: Destructor->getParent());
17307 }
17308
17309 // If any errors have occurred, clear out any temporaries that may have
17310 // been leftover. This ensures that these temporaries won't be picked up
17311 // for deletion in some later function.
17312 if (hasUncompilableErrorOccurred() ||
17313 hasAnyUnrecoverableErrorsInThisFunction() ||
17314 getDiagnostics().getSuppressAllDiagnostics()) {
17315 DiscardCleanupsInEvaluationContext();
17316 }
17317 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17318 // Since the body is valid, issue any analysis-based warnings that are
17319 // enabled.
17320 ActivePolicy = &WP;
17321 }
17322
17323 if (!IsInstantiation && FD &&
17324 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17325 !FD->isInvalidDecl() &&
17326 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17327 FD->setInvalidDecl();
17328
17329 if (FD && FD->hasAttr<NakedAttr>()) {
17330 for (const Stmt *S : Body->children()) {
17331 // Allow local register variables without initializer as they don't
17332 // require prologue.
17333 bool RegisterVariables = false;
17334 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17335 for (const auto *Decl : DS->decls()) {
17336 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17337 RegisterVariables =
17338 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17339 if (!RegisterVariables)
17340 break;
17341 }
17342 }
17343 }
17344 if (RegisterVariables)
17345 continue;
17346 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17347 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17348 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17349 FD->setInvalidDecl();
17350 break;
17351 }
17352 }
17353 }
17354
17355 assert(ExprCleanupObjects.size() ==
17356 ExprEvalContexts.back().NumCleanupObjects &&
17357 "Leftover temporaries in function");
17358 assert(!Cleanup.exprNeedsCleanups() &&
17359 "Unaccounted cleanups in function");
17360 assert(MaybeODRUseExprs.empty() &&
17361 "Leftover expressions for odr-use checking");
17362 }
17363 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17364 // the declaration context below. Otherwise, we're unable to transform
17365 // 'this' expressions when transforming immediate context functions.
17366
17367 if (FD)
17368 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17369
17370 if (!IsInstantiation)
17371 PopDeclContext();
17372
17373 if (!RetainFunctionScopeInfo)
17374 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17375 // If any errors have occurred, clear out any temporaries that may have
17376 // been leftover. This ensures that these temporaries won't be picked up for
17377 // deletion in some later function.
17378 if (hasUncompilableErrorOccurred()) {
17379 DiscardCleanupsInEvaluationContext();
17380 }
17381
17382 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17383 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17384 auto ES = getEmissionStatus(Decl: FD);
17385 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17386 ES == Sema::FunctionEmissionStatus::Unknown)
17387 DeclsToCheckForDeferredDiags.insert(X: FD);
17388 }
17389
17390 if (FD && !FD->isDeleted())
17391 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17392
17393 return dcl;
17394}
17395
17396/// When we finish delayed parsing of an attribute, we must attach it to the
17397/// relevant Decl.
17398void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17399 ParsedAttributes &Attrs) {
17400 // Always attach attributes to the underlying decl.
17401 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17402 D = TD->getTemplatedDecl();
17403 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17404 ProcessAPINotes(D);
17405
17406 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17407 if (Method->isStatic())
17408 checkThisInStaticMemberFunctionAttributes(Method);
17409}
17410
17411NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17412 IdentifierInfo &II, Scope *S) {
17413 // It is not valid to implicitly define a function in C23.
17414 assert(LangOpts.implicitFunctionsAllowed() &&
17415 "Implicit function declarations aren't allowed in this language mode");
17416
17417 // Find the scope in which the identifier is injected and the corresponding
17418 // DeclContext.
17419 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17420 // In that case, we inject the declaration into the translation unit scope
17421 // instead.
17422 Scope *BlockScope = S;
17423 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17424 BlockScope = BlockScope->getParent();
17425
17426 // Loop until we find a DeclContext that is either a function/method or the
17427 // translation unit, which are the only two valid places to implicitly define
17428 // a function. This avoids accidentally defining the function within a tag
17429 // declaration, for example.
17430 Scope *ContextScope = BlockScope;
17431 while (!ContextScope->getEntity() ||
17432 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17433 !ContextScope->getEntity()->isTranslationUnit()))
17434 ContextScope = ContextScope->getParent();
17435 ContextRAII SavedContext(*this, ContextScope->getEntity());
17436
17437 // Before we produce a declaration for an implicitly defined
17438 // function, see whether there was a locally-scoped declaration of
17439 // this name as a function or variable. If so, use that
17440 // (non-visible) declaration, and complain about it.
17441 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17442 if (ExternCPrev) {
17443 // We still need to inject the function into the enclosing block scope so
17444 // that later (non-call) uses can see it.
17445 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17446
17447 // C89 footnote 38:
17448 // If in fact it is not defined as having type "function returning int",
17449 // the behavior is undefined.
17450 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17451 !Context.typesAreCompatible(
17452 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17453 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17454 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17455 << ExternCPrev << !getLangOpts().C99;
17456 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17457 return ExternCPrev;
17458 }
17459 }
17460
17461 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17462 unsigned diag_id;
17463 if (II.getName().starts_with(Prefix: "__builtin_"))
17464 diag_id = diag::warn_builtin_unknown;
17465 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17466 else if (getLangOpts().C99)
17467 diag_id = diag::ext_implicit_function_decl_c99;
17468 else
17469 diag_id = diag::warn_implicit_function_decl;
17470
17471 TypoCorrection Corrected;
17472 // Because typo correction is expensive, only do it if the implicit
17473 // function declaration is going to be treated as an error.
17474 //
17475 // Perform the correction before issuing the main diagnostic, as some
17476 // consumers use typo-correction callbacks to enhance the main diagnostic.
17477 if (S && !ExternCPrev &&
17478 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17479 DeclFilterCCC<FunctionDecl> CCC{};
17480 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17481 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17482 }
17483
17484 Diag(Loc, DiagID: diag_id) << &II;
17485 if (Corrected) {
17486 // If the correction is going to suggest an implicitly defined function,
17487 // skip the correction as not being a particularly good idea.
17488 bool Diagnose = true;
17489 if (const auto *D = Corrected.getCorrectionDecl())
17490 Diagnose = !D->isImplicit();
17491 if (Diagnose)
17492 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17493 /*ErrorRecovery*/ false);
17494 }
17495
17496 // If we found a prior declaration of this function, don't bother building
17497 // another one. We've already pushed that one into scope, so there's nothing
17498 // more to do.
17499 if (ExternCPrev)
17500 return ExternCPrev;
17501
17502 // Set a Declarator for the implicit definition: int foo();
17503 const char *Dummy;
17504 AttributeFactory attrFactory;
17505 DeclSpec DS(attrFactory);
17506 unsigned DiagID;
17507 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17508 Policy: Context.getPrintingPolicy());
17509 (void)Error; // Silence warning.
17510 assert(!Error && "Error setting up implicit decl!");
17511 SourceLocation NoLoc;
17512 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17513 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17514 /*IsAmbiguous=*/false,
17515 /*LParenLoc=*/NoLoc,
17516 /*Params=*/nullptr,
17517 /*NumParams=*/0,
17518 /*EllipsisLoc=*/NoLoc,
17519 /*RParenLoc=*/NoLoc,
17520 /*RefQualifierIsLvalueRef=*/true,
17521 /*RefQualifierLoc=*/NoLoc,
17522 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17523 /*ESpecRange=*/SourceRange(),
17524 /*Exceptions=*/nullptr,
17525 /*ExceptionRanges=*/nullptr,
17526 /*NumExceptions=*/0,
17527 /*NoexceptExpr=*/nullptr,
17528 /*ExceptionSpecTokens=*/nullptr,
17529 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17530 TheDeclarator&: D),
17531 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17532 D.SetIdentifier(Id: &II, IdLoc: Loc);
17533
17534 // Insert this function into the enclosing block scope.
17535 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17536 FD->setImplicit();
17537
17538 AddKnownFunctionAttributes(FD);
17539
17540 return FD;
17541}
17542
17543void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17544 FunctionDecl *FD) {
17545 if (FD->isInvalidDecl())
17546 return;
17547
17548 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17549 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17550 return;
17551
17552 UnsignedOrNone AlignmentParam = std::nullopt;
17553 bool IsNothrow = false;
17554 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17555 return;
17556
17557 // C++2a [basic.stc.dynamic.allocation]p4:
17558 // An allocation function that has a non-throwing exception specification
17559 // indicates failure by returning a null pointer value. Any other allocation
17560 // function never returns a null pointer value and indicates failure only by
17561 // throwing an exception [...]
17562 //
17563 // However, -fcheck-new invalidates this possible assumption, so don't add
17564 // NonNull when that is enabled.
17565 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17566 !getLangOpts().CheckNew)
17567 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17568
17569 // C++2a [basic.stc.dynamic.allocation]p2:
17570 // An allocation function attempts to allocate the requested amount of
17571 // storage. [...] If the request succeeds, the value returned by a
17572 // replaceable allocation function is a [...] pointer value p0 different
17573 // from any previously returned value p1 [...]
17574 //
17575 // However, this particular information is being added in codegen,
17576 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17577
17578 // C++2a [basic.stc.dynamic.allocation]p2:
17579 // An allocation function attempts to allocate the requested amount of
17580 // storage. If it is successful, it returns the address of the start of a
17581 // block of storage whose length in bytes is at least as large as the
17582 // requested size.
17583 if (!FD->hasAttr<AllocSizeAttr>()) {
17584 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17585 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17586 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17587 }
17588
17589 // C++2a [basic.stc.dynamic.allocation]p3:
17590 // For an allocation function [...], the pointer returned on a successful
17591 // call shall represent the address of storage that is aligned as follows:
17592 // (3.1) If the allocation function takes an argument of type
17593 // std​::​align_­val_­t, the storage will have the alignment
17594 // specified by the value of this argument.
17595 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17596 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17597 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17598 }
17599
17600 // FIXME:
17601 // C++2a [basic.stc.dynamic.allocation]p3:
17602 // For an allocation function [...], the pointer returned on a successful
17603 // call shall represent the address of storage that is aligned as follows:
17604 // (3.2) Otherwise, if the allocation function is named operator new[],
17605 // the storage is aligned for any object that does not have
17606 // new-extended alignment ([basic.align]) and is no larger than the
17607 // requested size.
17608 // (3.3) Otherwise, the storage is aligned for any object that does not
17609 // have new-extended alignment and is of the requested size.
17610}
17611
17612void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17613 if (FD->isInvalidDecl())
17614 return;
17615
17616 // If this is a built-in function, map its builtin attributes to
17617 // actual attributes.
17618 if (unsigned BuiltinID = FD->getBuiltinID()) {
17619 // Handle printf-formatting attributes.
17620 unsigned FormatIdx;
17621 bool HasVAListArg;
17622 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17623 if (!FD->hasAttr<FormatAttr>()) {
17624 const char *fmt = "printf";
17625 unsigned int NumParams = FD->getNumParams();
17626 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17627 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17628 fmt = "NSString";
17629 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17630 Type: &Context.Idents.get(Name: fmt),
17631 FormatIdx: FormatIdx+1,
17632 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17633 Range: FD->getLocation()));
17634 }
17635 }
17636 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17637 HasVAListArg)) {
17638 if (!FD->hasAttr<FormatAttr>())
17639 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17640 Type: &Context.Idents.get(Name: "scanf"),
17641 FormatIdx: FormatIdx+1,
17642 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17643 Range: FD->getLocation()));
17644 }
17645
17646 // Handle automatically recognized callbacks.
17647 SmallVector<int, 4> Encoding;
17648 if (!FD->hasAttr<CallbackAttr>() &&
17649 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17650 FD->addAttr(A: CallbackAttr::CreateImplicit(
17651 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17652
17653 // Mark const if we don't care about errno and/or floating point exceptions
17654 // that are the only thing preventing the function from being const. This
17655 // allows IRgen to use LLVM intrinsics for such functions.
17656 bool NoExceptions =
17657 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17658 bool ConstWithoutErrnoAndExceptions =
17659 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17660 bool ConstWithoutExceptions =
17661 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17662 if (!FD->hasAttr<ConstAttr>() &&
17663 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17664 (!ConstWithoutErrnoAndExceptions ||
17665 (!getLangOpts().MathErrno && NoExceptions)) &&
17666 (!ConstWithoutExceptions || NoExceptions))
17667 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17668
17669 // We make "fma" on GNU or Windows const because we know it does not set
17670 // errno in those environments even though it could set errno based on the
17671 // C standard.
17672 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17673 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17674 !FD->hasAttr<ConstAttr>()) {
17675 switch (BuiltinID) {
17676 case Builtin::BI__builtin_fma:
17677 case Builtin::BI__builtin_fmaf:
17678 case Builtin::BI__builtin_fmal:
17679 case Builtin::BIfma:
17680 case Builtin::BIfmaf:
17681 case Builtin::BIfmal:
17682 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17683 break;
17684 default:
17685 break;
17686 }
17687 }
17688
17689 SmallVector<int, 4> Indxs;
17690 Builtin::Info::NonNullMode OptMode;
17691 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17692 !FD->hasAttr<NonNullAttr>()) {
17693 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17694 for (int I : Indxs) {
17695 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17696 QualType T = PVD->getType();
17697 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17698 PVD->setType(T);
17699 }
17700 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17701 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17702 for (int I : Indxs)
17703 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17704 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17705 ArgsSize: ParamIndxs.size()));
17706 }
17707 }
17708 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17709 !FD->hasAttr<ReturnsTwiceAttr>())
17710 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17711 Range: FD->getLocation()));
17712 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17713 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17714 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17715 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17716 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17717 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17718 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17719 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17720 // Add the appropriate attribute, depending on the CUDA compilation mode
17721 // and which target the builtin belongs to. For example, during host
17722 // compilation, aux builtins are __device__, while the rest are __host__.
17723 if (getLangOpts().CUDAIsDevice !=
17724 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17725 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17726 else
17727 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17728 }
17729
17730 // Add known guaranteed alignment for allocation functions.
17731 switch (BuiltinID) {
17732 case Builtin::BImemalign:
17733 case Builtin::BIaligned_alloc:
17734 if (!FD->hasAttr<AllocAlignAttr>())
17735 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17736 Range: FD->getLocation()));
17737 break;
17738 default:
17739 break;
17740 }
17741
17742 // Add allocsize attribute for allocation functions.
17743 switch (BuiltinID) {
17744 case Builtin::BIcalloc:
17745 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17746 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17747 break;
17748 case Builtin::BImemalign:
17749 case Builtin::BIaligned_alloc:
17750 case Builtin::BIrealloc:
17751 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17752 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17753 break;
17754 case Builtin::BImalloc:
17755 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17756 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17757 break;
17758 default:
17759 break;
17760 }
17761 }
17762
17763 LazyProcessLifetimeCaptureByParams(FD);
17764 inferLifetimeBoundAttribute(FD);
17765 inferLifetimeCaptureByAttribute(FD);
17766 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17767
17768 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17769 // throw, add an implicit nothrow attribute to any extern "C" function we come
17770 // across.
17771 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17772 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17773 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17774 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17775 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17776 }
17777
17778 IdentifierInfo *Name = FD->getIdentifier();
17779 if (!Name)
17780 return;
17781 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17782 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17783 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17784 LinkageSpecLanguageIDs::C)) {
17785 // Okay: this could be a libc/libm/Objective-C function we know
17786 // about.
17787 } else
17788 return;
17789
17790 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17791 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17792 // target-specific builtins, perhaps?
17793 if (!FD->hasAttr<FormatAttr>())
17794 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17795 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17796 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17797 Range: FD->getLocation()));
17798 }
17799
17800 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17801 // We already have a __builtin___CFStringMakeConstantString,
17802 // but builds that use -fno-constant-cfstrings don't go through that.
17803 if (!FD->hasAttr<FormatArgAttr>())
17804 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17805 Range: FD->getLocation()));
17806 }
17807}
17808
17809TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17810 TypeSourceInfo *TInfo) {
17811 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17812 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17813
17814 if (!TInfo) {
17815 assert(D.isInvalidType() && "no declarator info for valid type");
17816 TInfo = Context.getTrivialTypeSourceInfo(T);
17817 }
17818
17819 // Scope manipulation handled by caller.
17820 TypedefDecl *NewTD =
17821 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17822 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17823
17824 // Bail out immediately if we have an invalid declaration.
17825 if (D.isInvalidType()) {
17826 NewTD->setInvalidDecl();
17827 return NewTD;
17828 }
17829
17830 if (D.getDeclSpec().isModulePrivateSpecified()) {
17831 if (CurContext->isFunctionOrMethod())
17832 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17833 << 2 << NewTD
17834 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17835 << FixItHint::CreateRemoval(
17836 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17837 else
17838 NewTD->setModulePrivate();
17839 }
17840
17841 // C++ [dcl.typedef]p8:
17842 // If the typedef declaration defines an unnamed class (or
17843 // enum), the first typedef-name declared by the declaration
17844 // to be that class type (or enum type) is used to denote the
17845 // class type (or enum type) for linkage purposes only.
17846 // We need to check whether the type was declared in the declaration.
17847 switch (D.getDeclSpec().getTypeSpecType()) {
17848 case TST_enum:
17849 case TST_struct:
17850 case TST_interface:
17851 case TST_union:
17852 case TST_class: {
17853 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17854 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17855 break;
17856 }
17857
17858 default:
17859 break;
17860 }
17861
17862 return NewTD;
17863}
17864
17865bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17866 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17867 QualType T = TI->getType();
17868
17869 if (T->isDependentType())
17870 return false;
17871
17872 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17873 // integral type; any cv-qualification is ignored.
17874 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17875 // non-atomic version of the type specified by the type specifiers in the
17876 // specifier qualifier list.
17877 // Because of how odd C's rule is, we'll let the user know that operations
17878 // involving the enumeration type will be non-atomic.
17879 if (T->isAtomicType())
17880 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17881
17882 Qualifiers Q = T.getQualifiers();
17883 std::optional<unsigned> QualSelect;
17884 if (Q.hasConst() && Q.hasVolatile())
17885 QualSelect = diag::CVQualList::Both;
17886 else if (Q.hasConst())
17887 QualSelect = diag::CVQualList::Const;
17888 else if (Q.hasVolatile())
17889 QualSelect = diag::CVQualList::Volatile;
17890
17891 if (QualSelect)
17892 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17893
17894 T = T.getAtomicUnqualifiedType();
17895
17896 // This doesn't use 'isIntegralType' despite the error message mentioning
17897 // integral type because isIntegralType would also allow enum types in C.
17898 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17899 if (BT->isInteger())
17900 return false;
17901
17902 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17903 << T << T->isBitIntType();
17904}
17905
17906bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17907 QualType EnumUnderlyingTy, bool IsFixed,
17908 const EnumDecl *Prev) {
17909 if (IsScoped != Prev->isScoped()) {
17910 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17911 << Prev->isScoped();
17912 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17913 return true;
17914 }
17915
17916 if (IsFixed && Prev->isFixed()) {
17917 if (!EnumUnderlyingTy->isDependentType() &&
17918 !Prev->getIntegerType()->isDependentType() &&
17919 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17920 T2: Prev->getIntegerType())) {
17921 // TODO: Highlight the underlying type of the redeclaration.
17922 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17923 << EnumUnderlyingTy << Prev->getIntegerType();
17924 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17925 << Prev->getIntegerTypeRange();
17926 return true;
17927 }
17928 } else if (IsFixed != Prev->isFixed()) {
17929 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17930 << Prev->isFixed();
17931 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17932 return true;
17933 }
17934
17935 return false;
17936}
17937
17938/// Get diagnostic %select index for tag kind for
17939/// redeclaration diagnostic message.
17940/// WARNING: Indexes apply to particular diagnostics only!
17941///
17942/// \returns diagnostic %select index.
17943static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17944 switch (Tag) {
17945 case TagTypeKind::Struct:
17946 return 0;
17947 case TagTypeKind::Interface:
17948 return 1;
17949 case TagTypeKind::Class:
17950 return 2;
17951 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17952 }
17953}
17954
17955/// Determine if tag kind is a class-key compatible with
17956/// class for redeclaration (class, struct, or __interface).
17957///
17958/// \returns true iff the tag kind is compatible.
17959static bool isClassCompatTagKind(TagTypeKind Tag)
17960{
17961 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17962 Tag == TagTypeKind::Interface;
17963}
17964
17965NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17966 if (isa<TypedefDecl>(Val: PrevDecl))
17967 return NonTagKind::Typedef;
17968 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17969 return NonTagKind::TypeAlias;
17970 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17971 return NonTagKind::Template;
17972 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17973 return NonTagKind::TypeAliasTemplate;
17974 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17975 return NonTagKind::TemplateTemplateArgument;
17976 switch (TTK) {
17977 case TagTypeKind::Struct:
17978 case TagTypeKind::Interface:
17979 case TagTypeKind::Class:
17980 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17981 : NonTagKind::NonStruct;
17982 case TagTypeKind::Union:
17983 return NonTagKind::NonUnion;
17984 case TagTypeKind::Enum:
17985 return NonTagKind::NonEnum;
17986 }
17987 llvm_unreachable("invalid TTK");
17988}
17989
17990bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17991 TagTypeKind NewTag, bool isDefinition,
17992 SourceLocation NewTagLoc,
17993 const IdentifierInfo *Name) {
17994 // C++ [dcl.type.elab]p3:
17995 // The class-key or enum keyword present in the
17996 // elaborated-type-specifier shall agree in kind with the
17997 // declaration to which the name in the elaborated-type-specifier
17998 // refers. This rule also applies to the form of
17999 // elaborated-type-specifier that declares a class-name or
18000 // friend class since it can be construed as referring to the
18001 // definition of the class. Thus, in any
18002 // elaborated-type-specifier, the enum keyword shall be used to
18003 // refer to an enumeration (7.2), the union class-key shall be
18004 // used to refer to a union (clause 9), and either the class or
18005 // struct class-key shall be used to refer to a class (clause 9)
18006 // declared using the class or struct class-key.
18007 TagTypeKind OldTag = Previous->getTagKind();
18008 if (OldTag != NewTag &&
18009 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
18010 return false;
18011
18012 // Tags are compatible, but we might still want to warn on mismatched tags.
18013 // Non-class tags can't be mismatched at this point.
18014 if (!isClassCompatTagKind(Tag: NewTag))
18015 return true;
18016
18017 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18018 // by our warning analysis. We don't want to warn about mismatches with (eg)
18019 // declarations in system headers that are designed to be specialized, but if
18020 // a user asks us to warn, we should warn if their code contains mismatched
18021 // declarations.
18022 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18023 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
18024 Loc);
18025 };
18026 if (IsIgnoredLoc(NewTagLoc))
18027 return true;
18028
18029 auto IsIgnored = [&](const TagDecl *Tag) {
18030 return IsIgnoredLoc(Tag->getLocation());
18031 };
18032 while (IsIgnored(Previous)) {
18033 Previous = Previous->getPreviousDecl();
18034 if (!Previous)
18035 return true;
18036 OldTag = Previous->getTagKind();
18037 }
18038
18039 bool isTemplate = false;
18040 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
18041 isTemplate = Record->getDescribedClassTemplate();
18042
18043 if (inTemplateInstantiation()) {
18044 if (OldTag != NewTag) {
18045 // In a template instantiation, do not offer fix-its for tag mismatches
18046 // since they usually mess up the template instead of fixing the problem.
18047 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18048 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18049 << getRedeclDiagFromTagKind(Tag: OldTag);
18050 // FIXME: Note previous location?
18051 }
18052 return true;
18053 }
18054
18055 if (isDefinition) {
18056 // On definitions, check all previous tags and issue a fix-it for each
18057 // one that doesn't match the current tag.
18058 if (Previous->getDefinition()) {
18059 // Don't suggest fix-its for redefinitions.
18060 return true;
18061 }
18062
18063 bool previousMismatch = false;
18064 for (const TagDecl *I : Previous->redecls()) {
18065 if (I->getTagKind() != NewTag) {
18066 // Ignore previous declarations for which the warning was disabled.
18067 if (IsIgnored(I))
18068 continue;
18069
18070 if (!previousMismatch) {
18071 previousMismatch = true;
18072 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
18073 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18074 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
18075 }
18076 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
18077 << getRedeclDiagFromTagKind(Tag: NewTag)
18078 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
18079 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
18080 }
18081 }
18082 return true;
18083 }
18084
18085 // Identify the prevailing tag kind: this is the kind of the definition (if
18086 // there is a non-ignored definition), or otherwise the kind of the prior
18087 // (non-ignored) declaration.
18088 const TagDecl *PrevDef = Previous->getDefinition();
18089 if (PrevDef && IsIgnored(PrevDef))
18090 PrevDef = nullptr;
18091 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18092 if (Redecl->getTagKind() != NewTag) {
18093 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18094 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18095 << getRedeclDiagFromTagKind(Tag: OldTag);
18096 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
18097
18098 // If there is a previous definition, suggest a fix-it.
18099 if (PrevDef) {
18100 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
18101 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
18102 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
18103 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
18104 }
18105 }
18106
18107 return true;
18108}
18109
18110/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18111/// from an outer enclosing namespace or file scope inside a friend declaration.
18112/// This should provide the commented out code in the following snippet:
18113/// namespace N {
18114/// struct X;
18115/// namespace M {
18116/// struct Y { friend struct /*N::*/ X; };
18117/// }
18118/// }
18119static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
18120 SourceLocation NameLoc) {
18121 // While the decl is in a namespace, do repeated lookup of that name and see
18122 // if we get the same namespace back. If we do not, continue until
18123 // translation unit scope, at which point we have a fully qualified NNS.
18124 SmallVector<IdentifierInfo *, 4> Namespaces;
18125 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18126 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18127 // This tag should be declared in a namespace, which can only be enclosed by
18128 // other namespaces. Bail if there's an anonymous namespace in the chain.
18129 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
18130 if (!Namespace || Namespace->isAnonymousNamespace())
18131 return FixItHint();
18132 IdentifierInfo *II = Namespace->getIdentifier();
18133 Namespaces.push_back(Elt: II);
18134 NamedDecl *Lookup = SemaRef.LookupSingleName(
18135 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
18136 if (Lookup == Namespace)
18137 break;
18138 }
18139
18140 // Once we have all the namespaces, reverse them to go outermost first, and
18141 // build an NNS.
18142 SmallString<64> Insertion;
18143 llvm::raw_svector_ostream OS(Insertion);
18144 if (DC->isTranslationUnit())
18145 OS << "::";
18146 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
18147 for (auto *II : Namespaces)
18148 OS << II->getName() << "::";
18149 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
18150}
18151
18152/// Determine whether a tag originally declared in context \p OldDC can
18153/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18154/// found a declaration in \p OldDC as a previous decl, perhaps through a
18155/// using-declaration).
18156static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
18157 DeclContext *NewDC) {
18158 OldDC = OldDC->getRedeclContext();
18159 NewDC = NewDC->getRedeclContext();
18160
18161 if (OldDC->Equals(DC: NewDC))
18162 return true;
18163
18164 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18165 // encloses the other).
18166 if (S.getLangOpts().MSVCCompat &&
18167 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
18168 return true;
18169
18170 return false;
18171}
18172
18173DeclResult
18174Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18175 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18176 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18177 SourceLocation ModulePrivateLoc,
18178 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18179 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18180 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18181 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18182 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18183 // If this is not a definition, it must have a name.
18184 IdentifierInfo *OrigName = Name;
18185 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18186 "Nameless record must be a definition!");
18187 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18188
18189 OwnedDecl = false;
18190 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18191 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18192
18193 // FIXME: Check member specializations more carefully.
18194 bool isMemberSpecialization = false;
18195 bool IsInjectedClassName = false;
18196 bool Invalid = false;
18197
18198 // We only need to do this matching if we have template parameters
18199 // or a scope specifier, which also conveniently avoids this work
18200 // for non-C++ cases.
18201 if (TemplateParameterLists.size() > 0 ||
18202 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18203 TemplateParameterList *TemplateParams =
18204 MatchTemplateParametersToScopeSpecifier(
18205 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
18206 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
18207
18208 // C++23 [dcl.type.elab] p2:
18209 // If an elaborated-type-specifier is the sole constituent of a
18210 // declaration, the declaration is ill-formed unless it is an explicit
18211 // specialization, an explicit instantiation or it has one of the
18212 // following forms: [...]
18213 // C++23 [dcl.enum] p1:
18214 // If the enum-head-name of an opaque-enum-declaration contains a
18215 // nested-name-specifier, the declaration shall be an explicit
18216 // specialization.
18217 //
18218 // FIXME: Class template partial specializations can be forward declared
18219 // per CWG2213, but the resolution failed to allow qualified forward
18220 // declarations. This is almost certainly unintentional, so we allow them.
18221 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18222 !isMemberSpecialization)
18223 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18224 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18225
18226 if (TemplateParams) {
18227 if (Kind == TagTypeKind::Enum) {
18228 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18229 return true;
18230 }
18231
18232 if (TemplateParams->size() > 0) {
18233 // This is a declaration or definition of a class template (which may
18234 // be a member of another template).
18235
18236 if (Invalid)
18237 return true;
18238
18239 OwnedDecl = false;
18240 DeclResult Result = CheckClassTemplate(
18241 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18242 AS, ModulePrivateLoc,
18243 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18244 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18245 return Result.get();
18246 } else {
18247 // The "template<>" header is extraneous.
18248 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18249 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18250 isMemberSpecialization = true;
18251 }
18252 }
18253
18254 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18255 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18256 return true;
18257 }
18258
18259 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18260 // C++23 [dcl.type.elab]p4:
18261 // If an elaborated-type-specifier appears with the friend specifier as
18262 // an entire member-declaration, the member-declaration shall have one
18263 // of the following forms:
18264 // friend class-key nested-name-specifier(opt) identifier ;
18265 // friend class-key simple-template-id ;
18266 // friend class-key nested-name-specifier template(opt)
18267 // simple-template-id ;
18268 //
18269 // Since enum is not a class-key, so declarations like "friend enum E;"
18270 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18271 // invalid, most implementations accept so we issue a pedantic warning.
18272 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18273 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18274 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18275 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18276 << (ScopedEnum + ScopedEnumUsesClassTag);
18277 }
18278
18279 // Figure out the underlying type if this a enum declaration. We need to do
18280 // this early, because it's needed to detect if this is an incompatible
18281 // redeclaration.
18282 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18283 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18284
18285 if (Kind == TagTypeKind::Enum) {
18286 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18287 Invalid) {
18288 // No underlying type explicitly specified, or we failed to parse the
18289 // type, default to int.
18290 EnumUnderlying = Context.IntTy.getTypePtr();
18291 } else if (UnderlyingType.get()) {
18292 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18293 // integral type; any cv-qualification is ignored.
18294 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18295 // unqualified, non-atomic version of the type specified by the type
18296 // specifiers in the specifier qualifier list.
18297 TypeSourceInfo *TI = nullptr;
18298 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18299 EnumUnderlying = TI;
18300
18301 if (CheckEnumUnderlyingType(TI))
18302 // Recover by falling back to int.
18303 EnumUnderlying = Context.IntTy.getTypePtr();
18304
18305 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18306 UPPC: UPPC_FixedUnderlyingType))
18307 EnumUnderlying = Context.IntTy.getTypePtr();
18308
18309 // If the underlying type is atomic, we need to adjust the type before
18310 // continuing. This only happens in the case we stored a TypeSourceInfo
18311 // into EnumUnderlying because the other cases are error recovery up to
18312 // this point. But because it's not possible to gin up a TypeSourceInfo
18313 // for a non-atomic type from an atomic one, we'll store into the Type
18314 // field instead. FIXME: it would be nice to have an easy way to get a
18315 // derived TypeSourceInfo which strips qualifiers including the weird
18316 // ones like _Atomic where it forms a different type.
18317 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18318 TI && TI->getType()->isAtomicType())
18319 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18320
18321 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18322 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18323 // of 'int'. However, if this is an unfixed forward declaration, don't set
18324 // the underlying type unless the user enables -fms-compatibility. This
18325 // makes unfixed forward declared enums incomplete and is more conforming.
18326 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18327 EnumUnderlying = Context.IntTy.getTypePtr();
18328 }
18329 }
18330
18331 DeclContext *SearchDC = CurContext;
18332 DeclContext *DC = CurContext;
18333 bool isStdBadAlloc = false;
18334 bool isStdAlignValT = false;
18335
18336 RedeclarationKind Redecl = forRedeclarationInCurContext();
18337 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18338 Redecl = RedeclarationKind::NotForRedeclaration;
18339
18340 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18341 /// implemented asks for structural equivalence checking, the returned decl
18342 /// here is passed back to the parser, allowing the tag body to be parsed.
18343 auto createTagFromNewDecl = [&]() -> TagDecl * {
18344 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18345 // If there is an identifier, use the location of the identifier as the
18346 // location of the decl, otherwise use the location of the struct/union
18347 // keyword.
18348 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18349 TagDecl *New = nullptr;
18350
18351 if (Kind == TagTypeKind::Enum) {
18352 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18353 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18354 // If this is an undefined enum, bail.
18355 if (TUK != TagUseKind::Definition && !Invalid)
18356 return nullptr;
18357 if (EnumUnderlying) {
18358 EnumDecl *ED = cast<EnumDecl>(Val: New);
18359 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18360 ED->setIntegerTypeSourceInfo(TI);
18361 else
18362 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18363 QualType EnumTy = ED->getIntegerType();
18364 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18365 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18366 : EnumTy);
18367 }
18368 } else { // struct/union
18369 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18370 PrevDecl: nullptr);
18371 }
18372
18373 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18374 // Add alignment attributes if necessary; these attributes are checked
18375 // when the ASTContext lays out the structure.
18376 //
18377 // It is important for implementing the correct semantics that this
18378 // happen here (in ActOnTag). The #pragma pack stack is
18379 // maintained as a result of parser callbacks which can occur at
18380 // many points during the parsing of a struct declaration (because
18381 // the #pragma tokens are effectively skipped over during the
18382 // parsing of the struct).
18383 if (TUK == TagUseKind::Definition &&
18384 (!SkipBody || !SkipBody->ShouldSkip)) {
18385 if (LangOpts.HLSL)
18386 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18387 AddAlignmentAttributesForRecord(RD);
18388 AddMsStructLayoutForRecord(RD);
18389 }
18390 }
18391 New->setLexicalDeclContext(CurContext);
18392 return New;
18393 };
18394
18395 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18396 if (Name && SS.isNotEmpty()) {
18397 // We have a nested-name tag ('struct foo::bar').
18398
18399 // Check for invalid 'foo::'.
18400 if (SS.isInvalid()) {
18401 Name = nullptr;
18402 goto CreateNewDecl;
18403 }
18404
18405 // If this is a friend or a reference to a class in a dependent
18406 // context, don't try to make a decl for it.
18407 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18408 DC = computeDeclContext(SS, EnteringContext: false);
18409 if (!DC) {
18410 IsDependent = true;
18411 return true;
18412 }
18413 } else {
18414 DC = computeDeclContext(SS, EnteringContext: true);
18415 if (!DC) {
18416 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18417 << SS.getRange();
18418 return true;
18419 }
18420 }
18421
18422 if (RequireCompleteDeclContext(SS, DC))
18423 return true;
18424
18425 SearchDC = DC;
18426 // Look-up name inside 'foo::'.
18427 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18428
18429 if (Previous.isAmbiguous())
18430 return true;
18431
18432 if (Previous.empty()) {
18433 // Name lookup did not find anything. However, if the
18434 // nested-name-specifier refers to the current instantiation,
18435 // and that current instantiation has any dependent base
18436 // classes, we might find something at instantiation time: treat
18437 // this as a dependent elaborated-type-specifier.
18438 // But this only makes any sense for reference-like lookups.
18439 if (Previous.wasNotFoundInCurrentInstantiation() &&
18440 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18441 IsDependent = true;
18442 return true;
18443 }
18444
18445 // A tag 'foo::bar' must already exist.
18446 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18447 << Kind << Name << DC << SS.getRange();
18448 Name = nullptr;
18449 Invalid = true;
18450 goto CreateNewDecl;
18451 }
18452 } else if (Name) {
18453 // C++14 [class.mem]p14:
18454 // If T is the name of a class, then each of the following shall have a
18455 // name different from T:
18456 // -- every member of class T that is itself a type
18457 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18458 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18459 return true;
18460
18461 // If this is a named struct, check to see if there was a previous forward
18462 // declaration or definition.
18463 // FIXME: We're looking into outer scopes here, even when we
18464 // shouldn't be. Doing so can result in ambiguities that we
18465 // shouldn't be diagnosing.
18466 LookupName(R&: Previous, S);
18467
18468 // When declaring or defining a tag, ignore ambiguities introduced
18469 // by types using'ed into this scope.
18470 if (Previous.isAmbiguous() &&
18471 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18472 LookupResult::Filter F = Previous.makeFilter();
18473 while (F.hasNext()) {
18474 NamedDecl *ND = F.next();
18475 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18476 DC: SearchDC->getRedeclContext()))
18477 F.erase();
18478 }
18479 F.done();
18480 }
18481
18482 // C++11 [namespace.memdef]p3:
18483 // If the name in a friend declaration is neither qualified nor
18484 // a template-id and the declaration is a function or an
18485 // elaborated-type-specifier, the lookup to determine whether
18486 // the entity has been previously declared shall not consider
18487 // any scopes outside the innermost enclosing namespace.
18488 //
18489 // MSVC doesn't implement the above rule for types, so a friend tag
18490 // declaration may be a redeclaration of a type declared in an enclosing
18491 // scope. They do implement this rule for friend functions.
18492 //
18493 // Does it matter that this should be by scope instead of by
18494 // semantic context?
18495 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18496 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18497 LookupResult::Filter F = Previous.makeFilter();
18498 bool FriendSawTagOutsideEnclosingNamespace = false;
18499 while (F.hasNext()) {
18500 NamedDecl *ND = F.next();
18501 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18502 if (DC->isFileContext() &&
18503 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18504 if (getLangOpts().MSVCCompat)
18505 FriendSawTagOutsideEnclosingNamespace = true;
18506 else
18507 F.erase();
18508 }
18509 }
18510 F.done();
18511
18512 // Diagnose this MSVC extension in the easy case where lookup would have
18513 // unambiguously found something outside the enclosing namespace.
18514 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18515 NamedDecl *ND = Previous.getFoundDecl();
18516 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18517 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18518 }
18519 }
18520
18521 // Note: there used to be some attempt at recovery here.
18522 if (Previous.isAmbiguous())
18523 return true;
18524
18525 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18526 // FIXME: This makes sure that we ignore the contexts associated
18527 // with C structs, unions, and enums when looking for a matching
18528 // tag declaration or definition. See the similar lookup tweak
18529 // in Sema::LookupName; is there a better way to deal with this?
18530 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18531 SearchDC = SearchDC->getParent();
18532 } else if (getLangOpts().CPlusPlus) {
18533 // Inside ObjCContainer want to keep it as a lexical decl context but go
18534 // past it (most often to TranslationUnit) to find the semantic decl
18535 // context.
18536 while (isa<ObjCContainerDecl>(Val: SearchDC))
18537 SearchDC = SearchDC->getParent();
18538 }
18539 } else if (getLangOpts().CPlusPlus) {
18540 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18541 // TagDecl the same way as we skip it for named TagDecl.
18542 while (isa<ObjCContainerDecl>(Val: SearchDC))
18543 SearchDC = SearchDC->getParent();
18544 }
18545
18546 if (Previous.isSingleResult() &&
18547 Previous.getFoundDecl()->isTemplateParameter()) {
18548 // Maybe we will complain about the shadowed template parameter.
18549 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18550 // Just pretend that we didn't see the previous declaration.
18551 Previous.clear();
18552 }
18553
18554 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18555 DC->getRedeclContext()->Equals(DC: getStdNamespace())) {
18556 if (Name->isStr(Str: "bad_alloc")) {
18557 // This is a declaration of or a reference to "std::bad_alloc".
18558 isStdBadAlloc = true;
18559
18560 // If std::bad_alloc has been implicitly declared (but made invisible to
18561 // name lookup), fill in this implicit declaration as the previous
18562 // declaration, so that the declarations get chained appropriately.
18563 if (Previous.empty() && StdBadAlloc)
18564 Previous.addDecl(D: getStdBadAlloc());
18565 } else if (Name->isStr(Str: "align_val_t")) {
18566 isStdAlignValT = true;
18567 if (Previous.empty() && StdAlignValT)
18568 Previous.addDecl(D: getStdAlignValT());
18569 }
18570 }
18571
18572 // If we didn't find a previous declaration, and this is a reference
18573 // (or friend reference), move to the correct scope. In C++, we
18574 // also need to do a redeclaration lookup there, just in case
18575 // there's a shadow friend decl.
18576 if (Name && Previous.empty() &&
18577 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18578 IsTemplateParamOrArg)) {
18579 if (Invalid) goto CreateNewDecl;
18580 assert(SS.isEmpty());
18581
18582 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18583 // C++ [basic.scope.pdecl]p5:
18584 // -- for an elaborated-type-specifier of the form
18585 //
18586 // class-key identifier
18587 //
18588 // if the elaborated-type-specifier is used in the
18589 // decl-specifier-seq or parameter-declaration-clause of a
18590 // function defined in namespace scope, the identifier is
18591 // declared as a class-name in the namespace that contains
18592 // the declaration; otherwise, except as a friend
18593 // declaration, the identifier is declared in the smallest
18594 // non-class, non-function-prototype scope that contains the
18595 // declaration.
18596 //
18597 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18598 // C structs and unions.
18599 //
18600 // It is an error in C++ to declare (rather than define) an enum
18601 // type, including via an elaborated type specifier. We'll
18602 // diagnose that later; for now, declare the enum in the same
18603 // scope as we would have picked for any other tag type.
18604 //
18605 // GNU C also supports this behavior as part of its incomplete
18606 // enum types extension, while GNU C++ does not.
18607 //
18608 // Find the context where we'll be declaring the tag.
18609 // FIXME: We would like to maintain the current DeclContext as the
18610 // lexical context,
18611 SearchDC = getTagInjectionContext(DC: SearchDC);
18612
18613 // Find the scope where we'll be declaring the tag.
18614 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18615 } else {
18616 assert(TUK == TagUseKind::Friend);
18617 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18618
18619 // C++ [namespace.memdef]p3:
18620 // If a friend declaration in a non-local class first declares a
18621 // class or function, the friend class or function is a member of
18622 // the innermost enclosing namespace.
18623 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18624 : SearchDC->getEnclosingNamespaceContext();
18625 }
18626
18627 // In C++, we need to do a redeclaration lookup to properly
18628 // diagnose some problems.
18629 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18630 // hidden declaration so that we don't get ambiguity errors when using a
18631 // type declared by an elaborated-type-specifier. In C that is not correct
18632 // and we should instead merge compatible types found by lookup.
18633 if (getLangOpts().CPlusPlus) {
18634 // FIXME: This can perform qualified lookups into function contexts,
18635 // which are meaningless.
18636 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18637 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18638 } else {
18639 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18640 LookupName(R&: Previous, S);
18641 }
18642 }
18643
18644 // If we have a known previous declaration to use, then use it.
18645 if (Previous.empty() && SkipBody && SkipBody->Previous)
18646 Previous.addDecl(D: SkipBody->Previous);
18647
18648 if (!Previous.empty()) {
18649 NamedDecl *PrevDecl = Previous.getFoundDecl();
18650 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18651
18652 // It's okay to have a tag decl in the same scope as a typedef
18653 // which hides a tag decl in the same scope. Finding this
18654 // with a redeclaration lookup can only actually happen in C++.
18655 //
18656 // This is also okay for elaborated-type-specifiers, which is
18657 // technically forbidden by the current standard but which is
18658 // okay according to the likely resolution of an open issue;
18659 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18660 if (getLangOpts().CPlusPlus) {
18661 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18662 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18663 if (Tag->getDeclName() == Name &&
18664 Tag->getDeclContext()->getRedeclContext()
18665 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18666 PrevDecl = Tag;
18667 Previous.clear();
18668 Previous.addDecl(D: Tag);
18669 Previous.resolveKind();
18670 }
18671 }
18672 }
18673 }
18674
18675 // If this is a redeclaration of a using shadow declaration, it must
18676 // declare a tag in the same context. In MSVC mode, we allow a
18677 // redefinition if either context is within the other.
18678 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18679 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18680 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18681 TUK != TagUseKind::Friend &&
18682 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18683 !(OldTag && isAcceptableTagRedeclContext(
18684 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18685 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18686 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18687 DiagID: diag::note_using_decl_target);
18688 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18689 << 0;
18690 // Recover by ignoring the old declaration.
18691 Previous.clear();
18692 goto CreateNewDecl;
18693 }
18694 }
18695
18696 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18697 // If this is a use of a previous tag, or if the tag is already declared
18698 // in the same scope (so that the definition/declaration completes or
18699 // rementions the tag), reuse the decl.
18700 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18701 isTagRedeclarationInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18702 AllowInlineNamespace: SS.isNotEmpty() ||
18703 isMemberSpecialization)) {
18704
18705 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18706 RD && RD->isInjectedClassName()) {
18707 // If lookup found the injected class name, the previous declaration
18708 // is the class being injected into.
18709 Previous.clear();
18710 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(Val: RD->getDeclContext());
18711 Previous.addDecl(D: PrevDecl);
18712 Previous.resolveKind();
18713 IsInjectedClassName = true;
18714 }
18715
18716 // Make sure that this wasn't declared as an enum and now used as a
18717 // struct or something similar.
18718 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18719 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18720 Name)) {
18721 bool SafeToContinue =
18722 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18723 Kind != TagTypeKind::Enum);
18724 if (SafeToContinue)
18725 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18726 << Name
18727 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18728 Code: PrevTagDecl->getKindName());
18729 else
18730 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18731 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18732
18733 if (SafeToContinue)
18734 Kind = PrevTagDecl->getTagKind();
18735 else {
18736 // Recover by making this an anonymous redefinition.
18737 Name = nullptr;
18738 Previous.clear();
18739 Invalid = true;
18740 }
18741 }
18742
18743 if (Kind == TagTypeKind::Enum &&
18744 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18745 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18746 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18747 return PrevTagDecl;
18748
18749 QualType EnumUnderlyingTy;
18750 if (TypeSourceInfo *TI =
18751 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18752 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18753 else if (const Type *T =
18754 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18755 EnumUnderlyingTy = QualType(T, 0);
18756
18757 // All conflicts with previous declarations are recovered by
18758 // returning the previous declaration, unless this is a definition,
18759 // in which case we want the caller to bail out.
18760 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18761 IsScoped: ScopedEnum, EnumUnderlyingTy,
18762 IsFixed, Prev: PrevEnum))
18763 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18764 }
18765
18766 // C++11 [class.mem]p1:
18767 // A member shall not be declared twice in the member-specification,
18768 // except that a nested class or member class template can be declared
18769 // and then later defined.
18770 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18771 S->isDeclScope(D: PrevDecl)) {
18772 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18773 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18774 }
18775
18776 // C++ [class.local]p3:
18777 // A class nested within a local class is a local class. A member of
18778 // a local class X shall be declared only in the definition of X or,
18779 // if the member is a nested class, in the nearest enclosing block
18780 // scope of X.
18781 if (TUK == TagUseKind::Definition && SS.isValid()) {
18782 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18783 while (const auto *ParentClass =
18784 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18785 OutermostClass = ParentClass;
18786
18787 if (OutermostClass->isLocalClass() &&
18788 !S->isDeclScope(D: OutermostClass)) {
18789 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18790 << Name << OutermostClass;
18791 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18792 << OutermostClass;
18793 }
18794 }
18795 }
18796
18797 if (!Invalid) {
18798 // If this is a use, just return the declaration we found, unless
18799 // we have attributes.
18800 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18801 if (!Attrs.empty()) {
18802 // FIXME: Diagnose these attributes. For now, we create a new
18803 // declaration to hold them.
18804 } else if (TUK == TagUseKind::Reference &&
18805 (PrevTagDecl->getFriendObjectKind() ==
18806 Decl::FOK_Undeclared ||
18807 PrevDecl->getOwningModule() != getCurrentModule()) &&
18808 SS.isEmpty()) {
18809 // This declaration is a reference to an existing entity, but
18810 // has different visibility from that entity: it either makes
18811 // a friend visible or it makes a type visible in a new module.
18812 // In either case, create a new declaration. We only do this if
18813 // the declaration would have meant the same thing if no prior
18814 // declaration were found, that is, if it was found in the same
18815 // scope where we would have injected a declaration.
18816 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18817 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18818 return PrevTagDecl;
18819 // This is in the injected scope, create a new declaration in
18820 // that scope.
18821 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18822 } else {
18823 return PrevTagDecl;
18824 }
18825 }
18826
18827 // Diagnose attempts to redefine a tag.
18828 if (TUK == TagUseKind::Definition) {
18829 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18830 // If the type is currently being defined, complain
18831 // about a nested redefinition.
18832 if (Def->isBeingDefined()) {
18833 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18834 Diag(Loc: PrevTagDecl->getLocation(),
18835 DiagID: diag::note_previous_definition);
18836 Name = nullptr;
18837 Previous.clear();
18838 Invalid = true;
18839 } else {
18840 // If we're defining a specialization and the previous
18841 // definition is from an implicit instantiation, don't emit an
18842 // error here; we'll catch this in the general case below.
18843 bool IsExplicitSpecializationAfterInstantiation = false;
18844 if (isMemberSpecialization) {
18845 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18846 IsExplicitSpecializationAfterInstantiation =
18847 RD->getTemplateSpecializationKind() !=
18848 TSK_ExplicitSpecialization;
18849 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18850 IsExplicitSpecializationAfterInstantiation =
18851 ED->getTemplateSpecializationKind() !=
18852 TSK_ExplicitSpecialization;
18853 }
18854
18855 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18856 // do not keep more that one definition around (merge them).
18857 // However, ensure the decl passes the structural compatibility
18858 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18859 NamedDecl *Hidden = nullptr;
18860 bool HiddenDefVisible = false;
18861 if (SkipBody && (isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: NameLoc, Suggested: &Hidden,
18862 Visible&: HiddenDefVisible) ||
18863 getLangOpts().C23)) {
18864 // There is a definition of this tag, but it is not visible.
18865 // We explicitly make use of C++'s one definition rule here,
18866 // and assume that this definition is identical to the hidden
18867 // one we already have. Make the existing definition visible
18868 // and use it in place of this one.
18869 if (!getLangOpts().CPlusPlus) {
18870 // Postpone making the old definition visible until after we
18871 // complete parsing the new one and do the structural
18872 // comparison.
18873 SkipBody->CheckSameAsPrevious = true;
18874 SkipBody->New = createTagFromNewDecl();
18875 SkipBody->Previous = Def;
18876
18877 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18878 return Def;
18879 }
18880
18881 SkipBody->ShouldSkip = true;
18882 SkipBody->Previous = Def;
18883 if (!HiddenDefVisible && Hidden)
18884 makeMergedDefinitionVisible(ND: Hidden);
18885 // Carry on and handle it like a normal definition. We'll
18886 // skip starting the definition later.
18887
18888 } else if (!IsExplicitSpecializationAfterInstantiation) {
18889 // A redeclaration in function prototype scope in C isn't
18890 // visible elsewhere, so merely issue a warning.
18891 if (!getLangOpts().CPlusPlus &&
18892 S->containedInPrototypeScope())
18893 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18894 << Name;
18895 else
18896 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18897 notePreviousDefinition(Old: Def,
18898 New: NameLoc.isValid() ? NameLoc : KWLoc);
18899 // If this is a redefinition, recover by making this
18900 // struct be anonymous, which will make any later
18901 // references get the previous definition.
18902 Name = nullptr;
18903 Previous.clear();
18904 Invalid = true;
18905 }
18906 }
18907 }
18908
18909 // Okay, this is definition of a previously declared or referenced
18910 // tag. We're going to create a new Decl for it.
18911 }
18912
18913 // Okay, we're going to make a redeclaration. If this is some kind
18914 // of reference, make sure we build the redeclaration in the same DC
18915 // as the original, and ignore the current access specifier.
18916 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18917 IsInjectedClassName) {
18918 SearchDC = PrevTagDecl->getDeclContext();
18919 AS = AS_none;
18920 }
18921 }
18922 // If we get here we have (another) forward declaration or we
18923 // have a definition. Just create a new decl.
18924
18925 } else {
18926 // If we get here, this is a definition of a new tag type in a nested
18927 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18928 // new decl/type. We set PrevDecl to NULL so that the entities
18929 // have distinct types.
18930 Previous.clear();
18931 }
18932 // If we get here, we're going to create a new Decl. If PrevDecl
18933 // is non-NULL, it's a definition of the tag declared by
18934 // PrevDecl. If it's NULL, we have a new definition.
18935
18936 // Otherwise, PrevDecl is not a tag, but was found with tag
18937 // lookup. This is only actually possible in C++, where a few
18938 // things like templates still live in the tag namespace.
18939 } else {
18940 // Use a better diagnostic if an elaborated-type-specifier
18941 // found the wrong kind of type on the first
18942 // (non-redeclaration) lookup.
18943 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18944 !Previous.isForRedeclaration()) {
18945 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18946 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18947 << PrevDecl << NTK << Kind;
18948 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18949 Invalid = true;
18950
18951 // Otherwise, only diagnose if the declaration is in scope.
18952 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18953 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18954 // do nothing
18955
18956 // Diagnose implicit declarations introduced by elaborated types.
18957 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18958 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18959 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18960 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18961 Invalid = true;
18962
18963 // Otherwise it's a declaration. Call out a particularly common
18964 // case here.
18965 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18966 unsigned Kind = 0;
18967 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18968 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18969 << Name << Kind << TND->getUnderlyingType();
18970 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18971 Invalid = true;
18972
18973 // Otherwise, diagnose.
18974 } else {
18975 // The tag name clashes with something else in the target scope,
18976 // issue an error and recover by making this tag be anonymous.
18977 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18978 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18979 Name = nullptr;
18980 Invalid = true;
18981 }
18982
18983 // The existing declaration isn't relevant to us; we're in a
18984 // new scope, so clear out the previous declaration.
18985 Previous.clear();
18986 }
18987 }
18988
18989CreateNewDecl:
18990
18991 TagDecl *PrevDecl = nullptr;
18992 if (Previous.isSingleResult())
18993 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18994
18995 // If there is an identifier, use the location of the identifier as the
18996 // location of the decl, otherwise use the location of the struct/union
18997 // keyword.
18998 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18999
19000 // Otherwise, create a new declaration. If there is a previous
19001 // declaration of the same entity, the two will be linked via
19002 // PrevDecl.
19003 TagDecl *New;
19004
19005 if (Kind == TagTypeKind::Enum) {
19006 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19007 // enum X { A, B, C } D; D should chain to X.
19008 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19009 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
19010 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
19011
19012 EnumDecl *ED = cast<EnumDecl>(Val: New);
19013 ED->setEnumKeyRange(SourceRange(
19014 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19015
19016 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19017 StdAlignValT = cast<EnumDecl>(Val: New);
19018
19019 // If this is an undefined enum, warn.
19020 if (TUK != TagUseKind::Definition && !Invalid) {
19021 TagDecl *Def;
19022 if (IsFixed && ED->isFixed()) {
19023 // C++0x: 7.2p2: opaque-enum-declaration.
19024 // Conflicts are diagnosed above. Do nothing.
19025 } else if (PrevDecl &&
19026 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
19027 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
19028 << New;
19029 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
19030 } else {
19031 unsigned DiagID = diag::ext_forward_ref_enum;
19032 if (getLangOpts().MSVCCompat)
19033 DiagID = diag::ext_ms_forward_ref_enum;
19034 else if (getLangOpts().CPlusPlus)
19035 DiagID = diag::err_forward_ref_enum;
19036 Diag(Loc, DiagID);
19037 }
19038 }
19039
19040 if (EnumUnderlying) {
19041 EnumDecl *ED = cast<EnumDecl>(Val: New);
19042 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
19043 ED->setIntegerTypeSourceInfo(TI);
19044 else
19045 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
19046 QualType EnumTy = ED->getIntegerType();
19047 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
19048 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
19049 : EnumTy);
19050 assert(ED->isComplete() && "enum with type should be complete");
19051 }
19052 } else {
19053 // struct/union/class
19054
19055 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19056 // struct X { int A; } D; D should chain to X.
19057 if (getLangOpts().CPlusPlus) {
19058 // FIXME: Look for a way to use RecordDecl for simple structs.
19059 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19060 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
19061
19062 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19063 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
19064 } else
19065 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19066 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
19067 }
19068
19069 // Only C23 and later allow defining new types in 'offsetof()'.
19070 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19071 !getLangOpts().CPlusPlus && !getLangOpts().C23)
19072 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
19073 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19074
19075 // C++11 [dcl.type]p3:
19076 // A type-specifier-seq shall not define a class or enumeration [...].
19077 if (!Invalid && getLangOpts().CPlusPlus &&
19078 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19079 TUK == TagUseKind::Definition) {
19080 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
19081 << Context.getCanonicalTagType(TD: New);
19082 Invalid = true;
19083 }
19084
19085 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
19086 DC->getDeclKind() == Decl::Enum) {
19087 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
19088 << Context.getCanonicalTagType(TD: New);
19089 Invalid = true;
19090 }
19091
19092 // Maybe add qualifier info.
19093 if (SS.isNotEmpty()) {
19094 if (SS.isSet()) {
19095 // If this is either a declaration or a definition, check the
19096 // nested-name-specifier against the current context.
19097 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19098 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
19099 /*TemplateId=*/nullptr,
19100 IsMemberSpecialization: isMemberSpecialization))
19101 Invalid = true;
19102
19103 New->setQualifierInfo(SS.getWithLocInContext(Context));
19104 if (TemplateParameterLists.size() > 0) {
19105 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
19106 }
19107 }
19108 else
19109 Invalid = true;
19110 }
19111
19112 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
19113 // Add alignment attributes if necessary; these attributes are checked when
19114 // the ASTContext lays out the structure.
19115 //
19116 // It is important for implementing the correct semantics that this
19117 // happen here (in ActOnTag). The #pragma pack stack is
19118 // maintained as a result of parser callbacks which can occur at
19119 // many points during the parsing of a struct declaration (because
19120 // the #pragma tokens are effectively skipped over during the
19121 // parsing of the struct).
19122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19123 if (LangOpts.HLSL)
19124 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
19125 AddAlignmentAttributesForRecord(RD);
19126 AddMsStructLayoutForRecord(RD);
19127 }
19128 }
19129
19130 if (ModulePrivateLoc.isValid()) {
19131 if (isMemberSpecialization)
19132 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
19133 << 2
19134 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
19135 // __module_private__ does not apply to local classes. However, we only
19136 // diagnose this as an error when the declaration specifiers are
19137 // freestanding. Here, we just ignore the __module_private__.
19138 else if (!SearchDC->isFunctionOrMethod())
19139 New->setModulePrivate();
19140 }
19141
19142 // If this is a specialization of a member class (of a class template),
19143 // check the specialization.
19144 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
19145 Invalid = true;
19146
19147 // If we're declaring or defining a tag in function prototype scope in C,
19148 // note that this type can only be used within the function and add it to
19149 // the list of decls to inject into the function definition scope. However,
19150 // in C23 and later, while the type is only visible within the function, the
19151 // function can be called with a compatible type defined in the same TU, so
19152 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19153 if ((Name || Kind == TagTypeKind::Enum) &&
19154 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19155 if (getLangOpts().CPlusPlus) {
19156 // C++ [dcl.fct]p6:
19157 // Types shall not be defined in return or parameter types.
19158 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19159 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
19160 << Name;
19161 Invalid = true;
19162 }
19163 if (TUK == TagUseKind::Declaration)
19164 Invalid = true;
19165 } else if (!PrevDecl) {
19166 // In C23 mode, if the declaration is complete, we do not want to
19167 // diagnose.
19168 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19169 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
19170 << Context.getCanonicalTagType(TD: New);
19171 }
19172 }
19173
19174 if (Invalid)
19175 New->setInvalidDecl();
19176
19177 // Set the lexical context. If the tag has a C++ scope specifier, the
19178 // lexical context will be different from the semantic context.
19179 New->setLexicalDeclContext(CurContext);
19180
19181 // Mark this as a friend decl if applicable.
19182 // In Microsoft mode, a friend declaration also acts as a forward
19183 // declaration so we always pass true to setObjectOfFriendDecl to make
19184 // the tag name visible.
19185 if (TUK == TagUseKind::Friend)
19186 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19187
19188 // Set the access specifier.
19189 if (!Invalid && SearchDC->isRecord())
19190 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
19191
19192 if (PrevDecl)
19193 CheckRedeclarationInModule(New, Old: PrevDecl);
19194
19195 if (TUK == TagUseKind::Definition) {
19196 if (!SkipBody || !SkipBody->ShouldSkip) {
19197 New->startDefinition();
19198 } else {
19199 New->setCompleteDefinition();
19200 New->demoteThisDefinitionToDeclaration();
19201 }
19202 }
19203
19204 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
19205 AddPragmaAttributes(S, D: New);
19206
19207 // If this has an identifier, add it to the scope stack.
19208 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19209 // We might be replacing an existing declaration in the lookup tables;
19210 // if so, borrow its access specifier.
19211 if (PrevDecl)
19212 New->setAccess(PrevDecl->getAccess());
19213
19214 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19215 DC->makeDeclVisibleInContext(D: New);
19216 if (Name) // can be null along some error paths
19217 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19218 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
19219 } else if (Name) {
19220 S = getNonFieldDeclScope(S);
19221 PushOnScopeChains(D: New, S, AddToContext: true);
19222 } else {
19223 CurContext->addDecl(D: New);
19224 }
19225
19226 // If this is the C FILE type, notify the AST context.
19227 if (IdentifierInfo *II = New->getIdentifier())
19228 if (!New->isInvalidDecl() &&
19229 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19230 II->isStr(Str: "FILE"))
19231 Context.setFILEDecl(New);
19232
19233 if (PrevDecl)
19234 mergeDeclAttributes(New, Old: PrevDecl);
19235
19236 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19237 inferGslOwnerPointerAttribute(Record: CXXRD);
19238 inferNullableClassAttribute(CRD: CXXRD);
19239 }
19240
19241 // If there's a #pragma GCC visibility in scope, set the visibility of this
19242 // record.
19243 AddPushedVisibilityAttribute(RD: New);
19244
19245 // If this is not a definition, process API notes for it now.
19246 if (TUK != TagUseKind::Definition)
19247 ProcessAPINotes(D: New);
19248
19249 if (isMemberSpecialization && !New->isInvalidDecl())
19250 CompleteMemberSpecialization(Member: New, Previous);
19251
19252 OwnedDecl = true;
19253 // In C++, don't return an invalid declaration. We can't recover well from
19254 // the cases where we make the type anonymous.
19255 if (Invalid && getLangOpts().CPlusPlus) {
19256 if (New->isBeingDefined())
19257 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19258 RD->completeDefinition();
19259 return true;
19260 } else if (SkipBody && SkipBody->ShouldSkip) {
19261 return SkipBody->Previous;
19262 } else {
19263 return New;
19264 }
19265}
19266
19267void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19268 AdjustDeclIfTemplate(Decl&: TagD);
19269 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19270
19271 // Enter the tag context.
19272 PushDeclContext(S, DC: Tag);
19273
19274 ActOnDocumentableDecl(D: TagD);
19275
19276 // If there's a #pragma GCC visibility in scope, set the visibility of this
19277 // record.
19278 AddPushedVisibilityAttribute(RD: Tag);
19279}
19280
19281bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19282 SkipBodyInfo &SkipBody) {
19283 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19284 return false;
19285
19286 // Make the previous decl visible.
19287 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19288 CleanupMergedEnum(S, New: SkipBody.New);
19289 return true;
19290}
19291
19292void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19293 SourceLocation FinalLoc,
19294 bool IsFinalSpelledSealed,
19295 bool IsAbstract,
19296 SourceLocation LBraceLoc) {
19297 AdjustDeclIfTemplate(Decl&: TagD);
19298 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19299
19300 FieldCollector->StartClass();
19301
19302 if (!Record->getIdentifier())
19303 return;
19304
19305 if (IsAbstract)
19306 Record->markAbstract();
19307
19308 if (FinalLoc.isValid()) {
19309 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19310 S: IsFinalSpelledSealed
19311 ? FinalAttr::Keyword_sealed
19312 : FinalAttr::Keyword_final));
19313 }
19314
19315 // C++ [class]p2:
19316 // [...] The class-name is also inserted into the scope of the
19317 // class itself; this is known as the injected-class-name. For
19318 // purposes of access checking, the injected-class-name is treated
19319 // as if it were a public member name.
19320 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19321 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19322 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19323 InjectedClassName->setImplicit();
19324 InjectedClassName->setAccess(AS_public);
19325 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19326 InjectedClassName->setDescribedClassTemplate(Template);
19327
19328 PushOnScopeChains(D: InjectedClassName, S);
19329 assert(InjectedClassName->isInjectedClassName() &&
19330 "Broken injected-class-name");
19331}
19332
19333void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19334 SourceRange BraceRange) {
19335 AdjustDeclIfTemplate(Decl&: TagD);
19336 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19337 Tag->setBraceRange(BraceRange);
19338
19339 // Make sure we "complete" the definition even it is invalid.
19340 if (Tag->isBeingDefined()) {
19341 assert(Tag->isInvalidDecl() && "We should already have completed it");
19342 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19343 RD->completeDefinition();
19344 }
19345
19346 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19347 FieldCollector->FinishClass();
19348 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19349 auto *Def = RD->getDefinition();
19350 assert(Def && "The record is expected to have a completed definition");
19351 unsigned NumInitMethods = 0;
19352 for (auto *Method : Def->methods()) {
19353 if (!Method->getIdentifier())
19354 continue;
19355 if (Method->getName() == "__init")
19356 NumInitMethods++;
19357 }
19358 if (NumInitMethods > 1 || !Def->hasInitMethod())
19359 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19360 }
19361
19362 // If we're defining a dynamic class in a module interface unit, we always
19363 // need to produce the vtable for it, even if the vtable is not used in the
19364 // current TU.
19365 //
19366 // The case where the current class is not dynamic is handled in
19367 // MarkVTableUsed.
19368 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19369 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19370 }
19371
19372 // Exit this scope of this tag's definition.
19373 PopDeclContext();
19374
19375 if (getCurLexicalContext()->isObjCContainer() &&
19376 Tag->getDeclContext()->isFileContext())
19377 Tag->setTopLevelDeclInObjCContainer();
19378
19379 // Notify the consumer that we've defined a tag.
19380 if (!Tag->isInvalidDecl())
19381 Consumer.HandleTagDeclDefinition(D: Tag);
19382
19383 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19384 // from XLs and instead matches the XL #pragma pack(1) behavior.
19385 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19386 AlignPackStack.hasValue()) {
19387 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19388 // Only diagnose #pragma align(packed).
19389 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19390 return;
19391 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19392 if (!RD)
19393 return;
19394 // Only warn if there is at least 1 bitfield member.
19395 if (llvm::any_of(Range: RD->fields(),
19396 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19397 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19398 }
19399}
19400
19401void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19402 AdjustDeclIfTemplate(Decl&: TagD);
19403 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19404 Tag->setInvalidDecl();
19405
19406 // Make sure we "complete" the definition even it is invalid.
19407 if (Tag->isBeingDefined()) {
19408 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19409 RD->completeDefinition();
19410 }
19411
19412 // We're undoing ActOnTagStartDefinition here, not
19413 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19414 // the FieldCollector.
19415
19416 PopDeclContext();
19417}
19418
19419// Note that FieldName may be null for anonymous bitfields.
19420ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19421 const IdentifierInfo *FieldName,
19422 QualType FieldTy, bool IsMsStruct,
19423 Expr *BitWidth) {
19424 assert(BitWidth);
19425 if (BitWidth->containsErrors())
19426 return ExprError();
19427
19428 // C99 6.7.2.1p4 - verify the field type.
19429 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19430 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19431 // Handle incomplete and sizeless types with a specific error.
19432 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19433 DiagID: diag::err_field_incomplete_or_sizeless))
19434 return ExprError();
19435 if (FieldName)
19436 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19437 << FieldName << FieldTy << BitWidth->getSourceRange();
19438 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19439 << FieldTy << BitWidth->getSourceRange();
19440 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19441 return ExprError();
19442
19443 // If the bit-width is type- or value-dependent, don't try to check
19444 // it now.
19445 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19446 return BitWidth;
19447
19448 llvm::APSInt Value;
19449 ExprResult ICE =
19450 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19451 if (ICE.isInvalid())
19452 return ICE;
19453 BitWidth = ICE.get();
19454
19455 // Zero-width bitfield is ok for anonymous field.
19456 if (Value == 0 && FieldName)
19457 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19458 << FieldName << BitWidth->getSourceRange();
19459
19460 if (Value.isSigned() && Value.isNegative()) {
19461 if (FieldName)
19462 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19463 << FieldName << toString(I: Value, Radix: 10);
19464 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19465 << toString(I: Value, Radix: 10);
19466 }
19467
19468 // The size of the bit-field must not exceed our maximum permitted object
19469 // size.
19470 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19471 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19472 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19473 }
19474
19475 if (!FieldTy->isDependentType()) {
19476 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19477 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19478 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19479
19480 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19481 // ABI.
19482 bool CStdConstraintViolation =
19483 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19484 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19485 if (CStdConstraintViolation || MSBitfieldViolation) {
19486 unsigned DiagWidth =
19487 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19488 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19489 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19490 << !CStdConstraintViolation << DiagWidth;
19491 }
19492
19493 // Warn on types where the user might conceivably expect to get all
19494 // specified bits as value bits: that's all integral types other than
19495 // 'bool'.
19496 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19497 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19498 << FieldName << Value << (unsigned)TypeWidth;
19499 }
19500 }
19501
19502 if (isa<ConstantExpr>(Val: BitWidth))
19503 return BitWidth;
19504 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19505}
19506
19507Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19508 Declarator &D, Expr *BitfieldWidth) {
19509 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19510 D, BitfieldWidth,
19511 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19512 return Res;
19513}
19514
19515FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19516 SourceLocation DeclStart,
19517 Declarator &D, Expr *BitWidth,
19518 InClassInitStyle InitStyle,
19519 AccessSpecifier AS) {
19520 if (D.isDecompositionDeclarator()) {
19521 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19522 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19523 << Decomp.getSourceRange();
19524 return nullptr;
19525 }
19526
19527 const IdentifierInfo *II = D.getIdentifier();
19528 SourceLocation Loc = DeclStart;
19529 if (II) Loc = D.getIdentifierLoc();
19530
19531 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19532 QualType T = TInfo->getType();
19533 if (getLangOpts().CPlusPlus) {
19534 CheckExtraCXXDefaultArguments(D);
19535
19536 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19537 UPPC: UPPC_DataMemberType)) {
19538 D.setInvalidType();
19539 T = Context.IntTy;
19540 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19541 }
19542 }
19543
19544 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19545
19546 if (D.getDeclSpec().isInlineSpecified())
19547 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19548 << getLangOpts().CPlusPlus17;
19549 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19550 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19551 DiagID: diag::err_invalid_thread)
19552 << DeclSpec::getSpecifierName(S: TSCS);
19553
19554 // Check to see if this name was declared as a member previously
19555 NamedDecl *PrevDecl = nullptr;
19556 LookupResult Previous(*this, II, Loc, LookupMemberName,
19557 RedeclarationKind::ForVisibleRedeclaration);
19558 LookupName(R&: Previous, S);
19559 switch (Previous.getResultKind()) {
19560 case LookupResultKind::Found:
19561 case LookupResultKind::FoundUnresolvedValue:
19562 PrevDecl = Previous.getAsSingle<NamedDecl>();
19563 break;
19564
19565 case LookupResultKind::FoundOverloaded:
19566 PrevDecl = Previous.getRepresentativeDecl();
19567 break;
19568
19569 case LookupResultKind::NotFound:
19570 case LookupResultKind::NotFoundInCurrentInstantiation:
19571 case LookupResultKind::Ambiguous:
19572 break;
19573 }
19574 Previous.suppressDiagnostics();
19575
19576 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19577 // Maybe we will complain about the shadowed template parameter.
19578 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19579 // Just pretend that we didn't see the previous declaration.
19580 PrevDecl = nullptr;
19581 }
19582
19583 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19584 PrevDecl = nullptr;
19585
19586 bool Mutable
19587 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19588 SourceLocation TSSL = D.getBeginLoc();
19589 FieldDecl *NewFD
19590 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19591 TSSL, AS, PrevDecl, D: &D);
19592
19593 if (NewFD->isInvalidDecl())
19594 Record->setInvalidDecl();
19595
19596 if (D.getDeclSpec().isModulePrivateSpecified())
19597 NewFD->setModulePrivate();
19598
19599 if (NewFD->isInvalidDecl() && PrevDecl) {
19600 // Don't introduce NewFD into scope; there's already something
19601 // with the same name in the same scope.
19602 } else if (II) {
19603 PushOnScopeChains(D: NewFD, S);
19604 } else
19605 Record->addDecl(D: NewFD);
19606
19607 return NewFD;
19608}
19609
19610FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19611 TypeSourceInfo *TInfo,
19612 RecordDecl *Record, SourceLocation Loc,
19613 bool Mutable, Expr *BitWidth,
19614 InClassInitStyle InitStyle,
19615 SourceLocation TSSL,
19616 AccessSpecifier AS, NamedDecl *PrevDecl,
19617 Declarator *D) {
19618 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19619 bool InvalidDecl = false;
19620 if (D) InvalidDecl = D->isInvalidType();
19621
19622 // If we receive a broken type, recover by assuming 'int' and
19623 // marking this declaration as invalid.
19624 if (T.isNull() || T->containsErrors()) {
19625 InvalidDecl = true;
19626 T = Context.IntTy;
19627 }
19628
19629 QualType EltTy = Context.getBaseElementType(QT: T);
19630 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19631 bool isIncomplete =
19632 LangOpts.HLSL // HLSL allows sizeless builtin types
19633 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19634 : RequireCompleteSizedType(Loc, T: EltTy,
19635 DiagID: diag::err_field_incomplete_or_sizeless);
19636 if (isIncomplete) {
19637 // Fields of incomplete type force their record to be invalid.
19638 Record->setInvalidDecl();
19639 InvalidDecl = true;
19640 } else {
19641 NamedDecl *Def;
19642 EltTy->isIncompleteType(Def: &Def);
19643 if (Def && Def->isInvalidDecl()) {
19644 Record->setInvalidDecl();
19645 InvalidDecl = true;
19646 }
19647 }
19648 }
19649
19650 // TR 18037 does not allow fields to be declared with address space
19651 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19652 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19653 Diag(Loc, DiagID: diag::err_field_with_address_space);
19654 Record->setInvalidDecl();
19655 InvalidDecl = true;
19656 }
19657
19658 if (LangOpts.OpenCL) {
19659 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19660 // used as structure or union field: image, sampler, event or block types.
19661 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19662 T->isBlockPointerType()) {
19663 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19664 Record->setInvalidDecl();
19665 InvalidDecl = true;
19666 }
19667 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19668 // is enabled.
19669 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19670 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19671 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19672 InvalidDecl = true;
19673 }
19674 }
19675
19676 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19677 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19678 T.hasQualifiers()) {
19679 InvalidDecl = true;
19680 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19681 }
19682
19683 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19684 // than a variably modified type.
19685 if (!InvalidDecl && T->isVariablyModifiedType()) {
19686 if (!tryToFixVariablyModifiedVarType(
19687 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19688 InvalidDecl = true;
19689 }
19690
19691 // Fields can not have abstract class types
19692 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19693 DiagID: diag::err_abstract_type_in_decl,
19694 Args: AbstractFieldType))
19695 InvalidDecl = true;
19696
19697 if (InvalidDecl)
19698 BitWidth = nullptr;
19699 // If this is declared as a bit-field, check the bit-field.
19700 if (BitWidth) {
19701 BitWidth =
19702 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19703 if (!BitWidth) {
19704 InvalidDecl = true;
19705 BitWidth = nullptr;
19706 }
19707 }
19708
19709 // Check that 'mutable' is consistent with the type of the declaration.
19710 if (!InvalidDecl && Mutable) {
19711 unsigned DiagID = 0;
19712 if (T->isReferenceType())
19713 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19714 : diag::err_mutable_reference;
19715 else if (T.isConstQualified())
19716 DiagID = diag::err_mutable_const;
19717
19718 if (DiagID) {
19719 SourceLocation ErrLoc = Loc;
19720 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19721 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19722 Diag(Loc: ErrLoc, DiagID);
19723 if (DiagID != diag::ext_mutable_reference) {
19724 Mutable = false;
19725 InvalidDecl = true;
19726 }
19727 }
19728 }
19729
19730 // C++11 [class.union]p8 (DR1460):
19731 // At most one variant member of a union may have a
19732 // brace-or-equal-initializer.
19733 if (InitStyle != ICIS_NoInit)
19734 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19735
19736 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19737 BW: BitWidth, Mutable, InitStyle);
19738 if (InvalidDecl)
19739 NewFD->setInvalidDecl();
19740
19741 if (!InvalidDecl)
19742 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19743
19744 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19745 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19746 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19747 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19748 NewFD->setInvalidDecl();
19749 }
19750
19751 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19752 if (Record->isUnion()) {
19753 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19754 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19755
19756 // C++ [class.union]p1: An object of a class with a non-trivial
19757 // constructor, a non-trivial copy constructor, a non-trivial
19758 // destructor, or a non-trivial copy assignment operator
19759 // cannot be a member of a union, nor can an array of such
19760 // objects.
19761 if (CheckNontrivialField(FD: NewFD))
19762 NewFD->setInvalidDecl();
19763 }
19764
19765 // C++ [class.union]p1: If a union contains a member of reference type,
19766 // the program is ill-formed, except when compiling with MSVC extensions
19767 // enabled.
19768 if (EltTy->isReferenceType()) {
19769 const bool HaveMSExt =
19770 getLangOpts().MicrosoftExt &&
19771 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19772
19773 Diag(Loc: NewFD->getLocation(),
19774 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19775 : diag::err_union_member_of_reference_type)
19776 << NewFD->getDeclName() << EltTy;
19777 if (!HaveMSExt)
19778 NewFD->setInvalidDecl();
19779 }
19780 }
19781 }
19782
19783 // FIXME: We need to pass in the attributes given an AST
19784 // representation, not a parser representation.
19785 if (D) {
19786 // FIXME: The current scope is almost... but not entirely... correct here.
19787 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19788
19789 if (NewFD->hasAttrs())
19790 CheckAlignasUnderalignment(D: NewFD);
19791 }
19792
19793 // In auto-retain/release, infer strong retension for fields of
19794 // retainable type.
19795 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19796 NewFD->setInvalidDecl();
19797
19798 if (T.isObjCGCWeak())
19799 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19800
19801 // PPC MMA non-pointer types are not allowed as field types.
19802 if (Context.getTargetInfo().getTriple().isPPC64() &&
19803 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19804 NewFD->setInvalidDecl();
19805
19806 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19807 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewFD->getLocation()))
19808 NewFD->setInvalidDecl();
19809 }
19810
19811 NewFD->setAccess(AS);
19812 return NewFD;
19813}
19814
19815bool Sema::CheckNontrivialField(FieldDecl *FD) {
19816 assert(FD);
19817 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19818
19819 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19820 return false;
19821
19822 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19823 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19824 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19825 // We check for copy constructors before constructors
19826 // because otherwise we'll never get complaints about
19827 // copy constructors.
19828
19829 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19830 // We're required to check for any non-trivial constructors. Since the
19831 // implicit default constructor is suppressed if there are any
19832 // user-declared constructors, we just need to check that there is a
19833 // trivial default constructor and a trivial copy constructor. (We don't
19834 // worry about move constructors here, since this is a C++98 check.)
19835 if (RDecl->hasNonTrivialCopyConstructor())
19836 member = CXXSpecialMemberKind::CopyConstructor;
19837 else if (!RDecl->hasTrivialDefaultConstructor())
19838 member = CXXSpecialMemberKind::DefaultConstructor;
19839 else if (RDecl->hasNonTrivialCopyAssignment())
19840 member = CXXSpecialMemberKind::CopyAssignment;
19841 else if (RDecl->hasNonTrivialDestructor())
19842 member = CXXSpecialMemberKind::Destructor;
19843
19844 if (member != CXXSpecialMemberKind::Invalid) {
19845 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19846 RDecl->hasObjectMember()) {
19847 // Objective-C++ ARC: it is an error to have a non-trivial field of
19848 // a union. However, system headers in Objective-C programs
19849 // occasionally have Objective-C lifetime objects within unions,
19850 // and rather than cause the program to fail, we make those
19851 // members unavailable.
19852 SourceLocation Loc = FD->getLocation();
19853 if (getSourceManager().isInSystemHeader(Loc)) {
19854 if (!FD->hasAttr<UnavailableAttr>())
19855 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19856 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19857 return false;
19858 }
19859 }
19860
19861 Diag(Loc: FD->getLocation(),
19862 DiagID: getLangOpts().CPlusPlus11
19863 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19864 : diag::err_illegal_union_or_anon_struct_member)
19865 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19866 DiagnoseNontrivial(Record: RDecl, CSM: member);
19867 return !getLangOpts().CPlusPlus11;
19868 }
19869 }
19870
19871 return false;
19872}
19873
19874void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19875 SmallVectorImpl<Decl *> &AllIvarDecls) {
19876 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19877 return;
19878
19879 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19880 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19881
19882 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19883 return;
19884 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19885 if (!ID) {
19886 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19887 if (!CD->IsClassExtension())
19888 return;
19889 }
19890 // No need to add this to end of @implementation.
19891 else
19892 return;
19893 }
19894 // All conditions are met. Add a new bitfield to the tail end of ivars.
19895 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19896 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19897 Expr *BitWidth =
19898 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19899
19900 Ivar = ObjCIvarDecl::Create(
19901 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19902 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19903 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19904 AllIvarDecls.push_back(Elt: Ivar);
19905}
19906
19907/// [class.dtor]p4:
19908/// At the end of the definition of a class, overload resolution is
19909/// performed among the prospective destructors declared in that class with
19910/// an empty argument list to select the destructor for the class, also
19911/// known as the selected destructor.
19912///
19913/// We do the overload resolution here, then mark the selected constructor in the AST.
19914/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19915static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19916 if (!Record->hasUserDeclaredDestructor()) {
19917 return;
19918 }
19919
19920 SourceLocation Loc = Record->getLocation();
19921 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19922
19923 for (auto *Decl : Record->decls()) {
19924 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19925 if (DD->isInvalidDecl())
19926 continue;
19927 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19928 CandidateSet&: OCS);
19929 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19930 }
19931 }
19932
19933 if (OCS.empty()) {
19934 return;
19935 }
19936 OverloadCandidateSet::iterator Best;
19937 unsigned Msg = 0;
19938 OverloadCandidateDisplayKind DisplayKind;
19939
19940 switch (OCS.BestViableFunction(S, Loc, Best)) {
19941 case OR_Success:
19942 case OR_Deleted:
19943 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19944 break;
19945
19946 case OR_Ambiguous:
19947 Msg = diag::err_ambiguous_destructor;
19948 DisplayKind = OCD_AmbiguousCandidates;
19949 break;
19950
19951 case OR_No_Viable_Function:
19952 Msg = diag::err_no_viable_destructor;
19953 DisplayKind = OCD_AllCandidates;
19954 break;
19955 }
19956
19957 if (Msg) {
19958 // OpenCL have got their own thing going with destructors. It's slightly broken,
19959 // but we allow it.
19960 if (!S.LangOpts.OpenCL) {
19961 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19962 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19963 Record->setInvalidDecl();
19964 }
19965 // It's a bit hacky: At this point we've raised an error but we want the
19966 // rest of the compiler to continue somehow working. However almost
19967 // everything we'll try to do with the class will depend on there being a
19968 // destructor. So let's pretend the first one is selected and hope for the
19969 // best.
19970 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19971 }
19972}
19973
19974/// [class.mem.special]p5
19975/// Two special member functions are of the same kind if:
19976/// - they are both default constructors,
19977/// - they are both copy or move constructors with the same first parameter
19978/// type, or
19979/// - they are both copy or move assignment operators with the same first
19980/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19981static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19982 CXXMethodDecl *M1,
19983 CXXMethodDecl *M2,
19984 CXXSpecialMemberKind CSM) {
19985 // We don't want to compare templates to non-templates: See
19986 // https://github.com/llvm/llvm-project/issues/59206
19987 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19988 return bool(M1->getDescribedFunctionTemplate()) ==
19989 bool(M2->getDescribedFunctionTemplate());
19990 // FIXME: better resolve CWG
19991 // https://cplusplus.github.io/CWG/issues/2787.html
19992 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19993 T2: M2->getNonObjectParameter(I: 0)->getType()))
19994 return false;
19995 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19996 T2: M2->getFunctionObjectParameterReferenceType()))
19997 return false;
19998
19999 return true;
20000}
20001
20002/// [class.mem.special]p6:
20003/// An eligible special member function is a special member function for which:
20004/// - the function is not deleted,
20005/// - the associated constraints, if any, are satisfied, and
20006/// - no special member function of the same kind whose associated constraints
20007/// [CWG2595], if any, are satisfied is more constrained.
20008static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
20009 ArrayRef<CXXMethodDecl *> Methods,
20010 CXXSpecialMemberKind CSM) {
20011 SmallVector<bool, 4> SatisfactionStatus;
20012
20013 for (CXXMethodDecl *Method : Methods) {
20014 if (!Method->getTrailingRequiresClause())
20015 SatisfactionStatus.push_back(Elt: true);
20016 else {
20017 ConstraintSatisfaction Satisfaction;
20018 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
20019 SatisfactionStatus.push_back(Elt: false);
20020 else
20021 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
20022 }
20023 }
20024
20025 for (size_t i = 0; i < Methods.size(); i++) {
20026 if (!SatisfactionStatus[i])
20027 continue;
20028 CXXMethodDecl *Method = Methods[i];
20029 CXXMethodDecl *OrigMethod = Method;
20030 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20031 OrigMethod = cast<CXXMethodDecl>(Val: MF);
20032
20033 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
20034 bool AnotherMethodIsMoreConstrained = false;
20035 for (size_t j = 0; j < Methods.size(); j++) {
20036 if (i == j || !SatisfactionStatus[j])
20037 continue;
20038 CXXMethodDecl *OtherMethod = Methods[j];
20039 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20040 OtherMethod = cast<CXXMethodDecl>(Val: MF);
20041
20042 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
20043 CSM))
20044 continue;
20045
20046 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
20047 if (!Other)
20048 continue;
20049 if (!Orig) {
20050 AnotherMethodIsMoreConstrained = true;
20051 break;
20052 }
20053 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
20054 Result&: AnotherMethodIsMoreConstrained)) {
20055 // There was an error with the constraints comparison. Exit the loop
20056 // and don't consider this function eligible.
20057 AnotherMethodIsMoreConstrained = true;
20058 }
20059 if (AnotherMethodIsMoreConstrained)
20060 break;
20061 }
20062 // FIXME: Do not consider deleted methods as eligible after implementing
20063 // DR1734 and DR1496.
20064 if (!AnotherMethodIsMoreConstrained) {
20065 Method->setIneligibleOrNotSelected(false);
20066 Record->addedEligibleSpecialMemberFunction(MD: Method,
20067 SMKind: 1 << llvm::to_underlying(E: CSM));
20068 }
20069 }
20070}
20071
20072static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
20073 CXXRecordDecl *Record) {
20074 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20075 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20076 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20077 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20078 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20079
20080 for (auto *Decl : Record->decls()) {
20081 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
20082 if (!MD) {
20083 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
20084 if (FTD)
20085 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
20086 }
20087 if (!MD)
20088 continue;
20089 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
20090 if (CD->isInvalidDecl())
20091 continue;
20092 if (CD->isDefaultConstructor())
20093 DefaultConstructors.push_back(Elt: MD);
20094 else if (CD->isCopyConstructor())
20095 CopyConstructors.push_back(Elt: MD);
20096 else if (CD->isMoveConstructor())
20097 MoveConstructors.push_back(Elt: MD);
20098 } else if (MD->isCopyAssignmentOperator()) {
20099 CopyAssignmentOperators.push_back(Elt: MD);
20100 } else if (MD->isMoveAssignmentOperator()) {
20101 MoveAssignmentOperators.push_back(Elt: MD);
20102 }
20103 }
20104
20105 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
20106 CSM: CXXSpecialMemberKind::DefaultConstructor);
20107 SetEligibleMethods(S, Record, Methods: CopyConstructors,
20108 CSM: CXXSpecialMemberKind::CopyConstructor);
20109 SetEligibleMethods(S, Record, Methods: MoveConstructors,
20110 CSM: CXXSpecialMemberKind::MoveConstructor);
20111 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
20112 CSM: CXXSpecialMemberKind::CopyAssignment);
20113 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
20114 CSM: CXXSpecialMemberKind::MoveAssignment);
20115}
20116
20117bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20118 // Check to see if a FieldDecl is a pointer to a function.
20119 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20120 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
20121 if (!FD) {
20122 // Check whether this is a forward declaration that was inserted by
20123 // Clang. This happens when a non-forward declared / defined type is
20124 // used, e.g.:
20125 //
20126 // struct foo {
20127 // struct bar *(*f)();
20128 // struct bar *(*g)();
20129 // };
20130 //
20131 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20132 // incomplete definition.
20133 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
20134 return !TD->isCompleteDefinition();
20135 return false;
20136 }
20137 QualType FieldType = FD->getType().getDesugaredType(Context);
20138 if (isa<PointerType>(Val: FieldType)) {
20139 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
20140 return PointeeType.getDesugaredType(Context)->isFunctionType();
20141 }
20142 // If a member is a struct entirely of function pointers, that counts too.
20143 if (const auto *Record = FieldType->getAsRecordDecl();
20144 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20145 return true;
20146 return false;
20147 };
20148
20149 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
20150}
20151
20152void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20153 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20154 SourceLocation RBrac,
20155 const ParsedAttributesView &Attrs) {
20156 assert(EnclosingDecl && "missing record or interface decl");
20157
20158 // If this is an Objective-C @implementation or category and we have
20159 // new fields here we should reset the layout of the interface since
20160 // it will now change.
20161 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
20162 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
20163 switch (DC->getKind()) {
20164 default: break;
20165 case Decl::ObjCCategory:
20166 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
20167 break;
20168 case Decl::ObjCImplementation:
20169 Context.
20170 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
20171 break;
20172 }
20173 }
20174
20175 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
20176 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
20177
20178 // Start counting up the number of named members; make sure to include
20179 // members of anonymous structs and unions in the total.
20180 unsigned NumNamedMembers = 0;
20181 if (Record) {
20182 for (const auto *I : Record->decls()) {
20183 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
20184 if (IFD->getDeclName())
20185 ++NumNamedMembers;
20186 }
20187 }
20188
20189 // Verify that all the fields are okay.
20190 SmallVector<FieldDecl*, 32> RecFields;
20191 const FieldDecl *PreviousField = nullptr;
20192 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20193 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
20194 FieldDecl *FD = cast<FieldDecl>(Val: *i);
20195
20196 // Get the type for the field.
20197 const Type *FDTy = FD->getType().getTypePtr();
20198
20199 if (!FD->isAnonymousStructOrUnion()) {
20200 // Remember all fields written by the user.
20201 RecFields.push_back(Elt: FD);
20202 }
20203
20204 // If the field is already invalid for some reason, don't emit more
20205 // diagnostics about it.
20206 if (FD->isInvalidDecl()) {
20207 EnclosingDecl->setInvalidDecl();
20208 continue;
20209 }
20210
20211 // C99 6.7.2.1p2:
20212 // A structure or union shall not contain a member with
20213 // incomplete or function type (hence, a structure shall not
20214 // contain an instance of itself, but may contain a pointer to
20215 // an instance of itself), except that the last member of a
20216 // structure with more than one named member may have incomplete
20217 // array type; such a structure (and any union containing,
20218 // possibly recursively, a member that is such a structure)
20219 // shall not be a member of a structure or an element of an
20220 // array.
20221 bool IsLastField = (i + 1 == Fields.end());
20222 if (FDTy->isFunctionType()) {
20223 // Field declared as a function.
20224 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
20225 << FD->getDeclName();
20226 FD->setInvalidDecl();
20227 EnclosingDecl->setInvalidDecl();
20228 continue;
20229 } else if (FDTy->isIncompleteArrayType() &&
20230 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20231 if (Record) {
20232 // Flexible array member.
20233 // Microsoft and g++ is more permissive regarding flexible array.
20234 // It will accept flexible array in union and also
20235 // as the sole element of a struct/class.
20236 unsigned DiagID = 0;
20237 if (!Record->isUnion() && !IsLastField) {
20238 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20239 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20240 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20241 FD->setInvalidDecl();
20242 EnclosingDecl->setInvalidDecl();
20243 continue;
20244 } else if (Record->isUnion())
20245 DiagID = getLangOpts().MicrosoftExt
20246 ? diag::ext_flexible_array_union_ms
20247 : diag::ext_flexible_array_union_gnu;
20248 else if (NumNamedMembers < 1)
20249 DiagID = getLangOpts().MicrosoftExt
20250 ? diag::ext_flexible_array_empty_aggregate_ms
20251 : diag::ext_flexible_array_empty_aggregate_gnu;
20252
20253 if (DiagID)
20254 Diag(Loc: FD->getLocation(), DiagID)
20255 << FD->getDeclName() << Record->getTagKind();
20256 // While the layout of types that contain virtual bases is not specified
20257 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20258 // virtual bases after the derived members. This would make a flexible
20259 // array member declared at the end of an object not adjacent to the end
20260 // of the type.
20261 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20262 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20263 << FD->getDeclName() << Record->getTagKind();
20264 if (!getLangOpts().C99)
20265 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20266 << FD->getDeclName() << Record->getTagKind();
20267
20268 // If the element type has a non-trivial destructor, we would not
20269 // implicitly destroy the elements, so disallow it for now.
20270 //
20271 // FIXME: GCC allows this. We should probably either implicitly delete
20272 // the destructor of the containing class, or just allow this.
20273 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20274 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20275 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20276 << FD->getDeclName() << FD->getType();
20277 FD->setInvalidDecl();
20278 EnclosingDecl->setInvalidDecl();
20279 continue;
20280 }
20281 // Okay, we have a legal flexible array member at the end of the struct.
20282 Record->setHasFlexibleArrayMember(true);
20283 } else {
20284 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20285 // unless they are followed by another ivar. That check is done
20286 // elsewhere, after synthesized ivars are known.
20287 }
20288 } else if (!FDTy->isDependentType() &&
20289 (LangOpts.HLSL // HLSL allows sizeless builtin types
20290 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20291 DiagID: diag::err_incomplete_type)
20292 : RequireCompleteSizedType(
20293 Loc: FD->getLocation(), T: FD->getType(),
20294 DiagID: diag::err_field_incomplete_or_sizeless))) {
20295 // Incomplete type
20296 FD->setInvalidDecl();
20297 EnclosingDecl->setInvalidDecl();
20298 continue;
20299 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20300 if (Record && RD->hasFlexibleArrayMember()) {
20301 // A type which contains a flexible array member is considered to be a
20302 // flexible array member.
20303 Record->setHasFlexibleArrayMember(true);
20304 if (!Record->isUnion()) {
20305 // If this is a struct/class and this is not the last element, reject
20306 // it. Note that GCC supports variable sized arrays in the middle of
20307 // structures.
20308 if (!IsLastField)
20309 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20310 << FD->getDeclName() << FD->getType();
20311 else {
20312 // We support flexible arrays at the end of structs in
20313 // other structs as an extension.
20314 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20315 << FD->getDeclName();
20316 }
20317 }
20318 }
20319 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20320 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20321 DiagID: diag::err_abstract_type_in_decl,
20322 Args: AbstractIvarType)) {
20323 // Ivars can not have abstract class types
20324 FD->setInvalidDecl();
20325 }
20326 if (Record && RD->hasObjectMember())
20327 Record->setHasObjectMember(true);
20328 if (Record && RD->hasVolatileMember())
20329 Record->setHasVolatileMember(true);
20330 } else if (FDTy->isObjCObjectType()) {
20331 /// A field cannot be an Objective-c object
20332 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20333 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20334 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20335 FD->setType(T);
20336 } else if (Record && Record->isUnion() &&
20337 FD->getType().hasNonTrivialObjCLifetime() &&
20338 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20339 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20340 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20341 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20342 // For backward compatibility, fields of C unions declared in system
20343 // headers that have non-trivial ObjC ownership qualifications are marked
20344 // as unavailable unless the qualifier is explicit and __strong. This can
20345 // break ABI compatibility between programs compiled with ARC and MRR, but
20346 // is a better option than rejecting programs using those unions under
20347 // ARC.
20348 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20349 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20350 Range: FD->getLocation()));
20351 } else if (getLangOpts().ObjC &&
20352 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20353 !Record->hasObjectMember()) {
20354 if (FD->getType()->isObjCObjectPointerType() ||
20355 FD->getType().isObjCGCStrong())
20356 Record->setHasObjectMember(true);
20357 else if (Context.getAsArrayType(T: FD->getType())) {
20358 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20359 if (const auto *RD = BaseType->getAsRecordDecl();
20360 RD && RD->hasObjectMember())
20361 Record->setHasObjectMember(true);
20362 else if (BaseType->isObjCObjectPointerType() ||
20363 BaseType.isObjCGCStrong())
20364 Record->setHasObjectMember(true);
20365 }
20366 }
20367
20368 if (Record && !getLangOpts().CPlusPlus &&
20369 !shouldIgnoreForRecordTriviality(FD)) {
20370 QualType FT = FD->getType();
20371 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20372 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20373 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20374 Record->isUnion())
20375 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20376 }
20377 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20378 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20379 Record->setNonTrivialToPrimitiveCopy(true);
20380 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20381 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20382 }
20383 if (FD->hasAttr<ExplicitInitAttr>())
20384 Record->setHasUninitializedExplicitInitFields(true);
20385 if (FT.isDestructedType()) {
20386 Record->setNonTrivialToPrimitiveDestroy(true);
20387 Record->setParamDestroyedInCallee(true);
20388 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20389 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20390 }
20391
20392 if (const auto *RD = FT->getAsRecordDecl()) {
20393 if (RD->getArgPassingRestrictions() ==
20394 RecordArgPassingKind::CanNeverPassInRegs)
20395 Record->setArgPassingRestrictions(
20396 RecordArgPassingKind::CanNeverPassInRegs);
20397 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20398 Record->setArgPassingRestrictions(
20399 RecordArgPassingKind::CanNeverPassInRegs);
20400 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20401 Q && Q.isAddressDiscriminated()) {
20402 Record->setArgPassingRestrictions(
20403 RecordArgPassingKind::CanNeverPassInRegs);
20404 Record->setNonTrivialToPrimitiveCopy(true);
20405 }
20406 }
20407
20408 if (Record && FD->getType().isVolatileQualified())
20409 Record->setHasVolatileMember(true);
20410 bool ReportMSBitfieldStoragePacking =
20411 Record && PreviousField &&
20412 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20413 Loc: Record->getLocation());
20414 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20415 return FD->isBitField() && !FD->getType()->isDependentType();
20416 };
20417
20418 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20419 IsNonDependentBitField(PreviousField)) {
20420 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20421 CharUnits PreviousFieldStorageSize =
20422 Context.getTypeSizeInChars(T: PreviousField->getType());
20423 if (FDStorageSize != PreviousFieldStorageSize) {
20424 Diag(Loc: FD->getLocation(),
20425 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20426 << FD << FD->getType() << FDStorageSize.getQuantity()
20427 << PreviousFieldStorageSize.getQuantity();
20428 Diag(Loc: PreviousField->getLocation(),
20429 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20430 << PreviousField << PreviousField->getType();
20431 }
20432 }
20433 // Keep track of the number of named members.
20434 if (FD->getIdentifier())
20435 ++NumNamedMembers;
20436 }
20437
20438 // Okay, we successfully defined 'Record'.
20439 if (Record) {
20440 bool Completed = false;
20441 if (S) {
20442 Scope *Parent = S->getParent();
20443 if (Parent && Parent->isTypeAliasScope() &&
20444 Parent->isTemplateParamScope())
20445 Record->setInvalidDecl();
20446 }
20447
20448 if (CXXRecord) {
20449 if (!CXXRecord->isInvalidDecl()) {
20450 // Set access bits correctly on the directly-declared conversions.
20451 for (CXXRecordDecl::conversion_iterator
20452 I = CXXRecord->conversion_begin(),
20453 E = CXXRecord->conversion_end(); I != E; ++I)
20454 I.setAccess((*I)->getAccess());
20455 }
20456
20457 // Add any implicitly-declared members to this class.
20458 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20459
20460 if (!CXXRecord->isDependentType()) {
20461 if (!CXXRecord->isInvalidDecl()) {
20462 // If we have virtual base classes, we may end up finding multiple
20463 // final overriders for a given virtual function. Check for this
20464 // problem now.
20465 if (CXXRecord->getNumVBases()) {
20466 CXXFinalOverriderMap FinalOverriders;
20467 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20468
20469 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20470 MEnd = FinalOverriders.end();
20471 M != MEnd; ++M) {
20472 for (OverridingMethods::iterator SO = M->second.begin(),
20473 SOEnd = M->second.end();
20474 SO != SOEnd; ++SO) {
20475 assert(SO->second.size() > 0 &&
20476 "Virtual function without overriding functions?");
20477 if (SO->second.size() == 1)
20478 continue;
20479
20480 // C++ [class.virtual]p2:
20481 // In a derived class, if a virtual member function of a base
20482 // class subobject has more than one final overrider the
20483 // program is ill-formed.
20484 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20485 << (const NamedDecl *)M->first << Record;
20486 Diag(Loc: M->first->getLocation(),
20487 DiagID: diag::note_overridden_virtual_function);
20488 for (OverridingMethods::overriding_iterator
20489 OM = SO->second.begin(),
20490 OMEnd = SO->second.end();
20491 OM != OMEnd; ++OM)
20492 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20493 << (const NamedDecl *)M->first << OM->Method->getParent();
20494
20495 Record->setInvalidDecl();
20496 }
20497 }
20498 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20499 Completed = true;
20500 }
20501 }
20502 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20503 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20504 }
20505 }
20506
20507 if (!Completed)
20508 Record->completeDefinition();
20509
20510 // Handle attributes before checking the layout.
20511 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20512
20513 // Maybe randomize the record's decls. We automatically randomize a record
20514 // of function pointers, unless it has the "no_randomize_layout" attribute.
20515 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20516 !Record->isRandomized() && !Record->isUnion() &&
20517 (Record->hasAttr<RandomizeLayoutAttr>() ||
20518 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20519 EntirelyFunctionPointers(Record)))) {
20520 SmallVector<Decl *, 32> NewDeclOrdering;
20521 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20522 FinalOrdering&: NewDeclOrdering))
20523 Record->reorderDecls(Decls: NewDeclOrdering);
20524 }
20525
20526 // We may have deferred checking for a deleted destructor. Check now.
20527 if (CXXRecord) {
20528 auto *Dtor = CXXRecord->getDestructor();
20529 if (Dtor && Dtor->isImplicit() &&
20530 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20531 CXXRecord->setImplicitDestructorIsDeleted();
20532 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20533 }
20534 }
20535
20536 if (Record->hasAttrs()) {
20537 CheckAlignasUnderalignment(D: Record);
20538
20539 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20540 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20541 Range: IA->getRange(), BestCase: IA->getBestCase(),
20542 SemanticSpelling: IA->getInheritanceModel());
20543 }
20544
20545 // Check if the structure/union declaration is a type that can have zero
20546 // size in C. For C this is a language extension, for C++ it may cause
20547 // compatibility problems.
20548 bool CheckForZeroSize;
20549 if (!getLangOpts().CPlusPlus) {
20550 CheckForZeroSize = true;
20551 } else {
20552 // For C++ filter out types that cannot be referenced in C code.
20553 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20554 CheckForZeroSize =
20555 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20556 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20557 CXXRecord->isCLike();
20558 }
20559 if (CheckForZeroSize) {
20560 bool ZeroSize = true;
20561 bool IsEmpty = true;
20562 unsigned NonBitFields = 0;
20563 for (RecordDecl::field_iterator I = Record->field_begin(),
20564 E = Record->field_end();
20565 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20566 IsEmpty = false;
20567 if (I->isUnnamedBitField()) {
20568 if (!I->isZeroLengthBitField())
20569 ZeroSize = false;
20570 } else {
20571 ++NonBitFields;
20572 QualType FieldType = I->getType();
20573 if (FieldType->isIncompleteType() ||
20574 !Context.getTypeSizeInChars(T: FieldType).isZero())
20575 ZeroSize = false;
20576 }
20577 }
20578
20579 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20580 // allowed in C++, but warn if its declaration is inside
20581 // extern "C" block.
20582 if (ZeroSize) {
20583 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20584 diag::warn_zero_size_struct_union_in_extern_c :
20585 diag::warn_zero_size_struct_union_compat)
20586 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20587 }
20588
20589 // Structs without named members are extension in C (C99 6.7.2.1p7),
20590 // but are accepted by GCC. In C2y, this became implementation-defined
20591 // (C2y 6.7.3.2p10).
20592 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20593 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20594 : diag::ext_no_named_members_in_struct_union)
20595 << Record->isUnion();
20596 }
20597 }
20598 } else {
20599 ObjCIvarDecl **ClsFields =
20600 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20601 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20602 ID->setEndOfDefinitionLoc(RBrac);
20603 // Add ivar's to class's DeclContext.
20604 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20605 ClsFields[i]->setLexicalDeclContext(ID);
20606 ID->addDecl(D: ClsFields[i]);
20607 }
20608 // Must enforce the rule that ivars in the base classes may not be
20609 // duplicates.
20610 if (ID->getSuperClass())
20611 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20612 } else if (ObjCImplementationDecl *IMPDecl =
20613 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20614 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20615 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20616 // Ivar declared in @implementation never belongs to the implementation.
20617 // Only it is in implementation's lexical context.
20618 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20619 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20620 Loc: RBrac);
20621 IMPDecl->setIvarLBraceLoc(LBrac);
20622 IMPDecl->setIvarRBraceLoc(RBrac);
20623 } else if (ObjCCategoryDecl *CDecl =
20624 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20625 // case of ivars in class extension; all other cases have been
20626 // reported as errors elsewhere.
20627 // FIXME. Class extension does not have a LocEnd field.
20628 // CDecl->setLocEnd(RBrac);
20629 // Add ivar's to class extension's DeclContext.
20630 // Diagnose redeclaration of private ivars.
20631 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20632 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20633 if (IDecl) {
20634 if (const ObjCIvarDecl *ClsIvar =
20635 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20636 Diag(Loc: ClsFields[i]->getLocation(),
20637 DiagID: diag::err_duplicate_ivar_declaration);
20638 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20639 continue;
20640 }
20641 for (const auto *Ext : IDecl->known_extensions()) {
20642 if (const ObjCIvarDecl *ClsExtIvar
20643 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20644 Diag(Loc: ClsFields[i]->getLocation(),
20645 DiagID: diag::err_duplicate_ivar_declaration);
20646 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20647 continue;
20648 }
20649 }
20650 }
20651 ClsFields[i]->setLexicalDeclContext(CDecl);
20652 CDecl->addDecl(D: ClsFields[i]);
20653 }
20654 CDecl->setIvarLBraceLoc(LBrac);
20655 CDecl->setIvarRBraceLoc(RBrac);
20656 }
20657 }
20658
20659 if (Record)
20660 AMDGPU().checkNamedBarrierWrapper(R: Record);
20661
20662 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20663 ProcessAPINotes(D: Record);
20664}
20665
20666// Given an integral type, return the next larger integral type
20667// (or a NULL type of no such type exists).
20668static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20669 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20670 // enum checking below.
20671 assert((T->isIntegralType(Context) ||
20672 T->isEnumeralType()) && "Integral type required!");
20673 const unsigned NumTypes = 4;
20674 QualType SignedIntegralTypes[NumTypes] = {
20675 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20676 };
20677 QualType UnsignedIntegralTypes[NumTypes] = {
20678 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20679 Context.UnsignedLongLongTy
20680 };
20681
20682 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20683 // bits but a 64-bit standard type can still represent its incremented
20684 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20685 // bit-precise type either.
20686 unsigned BitWidth = Context.getIntWidth(T);
20687 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20688 : UnsignedIntegralTypes;
20689 for (unsigned I = 0; I != NumTypes; ++I)
20690 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20691 return Types[I];
20692
20693 return QualType();
20694}
20695
20696EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20697 EnumConstantDecl *LastEnumConst,
20698 SourceLocation IdLoc,
20699 IdentifierInfo *Id,
20700 Expr *Val) {
20701 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20702 llvm::APSInt EnumVal(IntWidth);
20703 QualType EltTy;
20704
20705 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20706 Val = nullptr;
20707
20708 if (Val)
20709 Val = DefaultLvalueConversion(E: Val).get();
20710
20711 if (Val) {
20712 if (Enum->isDependentType() || Val->isTypeDependent() ||
20713 Val->containsErrors())
20714 EltTy = Context.DependentTy;
20715 else {
20716 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20717 // underlying type, but do allow it in all other contexts.
20718 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20719 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20720 // constant-expression in the enumerator-definition shall be a converted
20721 // constant expression of the underlying type.
20722 EltTy = Enum->getIntegerType();
20723 ExprResult Converted = CheckConvertedConstantExpression(
20724 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20725 if (Converted.isInvalid())
20726 Val = nullptr;
20727 else
20728 Val = Converted.get();
20729 } else if (!Val->isValueDependent() &&
20730 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20731 CanFold: AllowFoldKind::Allow)
20732 .get())) {
20733 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20734 } else {
20735 if (Enum->isComplete()) {
20736 EltTy = Enum->getIntegerType();
20737
20738 // In Obj-C and Microsoft mode, require the enumeration value to be
20739 // representable in the underlying type of the enumeration. In C++11,
20740 // we perform a non-narrowing conversion as part of converted constant
20741 // expression checking.
20742 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20743 if (Context.getTargetInfo()
20744 .getTriple()
20745 .isWindowsMSVCEnvironment()) {
20746 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20747 } else {
20748 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20749 }
20750 }
20751
20752 // Cast to the underlying type.
20753 Val = ImpCastExprToType(E: Val, Type: EltTy,
20754 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20755 : CK_IntegralCast)
20756 .get();
20757 } else if (getLangOpts().CPlusPlus) {
20758 // C++11 [dcl.enum]p5:
20759 // If the underlying type is not fixed, the type of each enumerator
20760 // is the type of its initializing value:
20761 // - If an initializer is specified for an enumerator, the
20762 // initializing value has the same type as the expression.
20763 EltTy = Val->getType();
20764 } else {
20765 // C99 6.7.2.2p2:
20766 // The expression that defines the value of an enumeration constant
20767 // shall be an integer constant expression that has a value
20768 // representable as an int.
20769
20770 // Complain if the value is not representable in an int.
20771 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20772 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20773 ? diag::warn_c17_compat_enum_value_not_int
20774 : diag::ext_c23_enum_value_not_int)
20775 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20776 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20777 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20778 // Force the type of the expression to 'int'.
20779 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20780 }
20781 EltTy = Val->getType();
20782 }
20783 }
20784 }
20785 }
20786
20787 if (!Val) {
20788 if (Enum->isDependentType())
20789 EltTy = Context.DependentTy;
20790 else if (!LastEnumConst) {
20791 // C++0x [dcl.enum]p5:
20792 // If the underlying type is not fixed, the type of each enumerator
20793 // is the type of its initializing value:
20794 // - If no initializer is specified for the first enumerator, the
20795 // initializing value has an unspecified integral type.
20796 //
20797 // GCC uses 'int' for its unspecified integral type, as does
20798 // C99 6.7.2.2p3.
20799 if (Enum->isFixed()) {
20800 EltTy = Enum->getIntegerType();
20801 }
20802 else {
20803 EltTy = Context.IntTy;
20804 }
20805 } else {
20806 // Assign the last value + 1.
20807 EnumVal = LastEnumConst->getInitVal();
20808 ++EnumVal;
20809 EltTy = LastEnumConst->getType();
20810
20811 // Check for overflow on increment.
20812 if (EnumVal < LastEnumConst->getInitVal()) {
20813 // C++0x [dcl.enum]p5:
20814 // If the underlying type is not fixed, the type of each enumerator
20815 // is the type of its initializing value:
20816 //
20817 // - Otherwise the type of the initializing value is the same as
20818 // the type of the initializing value of the preceding enumerator
20819 // unless the incremented value is not representable in that type,
20820 // in which case the type is an unspecified integral type
20821 // sufficient to contain the incremented value. If no such type
20822 // exists, the program is ill-formed.
20823 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20824 if (T.isNull() || Enum->isFixed()) {
20825 // There is no integral type larger enough to represent this
20826 // value. Complain, then allow the value to wrap around.
20827 EnumVal = LastEnumConst->getInitVal();
20828 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20829 ++EnumVal;
20830 if (Enum->isFixed())
20831 // When the underlying type is fixed, this is ill-formed.
20832 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20833 << toString(I: EnumVal, Radix: 10)
20834 << EltTy;
20835 else
20836 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20837 << toString(I: EnumVal, Radix: 10);
20838 } else {
20839 EltTy = T;
20840 }
20841
20842 // Retrieve the last enumerator's value, extent that type to the
20843 // type that is supposed to be large enough to represent the incremented
20844 // value, then increment.
20845 EnumVal = LastEnumConst->getInitVal();
20846 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20847 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20848 ++EnumVal;
20849
20850 // If we're not in C++, diagnose the overflow of enumerator values,
20851 // which in C99 means that the enumerator value is not representable in
20852 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20853 // are representable in some larger integral type and we allow it in
20854 // older language modes as an extension.
20855 // Exclude fixed enumerators since they are diagnosed with an error for
20856 // this case.
20857 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20858 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20859 ? diag::warn_c17_compat_enum_value_not_int
20860 : diag::ext_c23_enum_value_not_int)
20861 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20862 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20863 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20864 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20865 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20866 : diag::ext_c23_enum_value_not_int)
20867 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20868 }
20869 }
20870 }
20871
20872 if (!EltTy->isDependentType()) {
20873 // Make the enumerator value match the signedness and size of the
20874 // enumerator's type.
20875 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20876 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20877 }
20878
20879 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20880 E: Val, V: EnumVal);
20881}
20882
20883SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20884 SourceLocation IILoc) {
20885 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20886 !getLangOpts().CPlusPlus)
20887 return SkipBodyInfo();
20888
20889 // We have an anonymous enum definition. Look up the first enumerator to
20890 // determine if we should merge the definition with an existing one and
20891 // skip the body.
20892 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20893 Redecl: forRedeclarationInCurContext());
20894 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20895 if (!PrevECD)
20896 return SkipBodyInfo();
20897
20898 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20899 NamedDecl *Hidden;
20900 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20901 SkipBodyInfo Skip;
20902 Skip.Previous = Hidden;
20903 return Skip;
20904 }
20905
20906 return SkipBodyInfo();
20907}
20908
20909Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20910 SourceLocation IdLoc, IdentifierInfo *Id,
20911 const ParsedAttributesView &Attrs,
20912 SourceLocation EqualLoc, Expr *Val,
20913 SkipBodyInfo *SkipBody) {
20914 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20915 EnumConstantDecl *LastEnumConst =
20916 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20917
20918 // The scope passed in may not be a decl scope. Zip up the scope tree until
20919 // we find one that is.
20920 S = getNonFieldDeclScope(S);
20921
20922 // Verify that there isn't already something declared with this name in this
20923 // scope.
20924 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20925 RedeclarationKind::ForVisibleRedeclaration);
20926 LookupName(R, S);
20927 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20928
20929 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20930 // Maybe we will complain about the shadowed template parameter.
20931 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20932 // Just pretend that we didn't see the previous declaration.
20933 PrevDecl = nullptr;
20934 }
20935
20936 // C++ [class.mem]p15:
20937 // If T is the name of a class, then each of the following shall have a name
20938 // different from T:
20939 // - every enumerator of every member of class T that is an unscoped
20940 // enumerated type
20941 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20942 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20943 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20944 return nullptr;
20945
20946 EnumConstantDecl *New =
20947 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20948 if (!New)
20949 return nullptr;
20950
20951 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20952 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20953 // Check for other kinds of shadowing not already handled.
20954 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20955 }
20956
20957 // When in C++, we may get a TagDecl with the same name; in this case the
20958 // enum constant will 'hide' the tag.
20959 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20960 "Received TagDecl when not in C++!");
20961 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20962 if (isa<EnumConstantDecl>(Val: PrevDecl))
20963 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20964 else
20965 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20966 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20967 return nullptr;
20968 }
20969 }
20970
20971 // Process attributes.
20972 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20973 AddPragmaAttributes(S, D: New);
20974 ProcessAPINotes(D: New);
20975
20976 // Register this decl in the current scope stack.
20977 New->setAccess(TheEnumDecl->getAccess());
20978 PushOnScopeChains(D: New, S);
20979
20980 ActOnDocumentableDecl(D: New);
20981
20982 return New;
20983}
20984
20985// Returns true when the enum initial expression does not trigger the
20986// duplicate enum warning. A few common cases are exempted as follows:
20987// Element2 = Element1
20988// Element2 = Element1 + 1
20989// Element2 = Element1 - 1
20990// Where Element2 and Element1 are from the same enum.
20991static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20992 Expr *InitExpr = ECD->getInitExpr();
20993 if (!InitExpr)
20994 return true;
20995 InitExpr = InitExpr->IgnoreImpCasts();
20996
20997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20998 if (!BO->isAdditiveOp())
20999 return true;
21000 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
21001 if (!IL)
21002 return true;
21003 if (IL->getValue() != 1)
21004 return true;
21005
21006 InitExpr = BO->getLHS();
21007 }
21008
21009 // This checks if the elements are from the same enum.
21010 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
21011 if (!DRE)
21012 return true;
21013
21014 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
21015 if (!EnumConstant)
21016 return true;
21017
21018 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
21019 Enum)
21020 return true;
21021
21022 return false;
21023}
21024
21025// Emits a warning when an element is implicitly set a value that
21026// a previous element has already been set to.
21027static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
21028 EnumDecl *Enum, QualType EnumType) {
21029 // Avoid anonymous enums
21030 if (!Enum->getIdentifier())
21031 return;
21032
21033 // Only check for small enums.
21034 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21035 return;
21036
21037 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
21038 return;
21039
21040 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21041 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21042
21043 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21044
21045 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21046 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21047
21048 // Use int64_t as a key to avoid needing special handling for map keys.
21049 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21050 llvm::APSInt Val = D->getInitVal();
21051 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21052 };
21053
21054 DuplicatesVector DupVector;
21055 ValueToVectorMap EnumMap;
21056
21057 // Populate the EnumMap with all values represented by enum constants without
21058 // an initializer.
21059 for (auto *Element : Elements) {
21060 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
21061
21062 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21063 // this constant. Skip this enum since it may be ill-formed.
21064 if (!ECD) {
21065 return;
21066 }
21067
21068 // Constants with initializers are handled in the next loop.
21069 if (ECD->getInitExpr())
21070 continue;
21071
21072 // Duplicate values are handled in the next loop.
21073 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
21074 }
21075
21076 if (EnumMap.size() == 0)
21077 return;
21078
21079 // Create vectors for any values that has duplicates.
21080 for (auto *Element : Elements) {
21081 // The last loop returned if any constant was null.
21082 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
21083 if (!ValidDuplicateEnum(ECD, Enum))
21084 continue;
21085
21086 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
21087 if (Iter == EnumMap.end())
21088 continue;
21089
21090 DeclOrVector& Entry = Iter->second;
21091 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
21092 // Ensure constants are different.
21093 if (D == ECD)
21094 continue;
21095
21096 // Create new vector and push values onto it.
21097 auto Vec = std::make_unique<ECDVector>();
21098 Vec->push_back(Elt: D);
21099 Vec->push_back(Elt: ECD);
21100
21101 // Update entry to point to the duplicates vector.
21102 Entry = Vec.get();
21103
21104 // Store the vector somewhere we can consult later for quick emission of
21105 // diagnostics.
21106 DupVector.emplace_back(Args: std::move(Vec));
21107 continue;
21108 }
21109
21110 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
21111 // Make sure constants are not added more than once.
21112 if (*Vec->begin() == ECD)
21113 continue;
21114
21115 Vec->push_back(Elt: ECD);
21116 }
21117
21118 // Emit diagnostics.
21119 for (const auto &Vec : DupVector) {
21120 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21121
21122 // Emit warning for one enum constant.
21123 auto *FirstECD = Vec->front();
21124 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
21125 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
21126 << FirstECD->getSourceRange();
21127
21128 // Emit one note for each of the remaining enum constants with
21129 // the same value.
21130 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
21131 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
21132 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
21133 << ECD->getSourceRange();
21134 }
21135}
21136
21137bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21138 bool AllowMask) const {
21139 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21140 assert(ED->isCompleteDefinition() && "expected enum definition");
21141
21142 auto R = FlagBitsCache.try_emplace(Key: ED);
21143 llvm::APInt &FlagBits = R.first->second;
21144
21145 if (R.second) {
21146 for (auto *E : ED->enumerators()) {
21147 const auto &EVal = E->getInitVal();
21148 // Only single-bit enumerators introduce new flag values.
21149 if (EVal.isPowerOf2())
21150 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
21151 }
21152 }
21153
21154 // A value is in a flag enum if either its bits are a subset of the enum's
21155 // flag bits (the first condition) or we are allowing masks and the same is
21156 // true of its complement (the second condition). When masks are allowed, we
21157 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21158 //
21159 // While it's true that any value could be used as a mask, the assumption is
21160 // that a mask will have all of the insignificant bits set. Anything else is
21161 // likely a logic error.
21162 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
21163 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21164}
21165
21166// Emits a warning when a suspicious comparison operator is used along side
21167// binary operators in enum initializers.
21168static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
21169 const EnumDecl *Enum) {
21170 bool HasBitwiseOp = false;
21171 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21172
21173 // Iterate over all the enum values, gather suspisious comparison ops and
21174 // whether any enum initialisers contain a binary operator.
21175 for (const auto *ECD : Enum->enumerators()) {
21176 const Expr *InitExpr = ECD->getInitExpr();
21177 if (!InitExpr)
21178 continue;
21179
21180 const Expr *E = InitExpr->IgnoreParenImpCasts();
21181
21182 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
21183 BinaryOperatorKind Op = BinOp->getOpcode();
21184
21185 // Check for bitwise ops (<<, >>, &, |)
21186 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21187 HasBitwiseOp = true;
21188 } else if (Op == BO_LT || Op == BO_GT) {
21189 // Check for the typo pattern (Comparison < or >)
21190 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21191 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
21192 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21193 if (IntLiteral->getValue() == 1)
21194 SuspiciousCompares.push_back(Elt: BinOp);
21195 }
21196 }
21197 }
21198 }
21199
21200 // If we found a bitwise op and some sus compares, iterate over the compares
21201 // and warn.
21202 if (HasBitwiseOp) {
21203 for (const auto *BinOp : SuspiciousCompares) {
21204 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21205 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
21206 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
21207 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21208
21209 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
21210 << BinOp->getOpcodeStr() << SuggestedOp;
21211
21212 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
21213 << SuggestedOp
21214 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
21215 }
21216 }
21217}
21218
21219void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
21220 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21221 const ParsedAttributesView &Attrs) {
21222 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
21223 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
21224
21225 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
21226 ProcessAPINotes(D: Enum);
21227
21228 if (Enum->isDependentType()) {
21229 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21230 EnumConstantDecl *ECD =
21231 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
21232 if (!ECD) continue;
21233
21234 ECD->setType(EnumType);
21235 }
21236
21237 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
21238 return;
21239 }
21240
21241 // Verify that all the values are okay, compute the size of the values, and
21242 // reverse the list.
21243 unsigned NumNegativeBits = 0;
21244 unsigned NumPositiveBits = 0;
21245 bool MembersRepresentableByInt =
21246 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21247
21248 // Figure out the type that should be used for this enum.
21249 QualType BestType;
21250 unsigned BestWidth;
21251
21252 // C++0x N3000 [conv.prom]p3:
21253 // An rvalue of an unscoped enumeration type whose underlying
21254 // type is not fixed can be converted to an rvalue of the first
21255 // of the following types that can represent all the values of
21256 // the enumeration: int, unsigned int, long int, unsigned long
21257 // int, long long int, or unsigned long long int.
21258 // C99 6.4.4.3p2:
21259 // An identifier declared as an enumeration constant has type int.
21260 // The C99 rule is modified by C23.
21261 QualType BestPromotionType;
21262
21263 bool Packed = Enum->hasAttr<PackedAttr>();
21264 // -fshort-enums is the equivalent to specifying the packed attribute on all
21265 // enum definitions.
21266 if (LangOpts.ShortEnums)
21267 Packed = true;
21268
21269 // If the enum already has a type because it is fixed or dictated by the
21270 // target, promote that type instead of analyzing the enumerators.
21271 if (Enum->isComplete()) {
21272 BestType = Enum->getIntegerType();
21273 if (Context.isPromotableIntegerType(T: BestType))
21274 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21275 else
21276 BestPromotionType = BestType;
21277
21278 BestWidth = Context.getIntWidth(T: BestType);
21279 } else {
21280 bool EnumTooLarge = Context.computeBestEnumTypes(
21281 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21282 BestWidth = Context.getIntWidth(T: BestType);
21283 if (EnumTooLarge)
21284 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21285 }
21286
21287 // Loop over all of the enumerator constants, changing their types to match
21288 // the type of the enum if needed.
21289 for (auto *D : Elements) {
21290 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21291 if (!ECD) continue; // Already issued a diagnostic.
21292
21293 // C99 says the enumerators have int type, but we allow, as an
21294 // extension, the enumerators to be larger than int size. If each
21295 // enumerator value fits in an int, type it as an int, otherwise type it the
21296 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21297 // that X has type 'int', not 'unsigned'.
21298
21299 // Determine whether the value fits into an int.
21300 llvm::APSInt InitVal = ECD->getInitVal();
21301
21302 // If it fits into an integer type, force it. Otherwise force it to match
21303 // the enum decl type.
21304 QualType NewTy;
21305 unsigned NewWidth;
21306 bool NewSign;
21307 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21308 MembersRepresentableByInt) {
21309 // C23 6.7.3.3.3p15:
21310 // The enumeration member type for an enumerated type without fixed
21311 // underlying type upon completion is:
21312 // - int if all the values of the enumeration are representable as an
21313 // int; or,
21314 // - the enumerated type
21315 NewTy = Context.IntTy;
21316 NewWidth = Context.getTargetInfo().getIntWidth();
21317 NewSign = true;
21318 } else if (ECD->getType() == BestType) {
21319 // Already the right type!
21320 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21321 // C++ [dcl.enum]p4: Following the closing brace of an
21322 // enum-specifier, each enumerator has the type of its
21323 // enumeration.
21324 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21325 // with fixed underlying type is the enumerated type.
21326 ECD->setType(EnumType);
21327 continue;
21328 } else {
21329 NewTy = BestType;
21330 NewWidth = BestWidth;
21331 NewSign = BestType->isSignedIntegerOrEnumerationType();
21332 }
21333
21334 // Adjust the APSInt value.
21335 InitVal = InitVal.extOrTrunc(width: NewWidth);
21336 InitVal.setIsSigned(NewSign);
21337 ECD->setInitVal(C: Context, V: InitVal);
21338
21339 // Adjust the Expr initializer and type.
21340 if (ECD->getInitExpr() &&
21341 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21342 ECD->setInitExpr(ImplicitCastExpr::Create(
21343 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21344 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21345 if (getLangOpts().CPlusPlus ||
21346 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21347 // C++ [dcl.enum]p4: Following the closing brace of an
21348 // enum-specifier, each enumerator has the type of its
21349 // enumeration.
21350 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21351 // with fixed underlying type is the enumerated type.
21352 ECD->setType(EnumType);
21353 else
21354 ECD->setType(NewTy);
21355 }
21356
21357 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21358 NumPositiveBits, NumNegativeBits);
21359
21360 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21361 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21362
21363 if (Enum->isClosedFlag()) {
21364 for (Decl *D : Elements) {
21365 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21366 if (!ECD) continue; // Already issued a diagnostic.
21367
21368 llvm::APSInt InitVal = ECD->getInitVal();
21369 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21370 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21371 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21372 << ECD << Enum;
21373 }
21374 }
21375
21376 // Now that the enum type is defined, ensure it's not been underaligned.
21377 if (Enum->hasAttrs())
21378 CheckAlignasUnderalignment(D: Enum);
21379}
21380
21381Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21382 SourceLocation EndLoc) {
21383
21384 FileScopeAsmDecl *New =
21385 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21386 CurContext->addDecl(D: New);
21387 return New;
21388}
21389
21390TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21391 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21392 CurContext->addDecl(D: New);
21393 PushDeclContext(S, DC: New);
21394 PushFunctionScope();
21395 PushCompoundScope(IsStmtExpr: false);
21396 return New;
21397}
21398
21399void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21400 if (Statement)
21401 D->setStmt(Statement);
21402 PopCompoundScope();
21403 PopFunctionScopeInfo();
21404 PopDeclContext();
21405}
21406
21407void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21408 IdentifierInfo* AliasName,
21409 SourceLocation PragmaLoc,
21410 SourceLocation NameLoc,
21411 SourceLocation AliasNameLoc) {
21412 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21413 NameKind: LookupOrdinaryName);
21414 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21415 AttributeCommonInfo::Form::Pragma());
21416 AsmLabelAttr *Attr =
21417 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21418
21419 // If a declaration that:
21420 // 1) declares a function or a variable
21421 // 2) has external linkage
21422 // already exists, add a label attribute to it.
21423 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21424 if (isDeclExternC(D: PrevDecl))
21425 PrevDecl->addAttr(A: Attr);
21426 else
21427 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21428 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21429 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21430 } else
21431 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21432}
21433
21434void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21435 SourceLocation PragmaLoc,
21436 SourceLocation NameLoc) {
21437 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21438
21439 if (PrevDecl) {
21440 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21441 } else {
21442 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21443 }
21444}
21445
21446void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21447 IdentifierInfo* AliasName,
21448 SourceLocation PragmaLoc,
21449 SourceLocation NameLoc,
21450 SourceLocation AliasNameLoc) {
21451 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21452 NameKind: LookupOrdinaryName);
21453 WeakInfo W = WeakInfo(Name, NameLoc);
21454
21455 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21456 if (!PrevDecl->hasAttr<AliasAttr>())
21457 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21458 DeclApplyPragmaWeak(S: TUScope, ND, W);
21459 } else {
21460 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21461 }
21462}
21463
21464Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21465 bool Final) {
21466 assert(FD && "Expected non-null FunctionDecl");
21467
21468 // Templates are emitted when they're instantiated.
21469 if (FD->isDependentContext())
21470 return FunctionEmissionStatus::TemplateDiscarded;
21471
21472 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21473 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21474 FD->hasAttr<SYCLExternalAttr>()))
21475 return FunctionEmissionStatus::Emitted;
21476
21477 // Check whether this function is an externally visible definition.
21478 auto IsEmittedForExternalSymbol = [this, FD]() {
21479 // We have to check the GVA linkage of the function's *definition* -- if we
21480 // only have a declaration, we don't know whether or not the function will
21481 // be emitted, because (say) the definition could include "inline".
21482 const FunctionDecl *Def = FD->getDefinition();
21483
21484 // We can't compute linkage when we skip function bodies.
21485 return Def && !Def->hasSkippedBody() &&
21486 !isDiscardableGVALinkage(
21487 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21488 };
21489
21490 if (LangOpts.OpenMPIsTargetDevice) {
21491 // In OpenMP device mode we will not emit host only functions, or functions
21492 // we don't need due to their linkage.
21493 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21494 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21495 // DevTy may be changed later by
21496 // #pragma omp declare target to(*) device_type(*).
21497 // Therefore DevTy having no value does not imply host. The emission status
21498 // will be checked again at the end of compilation unit with Final = true.
21499 if (DevTy)
21500 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21501 return FunctionEmissionStatus::OMPDiscarded;
21502 // If we have an explicit value for the device type, or we are in a target
21503 // declare context, we need to emit all extern and used symbols.
21504 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21505 if (IsEmittedForExternalSymbol())
21506 return FunctionEmissionStatus::Emitted;
21507 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21508 // we'll omit it.
21509 if (Final)
21510 return FunctionEmissionStatus::OMPDiscarded;
21511 } else if (LangOpts.OpenMP > 45) {
21512 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21513 // function. In 5.0, no_host was introduced which might cause a function to
21514 // be omitted.
21515 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21516 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21517 if (DevTy)
21518 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21519 return FunctionEmissionStatus::OMPDiscarded;
21520 }
21521
21522 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21523 return FunctionEmissionStatus::Emitted;
21524
21525 if (LangOpts.CUDA) {
21526 // When compiling for device, host functions are never emitted. Similarly,
21527 // when compiling for host, device and global functions are never emitted.
21528 // (Technically, we do emit a host-side stub for global functions, but this
21529 // doesn't count for our purposes here.)
21530 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21531 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21532 return FunctionEmissionStatus::CUDADiscarded;
21533 if (!LangOpts.CUDAIsDevice &&
21534 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21535 return FunctionEmissionStatus::CUDADiscarded;
21536
21537 if (IsEmittedForExternalSymbol())
21538 return FunctionEmissionStatus::Emitted;
21539 }
21540
21541 // Otherwise, the function is known-emitted if it's in our set of
21542 // known-emitted functions.
21543 return FunctionEmissionStatus::Unknown;
21544}
21545
21546bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21547 // Host-side references to a __global__ function refer to the stub, so the
21548 // function itself is never emitted and therefore should not be marked.
21549 // If we have host fn calls kernel fn calls host+device, the HD function
21550 // does not get instantiated on the host. We model this by omitting at the
21551 // call to the kernel from the callgraph. This ensures that, when compiling
21552 // for host, only HD functions actually called from the host get marked as
21553 // known-emitted.
21554 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21555 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21556}
21557
21558bool Sema::isRedefinitionAllowedFor(NamedDecl *D,
21559 SourceLocation NewDefinitionLoc,
21560 NamedDecl **Suggested, bool &Visible) {
21561 Visible = hasVisibleDefinition(D, Suggested);
21562 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21563 // for declaratins which is attached to named modules.
21564 // We only did this if the current module is named module as we have better
21565 // diagnostics for declarations in global module and named modules.
21566 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21567 D->isInNamedModule())
21568 return false;
21569 // The redefinition of D in the **current** TU is allowed if D is invisible or
21570 // D is defined in the global module of other module units or D is defined in
21571 // the same header in a different module.
21572 return D->isInAnotherModuleUnit() || !Visible ||
21573 isFromSameSingleIncludeHeader(PrevD: D, NewLoc: NewDefinitionLoc);
21574}
21575