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 S->setEntity(DC);
1389}
1390
1391void Sema::PopDeclContext() {
1392 assert(CurContext && "DeclContext imbalance!");
1393
1394 CurContext = CurContext->getLexicalParent();
1395 assert(CurContext && "Popped translation unit!");
1396}
1397
1398Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1399 Decl *D) {
1400 // Unlike PushDeclContext, the context to which we return is not necessarily
1401 // the containing DC of TD, because the new context will be some pre-existing
1402 // TagDecl definition instead of a fresh one.
1403 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1404 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1405 assert(CurContext && "skipping definition of undefined tag");
1406 // Start lookups from the parent of the current context; we don't want to look
1407 // into the pre-existing complete definition.
1408 S->setEntity(CurContext->getLookupParent());
1409 return Result;
1410}
1411
1412void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1413 CurContext = static_cast<decltype(CurContext)>(Context);
1414}
1415
1416void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1417 // C++0x [basic.lookup.unqual]p13:
1418 // A name used in the definition of a static data member of class
1419 // X (after the qualified-id of the static member) is looked up as
1420 // if the name was used in a member function of X.
1421 // C++0x [basic.lookup.unqual]p14:
1422 // If a variable member of a namespace is defined outside of the
1423 // scope of its namespace then any name used in the definition of
1424 // the variable member (after the declarator-id) is looked up as
1425 // if the definition of the variable member occurred in its
1426 // namespace.
1427 // Both of these imply that we should push a scope whose context
1428 // is the semantic context of the declaration. We can't use
1429 // PushDeclContext here because that context is not necessarily
1430 // lexically contained in the current context. Fortunately,
1431 // the containing scope should have the appropriate information.
1432
1433 assert(!S->getEntity() && "scope already has entity");
1434
1435#ifndef NDEBUG
1436 Scope *Ancestor = S->getParent();
1437 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1438 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1439#endif
1440
1441 CurContext = DC;
1442 S->setEntity(DC);
1443
1444 if (S->getParent()->isTemplateParamScope()) {
1445 // Also set the corresponding entities for all immediately-enclosing
1446 // template parameter scopes.
1447 EnterTemplatedContext(S: S->getParent(), DC);
1448 }
1449}
1450
1451void Sema::ExitDeclaratorContext(Scope *S) {
1452 assert(S->getEntity() == CurContext && "Context imbalance!");
1453
1454 // Switch back to the lexical context. The safety of this is
1455 // enforced by an assert in EnterDeclaratorContext.
1456 Scope *Ancestor = S->getParent();
1457 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1458 CurContext = Ancestor->getEntity();
1459
1460 // We don't need to do anything with the scope, which is going to
1461 // disappear.
1462}
1463
1464void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1465 assert(S->isTemplateParamScope() &&
1466 "expected to be initializing a template parameter scope");
1467
1468 // C++20 [temp.local]p7:
1469 // In the definition of a member of a class template that appears outside
1470 // of the class template definition, the name of a member of the class
1471 // template hides the name of a template-parameter of any enclosing class
1472 // templates (but not a template-parameter of the member if the member is a
1473 // class or function template).
1474 // C++20 [temp.local]p9:
1475 // In the definition of a class template or in the definition of a member
1476 // of such a template that appears outside of the template definition, for
1477 // each non-dependent base class (13.8.2.1), if the name of the base class
1478 // or the name of a member of the base class is the same as the name of a
1479 // template-parameter, the base class name or member name hides the
1480 // template-parameter name (6.4.10).
1481 //
1482 // This means that a template parameter scope should be searched immediately
1483 // after searching the DeclContext for which it is a template parameter
1484 // scope. For example, for
1485 // template<typename T> template<typename U> template<typename V>
1486 // void N::A<T>::B<U>::f(...)
1487 // we search V then B<U> (and base classes) then U then A<T> (and base
1488 // classes) then T then N then ::.
1489 unsigned ScopeDepth = getTemplateDepth(S);
1490 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1491 DeclContext *SearchDCAfterScope = DC;
1492 for (; DC; DC = DC->getLookupParent()) {
1493 if (const TemplateParameterList *TPL =
1494 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1495 unsigned DCDepth = TPL->getDepth() + 1;
1496 if (DCDepth > ScopeDepth)
1497 continue;
1498 if (ScopeDepth == DCDepth)
1499 SearchDCAfterScope = DC = DC->getLookupParent();
1500 break;
1501 }
1502 }
1503 S->setLookupEntity(SearchDCAfterScope);
1504 }
1505}
1506
1507void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1508 // We assume that the caller has already called
1509 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1510 FunctionDecl *FD = D->getAsFunction();
1511 if (!FD)
1512 return;
1513
1514 // Same implementation as PushDeclContext, but enters the context
1515 // from the lexical parent, rather than the top-level class.
1516 assert(CurContext == FD->getLexicalParent() &&
1517 "The next DeclContext should be lexically contained in the current one.");
1518 CurContext = FD;
1519 S->setEntity(CurContext);
1520
1521 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1522 ParmVarDecl *Param = FD->getParamDecl(i: P);
1523 // If the parameter has an identifier, then add it to the scope
1524 if (Param->getIdentifier()) {
1525 S->AddDecl(D: Param);
1526 IdResolver.AddDecl(D: Param);
1527 }
1528 }
1529}
1530
1531void Sema::ActOnExitFunctionContext() {
1532 // Same implementation as PopDeclContext, but returns to the lexical parent,
1533 // rather than the top-level class.
1534 assert(CurContext && "DeclContext imbalance!");
1535 CurContext = CurContext->getLexicalParent();
1536 assert(CurContext && "Popped translation unit!");
1537}
1538
1539/// Determine whether overloading is allowed for a new function
1540/// declaration considering prior declarations of the same name.
1541///
1542/// This routine determines whether overloading is possible, not
1543/// whether a new declaration actually overloads a previous one.
1544/// It will return true in C++ (where overloads are always permitted)
1545/// or, as a C extension, when either the new declaration or a
1546/// previous one is declared with the 'overloadable' attribute.
1547static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1548 ASTContext &Context,
1549 const FunctionDecl *New) {
1550 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1551 return true;
1552
1553 // Multiversion function declarations are not overloads in the
1554 // usual sense of that term, but lookup will report that an
1555 // overload set was found if more than one multiversion function
1556 // declaration is present for the same name. It is therefore
1557 // inadequate to assume that some prior declaration(s) had
1558 // the overloadable attribute; checking is required. Since one
1559 // declaration is permitted to omit the attribute, it is necessary
1560 // to check at least two; hence the 'any_of' check below. Note that
1561 // the overloadable attribute is implicitly added to declarations
1562 // that were required to have it but did not.
1563 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1564 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1565 return ND->hasAttr<OverloadableAttr>();
1566 });
1567 } else if (Previous.getResultKind() == LookupResultKind::Found)
1568 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1569
1570 return false;
1571}
1572
1573void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1574 // Move up the scope chain until we find the nearest enclosing
1575 // non-transparent context. The declaration will be introduced into this
1576 // scope.
1577 while (S->getEntity() && S->getEntity()->isTransparentContext())
1578 S = S->getParent();
1579
1580 // Add scoped declarations into their context, so that they can be
1581 // found later. Declarations without a context won't be inserted
1582 // into any context.
1583 if (AddToContext)
1584 CurContext->addDecl(D);
1585
1586 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1587 // are function-local declarations.
1588 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1589 if (!S->getFnParent())
1590 return;
1591
1592 // Even inside a function, an out-of-line definition of a type that is
1593 // nested inside a local class must not be pushed into the enclosing
1594 // function scope. For example:
1595 //
1596 // class A { public: class B; };
1597 // class A::B {}; // out-of-line definition inside the function
1598 // B b; // must fail - only A::B is valid
1599 // Wrapper{B{}} // must also fail
1600 //
1601 // Per C++ scoping rules only the qualified form A::B is accessible.
1602 // Without this guard, PushOnScopeChains would add B to the function's
1603 // local scope, making it findable via unqualified lookup, which is
1604 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1605 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1606 // of a local class being defined out-of-line.
1607 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1608 return;
1609 }
1610
1611 // Template instantiations should also not be pushed into scope.
1612 if (isa<FunctionDecl>(Val: D) &&
1613 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1614 return;
1615
1616 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1617 S->AddDecl(D);
1618 return;
1619 }
1620 // If this replaces anything in the current scope,
1621 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1622 IEnd = IdResolver.end();
1623 for (; I != IEnd; ++I) {
1624 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1625 S->RemoveDecl(D: *I);
1626 IdResolver.RemoveDecl(D: *I);
1627
1628 // Should only need to replace one decl.
1629 break;
1630 }
1631 }
1632
1633 S->AddDecl(D);
1634
1635 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1636 // Implicitly-generated labels may end up getting generated in an order that
1637 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1638 // the label at the appropriate place in the identifier chain.
1639 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1640 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1641 if (IDC == CurContext) {
1642 if (!S->isDeclScope(D: *I))
1643 continue;
1644 } else if (IDC->Encloses(DC: CurContext))
1645 break;
1646 }
1647
1648 IdResolver.InsertDeclAfter(Pos: I, D);
1649 } else {
1650 IdResolver.AddDecl(D);
1651 }
1652 warnOnReservedIdentifier(D);
1653}
1654
1655bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1656 bool AllowInlineNamespace) const {
1657 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1658}
1659
1660Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1661 DeclContext *TargetDC = DC->getPrimaryContext();
1662 do {
1663 if (DeclContext *ScopeDC = S->getEntity())
1664 if (ScopeDC->getPrimaryContext() == TargetDC)
1665 return S;
1666 } while ((S = S->getParent()));
1667
1668 return nullptr;
1669}
1670
1671static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1672 DeclContext*,
1673 ASTContext&);
1674
1675void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1676 bool ConsiderLinkage,
1677 bool AllowInlineNamespace) {
1678 LookupResult::Filter F = R.makeFilter();
1679 while (F.hasNext()) {
1680 NamedDecl *D = F.next();
1681
1682 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1683 continue;
1684
1685 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1686 continue;
1687
1688 F.erase();
1689 }
1690
1691 F.done();
1692}
1693
1694static bool isImplicitInstantiation(NamedDecl *D) {
1695 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1696 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1697 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1698 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1699 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1700 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1701
1702 return false;
1703}
1704
1705bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1706 // [module.interface]p7:
1707 // A declaration is attached to a module as follows:
1708 // - If the declaration is a non-dependent friend declaration that nominates a
1709 // function with a declarator-id that is a qualified-id or template-id or that
1710 // nominates a class other than with an elaborated-type-specifier with neither
1711 // a nested-name-specifier nor a simple-template-id, it is attached to the
1712 // module to which the friend is attached ([basic.link]).
1713 if (New->getFriendObjectKind() &&
1714 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1715 New->setLocalOwningModule(Old->getOwningModule());
1716 makeMergedDefinitionVisible(ND: New);
1717 return false;
1718 }
1719
1720 // Although we have questions for the module ownership of implicit
1721 // instantiations, it should be sure that we shouldn't diagnose the
1722 // redeclaration of incorrect module ownership for different implicit
1723 // instantiations in different modules. We will diagnose the redeclaration of
1724 // incorrect module ownership for the template itself.
1725 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1726 return false;
1727
1728 Module *NewM = New->getOwningModule();
1729 Module *OldM = Old->getOwningModule();
1730
1731 if (NewM && NewM->isPrivateModule())
1732 NewM = NewM->Parent;
1733 if (OldM && OldM->isPrivateModule())
1734 OldM = OldM->Parent;
1735
1736 if (NewM == OldM)
1737 return false;
1738
1739 if (NewM && OldM) {
1740 // A module implementation unit has visibility of the decls in its
1741 // implicitly imported interface.
1742 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1743 return false;
1744
1745 // Partitions are part of the module, but a partition could import another
1746 // module, so verify that the PMIs agree.
1747 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1748 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1749 return false;
1750 }
1751
1752 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1753 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1754 if (NewIsModuleInterface || OldIsModuleInterface) {
1755 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1756 // if a declaration of D [...] appears in the purview of a module, all
1757 // other such declarations shall appear in the purview of the same module
1758 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1759 << New
1760 << NewIsModuleInterface
1761 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1762 << OldIsModuleInterface
1763 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1764 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1765 New->setInvalidDecl();
1766 return true;
1767 }
1768
1769 return false;
1770}
1771
1772bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1773 // [module.interface]p1:
1774 // An export-declaration shall inhabit a namespace scope.
1775 //
1776 // So it is meaningless to talk about redeclaration which is not at namespace
1777 // scope.
1778 if (!New->getLexicalDeclContext()
1779 ->getNonTransparentContext()
1780 ->isFileContext() ||
1781 !Old->getLexicalDeclContext()
1782 ->getNonTransparentContext()
1783 ->isFileContext())
1784 return false;
1785
1786 bool IsNewExported = New->isInExportDeclContext();
1787 bool IsOldExported = Old->isInExportDeclContext();
1788
1789 // It should be irrevelant if both of them are not exported.
1790 if (!IsNewExported && !IsOldExported)
1791 return false;
1792
1793 if (IsOldExported)
1794 return false;
1795
1796 // If the Old declaration are not attached to named modules
1797 // and the New declaration are attached to global module.
1798 // It should be fine to allow the export since it doesn't change
1799 // the linkage of declarations. See
1800 // https://github.com/llvm/llvm-project/issues/98583 for details.
1801 if (!Old->isInNamedModule() && New->getOwningModule() &&
1802 New->getOwningModule()->isImplicitGlobalModule())
1803 return false;
1804
1805 assert(IsNewExported);
1806
1807 auto Lk = Old->getFormalLinkage();
1808 int S = 0;
1809 if (Lk == Linkage::Internal)
1810 S = 1;
1811 else if (Lk == Linkage::Module)
1812 S = 2;
1813 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1814 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1815 return true;
1816}
1817
1818bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1819 if (CheckRedeclarationModuleOwnership(New, Old))
1820 return true;
1821
1822 if (CheckRedeclarationExported(New, Old))
1823 return true;
1824
1825 return false;
1826}
1827
1828bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1829 const NamedDecl *Old) const {
1830 assert(getASTContext().isSameEntity(New, Old) &&
1831 "New and Old are not the same definition, we should diagnostic it "
1832 "immediately instead of checking it.");
1833 assert(const_cast<Sema *>(this)->isReachable(New) &&
1834 const_cast<Sema *>(this)->isReachable(Old) &&
1835 "We shouldn't see unreachable definitions here.");
1836
1837 Module *NewM = New->getOwningModule();
1838 Module *OldM = Old->getOwningModule();
1839
1840 // We only checks for named modules here. The header like modules is skipped.
1841 // FIXME: This is not right if we import the header like modules in the module
1842 // purview.
1843 //
1844 // For example, assuming "header.h" provides definition for `D`.
1845 // ```C++
1846 // //--- M.cppm
1847 // export module M;
1848 // import "header.h"; // or #include "header.h" but import it by clang modules
1849 // actually.
1850 //
1851 // //--- Use.cpp
1852 // import M;
1853 // import "header.h"; // or uses clang modules.
1854 // ```
1855 //
1856 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1857 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1858 // reject it. But the current implementation couldn't detect the case since we
1859 // don't record the information about the importee modules.
1860 //
1861 // But this might not be painful in practice. Since the design of C++20 Named
1862 // Modules suggests us to use headers in global module fragment instead of
1863 // module purview.
1864 if (NewM && NewM->isHeaderLikeModule())
1865 NewM = nullptr;
1866 if (OldM && OldM->isHeaderLikeModule())
1867 OldM = nullptr;
1868
1869 if (!NewM && !OldM)
1870 return true;
1871
1872 // [basic.def.odr]p14.3
1873 // Each such definition shall not be attached to a named module
1874 // ([module.unit]).
1875 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1876 return true;
1877
1878 // Then New and Old lives in the same TU if their share one same module unit.
1879 if (NewM)
1880 NewM = NewM->getTopLevelModule();
1881 if (OldM)
1882 OldM = OldM->getTopLevelModule();
1883 return OldM == NewM;
1884}
1885
1886static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1887 if (D->getDeclContext()->isFileContext())
1888 return false;
1889
1890 return isa<UsingShadowDecl>(Val: D) ||
1891 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1892 isa<UnresolvedUsingValueDecl>(Val: D);
1893}
1894
1895/// Removes using shadow declarations not at class scope from the lookup
1896/// results.
1897static void RemoveUsingDecls(LookupResult &R) {
1898 LookupResult::Filter F = R.makeFilter();
1899 while (F.hasNext())
1900 if (isUsingDeclNotAtClassScope(D: F.next()))
1901 F.erase();
1902
1903 F.done();
1904}
1905
1906/// Check for this common pattern:
1907/// @code
1908/// class S {
1909/// S(const S&); // DO NOT IMPLEMENT
1910/// void operator=(const S&); // DO NOT IMPLEMENT
1911/// };
1912/// @endcode
1913static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1914 // FIXME: Should check for private access too but access is set after we get
1915 // the decl here.
1916 if (D->doesThisDeclarationHaveABody())
1917 return false;
1918
1919 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1920 return CD->isCopyConstructor();
1921 return D->isCopyAssignmentOperator();
1922}
1923
1924bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1925 const DeclContext *DC = D->getDeclContext();
1926 while (!DC->isTranslationUnit()) {
1927 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1928 if (!RD->hasNameForLinkage())
1929 return true;
1930 }
1931 DC = DC->getParent();
1932 }
1933
1934 return !D->isExternallyVisible();
1935}
1936
1937bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1938 assert(D);
1939
1940 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1941 return false;
1942
1943 // Ignore all entities declared within templates, and out-of-line definitions
1944 // of members of class templates.
1945 if (D->getDeclContext()->isDependentContext() ||
1946 D->getLexicalDeclContext()->isDependentContext())
1947 return false;
1948
1949 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1950 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1951 return false;
1952 // A non-out-of-line declaration of a member specialization was implicitly
1953 // instantiated; it's the out-of-line declaration that we're interested in.
1954 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1955 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1956 return false;
1957
1958 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1959 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1960 return false;
1961 } else {
1962 // 'static inline' functions are defined in headers; don't warn.
1963 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1964 return false;
1965 }
1966
1967 if (FD->doesThisDeclarationHaveABody() &&
1968 Context.DeclMustBeEmitted(D: FD))
1969 return false;
1970 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1971 // Constants and utility variables are defined in headers with internal
1972 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1973 // like "inline".)
1974 if (!isMainFileLoc(Loc: VD->getLocation()))
1975 return false;
1976
1977 if (Context.DeclMustBeEmitted(D: VD))
1978 return false;
1979
1980 if (VD->isStaticDataMember() &&
1981 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1982 return false;
1983 if (VD->isStaticDataMember() &&
1984 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1985 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1986 return false;
1987
1988 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
1989 return false;
1990 } else {
1991 return false;
1992 }
1993
1994 // Only warn for unused decls internal to the translation unit.
1995 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1996 // for inline functions defined in the main source file, for instance.
1997 return mightHaveNonExternalLinkage(D);
1998}
1999
2000void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2001 if (!D)
2002 return;
2003
2004 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2005 const FunctionDecl *First = FD->getFirstDecl();
2006 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2007 return; // First should already be in the vector.
2008 }
2009
2010 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2011 const VarDecl *First = VD->getFirstDecl();
2012 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2013 return; // First should already be in the vector.
2014 }
2015
2016 if (ShouldWarnIfUnusedFileScopedDecl(D))
2017 UnusedFileScopedDecls.push_back(LocalValue: D);
2018}
2019
2020static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2021 const NamedDecl *D) {
2022 if (D->isInvalidDecl())
2023 return false;
2024
2025 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2026 // For a decomposition declaration, warn if none of the bindings are
2027 // referenced, instead of if the variable itself is referenced (which
2028 // it is, by the bindings' expressions).
2029 bool IsAllIgnored = true;
2030 for (const auto *BD : DD->bindings()) {
2031 if (BD->isReferenced())
2032 return false;
2033 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2034 BD->hasAttr<UnusedAttr>());
2035 }
2036 if (IsAllIgnored)
2037 return false;
2038 } else if (!D->getDeclName()) {
2039 return false;
2040 } else if (D->isReferenced() || D->isUsed()) {
2041 return false;
2042 }
2043
2044 if (D->isPlaceholderVar(LangOpts))
2045 return false;
2046
2047 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2048 D->hasAttr<CleanupAttr>())
2049 return false;
2050
2051 if (isa<LabelDecl>(Val: D))
2052 return true;
2053
2054 // Except for labels, we only care about unused decls that are local to
2055 // functions.
2056 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2057 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2058 // For dependent types, the diagnostic is deferred.
2059 WithinFunction =
2060 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2061 if (!WithinFunction)
2062 return false;
2063
2064 if (isa<TypedefNameDecl>(Val: D))
2065 return true;
2066
2067 // White-list anything that isn't a local variable.
2068 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2069 return false;
2070
2071 // Types of valid local variables should be complete, so this should succeed.
2072 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2073
2074 const Expr *Init = VD->getInit();
2075 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2076 Init = Cleanups->getSubExpr();
2077
2078 const auto *Ty = VD->getType().getTypePtr();
2079
2080 // Only look at the outermost level of typedef.
2081 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2082 // Allow anything marked with __attribute__((unused)).
2083 if (TT->getDecl()->hasAttr<UnusedAttr>())
2084 return false;
2085 }
2086
2087 // Warn for reference variables whose initializtion performs lifetime
2088 // extension.
2089 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2090 MTE && MTE->getExtendingDecl()) {
2091 Ty = VD->getType().getNonReferenceType().getTypePtr();
2092 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2093 }
2094
2095 // If we failed to complete the type for some reason, or if the type is
2096 // dependent, don't diagnose the variable.
2097 if (Ty->isIncompleteType() || Ty->isDependentType())
2098 return false;
2099
2100 // Look at the element type to ensure that the warning behaviour is
2101 // consistent for both scalars and arrays.
2102 Ty = Ty->getBaseElementTypeUnsafe();
2103
2104 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2105 if (Tag->hasAttr<UnusedAttr>())
2106 return false;
2107
2108 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2109 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2110 return false;
2111
2112 if (Init) {
2113 const auto *Construct =
2114 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2115 if (Construct && !Construct->isElidable()) {
2116 const CXXConstructorDecl *CD = Construct->getConstructor();
2117 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2118 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2119 return false;
2120 }
2121
2122 // Suppress the warning if we don't know how this is constructed, and
2123 // it could possibly be non-trivial constructor.
2124 if (Init->isTypeDependent()) {
2125 for (const CXXConstructorDecl *Ctor : RD->ctors())
2126 if (!Ctor->isTrivial())
2127 return false;
2128 }
2129
2130 // Suppress the warning if the constructor is unresolved because
2131 // its arguments are dependent.
2132 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2133 return false;
2134 }
2135 }
2136 }
2137
2138 // TODO: __attribute__((unused)) templates?
2139 }
2140
2141 return true;
2142}
2143
2144static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2145 FixItHint &Hint) {
2146 if (isa<LabelDecl>(Val: D)) {
2147 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2148 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2149 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2150 if (AfterColon.isInvalid())
2151 return;
2152 Hint = FixItHint::CreateRemoval(
2153 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2154 }
2155}
2156
2157void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2158 DiagnoseUnusedNestedTypedefs(
2159 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2160}
2161
2162void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2163 DiagReceiverTy DiagReceiver) {
2164 if (D->isDependentType())
2165 return;
2166
2167 for (auto *TmpD : D->decls()) {
2168 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2169 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2170 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2171 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2172 }
2173}
2174
2175void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2176 DiagnoseUnusedDecl(
2177 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2178}
2179
2180void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2181 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2182 return;
2183
2184 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2185 // typedefs can be referenced later on, so the diagnostics are emitted
2186 // at end-of-translation-unit.
2187 UnusedLocalTypedefNameCandidates.insert(X: TD);
2188 return;
2189 }
2190
2191 FixItHint Hint;
2192 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2193
2194 unsigned DiagID;
2195 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2196 DiagID = diag::warn_unused_exception_param;
2197 else if (isa<LabelDecl>(Val: D))
2198 DiagID = diag::warn_unused_label;
2199 else
2200 DiagID = diag::warn_unused_variable;
2201
2202 SourceLocation DiagLoc = D->getLocation();
2203 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2204}
2205
2206void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2207 DiagReceiverTy DiagReceiver) {
2208 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2209 // it's not really unused.
2210 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2211 return;
2212
2213 // In C++, `_` variables behave as if they were maybe_unused
2214 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2215 return;
2216
2217 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2218
2219 if (Ty->isReferenceType() || Ty->isDependentType())
2220 return;
2221
2222 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2223 if (Tag->hasAttr<UnusedAttr>())
2224 return;
2225 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2226 // mimic gcc's behavior.
2227 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2228 RD && !RD->hasAttr<WarnUnusedAttr>())
2229 return;
2230 }
2231
2232 // Don't warn on volatile file-scope variables. They are visible beyond their
2233 // declaring function and writes to them could be observable side effects.
2234 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2235 return;
2236
2237 // Don't warn about __block Objective-C pointer variables, as they might
2238 // be assigned in the block but not used elsewhere for the purpose of lifetime
2239 // extension.
2240 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2241 return;
2242
2243 // Don't warn about Objective-C pointer variables with precise lifetime
2244 // semantics; they can be used to ensure ARC releases the object at a known
2245 // time, which may mean assignment but no other references.
2246 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2247 return;
2248
2249 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2250 if (iter == RefsMinusAssignments.end())
2251 return;
2252
2253 assert(iter->getSecond() >= 0 &&
2254 "Found a negative number of references to a VarDecl");
2255 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2256 // Assume the given VarDecl is "used" if its ref count stored in
2257 // `RefMinusAssignments` is positive, with one exception.
2258 //
2259 // For a C++ variable whose decl (with initializer) entirely consist the
2260 // condition expression of a if/while/for construct,
2261 // Clang creates a DeclRefExpr for the condition expression rather than a
2262 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2263 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2264 // used in the body of the if/while/for construct.
2265 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2266 if (!UnusedCXXCondDecl)
2267 return;
2268 }
2269
2270 unsigned DiagID;
2271 if (isa<ParmVarDecl>(Val: VD))
2272 DiagID = diag::warn_unused_but_set_parameter;
2273 else if (VD->isFileVarDecl())
2274 DiagID = diag::warn_unused_but_set_global;
2275 else
2276 DiagID = diag::warn_unused_but_set_variable;
2277 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2278}
2279
2280static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2281 Sema::DiagReceiverTy DiagReceiver) {
2282 // Verify that we have no forward references left. If so, there was a goto
2283 // or address of a label taken, but no definition of it. Label fwd
2284 // definitions are indicated with a null substmt which is also not a resolved
2285 // MS inline assembly label name.
2286 bool Diagnose = false;
2287 if (L->isMSAsmLabel())
2288 Diagnose = !L->isResolvedMSAsmLabel();
2289 else
2290 Diagnose = L->getStmt() == nullptr;
2291 if (Diagnose)
2292 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2293 << L);
2294}
2295
2296void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2297 S->applyNRVO();
2298
2299 if (S->decl_empty()) return;
2300 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2301 "Scope shouldn't contain decls!");
2302
2303 /// We visit the decls in non-deterministic order, but we want diagnostics
2304 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2305 /// and sort the diagnostics before emitting them, after we visited all decls.
2306 struct LocAndDiag {
2307 SourceLocation Loc;
2308 std::optional<SourceLocation> PreviousDeclLoc;
2309 PartialDiagnostic PD;
2310 };
2311 SmallVector<LocAndDiag, 16> DeclDiags;
2312 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2313 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2314 };
2315 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2316 SourceLocation PreviousDeclLoc,
2317 PartialDiagnostic PD) {
2318 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2319 };
2320
2321 for (auto *TmpD : S->decls()) {
2322 assert(TmpD && "This decl didn't get pushed??");
2323
2324 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2325 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2326
2327 // Diagnose unused variables in this scope.
2328 if (!S->hasUnrecoverableErrorOccurred()) {
2329 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2330 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2331 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2332 // Wait until end of TU to diagnose internal linkage file vars.
2333 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2334 VD && !VD->isInternalLinkageFileVar()) {
2335 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2336 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2337 }
2338 }
2339
2340 if (!D->getDeclName()) continue;
2341
2342 // If this was a forward reference to a label, verify it was defined.
2343 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2344 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2345
2346 // Partial translation units that are created in incremental processing must
2347 // not clean up the IdResolver because PTUs should take into account the
2348 // declarations that came from previous PTUs.
2349 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2350 getLangOpts().CPlusPlus)
2351 IdResolver.RemoveDecl(D);
2352
2353 // Warn on it if we are shadowing a declaration.
2354 auto ShadowI = ShadowingDecls.find(Val: D);
2355 if (ShadowI != ShadowingDecls.end()) {
2356 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2357 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2358 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2359 << D << FD << FD->getParent());
2360 }
2361 ShadowingDecls.erase(I: ShadowI);
2362 }
2363 }
2364
2365 llvm::sort(C&: DeclDiags,
2366 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2367 // The particular order for diagnostics is not important, as long
2368 // as the order is deterministic. Using the raw location is going
2369 // to generally be in source order unless there are macro
2370 // expansions involved.
2371 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2372 });
2373 for (const LocAndDiag &D : DeclDiags) {
2374 Diag(Loc: D.Loc, PD: D.PD);
2375 if (D.PreviousDeclLoc)
2376 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2377 }
2378}
2379
2380Scope *Sema::getNonFieldDeclScope(Scope *S) {
2381 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2382 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2383 (S->isClassScope() && !getLangOpts().CPlusPlus))
2384 S = S->getParent();
2385 return S;
2386}
2387
2388static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2389 ASTContext::GetBuiltinTypeError Error) {
2390 switch (Error) {
2391 case ASTContext::GE_None:
2392 return "";
2393 case ASTContext::GE_Missing_type:
2394 return BuiltinInfo.getHeaderName(ID);
2395 case ASTContext::GE_Missing_stdio:
2396 return "stdio.h";
2397 case ASTContext::GE_Missing_setjmp:
2398 return "setjmp.h";
2399 case ASTContext::GE_Missing_ucontext:
2400 return "ucontext.h";
2401 }
2402 llvm_unreachable("unhandled error kind");
2403}
2404
2405FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2406 unsigned ID, SourceLocation Loc) {
2407 DeclContext *Parent = Context.getTranslationUnitDecl();
2408
2409 if (getLangOpts().CPlusPlus) {
2410 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2411 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2412 CLinkageDecl->setImplicit();
2413 Parent->addDecl(D: CLinkageDecl);
2414 Parent = CLinkageDecl;
2415 }
2416
2417 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2418 if (Context.BuiltinInfo.isImmediate(ID)) {
2419 assert(getLangOpts().CPlusPlus20 &&
2420 "consteval builtins should only be available in C++20 mode");
2421 ConstexprKind = ConstexprSpecKind::Consteval;
2422 }
2423
2424 FunctionDecl *New = FunctionDecl::Create(
2425 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2426 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2427 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2428 New->setImplicit();
2429 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2430
2431 // Create Decl objects for each parameter, adding them to the
2432 // FunctionDecl.
2433 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2434 SmallVector<ParmVarDecl *, 16> Params;
2435 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2436 ParmVarDecl *parm = ParmVarDecl::Create(
2437 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2438 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2439 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2440 Params.push_back(Elt: parm);
2441 }
2442 New->setParams(Params);
2443 }
2444
2445 AddKnownFunctionAttributes(FD: New);
2446 return New;
2447}
2448
2449NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2450 Scope *S, bool ForRedeclaration,
2451 SourceLocation Loc) {
2452 LookupNecessaryTypesForBuiltin(S, ID);
2453
2454 ASTContext::GetBuiltinTypeError Error;
2455 QualType R = Context.GetBuiltinType(ID, Error);
2456 if (Error) {
2457 if (!ForRedeclaration)
2458 return nullptr;
2459
2460 // If we have a builtin without an associated type we should not emit a
2461 // warning when we were not able to find a type for it.
2462 if (Error == ASTContext::GE_Missing_type ||
2463 Context.BuiltinInfo.allowTypeMismatch(ID))
2464 return nullptr;
2465
2466 // If we could not find a type for setjmp it is because the jmp_buf type was
2467 // not defined prior to the setjmp declaration.
2468 if (Error == ASTContext::GE_Missing_setjmp) {
2469 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2470 << Context.BuiltinInfo.getName(ID);
2471 return nullptr;
2472 }
2473
2474 // Generally, we emit a warning that the declaration requires the
2475 // appropriate header.
2476 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2477 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2478 << Context.BuiltinInfo.getName(ID);
2479 return nullptr;
2480 }
2481
2482 if (!ForRedeclaration &&
2483 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2484 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2485 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2486 : diag::ext_implicit_lib_function_decl)
2487 << Context.BuiltinInfo.getName(ID) << R;
2488 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2489 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2490 << Header << Context.BuiltinInfo.getName(ID);
2491 }
2492
2493 if (R.isNull())
2494 return nullptr;
2495
2496 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2497 RegisterLocallyScopedExternCDecl(ND: New, S);
2498
2499 // TUScope is the translation-unit scope to insert this function into.
2500 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2501 // relate Scopes to DeclContexts, and probably eliminate CurContext
2502 // entirely, but we're not there yet.
2503 DeclContext *SavedContext = CurContext;
2504 CurContext = New->getDeclContext();
2505 PushOnScopeChains(D: New, S: TUScope);
2506 CurContext = SavedContext;
2507 return New;
2508}
2509
2510/// Typedef declarations don't have linkage, but they still denote the same
2511/// entity if their types are the same.
2512/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2513/// isSameEntity.
2514static void
2515filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2516 LookupResult &Previous) {
2517 // This is only interesting when modules are enabled.
2518 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2519 return;
2520
2521 // Empty sets are uninteresting.
2522 if (Previous.empty())
2523 return;
2524
2525 LookupResult::Filter Filter = Previous.makeFilter();
2526 while (Filter.hasNext()) {
2527 NamedDecl *Old = Filter.next();
2528
2529 // Non-hidden declarations are never ignored.
2530 if (S.isVisible(D: Old))
2531 continue;
2532
2533 // Declarations of the same entity are not ignored, even if they have
2534 // different linkages.
2535 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2536 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2537 T2: Decl->getUnderlyingType()))
2538 continue;
2539
2540 // If both declarations give a tag declaration a typedef name for linkage
2541 // purposes, then they declare the same entity.
2542 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2543 Decl->getAnonDeclWithTypedefName())
2544 continue;
2545 }
2546
2547 Filter.erase();
2548 }
2549
2550 Filter.done();
2551}
2552
2553bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2554 QualType OldType;
2555 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2556 OldType = OldTypedef->getUnderlyingType();
2557 else
2558 OldType = Context.getTypeDeclType(Decl: Old);
2559 QualType NewType = New->getUnderlyingType();
2560
2561 if (NewType->isVariablyModifiedType()) {
2562 // Must not redefine a typedef with a variably-modified type.
2563 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2564 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2565 << Kind << NewType;
2566 if (Old->getLocation().isValid())
2567 notePreviousDefinition(Old, New: New->getLocation());
2568 New->setInvalidDecl();
2569 return true;
2570 }
2571
2572 if (OldType != NewType &&
2573 !OldType->isDependentType() &&
2574 !NewType->isDependentType() &&
2575 !Context.hasSameType(T1: OldType, T2: NewType)) {
2576 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2577 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2578 << Kind << NewType << OldType;
2579 if (Old->getLocation().isValid())
2580 notePreviousDefinition(Old, New: New->getLocation());
2581 New->setInvalidDecl();
2582 return true;
2583 }
2584 return false;
2585}
2586
2587void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2588 LookupResult &OldDecls) {
2589 // If the new decl is known invalid already, don't bother doing any
2590 // merging checks.
2591 if (New->isInvalidDecl()) return;
2592
2593 // Allow multiple definitions for ObjC built-in typedefs.
2594 // FIXME: Verify the underlying types are equivalent!
2595 if (getLangOpts().ObjC) {
2596 const IdentifierInfo *TypeID = New->getIdentifier();
2597 switch (TypeID->getLength()) {
2598 default: break;
2599 case 2:
2600 {
2601 if (!TypeID->isStr(Str: "id"))
2602 break;
2603 QualType T = New->getUnderlyingType();
2604 if (!T->isPointerType())
2605 break;
2606 if (!T->isVoidPointerType()) {
2607 QualType PT = T->castAs<PointerType>()->getPointeeType();
2608 if (!PT->isStructureType())
2609 break;
2610 }
2611 Context.setObjCIdRedefinitionType(T);
2612 // Install the built-in type for 'id', ignoring the current definition.
2613 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2614 modedTy: Context.getObjCIdType());
2615 return;
2616 }
2617 case 5:
2618 if (!TypeID->isStr(Str: "Class"))
2619 break;
2620 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2621 // Install the built-in type for 'Class', ignoring the current definition.
2622 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2623 modedTy: Context.getObjCClassType());
2624 return;
2625 case 3:
2626 if (!TypeID->isStr(Str: "SEL"))
2627 break;
2628 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2629 // Install the built-in type for 'SEL', ignoring the current definition.
2630 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2631 modedTy: Context.getObjCSelType());
2632 return;
2633 }
2634 // Fall through - the typedef name was not a builtin type.
2635 }
2636
2637 // Verify the old decl was also a type.
2638 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2639 if (!Old) {
2640 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2641 << New->getDeclName();
2642
2643 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2644 if (OldD->getLocation().isValid())
2645 notePreviousDefinition(Old: OldD, New: New->getLocation());
2646
2647 return New->setInvalidDecl();
2648 }
2649
2650 // If the old declaration is invalid, just give up here.
2651 if (Old->isInvalidDecl())
2652 return New->setInvalidDecl();
2653
2654 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2655 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2656 auto *NewTag = New->getAnonDeclWithTypedefName();
2657 NamedDecl *Hidden = nullptr;
2658 if (OldTag && NewTag &&
2659 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2660 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2661 // There is a definition of this tag, but it is not visible. Use it
2662 // instead of our tag.
2663 if (OldTD->isModed())
2664 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2665 modedTy: OldTD->getUnderlyingType());
2666 else
2667 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2668
2669 // Make the old tag definition visible.
2670 makeMergedDefinitionVisible(ND: Hidden);
2671
2672 CleanupMergedEnum(S, New: NewTag);
2673 }
2674 }
2675
2676 // If the typedef types are not identical, reject them in all languages and
2677 // with any extensions enabled.
2678 if (isIncompatibleTypedef(Old, New))
2679 return;
2680
2681 // The types match. Link up the redeclaration chain and merge attributes if
2682 // the old declaration was a typedef.
2683 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2684 New->setPreviousDecl(Typedef);
2685 mergeDeclAttributes(New, Old);
2686 }
2687
2688 if (getLangOpts().MicrosoftExt)
2689 return;
2690
2691 if (getLangOpts().CPlusPlus) {
2692 // C++ [dcl.typedef]p2:
2693 // In a given non-class scope, a typedef specifier can be used to
2694 // redefine the name of any type declared in that scope to refer
2695 // to the type to which it already refers.
2696 if (!isa<CXXRecordDecl>(Val: CurContext))
2697 return;
2698
2699 // C++0x [dcl.typedef]p4:
2700 // In a given class scope, a typedef specifier can be used to redefine
2701 // any class-name declared in that scope that is not also a typedef-name
2702 // to refer to the type to which it already refers.
2703 //
2704 // This wording came in via DR424, which was a correction to the
2705 // wording in DR56, which accidentally banned code like:
2706 //
2707 // struct S {
2708 // typedef struct A { } A;
2709 // };
2710 //
2711 // in the C++03 standard. We implement the C++0x semantics, which
2712 // allow the above but disallow
2713 //
2714 // struct S {
2715 // typedef int I;
2716 // typedef int I;
2717 // };
2718 //
2719 // since that was the intent of DR56.
2720 if (!isa<TypedefNameDecl>(Val: Old))
2721 return;
2722
2723 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2724 << New->getDeclName();
2725 notePreviousDefinition(Old, New: New->getLocation());
2726 return New->setInvalidDecl();
2727 }
2728
2729 // Modules always permit redefinition of typedefs, as does C11.
2730 if (getLangOpts().Modules || getLangOpts().C11)
2731 return;
2732
2733 // If we have a redefinition of a typedef in C, emit a warning. This warning
2734 // is normally mapped to an error, but can be controlled with
2735 // -Wtypedef-redefinition. If either the original or the redefinition is
2736 // in a system header, don't emit this for compatibility with GCC.
2737 if (getDiagnostics().getSuppressSystemWarnings() &&
2738 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2739 (Old->isImplicit() ||
2740 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2741 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2742 return;
2743
2744 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2745 << New->getDeclName();
2746 notePreviousDefinition(Old, New: New->getLocation());
2747}
2748
2749void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2750 // If this was an unscoped enumeration, yank all of its enumerators
2751 // out of the scope.
2752 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2753 Scope *EnumScope = getNonFieldDeclScope(S);
2754 for (auto *ECD : ED->enumerators()) {
2755 assert(EnumScope->isDeclScope(ECD));
2756 EnumScope->RemoveDecl(D: ECD);
2757 IdResolver.RemoveDecl(D: ECD);
2758 }
2759 }
2760}
2761
2762/// DeclhasAttr - returns true if decl Declaration already has the target
2763/// attribute.
2764static bool DeclHasAttr(const Decl *D, const Attr *A) {
2765 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2766 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2767 for (const auto *i : D->attrs())
2768 if (i->getKind() == A->getKind()) {
2769 if (Ann) {
2770 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2771 return true;
2772 continue;
2773 }
2774 // FIXME: Don't hardcode this check
2775 if (OA && isa<OwnershipAttr>(Val: i))
2776 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2777 return true;
2778 }
2779
2780 return false;
2781}
2782
2783static bool isAttributeTargetADefinition(Decl *D) {
2784 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2785 return VD->isThisDeclarationADefinition();
2786 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2787 return TD->isCompleteDefinition() || TD->isBeingDefined();
2788 return true;
2789}
2790
2791/// Merge alignment attributes from \p Old to \p New, taking into account the
2792/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2793///
2794/// \return \c true if any attributes were added to \p New.
2795static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2796 // Look for alignas attributes on Old, and pick out whichever attribute
2797 // specifies the strictest alignment requirement.
2798 AlignedAttr *OldAlignasAttr = nullptr;
2799 AlignedAttr *OldStrictestAlignAttr = nullptr;
2800 unsigned OldAlign = 0;
2801 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2802 // FIXME: We have no way of representing inherited dependent alignments
2803 // in a case like:
2804 // template<int A, int B> struct alignas(A) X;
2805 // template<int A, int B> struct alignas(B) X {};
2806 // For now, we just ignore any alignas attributes which are not on the
2807 // definition in such a case.
2808 if (I->isAlignmentDependent())
2809 return false;
2810
2811 if (I->isAlignas())
2812 OldAlignasAttr = I;
2813
2814 unsigned Align = I->getAlignment(Ctx&: S.Context);
2815 if (Align > OldAlign) {
2816 OldAlign = Align;
2817 OldStrictestAlignAttr = I;
2818 }
2819 }
2820
2821 // Look for alignas attributes on New.
2822 AlignedAttr *NewAlignasAttr = nullptr;
2823 unsigned NewAlign = 0;
2824 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2825 if (I->isAlignmentDependent())
2826 return false;
2827
2828 if (I->isAlignas())
2829 NewAlignasAttr = I;
2830
2831 unsigned Align = I->getAlignment(Ctx&: S.Context);
2832 if (Align > NewAlign)
2833 NewAlign = Align;
2834 }
2835
2836 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2837 // Both declarations have 'alignas' attributes. We require them to match.
2838 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2839 // fall short. (If two declarations both have alignas, they must both match
2840 // every definition, and so must match each other if there is a definition.)
2841
2842 // If either declaration only contains 'alignas(0)' specifiers, then it
2843 // specifies the natural alignment for the type.
2844 if (OldAlign == 0 || NewAlign == 0) {
2845 QualType Ty;
2846 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2847 Ty = VD->getType();
2848 else
2849 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2850
2851 if (OldAlign == 0)
2852 OldAlign = S.Context.getTypeAlign(T: Ty);
2853 if (NewAlign == 0)
2854 NewAlign = S.Context.getTypeAlign(T: Ty);
2855 }
2856
2857 if (OldAlign != NewAlign) {
2858 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2859 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2860 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2861 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2862 }
2863 }
2864
2865 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2866 // C++11 [dcl.align]p6:
2867 // if any declaration of an entity has an alignment-specifier,
2868 // every defining declaration of that entity shall specify an
2869 // equivalent alignment.
2870 // C11 6.7.5/7:
2871 // If the definition of an object does not have an alignment
2872 // specifier, any other declaration of that object shall also
2873 // have no alignment specifier.
2874 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2875 << OldAlignasAttr;
2876 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2877 << OldAlignasAttr;
2878 }
2879
2880 bool AnyAdded = false;
2881
2882 // Ensure we have an attribute representing the strictest alignment.
2883 if (OldAlign > NewAlign) {
2884 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2885 Clone->setInherited(true);
2886 New->addAttr(A: Clone);
2887 AnyAdded = true;
2888 }
2889
2890 // Ensure we have an alignas attribute if the old declaration had one.
2891 if (OldAlignasAttr && !NewAlignasAttr &&
2892 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2893 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2894 Clone->setInherited(true);
2895 New->addAttr(A: Clone);
2896 AnyAdded = true;
2897 }
2898
2899 return AnyAdded;
2900}
2901
2902#define WANT_DECL_MERGE_LOGIC
2903#include "clang/Sema/AttrParsedAttrImpl.inc"
2904#undef WANT_DECL_MERGE_LOGIC
2905
2906static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2907 const InheritableAttr *Attr,
2908 AvailabilityMergeKind AMK) {
2909 // Diagnose any mutual exclusions between the attribute that we want to add
2910 // and attributes that already exist on the declaration.
2911 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2912 return false;
2913
2914 // This function copies an attribute Attr from a previous declaration to the
2915 // new declaration D if the new declaration doesn't itself have that attribute
2916 // yet or if that attribute allows duplicates.
2917 // If you're adding a new attribute that requires logic different from
2918 // "use explicit attribute on decl if present, else use attribute from
2919 // previous decl", for example if the attribute needs to be consistent
2920 // between redeclarations, you need to call a custom merge function here.
2921 InheritableAttr *NewAttr = nullptr;
2922 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2923 const IdentifierInfo *InferredPlatformII = nullptr;
2924 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2925 InferredPlatformII = Inf->getPlatform();
2926 NewAttr = S.mergeAndInferAvailabilityAttr(
2927 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2928 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2929 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2930 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2931 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2932 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2933 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2934 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2935 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2936 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2937 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2938 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2939 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2940 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2941 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2942 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2943 FirstArg: FA->getFirstArg());
2944 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2945 NewAttr = S.mergeFormatMatchesAttr(
2946 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2947 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2948 NewAttr = S.mergeModularFormatAttr(
2949 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2950 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2951 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2952 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2953 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2954 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2955 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2956 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2957 Model: IA->getInheritanceModel());
2958 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2959 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2960 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2961 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2962 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2963 isa<CUDAGlobalAttr>(Val: Attr))) {
2964 // CUDA target attributes are part of function signature for
2965 // overloading purposes and must not be merged.
2966 return false;
2967 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2968 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2969 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2970 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2971 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2972 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2973 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2974 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2975 else if (isa<AlignedAttr>(Val: Attr))
2976 // AlignedAttrs are handled separately, because we need to handle all
2977 // such attributes on a declaration at the same time.
2978 NewAttr = nullptr;
2979 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2980 (AMK == AvailabilityMergeKind::Override ||
2981 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2982 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2983 NewAttr = nullptr;
2984 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2985 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2986 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2987 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2988 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2989 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2990 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2991 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2992 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2993 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2994 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2995 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2996 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2997 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2998 Z: NT->getZ());
2999 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3000 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3001 Preferred: WS->getPreferred(),
3002 SpelledArgsCount: WS->getSpelledArgsCount());
3003 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3004 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3005 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3006 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3007 else if (isa<SuppressAttr>(Val: Attr))
3008 // Do nothing. Each redeclaration should be suppressed separately.
3009 NewAttr = nullptr;
3010 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3011 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3012 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3013 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3014 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3015 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3016
3017 if (NewAttr) {
3018 NewAttr->setInherited(true);
3019 D->addAttr(A: NewAttr);
3020 if (isa<MSInheritanceAttr>(Val: NewAttr))
3021 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3022 return true;
3023 }
3024
3025 return false;
3026}
3027
3028static const NamedDecl *getDefinition(const Decl *D) {
3029 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3030 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3031 return Def;
3032 return nullptr;
3033 }
3034 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3035 const VarDecl *Def = VD->getDefinition();
3036 if (Def)
3037 return Def;
3038 return VD->getActingDefinition();
3039 }
3040 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3041 const FunctionDecl *Def = nullptr;
3042 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3043 return Def;
3044 }
3045 return nullptr;
3046}
3047
3048static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3049 for (const auto *Attribute : D->attrs())
3050 if (Attribute->getKind() == Kind)
3051 return true;
3052 return false;
3053}
3054
3055/// checkNewAttributesAfterDef - If we already have a definition, check that
3056/// there are no new attributes in this declaration.
3057static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3058 if (!New->hasAttrs())
3059 return;
3060
3061 const NamedDecl *Def = getDefinition(D: Old);
3062 if (!Def || Def == New)
3063 return;
3064
3065 AttrVec &NewAttributes = New->getAttrs();
3066 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3067 Attr *NewAttribute = NewAttributes[I];
3068
3069 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3071 SkipBodyInfo SkipBody;
3072 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3073
3074 // If we're skipping this definition, drop the "alias" attribute.
3075 if (SkipBody.ShouldSkip) {
3076 NewAttributes.erase(CI: NewAttributes.begin() + I);
3077 --E;
3078 continue;
3079 }
3080 } else {
3081 VarDecl *VD = cast<VarDecl>(Val: New);
3082 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3083 VarDecl::TentativeDefinition
3084 ? diag::err_alias_after_tentative
3085 : diag::err_redefinition;
3086 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3087 if (Diag == diag::err_redefinition)
3088 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3089 else
3090 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3091 VD->setInvalidDecl();
3092 }
3093 ++I;
3094 continue;
3095 }
3096
3097 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3098 // Tentative definitions are only interesting for the alias check above.
3099 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3100 ++I;
3101 continue;
3102 }
3103 }
3104
3105 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3106 ++I;
3107 continue; // regular attr merging will take care of validating this.
3108 }
3109
3110 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3111 // C's _Noreturn is allowed to be added to a function after it is defined.
3112 ++I;
3113 continue;
3114 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3115 // msvc will allow a subsequent definition to add an uuid to a class
3116 ++I;
3117 continue;
3118 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3119 Val: NewAttribute) &&
3120 NewAttribute->isStandardAttributeSyntax()) {
3121 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3122 // deprecated attribute can later be re-declared with the attribute and
3123 // vice-versa.
3124 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3125 // maybe_unused attribute can later be redeclared with the attribute and
3126 // vice versa.
3127 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3128 // nodiscard attribute can later be redeclared with the attribute and
3129 // vice-versa.
3130 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3131 ++I;
3132 continue;
3133 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3134 if (AA->isAlignas()) {
3135 // C++11 [dcl.align]p6:
3136 // if any declaration of an entity has an alignment-specifier,
3137 // every defining declaration of that entity shall specify an
3138 // equivalent alignment.
3139 // C11 6.7.5/7:
3140 // If the definition of an object does not have an alignment
3141 // specifier, any other declaration of that object shall also
3142 // have no alignment specifier.
3143 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3144 << AA;
3145 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3146 << AA;
3147 NewAttributes.erase(CI: NewAttributes.begin() + I);
3148 --E;
3149 continue;
3150 }
3151 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3152 // If there is a C definition followed by a redeclaration with this
3153 // attribute then there are two different definitions. In C++, prefer the
3154 // standard diagnostics.
3155 if (!S.getLangOpts().CPlusPlus) {
3156 S.Diag(Loc: NewAttribute->getLocation(),
3157 DiagID: diag::err_loader_uninitialized_redeclaration);
3158 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3159 NewAttributes.erase(CI: NewAttributes.begin() + I);
3160 --E;
3161 continue;
3162 }
3163 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3164 cast<VarDecl>(Val: New)->isInline() &&
3165 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3166 // Don't warn about applying selectany to implicitly inline variables.
3167 // Older compilers and language modes would require the use of selectany
3168 // to make such variables inline, and it would have no effect if we
3169 // honored it.
3170 ++I;
3171 continue;
3172 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3173 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3174 // declarations after definitions.
3175 ++I;
3176 continue;
3177 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3178 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3179 // error since the definition will have already been created without
3180 // the semantic effects of the attribute having been applied.
3181 S.Diag(Loc: NewAttribute->getLocation(),
3182 DiagID: diag::err_sycl_entry_point_after_definition)
3183 << NewAttribute;
3184 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3185 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3186 ++I;
3187 continue;
3188 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3189 // SYCLExternalAttr may be added after a definition.
3190 ++I;
3191 continue;
3192 }
3193
3194 S.Diag(Loc: NewAttribute->getLocation(),
3195 DiagID: diag::warn_attribute_precede_definition);
3196 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3197 NewAttributes.erase(CI: NewAttributes.begin() + I);
3198 --E;
3199 }
3200}
3201
3202static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3203 const ConstInitAttr *CIAttr,
3204 bool AttrBeforeInit) {
3205 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3206
3207 // Figure out a good way to write this specifier on the old declaration.
3208 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3209 // enough of the attribute list spelling information to extract that without
3210 // heroics.
3211 std::string SuitableSpelling;
3212 if (S.getLangOpts().CPlusPlus20)
3213 SuitableSpelling = std::string(
3214 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3215 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3216 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3217 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3218 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3219 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3220 tok::r_square, tok::r_square}));
3221 if (SuitableSpelling.empty())
3222 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3223 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3224 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3225 tok::r_paren, tok::r_paren}));
3226 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3227 SuitableSpelling = "constinit";
3228 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3229 SuitableSpelling = "[[clang::require_constant_initialization]]";
3230 if (SuitableSpelling.empty())
3231 SuitableSpelling = "__attribute__((require_constant_initialization))";
3232 SuitableSpelling += " ";
3233
3234 if (AttrBeforeInit) {
3235 // extern constinit int a;
3236 // int a = 0; // error (missing 'constinit'), accepted as extension
3237 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3238 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3239 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3240 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3241 } else {
3242 // int a = 0;
3243 // constinit extern int a; // error (missing 'constinit')
3244 S.Diag(Loc: CIAttr->getLocation(),
3245 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3246 : diag::warn_require_const_init_added_too_late)
3247 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3248 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3249 << CIAttr->isConstinit()
3250 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3251 }
3252}
3253
3254void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3255 AvailabilityMergeKind AMK) {
3256 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3257 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3258 NewAttr->setInherited(true);
3259 New->addAttr(A: NewAttr);
3260 }
3261 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3262 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3263 NewAttr->setInherited(true);
3264 New->addAttr(A: NewAttr);
3265 }
3266
3267 if (!Old->hasAttrs() && !New->hasAttrs())
3268 return;
3269
3270 // [dcl.constinit]p1:
3271 // If the [constinit] specifier is applied to any declaration of a
3272 // variable, it shall be applied to the initializing declaration.
3273 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3274 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3275 if (bool(OldConstInit) != bool(NewConstInit)) {
3276 const auto *OldVD = cast<VarDecl>(Val: Old);
3277 auto *NewVD = cast<VarDecl>(Val: New);
3278
3279 // Find the initializing declaration. Note that we might not have linked
3280 // the new declaration into the redeclaration chain yet.
3281 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3282 if (!InitDecl &&
3283 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3284 InitDecl = NewVD;
3285
3286 if (InitDecl == NewVD) {
3287 // This is the initializing declaration. If it would inherit 'constinit',
3288 // that's ill-formed. (Note that we do not apply this to the attribute
3289 // form).
3290 if (OldConstInit && OldConstInit->isConstinit())
3291 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3292 /*AttrBeforeInit=*/true);
3293 } else if (NewConstInit) {
3294 // This is the first time we've been told that this declaration should
3295 // have a constant initializer. If we already saw the initializing
3296 // declaration, this is too late.
3297 if (InitDecl && InitDecl != NewVD) {
3298 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3299 /*AttrBeforeInit=*/false);
3300 NewVD->dropAttr<ConstInitAttr>();
3301 }
3302 }
3303 }
3304
3305 // Attributes declared post-definition are currently ignored.
3306 checkNewAttributesAfterDef(S&: *this, New, Old);
3307
3308 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3309 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3310 if (!OldA->isEquivalent(Other: NewA)) {
3311 // This redeclaration changes __asm__ label.
3312 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3313 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3314 }
3315 } else if (Old->isUsed()) {
3316 // This redeclaration adds an __asm__ label to a declaration that has
3317 // already been ODR-used.
3318 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3319 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3320 }
3321 }
3322
3323 // Re-declaration cannot add abi_tag's.
3324 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3325 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3326 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3327 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3328 Diag(Loc: NewAbiTagAttr->getLocation(),
3329 DiagID: diag::err_new_abi_tag_on_redeclaration)
3330 << NewTag;
3331 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3332 }
3333 }
3334 } else {
3335 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3336 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3337 }
3338 }
3339
3340 // This redeclaration adds a section attribute.
3341 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3342 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3343 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3344 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3345 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3346 }
3347 }
3348 }
3349
3350 // Redeclaration adds code-seg attribute.
3351 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3352 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3353 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3354 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3355 << 0 /*codeseg*/;
3356 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3357 }
3358
3359 if (!Old->hasAttrs())
3360 return;
3361
3362 bool foundAny = New->hasAttrs();
3363
3364 // Ensure that any moving of objects within the allocated map is done before
3365 // we process them.
3366 if (!foundAny) New->setAttrs(AttrVec());
3367
3368 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3369 // Ignore deprecated/unavailable/availability attributes if requested.
3370 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3371 if (isa<DeprecatedAttr>(Val: I) ||
3372 isa<UnavailableAttr>(Val: I) ||
3373 isa<AvailabilityAttr>(Val: I)) {
3374 switch (AMK) {
3375 case AvailabilityMergeKind::None:
3376 continue;
3377
3378 case AvailabilityMergeKind::Redeclaration:
3379 case AvailabilityMergeKind::Override:
3380 case AvailabilityMergeKind::ProtocolImplementation:
3381 case AvailabilityMergeKind::OptionalProtocolImplementation:
3382 LocalAMK = AMK;
3383 break;
3384 }
3385 }
3386
3387 // Already handled.
3388 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3389 continue;
3390
3391 if (isa<InferredNoReturnAttr>(Val: I)) {
3392 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3393 FD &&
3394 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3395 continue; // Don't propagate inferred noreturn attributes to explicit
3396 }
3397
3398 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3399 foundAny = true;
3400 }
3401
3402 if (mergeAlignedAttrs(S&: *this, New, Old))
3403 foundAny = true;
3404
3405 if (!foundAny) New->dropAttrs();
3406}
3407
3408void Sema::CheckAttributesOnDeducedType(Decl *D) {
3409 for (const Attr *A : D->attrs())
3410 checkAttrIsTypeDependent(D, A);
3411}
3412
3413// Returns the number of added attributes.
3414template <class T>
3415static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3416 Sema &S) {
3417 unsigned found = 0;
3418 for (const auto *I : From->specific_attrs<T>()) {
3419 if (!DeclHasAttr(To, I)) {
3420 T *newAttr = cast<T>(I->clone(S.Context));
3421 newAttr->setInherited(true);
3422 To->addAttr(A: newAttr);
3423 ++found;
3424 }
3425 }
3426 return found;
3427}
3428
3429template <class F>
3430static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3431 F &&propagator) {
3432 if (!From->hasAttrs()) {
3433 return;
3434 }
3435
3436 bool foundAny = To->hasAttrs();
3437
3438 // Ensure that any moving of objects within the allocated map is
3439 // done before we process them.
3440 if (!foundAny)
3441 To->setAttrs(AttrVec());
3442
3443 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3444
3445 if (!foundAny)
3446 To->dropAttrs();
3447}
3448
3449/// mergeParamDeclAttributes - Copy attributes from the old parameter
3450/// to the new one.
3451static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3452 const ParmVarDecl *oldDecl,
3453 Sema &S) {
3454 // C++11 [dcl.attr.depend]p2:
3455 // The first declaration of a function shall specify the
3456 // carries_dependency attribute for its declarator-id if any declaration
3457 // of the function specifies the carries_dependency attribute.
3458 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3459 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3460 S.Diag(Loc: CDA->getLocation(),
3461 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3462 // Find the first declaration of the parameter.
3463 // FIXME: Should we build redeclaration chains for function parameters?
3464 const FunctionDecl *FirstFD =
3465 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3466 const ParmVarDecl *FirstVD =
3467 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3468 S.Diag(Loc: FirstVD->getLocation(),
3469 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3470 }
3471
3472 propagateAttributes(
3473 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3474 unsigned found = 0;
3475 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3476 // Propagate the lifetimebound attribute from parameters to the
3477 // most recent declaration. Note that this doesn't include the implicit
3478 // 'this' parameter, as the attribute is applied to the function type in
3479 // that case.
3480 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3481 return found;
3482 });
3483}
3484
3485static bool EquivalentArrayTypes(QualType Old, QualType New,
3486 const ASTContext &Ctx) {
3487
3488 auto NoSizeInfo = [&Ctx](QualType Ty) {
3489 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3490 return true;
3491 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3492 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3493 return false;
3494 };
3495
3496 // `type[]` is equivalent to `type *` and `type[*]`.
3497 if (NoSizeInfo(Old) && NoSizeInfo(New))
3498 return true;
3499
3500 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3501 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3502 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3503 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3504 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3505 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3506 return false;
3507 return true;
3508 }
3509
3510 // Only compare size, ignore Size modifiers and CVR.
3511 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3512 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3513 Ctx.getAsConstantArrayType(T: New)->getSize();
3514 }
3515
3516 // Don't try to compare dependent sized array
3517 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3518 return true;
3519 }
3520
3521 return Old == New;
3522}
3523
3524static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3525 const ParmVarDecl *OldParam,
3526 Sema &S) {
3527 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3528 if (auto Newnullability = NewParam->getType()->getNullability()) {
3529 if (*Oldnullability != *Newnullability) {
3530 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3531 << DiagNullabilityKind(
3532 *Newnullability,
3533 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3534 != 0))
3535 << DiagNullabilityKind(
3536 *Oldnullability,
3537 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3538 != 0));
3539 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3540 }
3541 } else {
3542 QualType NewT = NewParam->getType();
3543 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3544 NewParam->setType(NewT);
3545 }
3546 }
3547 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3548 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3549 if (OldParamDT && NewParamDT &&
3550 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3551 QualType OldParamOT = OldParamDT->getOriginalType();
3552 QualType NewParamOT = NewParamDT->getOriginalType();
3553 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3554 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3555 << NewParam << NewParamOT;
3556 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3557 << OldParamOT;
3558 }
3559 }
3560}
3561
3562namespace {
3563
3564/// Used in MergeFunctionDecl to keep track of function parameters in
3565/// C.
3566struct GNUCompatibleParamWarning {
3567 ParmVarDecl *OldParm;
3568 ParmVarDecl *NewParm;
3569 QualType PromotedType;
3570};
3571
3572} // end anonymous namespace
3573
3574// Determine whether the previous declaration was a definition, implicit
3575// declaration, or a declaration.
3576template <typename T>
3577static std::pair<diag::kind, SourceLocation>
3578getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3579 diag::kind PrevDiag;
3580 SourceLocation OldLocation = Old->getLocation();
3581 if (Old->isThisDeclarationADefinition())
3582 PrevDiag = diag::note_previous_definition;
3583 else if (Old->isImplicit()) {
3584 PrevDiag = diag::note_previous_implicit_declaration;
3585 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3586 if (FD->getBuiltinID())
3587 PrevDiag = diag::note_previous_builtin_declaration;
3588 }
3589 if (OldLocation.isInvalid())
3590 OldLocation = New->getLocation();
3591 } else
3592 PrevDiag = diag::note_previous_declaration;
3593 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3594}
3595
3596/// canRedefineFunction - checks if a function can be redefined. Currently,
3597/// only extern inline functions can be redefined, and even then only in
3598/// GNU89 mode.
3599static bool canRedefineFunction(const FunctionDecl *FD,
3600 const LangOptions& LangOpts) {
3601 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3602 !LangOpts.CPlusPlus &&
3603 FD->isInlineSpecified() &&
3604 FD->getStorageClass() == SC_Extern);
3605}
3606
3607const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3608 const AttributedType *AT = T->getAs<AttributedType>();
3609 while (AT && !AT->isCallingConv())
3610 AT = AT->getModifiedType()->getAs<AttributedType>();
3611 return AT;
3612}
3613
3614template <typename T>
3615static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3616 const DeclContext *DC = Old->getDeclContext();
3617 if (DC->isRecord())
3618 return false;
3619
3620 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3621 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3622 return true;
3623 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3624 return true;
3625 return false;
3626}
3627
3628template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3629static bool isExternC(VarTemplateDecl *) { return false; }
3630static bool isExternC(FunctionTemplateDecl *) { return false; }
3631
3632/// Check whether a redeclaration of an entity introduced by a
3633/// using-declaration is valid, given that we know it's not an overload
3634/// (nor a hidden tag declaration).
3635template<typename ExpectedDecl>
3636static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3637 ExpectedDecl *New) {
3638 // C++11 [basic.scope.declarative]p4:
3639 // Given a set of declarations in a single declarative region, each of
3640 // which specifies the same unqualified name,
3641 // -- they shall all refer to the same entity, or all refer to functions
3642 // and function templates; or
3643 // -- exactly one declaration shall declare a class name or enumeration
3644 // name that is not a typedef name and the other declarations shall all
3645 // refer to the same variable or enumerator, or all refer to functions
3646 // and function templates; in this case the class name or enumeration
3647 // name is hidden (3.3.10).
3648
3649 // C++11 [namespace.udecl]p14:
3650 // If a function declaration in namespace scope or block scope has the
3651 // same name and the same parameter-type-list as a function introduced
3652 // by a using-declaration, and the declarations do not declare the same
3653 // function, the program is ill-formed.
3654
3655 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3656 if (Old &&
3657 !Old->getDeclContext()->getRedeclContext()->Equals(
3658 New->getDeclContext()->getRedeclContext()) &&
3659 !(isExternC(Old) && isExternC(New)))
3660 Old = nullptr;
3661
3662 if (!Old) {
3663 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3664 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3665 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3666 return true;
3667 }
3668 return false;
3669}
3670
3671static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3672 const FunctionDecl *B) {
3673 assert(A->getNumParams() == B->getNumParams());
3674
3675 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3676 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3677 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3678 if (AttrA == AttrB)
3679 return true;
3680 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3681 AttrA->isDynamic() == AttrB->isDynamic();
3682 };
3683
3684 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3685}
3686
3687/// If necessary, adjust the semantic declaration context for a qualified
3688/// declaration to name the correct inline namespace within the qualifier.
3689static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3690 DeclaratorDecl *OldD) {
3691 // The only case where we need to update the DeclContext is when
3692 // redeclaration lookup for a qualified name finds a declaration
3693 // in an inline namespace within the context named by the qualifier:
3694 //
3695 // inline namespace N { int f(); }
3696 // int ::f(); // Sema DC needs adjusting from :: to N::.
3697 //
3698 // For unqualified declarations, the semantic context *can* change
3699 // along the redeclaration chain (for local extern declarations,
3700 // extern "C" declarations, and friend declarations in particular).
3701 if (!NewD->getQualifier())
3702 return;
3703
3704 // NewD is probably already in the right context.
3705 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3706 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3707 if (NamedDC->Equals(DC: SemaDC))
3708 return;
3709
3710 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3711 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3712 "unexpected context for redeclaration");
3713
3714 auto *LexDC = NewD->getLexicalDeclContext();
3715 auto FixSemaDC = [=](NamedDecl *D) {
3716 if (!D)
3717 return;
3718 D->setDeclContext(SemaDC);
3719 D->setLexicalDeclContext(LexDC);
3720 };
3721
3722 FixSemaDC(NewD);
3723 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3724 FixSemaDC(FD->getDescribedFunctionTemplate());
3725 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3726 FixSemaDC(VD->getDescribedVarTemplate());
3727}
3728
3729bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3730 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3731 // Verify the old decl was also a function.
3732 FunctionDecl *Old = OldD->getAsFunction();
3733 if (!Old) {
3734 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3735 // We don't need to check the using friend pattern from other module unit
3736 // since we should have diagnosed such cases in its unit already.
3737 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3738 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3739 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3740 DiagID: diag::note_using_decl_target);
3741 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3742 << 0;
3743 return true;
3744 }
3745
3746 // Check whether the two declarations might declare the same function or
3747 // function template.
3748 if (FunctionTemplateDecl *NewTemplate =
3749 New->getDescribedFunctionTemplate()) {
3750 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3751 New: NewTemplate))
3752 return true;
3753 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3754 ->getAsFunction();
3755 } else {
3756 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3757 return true;
3758 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3759 }
3760 } else {
3761 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3762 << New->getDeclName();
3763 notePreviousDefinition(Old: OldD, New: New->getLocation());
3764 return true;
3765 }
3766 }
3767
3768 // If the old declaration was found in an inline namespace and the new
3769 // declaration was qualified, update the DeclContext to match.
3770 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3771
3772 // If the old declaration is invalid, just give up here.
3773 if (Old->isInvalidDecl())
3774 return true;
3775
3776 // Disallow redeclaration of some builtins.
3777 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3778 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3779 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3780 << Old << Old->getType();
3781 return true;
3782 }
3783
3784 diag::kind PrevDiag;
3785 SourceLocation OldLocation;
3786 std::tie(args&: PrevDiag, args&: OldLocation) =
3787 getNoteDiagForInvalidRedeclaration(Old, New);
3788
3789 // Don't complain about this if we're in GNU89 mode and the old function
3790 // is an extern inline function.
3791 // Don't complain about specializations. They are not supposed to have
3792 // storage classes.
3793 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3794 New->getStorageClass() == SC_Static &&
3795 Old->hasExternalFormalLinkage() &&
3796 !New->getTemplateSpecializationInfo() &&
3797 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3798 if (getLangOpts().MicrosoftExt) {
3799 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3800 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3801 } else {
3802 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3803 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3804 return true;
3805 }
3806 }
3807
3808 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3809 if (!Old->hasAttr<InternalLinkageAttr>()) {
3810 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3811 << ILA;
3812 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3813 New->dropAttr<InternalLinkageAttr>();
3814 }
3815
3816 if (auto *EA = New->getAttr<ErrorAttr>()) {
3817 if (!Old->hasAttr<ErrorAttr>()) {
3818 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3819 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3820 New->dropAttr<ErrorAttr>();
3821 }
3822 }
3823
3824 if (CheckRedeclarationInModule(New, Old))
3825 return true;
3826
3827 if (!getLangOpts().CPlusPlus) {
3828 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3829 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3830 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3831 << New << OldOvl;
3832
3833 // Try our best to find a decl that actually has the overloadable
3834 // attribute for the note. In most cases (e.g. programs with only one
3835 // broken declaration/definition), this won't matter.
3836 //
3837 // FIXME: We could do this if we juggled some extra state in
3838 // OverloadableAttr, rather than just removing it.
3839 const Decl *DiagOld = Old;
3840 if (OldOvl) {
3841 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3842 const auto *A = D->getAttr<OverloadableAttr>();
3843 return A && !A->isImplicit();
3844 });
3845 // If we've implicitly added *all* of the overloadable attrs to this
3846 // chain, emitting a "previous redecl" note is pointless.
3847 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3848 }
3849
3850 if (DiagOld)
3851 Diag(Loc: DiagOld->getLocation(),
3852 DiagID: diag::note_attribute_overloadable_prev_overload)
3853 << OldOvl;
3854
3855 if (OldOvl)
3856 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3857 else
3858 New->dropAttr<OverloadableAttr>();
3859 }
3860 }
3861
3862 // It is not permitted to redeclare an SME function with different SME
3863 // attributes.
3864 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3865 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3866 << New->getType() << Old->getType();
3867 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3868 return true;
3869 }
3870
3871 // If a function is first declared with a calling convention, but is later
3872 // declared or defined without one, all following decls assume the calling
3873 // convention of the first.
3874 //
3875 // It's OK if a function is first declared without a calling convention,
3876 // but is later declared or defined with the default calling convention.
3877 //
3878 // To test if either decl has an explicit calling convention, we look for
3879 // AttributedType sugar nodes on the type as written. If they are missing or
3880 // were canonicalized away, we assume the calling convention was implicit.
3881 //
3882 // Note also that we DO NOT return at this point, because we still have
3883 // other tests to run.
3884 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3885 QualType NewQType = Context.getCanonicalType(T: New->getType());
3886 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3887 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3888 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3889 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3890 bool RequiresAdjustment = false;
3891
3892 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3893 FunctionDecl *First = Old->getFirstDecl();
3894 const FunctionType *FT =
3895 First->getType().getCanonicalType()->castAs<FunctionType>();
3896 FunctionType::ExtInfo FI = FT->getExtInfo();
3897 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3898 if (!NewCCExplicit) {
3899 // Inherit the CC from the previous declaration if it was specified
3900 // there but not here.
3901 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3902 RequiresAdjustment = true;
3903 } else if (Old->getBuiltinID()) {
3904 // Builtin attribute isn't propagated to the new one yet at this point,
3905 // so we check if the old one is a builtin.
3906
3907 // Calling Conventions on a Builtin aren't really useful and setting a
3908 // default calling convention and cdecl'ing some builtin redeclarations is
3909 // common, so warn and ignore the calling convention on the redeclaration.
3910 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3911 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3912 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3913 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3914 RequiresAdjustment = true;
3915 } else {
3916 // Calling conventions aren't compatible, so complain.
3917 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3918 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3919 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3920 << !FirstCCExplicit
3921 << (!FirstCCExplicit ? "" :
3922 FunctionType::getNameForCallConv(CC: FI.getCC()));
3923
3924 // Put the note on the first decl, since it is the one that matters.
3925 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3926 return true;
3927 }
3928 }
3929
3930 // FIXME: diagnose the other way around?
3931 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3932 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3933 RequiresAdjustment = true;
3934 }
3935
3936 // If the declaration is marked with cfi_unchecked_callee but the definition
3937 // isn't, the definition is also cfi_unchecked_callee.
3938 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3939 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3940 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3941 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3942
3943 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3944 EPI2.CFIUncheckedCallee = true;
3945 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3946 Args: FPT2->getParamTypes(), EPI: EPI2);
3947 NewType = cast<FunctionType>(Val&: NewQType);
3948 New->setType(NewQType);
3949 }
3950 }
3951 }
3952
3953 // Merge regparm attribute.
3954 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3955 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3956 if (NewTypeInfo.getHasRegParm()) {
3957 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3958 << NewType->getRegParmType()
3959 << OldType->getRegParmType();
3960 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3961 return true;
3962 }
3963
3964 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3965 RequiresAdjustment = true;
3966 }
3967
3968 // Merge ns_returns_retained attribute.
3969 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3970 if (NewTypeInfo.getProducesResult()) {
3971 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3972 << "'ns_returns_retained'";
3973 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3974 return true;
3975 }
3976
3977 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3978 RequiresAdjustment = true;
3979 }
3980
3981 if (OldTypeInfo.getNoCallerSavedRegs() !=
3982 NewTypeInfo.getNoCallerSavedRegs()) {
3983 if (NewTypeInfo.getNoCallerSavedRegs()) {
3984 AnyX86NoCallerSavedRegistersAttr *Attr =
3985 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3986 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3987 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3988 return true;
3989 }
3990
3991 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3992 RequiresAdjustment = true;
3993 }
3994
3995 if (RequiresAdjustment) {
3996 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3997 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3998 New->setType(QualType(AdjustedType, 0));
3999 NewQType = Context.getCanonicalType(T: New->getType());
4000 }
4001
4002 // If this redeclaration makes the function inline, we may need to add it to
4003 // UndefinedButUsed.
4004 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4005 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4006 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4007 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4008 y: SourceLocation()));
4009
4010 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4011 // about it.
4012 if (New->hasAttr<GNUInlineAttr>() &&
4013 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4014 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4015 }
4016
4017 // If pass_object_size params don't match up perfectly, this isn't a valid
4018 // redeclaration.
4019 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4020 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4021 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4022 << New->getDeclName();
4023 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4024 return true;
4025 }
4026
4027 QualType OldQTypeForComparison = OldQType;
4028 if (Context.hasAnyFunctionEffects()) {
4029 const auto OldFX = Old->getFunctionEffects();
4030 const auto NewFX = New->getFunctionEffects();
4031 if (OldFX != NewFX) {
4032 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4033 for (const auto &Diff : Diffs) {
4034 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4035 Diag(Loc: New->getLocation(),
4036 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4037 << Diff.effectName();
4038 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4039 }
4040 }
4041 // Following a warning, we could skip merging effects from the previous
4042 // declaration, but that would trigger an additional "conflicting types"
4043 // error.
4044 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4045 FunctionEffectSet::Conflicts MergeErrs;
4046 FunctionEffectSet MergedFX =
4047 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4048 if (!MergeErrs.empty())
4049 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4050 OldLoc: Old->getLocation());
4051
4052 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4053 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4054 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4055 Args: NewFPT->getParamTypes(), EPI);
4056
4057 New->setType(ModQT);
4058 NewQType = New->getType();
4059
4060 // Revise OldQTForComparison to include the merged effects,
4061 // so as not to fail due to differences later.
4062 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4063 EPI = OldFPT->getExtProtoInfo();
4064 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4065 OldQTypeForComparison = Context.getFunctionType(
4066 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4067 }
4068 if (OldFX.empty()) {
4069 // A redeclaration may add the attribute to a previously seen function
4070 // body which needs to be verified.
4071 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4072 }
4073 }
4074 }
4075 }
4076
4077 if (getLangOpts().CPlusPlus) {
4078 OldQType = Context.getCanonicalType(T: Old->getType());
4079 NewQType = Context.getCanonicalType(T: New->getType());
4080
4081 // Go back to the type source info to compare the declared return types,
4082 // per C++1y [dcl.type.auto]p13:
4083 // Redeclarations or specializations of a function or function template
4084 // with a declared return type that uses a placeholder type shall also
4085 // use that placeholder, not a deduced type.
4086 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4087 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4088 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4089 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4090 OldT: OldDeclaredReturnType)) {
4091 QualType ResQT;
4092 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4093 OldDeclaredReturnType->isObjCObjectPointerType())
4094 // FIXME: This does the wrong thing for a deduced return type.
4095 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4096 if (ResQT.isNull()) {
4097 if (New->isCXXClassMember() && New->isOutOfLine())
4098 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4099 << New << New->getReturnTypeSourceRange();
4100 else if (Old->isExternC() && New->isExternC() &&
4101 !Old->hasAttr<OverloadableAttr>() &&
4102 !New->hasAttr<OverloadableAttr>())
4103 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4104 else
4105 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4106 << New->getReturnTypeSourceRange();
4107 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4108 << Old->getReturnTypeSourceRange();
4109 return true;
4110 }
4111 else
4112 NewQType = ResQT;
4113 }
4114
4115 QualType OldReturnType = OldType->getReturnType();
4116 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4117 if (OldReturnType != NewReturnType) {
4118 // If this function has a deduced return type and has already been
4119 // defined, copy the deduced value from the old declaration.
4120 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4121 if (OldAT && OldAT->isDeduced()) {
4122 QualType DT = OldAT->getDeducedType();
4123 if (DT.isNull()) {
4124 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4125 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4126 } else {
4127 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4128 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4129 }
4130 }
4131 }
4132
4133 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4134 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4135 if (OldMethod && NewMethod) {
4136 // Preserve triviality.
4137 NewMethod->setTrivial(OldMethod->isTrivial());
4138
4139 // MSVC allows explicit template specialization at class scope:
4140 // 2 CXXMethodDecls referring to the same function will be injected.
4141 // We don't want a redeclaration error.
4142 bool IsClassScopeExplicitSpecialization =
4143 OldMethod->isFunctionTemplateSpecialization() &&
4144 NewMethod->isFunctionTemplateSpecialization();
4145 bool isFriend = NewMethod->getFriendObjectKind();
4146
4147 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4148 !IsClassScopeExplicitSpecialization) {
4149 // -- Member function declarations with the same name and the
4150 // same parameter types cannot be overloaded if any of them
4151 // is a static member function declaration.
4152 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4153 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4154 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4155 return true;
4156 }
4157
4158 // C++ [class.mem]p1:
4159 // [...] A member shall not be declared twice in the
4160 // member-specification, except that a nested class or member
4161 // class template can be declared and then later defined.
4162 if (!inTemplateInstantiation()) {
4163 unsigned NewDiag;
4164 if (isa<CXXConstructorDecl>(Val: OldMethod))
4165 NewDiag = diag::err_constructor_redeclared;
4166 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4167 NewDiag = diag::err_destructor_redeclared;
4168 else if (isa<CXXConversionDecl>(Val: NewMethod))
4169 NewDiag = diag::err_conv_function_redeclared;
4170 else
4171 NewDiag = diag::err_member_redeclared;
4172
4173 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4174 } else {
4175 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4176 << New << New->getType();
4177 }
4178 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4179 return true;
4180
4181 // Complain if this is an explicit declaration of a special
4182 // member that was initially declared implicitly.
4183 //
4184 // As an exception, it's okay to befriend such methods in order
4185 // to permit the implicit constructor/destructor/operator calls.
4186 } else if (OldMethod->isImplicit()) {
4187 if (isFriend) {
4188 NewMethod->setImplicit();
4189 } else {
4190 Diag(Loc: NewMethod->getLocation(),
4191 DiagID: diag::err_definition_of_implicitly_declared_member)
4192 << New << getSpecialMember(MD: OldMethod);
4193 return true;
4194 }
4195 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4196 Diag(Loc: NewMethod->getLocation(),
4197 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4198 << getSpecialMember(MD: OldMethod);
4199 return true;
4200 }
4201 }
4202
4203 // C++1z [over.load]p2
4204 // Certain function declarations cannot be overloaded:
4205 // -- Function declarations that differ only in the return type,
4206 // the exception specification, or both cannot be overloaded.
4207
4208 // Check the exception specifications match. This may recompute the type of
4209 // both Old and New if it resolved exception specifications, so grab the
4210 // types again after this. Because this updates the type, we do this before
4211 // any of the other checks below, which may update the "de facto" NewQType
4212 // but do not necessarily update the type of New.
4213 if (CheckEquivalentExceptionSpec(Old, New))
4214 return true;
4215
4216 // C++11 [dcl.attr.noreturn]p1:
4217 // The first declaration of a function shall specify the noreturn
4218 // attribute if any declaration of that function specifies the noreturn
4219 // attribute.
4220 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4221 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4222 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4223 << NRA;
4224 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4225 }
4226
4227 // C++11 [dcl.attr.depend]p2:
4228 // The first declaration of a function shall specify the
4229 // carries_dependency attribute for its declarator-id if any declaration
4230 // of the function specifies the carries_dependency attribute.
4231 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4232 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4233 Diag(Loc: CDA->getLocation(),
4234 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4235 Diag(Loc: Old->getFirstDecl()->getLocation(),
4236 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4237 }
4238
4239 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4240 // When a function is declared with SYCL_EXTERNAL, that macro must be
4241 // used on the first declaration of that function in the translation unit.
4242 // Redeclarations of the function in the same translation unit may
4243 // optionally use SYCL_EXTERNAL, but this is not required.
4244 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4245 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4246 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4247 << SEA;
4248 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4249 }
4250
4251 // (C++98 8.3.5p3):
4252 // All declarations for a function shall agree exactly in both the
4253 // return type and the parameter-type-list.
4254 // We also want to respect all the extended bits except noreturn.
4255
4256 // noreturn should now match unless the old type info didn't have it.
4257 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4258 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4259 const FunctionType *OldTypeForComparison
4260 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4261 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4262 assert(OldQTypeForComparison.isCanonical());
4263 }
4264
4265 if (haveIncompatibleLanguageLinkages(Old, New)) {
4266 // As a special case, retain the language linkage from previous
4267 // declarations of a friend function as an extension.
4268 //
4269 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4270 // and is useful because there's otherwise no way to specify language
4271 // linkage within class scope.
4272 //
4273 // Check cautiously as the friend object kind isn't yet complete.
4274 if (New->getFriendObjectKind() != Decl::FOK_None) {
4275 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4276 Diag(Loc: OldLocation, DiagID: PrevDiag);
4277 } else {
4278 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4279 Diag(Loc: OldLocation, DiagID: PrevDiag);
4280 return true;
4281 }
4282 }
4283
4284 // HLSL check parameters for matching ABI specifications.
4285 if (getLangOpts().HLSL) {
4286 if (HLSL().CheckCompatibleParameterABI(New, Old))
4287 return true;
4288
4289 // If no errors are generated when checking parameter ABIs we can check if
4290 // the two declarations have the same type ignoring the ABIs and if so,
4291 // the declarations can be merged. This case for merging is only valid in
4292 // HLSL because there are no valid cases of merging mismatched parameter
4293 // ABIs except the HLSL implicit in and explicit in.
4294 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4295 U: NewQType))
4296 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4297 // Fall through for conflicting redeclarations and redefinitions.
4298 }
4299
4300 // If the function types are compatible, merge the declarations. Ignore the
4301 // exception specifier because it was already checked above in
4302 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4303 // about incompatible types under -fms-compatibility.
4304 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4305 U: NewQType))
4306 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4307
4308 // If the types are imprecise (due to dependent constructs in friends or
4309 // local extern declarations), it's OK if they differ. We'll check again
4310 // during instantiation.
4311 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4312 return false;
4313
4314 // Fall through for conflicting redeclarations and redefinitions.
4315 }
4316
4317 // C: Function types need to be compatible, not identical. This handles
4318 // duplicate function decls like "void f(int); void f(enum X);" properly.
4319 if (!getLangOpts().CPlusPlus) {
4320 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4321 // type is specified by a function definition that contains a (possibly
4322 // empty) identifier list, both shall agree in the number of parameters
4323 // and the type of each parameter shall be compatible with the type that
4324 // results from the application of default argument promotions to the
4325 // type of the corresponding identifier. ...
4326 // This cannot be handled by ASTContext::typesAreCompatible() because that
4327 // doesn't know whether the function type is for a definition or not when
4328 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4329 // we need to cover here is that the number of arguments agree as the
4330 // default argument promotion rules were already checked by
4331 // ASTContext::typesAreCompatible().
4332 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4333 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4334 if (Old->hasInheritedPrototype())
4335 Old = Old->getCanonicalDecl();
4336 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4337 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4338 return true;
4339 }
4340
4341 // If we are merging two functions where only one of them has a prototype,
4342 // we may have enough information to decide to issue a diagnostic that the
4343 // function without a prototype will change behavior in C23. This handles
4344 // cases like:
4345 // void i(); void i(int j);
4346 // void i(int j); void i();
4347 // void i(); void i(int j) {}
4348 // See ActOnFinishFunctionBody() for other cases of the behavior change
4349 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4350 // type without a prototype.
4351 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4352 !New->isImplicit() && !Old->isImplicit()) {
4353 const FunctionDecl *WithProto, *WithoutProto;
4354 if (New->hasWrittenPrototype()) {
4355 WithProto = New;
4356 WithoutProto = Old;
4357 } else {
4358 WithProto = Old;
4359 WithoutProto = New;
4360 }
4361
4362 if (WithProto->getNumParams() != 0) {
4363 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4364 // The one without the prototype will be changing behavior in C23, so
4365 // warn about that one so long as it's a user-visible declaration.
4366 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4367 if (WithoutProto == New)
4368 IsWithoutProtoADef = NewDeclIsDefn;
4369 else
4370 IsWithProtoADef = NewDeclIsDefn;
4371 Diag(Loc: WithoutProto->getLocation(),
4372 DiagID: diag::warn_non_prototype_changes_behavior)
4373 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4374 << (WithoutProto == Old) << IsWithProtoADef;
4375
4376 // The reason the one without the prototype will be changing behavior
4377 // is because of the one with the prototype, so note that so long as
4378 // it's a user-visible declaration. There is one exception to this:
4379 // when the new declaration is a definition without a prototype, the
4380 // old declaration with a prototype is not the cause of the issue,
4381 // and that does not need to be noted because the one with a
4382 // prototype will not change behavior in C23.
4383 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4384 !IsWithoutProtoADef)
4385 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4386 }
4387 }
4388 }
4389
4390 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4391 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4392 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4393 const FunctionProtoType *OldProto = nullptr;
4394 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4395 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4396 // The old declaration provided a function prototype, but the
4397 // new declaration does not. Merge in the prototype.
4398 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4399 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4400 Args: OldProto->getParamTypes(),
4401 EPI: OldProto->getExtProtoInfo());
4402 New->setType(NewQType);
4403 New->setHasInheritedPrototype();
4404
4405 // Synthesize parameters with the same types.
4406 SmallVector<ParmVarDecl *, 16> Params;
4407 for (const auto &ParamType : OldProto->param_types()) {
4408 ParmVarDecl *Param = ParmVarDecl::Create(
4409 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4410 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4411 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4412 Param->setImplicit();
4413 Params.push_back(Elt: Param);
4414 }
4415
4416 New->setParams(Params);
4417 }
4418
4419 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4420 }
4421 }
4422
4423 // Check if the function types are compatible when pointer size address
4424 // spaces are ignored.
4425 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4426 return false;
4427
4428 // GNU C permits a K&R definition to follow a prototype declaration
4429 // if the declared types of the parameters in the K&R definition
4430 // match the types in the prototype declaration, even when the
4431 // promoted types of the parameters from the K&R definition differ
4432 // from the types in the prototype. GCC then keeps the types from
4433 // the prototype.
4434 //
4435 // If a variadic prototype is followed by a non-variadic K&R definition,
4436 // the K&R definition becomes variadic. This is sort of an edge case, but
4437 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4438 // C99 6.9.1p8.
4439 if (!getLangOpts().CPlusPlus &&
4440 Old->hasPrototype() && !New->hasPrototype() &&
4441 New->getType()->getAs<FunctionProtoType>() &&
4442 Old->getNumParams() == New->getNumParams()) {
4443 SmallVector<QualType, 16> ArgTypes;
4444 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4445 const FunctionProtoType *OldProto
4446 = Old->getType()->getAs<FunctionProtoType>();
4447 const FunctionProtoType *NewProto
4448 = New->getType()->getAs<FunctionProtoType>();
4449
4450 // Determine whether this is the GNU C extension.
4451 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4452 NewProto->getReturnType());
4453 bool LooseCompatible = !MergedReturn.isNull();
4454 for (unsigned Idx = 0, End = Old->getNumParams();
4455 LooseCompatible && Idx != End; ++Idx) {
4456 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4457 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4458 if (Context.typesAreCompatible(T1: OldParm->getType(),
4459 T2: NewProto->getParamType(i: Idx))) {
4460 ArgTypes.push_back(Elt: NewParm->getType());
4461 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4462 T2: NewParm->getType(),
4463 /*CompareUnqualified=*/true)) {
4464 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4465 .PromotedType: NewProto->getParamType(i: Idx) };
4466 Warnings.push_back(Elt: Warn);
4467 ArgTypes.push_back(Elt: NewParm->getType());
4468 } else
4469 LooseCompatible = false;
4470 }
4471
4472 if (LooseCompatible) {
4473 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4474 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4475 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4476 << Warnings[Warn].PromotedType
4477 << Warnings[Warn].OldParm->getType();
4478 if (Warnings[Warn].OldParm->getLocation().isValid())
4479 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4480 DiagID: diag::note_previous_declaration);
4481 }
4482
4483 if (MergeTypeWithOld)
4484 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4485 EPI: OldProto->getExtProtoInfo()));
4486 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4487 }
4488
4489 // Fall through to diagnose conflicting types.
4490 }
4491
4492 // A function that has already been declared has been redeclared or
4493 // defined with a different type; show an appropriate diagnostic.
4494
4495 // If the previous declaration was an implicitly-generated builtin
4496 // declaration, then at the very least we should use a specialized note.
4497 unsigned BuiltinID;
4498 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4499 // If it's actually a library-defined builtin function like 'malloc'
4500 // or 'printf', just warn about the incompatible redeclaration.
4501 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4502 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4503 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4504 << Old << Old->getType();
4505 return false;
4506 }
4507
4508 PrevDiag = diag::note_previous_builtin_declaration;
4509 }
4510
4511 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4512 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4513 return true;
4514}
4515
4516bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4517 Scope *S, bool MergeTypeWithOld) {
4518 // Merge the attributes
4519 mergeDeclAttributes(New, Old);
4520
4521 // Merge "pure" flag.
4522 if (Old->isPureVirtual())
4523 New->setIsPureVirtual();
4524
4525 // Merge "used" flag.
4526 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4527 New->setIsUsed();
4528
4529 // Merge attributes from the parameters. These can mismatch with K&R
4530 // declarations.
4531 if (New->getNumParams() == Old->getNumParams())
4532 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4533 ParmVarDecl *NewParam = New->getParamDecl(i);
4534 ParmVarDecl *OldParam = Old->getParamDecl(i);
4535 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4536 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4537 }
4538
4539 if (getLangOpts().CPlusPlus)
4540 return MergeCXXFunctionDecl(New, Old, S);
4541
4542 // Merge the function types so the we get the composite types for the return
4543 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4544 // was visible.
4545 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4546 if (!Merged.isNull() && MergeTypeWithOld)
4547 New->setType(Merged);
4548
4549 return false;
4550}
4551
4552void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4553 ObjCMethodDecl *oldMethod) {
4554 // Merge the attributes, including deprecated/unavailable
4555 AvailabilityMergeKind MergeKind =
4556 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4557 ? (oldMethod->isOptional()
4558 ? AvailabilityMergeKind::OptionalProtocolImplementation
4559 : AvailabilityMergeKind::ProtocolImplementation)
4560 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4561 ? AvailabilityMergeKind::Redeclaration
4562 : AvailabilityMergeKind::Override;
4563
4564 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4565
4566 // Merge attributes from the parameters.
4567 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4568 oe = oldMethod->param_end();
4569 for (ObjCMethodDecl::param_iterator
4570 ni = newMethod->param_begin(), ne = newMethod->param_end();
4571 ni != ne && oi != oe; ++ni, ++oi)
4572 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4573
4574 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4575}
4576
4577static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4578 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4579
4580 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4581 ? diag::err_redefinition_different_type
4582 : diag::err_redeclaration_different_type)
4583 << New->getDeclName() << New->getType() << Old->getType();
4584
4585 diag::kind PrevDiag;
4586 SourceLocation OldLocation;
4587 std::tie(args&: PrevDiag, args&: OldLocation)
4588 = getNoteDiagForInvalidRedeclaration(Old, New);
4589 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4590 New->setInvalidDecl();
4591}
4592
4593void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4594 bool MergeTypeWithOld) {
4595 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4596 return;
4597
4598 QualType MergedT;
4599 if (getLangOpts().CPlusPlus) {
4600 if (New->getType()->isUndeducedType()) {
4601 // We don't know what the new type is until the initializer is attached.
4602 return;
4603 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4604 // These could still be something that needs exception specs checked.
4605 return MergeVarDeclExceptionSpecs(New, Old);
4606 }
4607 // C++ [basic.link]p10:
4608 // [...] the types specified by all declarations referring to a given
4609 // object or function shall be identical, except that declarations for an
4610 // array object can specify array types that differ by the presence or
4611 // absence of a major array bound (8.3.4).
4612 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4613 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4614 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4615
4616 // We are merging a variable declaration New into Old. If it has an array
4617 // bound, and that bound differs from Old's bound, we should diagnose the
4618 // mismatch.
4619 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4620 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4621 PrevVD = PrevVD->getPreviousDecl()) {
4622 QualType PrevVDTy = PrevVD->getType();
4623 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4624 continue;
4625
4626 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4627 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4628 }
4629 }
4630
4631 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4632 if (Context.hasSameType(T1: OldArray->getElementType(),
4633 T2: NewArray->getElementType()))
4634 MergedT = New->getType();
4635 }
4636 // FIXME: Check visibility. New is hidden but has a complete type. If New
4637 // has no array bound, it should not inherit one from Old, if Old is not
4638 // visible.
4639 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4640 if (Context.hasSameType(T1: OldArray->getElementType(),
4641 T2: NewArray->getElementType()))
4642 MergedT = Old->getType();
4643 }
4644 }
4645 else if (New->getType()->isObjCObjectPointerType() &&
4646 Old->getType()->isObjCObjectPointerType()) {
4647 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4648 Old->getType());
4649 }
4650 } else {
4651 // C 6.2.7p2:
4652 // All declarations that refer to the same object or function shall have
4653 // compatible type.
4654 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4655 }
4656 if (MergedT.isNull()) {
4657 // It's OK if we couldn't merge types if either type is dependent, for a
4658 // block-scope variable. In other cases (static data members of class
4659 // templates, variable templates, ...), we require the types to be
4660 // equivalent.
4661 // FIXME: The C++ standard doesn't say anything about this.
4662 if ((New->getType()->isDependentType() ||
4663 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4664 // If the old type was dependent, we can't merge with it, so the new type
4665 // becomes dependent for now. We'll reproduce the original type when we
4666 // instantiate the TypeSourceInfo for the variable.
4667 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4668 New->setType(Context.DependentTy);
4669 return;
4670 }
4671 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4672 }
4673
4674 // Don't actually update the type on the new declaration if the old
4675 // declaration was an extern declaration in a different scope.
4676 if (MergeTypeWithOld)
4677 New->setType(MergedT);
4678}
4679
4680static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4681 LookupResult &Previous) {
4682 // C11 6.2.7p4:
4683 // For an identifier with internal or external linkage declared
4684 // in a scope in which a prior declaration of that identifier is
4685 // visible, if the prior declaration specifies internal or
4686 // external linkage, the type of the identifier at the later
4687 // declaration becomes the composite type.
4688 //
4689 // If the variable isn't visible, we do not merge with its type.
4690 if (Previous.isShadowed())
4691 return false;
4692
4693 if (S.getLangOpts().CPlusPlus) {
4694 // C++11 [dcl.array]p3:
4695 // If there is a preceding declaration of the entity in the same
4696 // scope in which the bound was specified, an omitted array bound
4697 // is taken to be the same as in that earlier declaration.
4698 return NewVD->isPreviousDeclInSameBlockScope() ||
4699 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4700 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4701 } else {
4702 // If the old declaration was function-local, don't merge with its
4703 // type unless we're in the same function.
4704 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4705 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4706 }
4707}
4708
4709void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4710 // If the new decl is already invalid, don't do any other checking.
4711 if (New->isInvalidDecl())
4712 return;
4713
4714 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4715 return;
4716
4717 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4718
4719 // Verify the old decl was also a variable or variable template.
4720 VarDecl *Old = nullptr;
4721 VarTemplateDecl *OldTemplate = nullptr;
4722 if (Previous.isSingleResult()) {
4723 if (NewTemplate) {
4724 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4725 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4726
4727 if (auto *Shadow =
4728 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4729 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4730 return New->setInvalidDecl();
4731 } else {
4732 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4733
4734 if (auto *Shadow =
4735 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4736 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4737 return New->setInvalidDecl();
4738 }
4739 }
4740 if (!Old) {
4741 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4742 << New->getDeclName();
4743 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4744 New: New->getLocation());
4745 return New->setInvalidDecl();
4746 }
4747
4748 // If the old declaration was found in an inline namespace and the new
4749 // declaration was qualified, update the DeclContext to match.
4750 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4751
4752 // Ensure the template parameters are compatible.
4753 if (NewTemplate &&
4754 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4755 Old: OldTemplate->getTemplateParameters(),
4756 /*Complain=*/true, Kind: TPL_TemplateMatch))
4757 return New->setInvalidDecl();
4758
4759 // C++ [class.mem]p1:
4760 // A member shall not be declared twice in the member-specification [...]
4761 //
4762 // Here, we need only consider static data members.
4763 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4764 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4765 << New->getIdentifier();
4766 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4767 New->setInvalidDecl();
4768 }
4769
4770 mergeDeclAttributes(New, Old);
4771 // Warn if an already-defined variable is made a weak_import in a subsequent
4772 // declaration
4773 if (New->hasAttr<WeakImportAttr>())
4774 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4775 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4776 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4777 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4778 // Remove weak_import attribute on new declaration.
4779 New->dropAttr<WeakImportAttr>();
4780 break;
4781 }
4782 }
4783
4784 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4785 if (!Old->hasAttr<InternalLinkageAttr>()) {
4786 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4787 << ILA;
4788 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4789 New->dropAttr<InternalLinkageAttr>();
4790 }
4791
4792 // Merge the types.
4793 VarDecl *MostRecent = Old->getMostRecentDecl();
4794 if (MostRecent != Old) {
4795 MergeVarDeclTypes(New, Old: MostRecent,
4796 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4797 if (New->isInvalidDecl())
4798 return;
4799 }
4800
4801 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4802 if (New->isInvalidDecl())
4803 return;
4804
4805 diag::kind PrevDiag;
4806 SourceLocation OldLocation;
4807 std::tie(args&: PrevDiag, args&: OldLocation) =
4808 getNoteDiagForInvalidRedeclaration(Old, New);
4809
4810 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4811 if (New->getStorageClass() == SC_Static &&
4812 !New->isStaticDataMember() &&
4813 Old->hasExternalFormalLinkage()) {
4814 if (getLangOpts().MicrosoftExt) {
4815 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4816 << New->getDeclName();
4817 Diag(Loc: OldLocation, DiagID: PrevDiag);
4818 } else {
4819 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4820 << New->getDeclName();
4821 Diag(Loc: OldLocation, DiagID: PrevDiag);
4822 return New->setInvalidDecl();
4823 }
4824 }
4825 // C99 6.2.2p4:
4826 // For an identifier declared with the storage-class specifier
4827 // extern in a scope in which a prior declaration of that
4828 // identifier is visible,23) if the prior declaration specifies
4829 // internal or external linkage, the linkage of the identifier at
4830 // the later declaration is the same as the linkage specified at
4831 // the prior declaration. If no prior declaration is visible, or
4832 // if the prior declaration specifies no linkage, then the
4833 // identifier has external linkage.
4834 if (New->hasExternalStorage() && Old->hasLinkage())
4835 /* Okay */;
4836 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4837 !New->isStaticDataMember() &&
4838 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4839 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4840 Diag(Loc: OldLocation, DiagID: PrevDiag);
4841 return New->setInvalidDecl();
4842 }
4843
4844 // Check if extern is followed by non-extern and vice-versa.
4845 if (New->hasExternalStorage() &&
4846 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4847 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4848 Diag(Loc: OldLocation, DiagID: PrevDiag);
4849 return New->setInvalidDecl();
4850 }
4851 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4852 !New->hasExternalStorage()) {
4853 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4854 Diag(Loc: OldLocation, DiagID: PrevDiag);
4855 return New->setInvalidDecl();
4856 }
4857
4858 if (CheckRedeclarationInModule(New, Old))
4859 return;
4860
4861 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4862
4863 // FIXME: The test for external storage here seems wrong? We still
4864 // need to check for mismatches.
4865 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4866 // Don't complain about out-of-line definitions of static members.
4867 !(Old->getLexicalDeclContext()->isRecord() &&
4868 !New->getLexicalDeclContext()->isRecord())) {
4869 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4870 Diag(Loc: OldLocation, DiagID: PrevDiag);
4871 return New->setInvalidDecl();
4872 }
4873
4874 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4875 if (VarDecl *Def = Old->getDefinition()) {
4876 // C++1z [dcl.fcn.spec]p4:
4877 // If the definition of a variable appears in a translation unit before
4878 // its first declaration as inline, the program is ill-formed.
4879 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4880 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4881 }
4882 }
4883
4884 // If this redeclaration makes the variable inline, we may need to add it to
4885 // UndefinedButUsed.
4886 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4887 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4888 !Old->isInAnotherModuleUnit())
4889 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4890 y: SourceLocation()));
4891
4892 if (New->getTLSKind() != Old->getTLSKind()) {
4893 if (!Old->getTLSKind()) {
4894 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4895 Diag(Loc: OldLocation, DiagID: PrevDiag);
4896 } else if (!New->getTLSKind()) {
4897 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4898 Diag(Loc: OldLocation, DiagID: PrevDiag);
4899 } else {
4900 // Do not allow redeclaration to change the variable between requiring
4901 // static and dynamic initialization.
4902 // FIXME: GCC allows this, but uses the TLS keyword on the first
4903 // declaration to determine the kind. Do we need to be compatible here?
4904 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4905 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4906 Diag(Loc: OldLocation, DiagID: PrevDiag);
4907 }
4908 }
4909
4910 // C++ doesn't have tentative definitions, so go right ahead and check here.
4911 if (getLangOpts().CPlusPlus) {
4912 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4913 Old->getCanonicalDecl()->isConstexpr()) {
4914 // This definition won't be a definition any more once it's been merged.
4915 Diag(Loc: New->getLocation(),
4916 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4917 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4918 VarDecl *Def = Old->getDefinition();
4919 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4920 return;
4921 if (Old->isInvalidDecl())
4922 New->setInvalidDecl();
4923 }
4924 } else {
4925 // C++ may not have a tentative definition rule, but it has a different
4926 // rule about what constitutes a definition in the first place. See
4927 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4928 // contains the extern specifier and doesn't have an initializer, it's fine
4929 // in C++.
4930 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4931 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4932 << New;
4933 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4934 }
4935 }
4936
4937 if (haveIncompatibleLanguageLinkages(Old, New)) {
4938 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4939 Diag(Loc: OldLocation, DiagID: PrevDiag);
4940 New->setInvalidDecl();
4941 return;
4942 }
4943
4944 // Merge "used" flag.
4945 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4946 New->setIsUsed();
4947
4948 // Keep a chain of previous declarations.
4949 New->setPreviousDecl(Old);
4950 if (NewTemplate)
4951 NewTemplate->setPreviousDecl(OldTemplate);
4952
4953 // Inherit access appropriately.
4954 New->setAccess(Old->getAccess());
4955 if (NewTemplate)
4956 NewTemplate->setAccess(New->getAccess());
4957
4958 if (Old->isInline())
4959 New->setImplicitlyInline();
4960}
4961
4962void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4963 SourceManager &SrcMgr = getSourceManager();
4964 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4965 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4966 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4967 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4968 auto &HSI = PP.getHeaderSearchInfo();
4969 StringRef HdrFilename =
4970 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4971
4972 auto noteFromModuleOrInclude = [&](Module *Mod,
4973 SourceLocation IncLoc) -> bool {
4974 // Redefinition errors with modules are common with non modular mapped
4975 // headers, example: a non-modular header H in module A that also gets
4976 // included directly in a TU. Pointing twice to the same header/definition
4977 // is confusing, try to get better diagnostics when modules is on.
4978 if (IncLoc.isValid()) {
4979 if (Mod) {
4980 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4981 << HdrFilename.str() << Mod->getFullModuleName();
4982 if (!Mod->DefinitionLoc.isInvalid())
4983 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4984 << Mod->getFullModuleName();
4985 } else {
4986 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4987 << HdrFilename.str();
4988 }
4989 return true;
4990 }
4991
4992 return false;
4993 };
4994
4995 // Is it the same file and same offset? Provide more information on why
4996 // this leads to a redefinition error.
4997 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4998 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4999 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5000 bool EmittedDiag =
5001 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5002 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5003
5004 // If the header has no guards, emit a note suggesting one.
5005 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5006 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5007
5008 if (EmittedDiag)
5009 return;
5010 }
5011
5012 // Redefinition coming from different files or couldn't do better above.
5013 if (Old->getLocation().isValid())
5014 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5015}
5016
5017bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5018 if (!hasVisibleDefinition(D: Old) &&
5019 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5020 isa<VarTemplateSpecializationDecl>(Val: New) ||
5021 New->getDescribedVarTemplate() ||
5022 !New->getTemplateParameterLists().empty() ||
5023 New->getDeclContext()->isDependentContext() ||
5024 New->hasAttr<SelectAnyAttr>())) {
5025 // The previous definition is hidden, and multiple definitions are
5026 // permitted (in separate TUs). Demote this to a declaration.
5027 New->demoteThisDefinitionToDeclaration();
5028
5029 // Make the canonical definition visible.
5030 if (auto *OldTD = Old->getDescribedVarTemplate())
5031 makeMergedDefinitionVisible(ND: OldTD);
5032 makeMergedDefinitionVisible(ND: Old);
5033 return false;
5034 } else {
5035 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5036 notePreviousDefinition(Old, New: New->getLocation());
5037 New->setInvalidDecl();
5038 return true;
5039 }
5040}
5041
5042Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5043 DeclSpec &DS,
5044 const ParsedAttributesView &DeclAttrs,
5045 RecordDecl *&AnonRecord) {
5046 return ParsedFreeStandingDeclSpec(
5047 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5048}
5049
5050// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5051// disambiguate entities defined in different scopes.
5052// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5053// compatibility.
5054// We will pick our mangling number depending on which version of MSVC is being
5055// targeted.
5056static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5057 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5058 ? S->getMSCurManglingNumber()
5059 : S->getMSLastManglingNumber();
5060}
5061
5062void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5063 if (!Context.getLangOpts().CPlusPlus)
5064 return;
5065
5066 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5067 // If this tag is the direct child of a class, number it if
5068 // it is anonymous.
5069 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5070 return;
5071 MangleNumberingContext &MCtx =
5072 Context.getManglingNumberContext(DC: Tag->getParent());
5073 Context.setManglingNumber(
5074 ND: Tag, Number: MCtx.getManglingNumber(
5075 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5076 return;
5077 }
5078
5079 // If this tag isn't a direct child of a class, number it if it is local.
5080 MangleNumberingContext *MCtx;
5081 Decl *ManglingContextDecl;
5082 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5083 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5084 if (MCtx) {
5085 Context.setManglingNumber(
5086 ND: Tag, Number: MCtx->getManglingNumber(
5087 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5088 }
5089}
5090
5091namespace {
5092struct NonCLikeKind {
5093 enum {
5094 None,
5095 BaseClass,
5096 DefaultMemberInit,
5097 Lambda,
5098 Friend,
5099 OtherMember,
5100 Invalid,
5101 } Kind = None;
5102 SourceRange Range;
5103
5104 explicit operator bool() { return Kind != None; }
5105};
5106}
5107
5108/// Determine whether a class is C-like, according to the rules of C++
5109/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5110static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5111 if (RD->isInvalidDecl())
5112 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5113
5114 // C++ [dcl.typedef]p9: [P1766R1]
5115 // An unnamed class with a typedef name for linkage purposes shall not
5116 //
5117 // -- have any base classes
5118 if (RD->getNumBases())
5119 return {.Kind: NonCLikeKind::BaseClass,
5120 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5121 RD->bases_end()[-1].getEndLoc())};
5122 bool Invalid = false;
5123 for (Decl *D : RD->decls()) {
5124 // Don't complain about things we already diagnosed.
5125 if (D->isInvalidDecl()) {
5126 Invalid = true;
5127 continue;
5128 }
5129
5130 // -- have any [...] default member initializers
5131 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5132 if (FD->hasInClassInitializer()) {
5133 auto *Init = FD->getInClassInitializer();
5134 return {.Kind: NonCLikeKind::DefaultMemberInit,
5135 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5136 }
5137 continue;
5138 }
5139
5140 // FIXME: We don't allow friend declarations. This violates the wording of
5141 // P1766, but not the intent.
5142 if (isa<FriendDecl>(Val: D))
5143 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5144
5145 // -- declare any members other than non-static data members, member
5146 // enumerations, or member classes,
5147 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5148 isa<EnumDecl>(Val: D))
5149 continue;
5150 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5151 if (!MemberRD) {
5152 if (D->isImplicit())
5153 continue;
5154 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5155 }
5156
5157 // -- contain a lambda-expression,
5158 if (MemberRD->isLambda())
5159 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5160
5161 // and all member classes shall also satisfy these requirements
5162 // (recursively).
5163 if (MemberRD->isThisDeclarationADefinition()) {
5164 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5165 return Kind;
5166 }
5167 }
5168
5169 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5170}
5171
5172void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5173 TypedefNameDecl *NewTD) {
5174 if (TagFromDeclSpec->isInvalidDecl())
5175 return;
5176
5177 // Do nothing if the tag already has a name for linkage purposes.
5178 if (TagFromDeclSpec->hasNameForLinkage())
5179 return;
5180
5181 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5182 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5183
5184 // The type must match the tag exactly; no qualifiers allowed.
5185 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5186 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5187 if (getLangOpts().CPlusPlus)
5188 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5189 return;
5190 }
5191
5192 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5193 // An unnamed class with a typedef name for linkage purposes shall [be
5194 // C-like].
5195 //
5196 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5197 // shouldn't happen, but there are constructs that the language rule doesn't
5198 // disallow for which we can't reasonably avoid computing linkage early.
5199 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5200 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5201 : NonCLikeKind();
5202 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5203 if (NonCLike || ChangesLinkage) {
5204 if (NonCLike.Kind == NonCLikeKind::Invalid)
5205 return;
5206
5207 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5208 if (ChangesLinkage) {
5209 // If the linkage changes, we can't accept this as an extension.
5210 if (NonCLike.Kind == NonCLikeKind::None)
5211 DiagID = diag::err_typedef_changes_linkage;
5212 else
5213 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5214 }
5215
5216 SourceLocation FixitLoc =
5217 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5218 llvm::SmallString<40> TextToInsert;
5219 TextToInsert += ' ';
5220 TextToInsert += NewTD->getIdentifier()->getName();
5221
5222 Diag(Loc: FixitLoc, DiagID)
5223 << isa<TypeAliasDecl>(Val: NewTD)
5224 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5225 if (NonCLike.Kind != NonCLikeKind::None) {
5226 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5227 << NonCLike.Kind - 1 << NonCLike.Range;
5228 }
5229 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5230 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5231
5232 if (ChangesLinkage)
5233 return;
5234 }
5235
5236 // Otherwise, set this as the anon-decl typedef for the tag.
5237 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5238
5239 // Now that we have a name for the tag, process API notes again.
5240 ProcessAPINotes(D: TagFromDeclSpec);
5241}
5242
5243static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5244 DeclSpec::TST T = DS.getTypeSpecType();
5245 switch (T) {
5246 case DeclSpec::TST_class:
5247 return 0;
5248 case DeclSpec::TST_struct:
5249 return 1;
5250 case DeclSpec::TST_interface:
5251 return 2;
5252 case DeclSpec::TST_union:
5253 return 3;
5254 case DeclSpec::TST_enum:
5255 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5256 if (ED->isScopedUsingClassTag())
5257 return 5;
5258 if (ED->isScoped())
5259 return 6;
5260 }
5261 return 4;
5262 default:
5263 llvm_unreachable("unexpected type specifier");
5264 }
5265}
5266
5267Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5268 DeclSpec &DS,
5269 const ParsedAttributesView &DeclAttrs,
5270 MultiTemplateParamsArg TemplateParams,
5271 bool IsExplicitInstantiation,
5272 RecordDecl *&AnonRecord,
5273 SourceLocation EllipsisLoc) {
5274 Decl *TagD = nullptr;
5275 TagDecl *Tag = nullptr;
5276 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5277 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5278 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5279 DS.getTypeSpecType() == DeclSpec::TST_union ||
5280 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5281 TagD = DS.getRepAsDecl();
5282
5283 if (!TagD) // We probably had an error
5284 return nullptr;
5285
5286 // Note that the above type specs guarantee that the
5287 // type rep is a Decl, whereas in many of the others
5288 // it's a Type.
5289 if (isa<TagDecl>(Val: TagD))
5290 Tag = cast<TagDecl>(Val: TagD);
5291 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5292 Tag = CTD->getTemplatedDecl();
5293 }
5294
5295 if (Tag) {
5296 handleTagNumbering(Tag, TagScope: S);
5297 Tag->setFreeStanding();
5298 if (Tag->isInvalidDecl())
5299 return Tag;
5300 }
5301
5302 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5303 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5304 // or incomplete types shall not be restrict-qualified."
5305 if (TypeQuals & DeclSpec::TQ_restrict)
5306 Diag(Loc: DS.getRestrictSpecLoc(),
5307 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5308 << DS.getSourceRange();
5309 }
5310
5311 if (DS.isInlineSpecified())
5312 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5313 << getLangOpts().CPlusPlus17;
5314
5315 if (DS.hasConstexprSpecifier()) {
5316 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5317 // and definitions of functions and variables.
5318 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5319 // the declaration of a function or function template
5320 if (Tag)
5321 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5322 << GetDiagnosticTypeSpecifierID(DS)
5323 << static_cast<int>(DS.getConstexprSpecifier());
5324 else if (getLangOpts().C23)
5325 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5326 else
5327 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5328 << static_cast<int>(DS.getConstexprSpecifier());
5329 // Don't emit warnings after this error.
5330 return TagD;
5331 }
5332
5333 DiagnoseFunctionSpecifiers(DS);
5334
5335 if (DS.isFriendSpecified()) {
5336 // If we're dealing with a decl but not a TagDecl, assume that
5337 // whatever routines created it handled the friendship aspect.
5338 if (TagD && !Tag)
5339 return nullptr;
5340 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5341 }
5342
5343 assert(EllipsisLoc.isInvalid() &&
5344 "Friend ellipsis but not friend-specified?");
5345
5346 // Track whether this decl-specifier declares anything.
5347 bool DeclaresAnything = true;
5348
5349 // Handle anonymous struct definitions.
5350 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5351 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5352 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5353 if (getLangOpts().CPlusPlus ||
5354 Record->getDeclContext()->isRecord()) {
5355 // If CurContext is a DeclContext that can contain statements,
5356 // RecursiveASTVisitor won't visit the decls that
5357 // BuildAnonymousStructOrUnion() will put into CurContext.
5358 // Also store them here so that they can be part of the
5359 // DeclStmt that gets created in this case.
5360 // FIXME: Also return the IndirectFieldDecls created by
5361 // BuildAnonymousStructOr union, for the same reason?
5362 if (CurContext->isFunctionOrMethod())
5363 AnonRecord = Record;
5364 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5365 Policy: Context.getPrintingPolicy());
5366 }
5367
5368 DeclaresAnything = false;
5369 }
5370 }
5371
5372 // C11 6.7.2.1p2:
5373 // A struct-declaration that does not declare an anonymous structure or
5374 // anonymous union shall contain a struct-declarator-list.
5375 //
5376 // This rule also existed in C89 and C99; the grammar for struct-declaration
5377 // did not permit a struct-declaration without a struct-declarator-list.
5378 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5379 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5380 // Check for Microsoft C extension: anonymous struct/union member.
5381 // Handle 2 kinds of anonymous struct/union:
5382 // struct STRUCT;
5383 // union UNION;
5384 // and
5385 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5386 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5387 if ((Tag && Tag->getDeclName()) ||
5388 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5389 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5390 : DS.getRepAsType().get()->getAsRecordDecl();
5391 if (Record && getLangOpts().MSAnonymousStructs) {
5392 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5393 << Record->isUnion() << DS.getSourceRange();
5394 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5395 }
5396
5397 DeclaresAnything = false;
5398 }
5399 }
5400
5401 // Skip all the checks below if we have a type error.
5402 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5403 (TagD && TagD->isInvalidDecl()))
5404 return TagD;
5405
5406 if (getLangOpts().CPlusPlus &&
5407 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5408 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5409 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5410 !Enum->isInvalidDecl())
5411 DeclaresAnything = false;
5412
5413 if (!DS.isMissingDeclaratorOk()) {
5414 // Customize diagnostic for a typedef missing a name.
5415 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5416 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5417 << DS.getSourceRange();
5418 else
5419 DeclaresAnything = false;
5420 }
5421
5422 if (DS.isModulePrivateSpecified() &&
5423 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5424 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5425 << Tag->getTagKind()
5426 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5427
5428 ActOnDocumentableDecl(D: TagD);
5429
5430 // C 6.7/2:
5431 // A declaration [...] shall declare at least a declarator [...], a tag,
5432 // or the members of an enumeration.
5433 // C++ [dcl.dcl]p3:
5434 // [If there are no declarators], and except for the declaration of an
5435 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5436 // names into the program, or shall redeclare a name introduced by a
5437 // previous declaration.
5438 if (!DeclaresAnything) {
5439 // In C, we allow this as a (popular) extension / bug. Don't bother
5440 // producing further diagnostics for redundant qualifiers after this.
5441 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5442 ? diag::err_no_declarators
5443 : diag::ext_no_declarators)
5444 << DS.getSourceRange();
5445 return TagD;
5446 }
5447
5448 // C++ [dcl.stc]p1:
5449 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5450 // init-declarator-list of the declaration shall not be empty.
5451 // C++ [dcl.fct.spec]p1:
5452 // If a cv-qualifier appears in a decl-specifier-seq, the
5453 // init-declarator-list of the declaration shall not be empty.
5454 //
5455 // Spurious qualifiers here appear to be valid in C.
5456 unsigned DiagID = diag::warn_standalone_specifier;
5457 if (getLangOpts().CPlusPlus)
5458 DiagID = diag::ext_standalone_specifier;
5459
5460 // Note that a linkage-specification sets a storage class, but
5461 // 'extern "C" struct foo;' is actually valid and not theoretically
5462 // useless.
5463 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5464 if (SCS == DeclSpec::SCS_mutable)
5465 // Since mutable is not a viable storage class specifier in C, there is
5466 // no reason to treat it as an extension. Instead, diagnose as an error.
5467 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5468 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5469 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5470 << DeclSpec::getSpecifierName(S: SCS);
5471 }
5472
5473 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5474 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5475 << DeclSpec::getSpecifierName(S: TSCS);
5476 if (DS.getTypeQualifiers()) {
5477 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5478 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5479 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5480 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5481 // Restrict is covered above.
5482 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5483 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5484 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5485 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5486 }
5487
5488 // Warn about ignored type attributes, for example:
5489 // __attribute__((aligned)) struct A;
5490 // Attributes should be placed after tag to apply to type declaration.
5491 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5492 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5493 if (TypeSpecType == DeclSpec::TST_class ||
5494 TypeSpecType == DeclSpec::TST_struct ||
5495 TypeSpecType == DeclSpec::TST_interface ||
5496 TypeSpecType == DeclSpec::TST_union ||
5497 TypeSpecType == DeclSpec::TST_enum) {
5498
5499 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5500 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5501 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5502 DiagnosticId = diag::warn_attribute_ignored;
5503 else if (AL.isRegularKeywordAttribute())
5504 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5505 else
5506 DiagnosticId = diag::warn_declspec_attribute_ignored;
5507 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5508 << AL << GetDiagnosticTypeSpecifierID(DS);
5509 };
5510
5511 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5512 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5513 }
5514 }
5515
5516 return TagD;
5517}
5518
5519/// We are trying to inject an anonymous member into the given scope;
5520/// check if there's an existing declaration that can't be overloaded.
5521///
5522/// \return true if this is a forbidden redeclaration
5523static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5524 DeclContext *Owner,
5525 DeclarationName Name,
5526 SourceLocation NameLoc, bool IsUnion,
5527 StorageClass SC) {
5528 LookupResult R(SemaRef, Name, NameLoc,
5529 Owner->isRecord() ? Sema::LookupMemberName
5530 : Sema::LookupOrdinaryName,
5531 RedeclarationKind::ForVisibleRedeclaration);
5532 if (!SemaRef.LookupName(R, S)) return false;
5533
5534 // Pick a representative declaration.
5535 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5536 assert(PrevDecl && "Expected a non-null Decl");
5537
5538 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5539 return false;
5540
5541 if (SC == StorageClass::SC_None &&
5542 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5543 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5544 if (!Owner->isRecord())
5545 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5546 return false;
5547 }
5548
5549 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5550 << IsUnion << Name;
5551 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5552
5553 return true;
5554}
5555
5556void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5557 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5558 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5559}
5560
5561void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5562 if (!getLangOpts().CPlusPlus)
5563 return;
5564
5565 // This function can be parsed before we have validated the
5566 // structure as an anonymous struct
5567 if (Record->isAnonymousStructOrUnion())
5568 return;
5569
5570 const NamedDecl *First = 0;
5571 for (const Decl *D : Record->decls()) {
5572 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5573 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5574 continue;
5575 if (!First)
5576 First = ND;
5577 else
5578 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5579 }
5580}
5581
5582/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5583/// anonymous struct or union AnonRecord into the owning context Owner
5584/// and scope S. This routine will be invoked just after we realize
5585/// that an unnamed union or struct is actually an anonymous union or
5586/// struct, e.g.,
5587///
5588/// @code
5589/// union {
5590/// int i;
5591/// float f;
5592/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5593/// // f into the surrounding scope.x
5594/// @endcode
5595///
5596/// This routine is recursive, injecting the names of nested anonymous
5597/// structs/unions into the owning context and scope as well.
5598static bool
5599InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5600 RecordDecl *AnonRecord, AccessSpecifier AS,
5601 StorageClass SC,
5602 SmallVectorImpl<NamedDecl *> &Chaining) {
5603 bool Invalid = false;
5604
5605 // Look every FieldDecl and IndirectFieldDecl with a name.
5606 for (auto *D : AnonRecord->decls()) {
5607 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5608 cast<NamedDecl>(Val: D)->getDeclName()) {
5609 ValueDecl *VD = cast<ValueDecl>(Val: D);
5610 // C++ [class.union]p2:
5611 // The names of the members of an anonymous union shall be
5612 // distinct from the names of any other entity in the
5613 // scope in which the anonymous union is declared.
5614
5615 bool FieldInvalid = CheckAnonMemberRedeclaration(
5616 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5617 IsUnion: AnonRecord->isUnion(), SC);
5618 if (FieldInvalid)
5619 Invalid = true;
5620
5621 // Inject the IndirectFieldDecl even if invalid, because later
5622 // diagnostics may depend on it being present, see findDefaultInitializer.
5623
5624 // C++ [class.union]p2:
5625 // For the purpose of name lookup, after the anonymous union
5626 // definition, the members of the anonymous union are
5627 // considered to have been defined in the scope in which the
5628 // anonymous union is declared.
5629 unsigned OldChainingSize = Chaining.size();
5630 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5631 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5632 else
5633 Chaining.push_back(Elt: VD);
5634
5635 assert(Chaining.size() >= 2);
5636 NamedDecl **NamedChain =
5637 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5638 for (unsigned i = 0; i < Chaining.size(); i++)
5639 NamedChain[i] = Chaining[i];
5640
5641 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5642 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5643 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5644
5645 for (const auto *Attr : VD->attrs())
5646 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5647
5648 IndirectField->setAccess(AS);
5649 IndirectField->setImplicit();
5650 IndirectField->setInvalidDecl(FieldInvalid);
5651 SemaRef.PushOnScopeChains(D: IndirectField, S);
5652
5653 // That includes picking up the appropriate access specifier.
5654 if (AS != AS_none)
5655 IndirectField->setAccess(AS);
5656
5657 Chaining.resize(N: OldChainingSize);
5658 }
5659 }
5660
5661 return Invalid;
5662}
5663
5664/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5665/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5666/// illegal input values are mapped to SC_None.
5667static StorageClass
5668StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5669 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5670 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5671 "Parser allowed 'typedef' as storage class VarDecl.");
5672 switch (StorageClassSpec) {
5673 case DeclSpec::SCS_unspecified: return SC_None;
5674 case DeclSpec::SCS_extern:
5675 if (DS.isExternInLinkageSpec())
5676 return SC_None;
5677 return SC_Extern;
5678 case DeclSpec::SCS_static: return SC_Static;
5679 case DeclSpec::SCS_auto: return SC_Auto;
5680 case DeclSpec::SCS_register: return SC_Register;
5681 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5682 // Illegal SCSs map to None: error reporting is up to the caller.
5683 case DeclSpec::SCS_mutable: // Fall through.
5684 case DeclSpec::SCS_typedef: return SC_None;
5685 }
5686 llvm_unreachable("unknown storage class specifier");
5687}
5688
5689static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5690 assert(Record->hasInClassInitializer());
5691
5692 for (const auto *I : Record->decls()) {
5693 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5694 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5695 FD = IFD->getAnonField();
5696 if (FD && FD->hasInClassInitializer())
5697 return FD->getLocation();
5698 }
5699
5700 llvm_unreachable("couldn't find in-class initializer");
5701}
5702
5703static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5704 SourceLocation DefaultInitLoc) {
5705 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5706 return;
5707
5708 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5709 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5710}
5711
5712static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5713 CXXRecordDecl *AnonUnion) {
5714 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5715 return;
5716
5717 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5718}
5719
5720Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5721 AccessSpecifier AS,
5722 RecordDecl *Record,
5723 const PrintingPolicy &Policy) {
5724 DeclContext *Owner = Record->getDeclContext();
5725
5726 // Diagnose whether this anonymous struct/union is an extension.
5727 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5728 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5729 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5730 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5731 else if (!Record->isUnion() && !getLangOpts().C11)
5732 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5733
5734 // C and C++ require different kinds of checks for anonymous
5735 // structs/unions.
5736 bool Invalid = false;
5737 if (getLangOpts().CPlusPlus) {
5738 const char *PrevSpec = nullptr;
5739 if (Record->isUnion()) {
5740 // C++ [class.union]p6:
5741 // C++17 [class.union.anon]p2:
5742 // Anonymous unions declared in a named namespace or in the
5743 // global namespace shall be declared static.
5744 unsigned DiagID;
5745 DeclContext *OwnerScope = Owner->getRedeclContext();
5746 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5747 (OwnerScope->isTranslationUnit() ||
5748 (OwnerScope->isNamespace() &&
5749 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5750 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5751 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5752
5753 // Recover by adding 'static'.
5754 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5755 PrevSpec, DiagID, Policy);
5756 }
5757 // C++ [class.union]p6:
5758 // A storage class is not allowed in a declaration of an
5759 // anonymous union in a class scope.
5760 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5761 isa<RecordDecl>(Val: Owner)) {
5762 Diag(Loc: DS.getStorageClassSpecLoc(),
5763 DiagID: diag::err_anonymous_union_with_storage_spec)
5764 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5765
5766 // Recover by removing the storage specifier.
5767 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5768 Loc: SourceLocation(),
5769 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5770 }
5771 }
5772
5773 // Ignore const/volatile/restrict qualifiers.
5774 if (DS.getTypeQualifiers()) {
5775 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5776 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5777 << Record->isUnion() << "const"
5778 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5779 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5780 Diag(Loc: DS.getVolatileSpecLoc(),
5781 DiagID: diag::ext_anonymous_struct_union_qualified)
5782 << Record->isUnion() << "volatile"
5783 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5784 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5785 Diag(Loc: DS.getRestrictSpecLoc(),
5786 DiagID: diag::ext_anonymous_struct_union_qualified)
5787 << Record->isUnion() << "restrict"
5788 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5789 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5790 Diag(Loc: DS.getAtomicSpecLoc(),
5791 DiagID: diag::ext_anonymous_struct_union_qualified)
5792 << Record->isUnion() << "_Atomic"
5793 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5794 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5795 Diag(Loc: DS.getUnalignedSpecLoc(),
5796 DiagID: diag::ext_anonymous_struct_union_qualified)
5797 << Record->isUnion() << "__unaligned"
5798 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5799
5800 DS.ClearTypeQualifiers();
5801 }
5802
5803 // C++ [class.union]p2:
5804 // The member-specification of an anonymous union shall only
5805 // define non-static data members. [Note: nested types and
5806 // functions cannot be declared within an anonymous union. ]
5807 for (auto *Mem : Record->decls()) {
5808 // Ignore invalid declarations; we already diagnosed them.
5809 if (Mem->isInvalidDecl())
5810 continue;
5811
5812 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5813 // C++ [class.union]p3:
5814 // An anonymous union shall not have private or protected
5815 // members (clause 11).
5816 assert(FD->getAccess() != AS_none);
5817 if (FD->getAccess() != AS_public) {
5818 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5819 << Record->isUnion() << (FD->getAccess() == AS_protected);
5820 Invalid = true;
5821 }
5822
5823 // C++ [class.union]p1
5824 // An object of a class with a non-trivial constructor, a non-trivial
5825 // copy constructor, a non-trivial destructor, or a non-trivial copy
5826 // assignment operator cannot be a member of a union, nor can an
5827 // array of such objects.
5828 if (CheckNontrivialField(FD))
5829 Invalid = true;
5830 } else if (Mem->isImplicit()) {
5831 // Any implicit members are fine.
5832 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5833 // This is a type that showed up in an
5834 // elaborated-type-specifier inside the anonymous struct or
5835 // union, but which actually declares a type outside of the
5836 // anonymous struct or union. It's okay.
5837 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5838 if (!MemRecord->isAnonymousStructOrUnion() &&
5839 MemRecord->getDeclName()) {
5840 // Visual C++ allows type definition in anonymous struct or union.
5841 if (getLangOpts().MicrosoftExt)
5842 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5843 << Record->isUnion();
5844 else {
5845 // This is a nested type declaration.
5846 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5847 << Record->isUnion();
5848 Invalid = true;
5849 }
5850 } else {
5851 // This is an anonymous type definition within another anonymous type.
5852 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5853 // not part of standard C++.
5854 Diag(Loc: MemRecord->getLocation(),
5855 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5856 << Record->isUnion();
5857 }
5858 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5859 // Any access specifier is fine.
5860 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5861 // In C++1z, static_assert declarations are also fine.
5862 } else {
5863 // We have something that isn't a non-static data
5864 // member. Complain about it.
5865 unsigned DK = diag::err_anonymous_record_bad_member;
5866 if (isa<TypeDecl>(Val: Mem))
5867 DK = diag::err_anonymous_record_with_type;
5868 else if (isa<FunctionDecl>(Val: Mem))
5869 DK = diag::err_anonymous_record_with_function;
5870 else if (isa<VarDecl>(Val: Mem))
5871 DK = diag::err_anonymous_record_with_static;
5872
5873 // Visual C++ allows type definition in anonymous struct or union.
5874 if (getLangOpts().MicrosoftExt &&
5875 DK == diag::err_anonymous_record_with_type)
5876 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5877 << Record->isUnion();
5878 else {
5879 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5880 Invalid = true;
5881 }
5882 }
5883 }
5884
5885 // C++11 [class.union]p8 (DR1460):
5886 // At most one variant member of a union may have a
5887 // brace-or-equal-initializer.
5888 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5889 Owner->isRecord())
5890 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5891 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5892 }
5893
5894 if (!Record->isUnion() && !Owner->isRecord()) {
5895 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5896 << getLangOpts().CPlusPlus;
5897 Invalid = true;
5898 }
5899
5900 // C++ [dcl.dcl]p3:
5901 // [If there are no declarators], and except for the declaration of an
5902 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5903 // names into the program
5904 // C++ [class.mem]p2:
5905 // each such member-declaration shall either declare at least one member
5906 // name of the class or declare at least one unnamed bit-field
5907 //
5908 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5909 if (getLangOpts().CPlusPlus && Record->field_empty())
5910 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5911
5912 // Mock up a declarator.
5913 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5914 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5915 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5916 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5917
5918 // Create a declaration for this anonymous struct/union.
5919 NamedDecl *Anon = nullptr;
5920 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5921 Anon = FieldDecl::Create(
5922 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5923 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5924 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5925 /*InitStyle=*/ICIS_NoInit);
5926 Anon->setAccess(AS);
5927 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5928
5929 if (getLangOpts().CPlusPlus)
5930 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5931 } else {
5932 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5933 if (SCSpec == DeclSpec::SCS_mutable) {
5934 // mutable can only appear on non-static class members, so it's always
5935 // an error here
5936 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5937 Invalid = true;
5938 SC = SC_None;
5939 }
5940
5941 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5942 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5943 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5944 if (Invalid)
5945 Anon->setInvalidDecl();
5946
5947 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5948
5949 // Default-initialize the implicit variable. This initialization will be
5950 // trivial in almost all cases, except if a union member has an in-class
5951 // initializer:
5952 // union { int n = 0; };
5953 ActOnUninitializedDecl(dcl: Anon);
5954 }
5955 Anon->setImplicit();
5956
5957 // Mark this as an anonymous struct/union type.
5958 Record->setAnonymousStructOrUnion(true);
5959
5960 // Add the anonymous struct/union object to the current
5961 // context. We'll be referencing this object when we refer to one of
5962 // its members.
5963 Owner->addDecl(D: Anon);
5964
5965 // Inject the members of the anonymous struct/union into the owning
5966 // context and into the identifier resolver chain for name lookup
5967 // purposes.
5968 SmallVector<NamedDecl*, 2> Chain;
5969 Chain.push_back(Elt: Anon);
5970
5971 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5972 Chaining&: Chain))
5973 Invalid = true;
5974
5975 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5976 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5977 MangleNumberingContext *MCtx;
5978 Decl *ManglingContextDecl;
5979 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5980 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5981 if (MCtx) {
5982 Context.setManglingNumber(
5983 ND: NewVD, Number: MCtx->getManglingNumber(
5984 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5985 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5986 }
5987 }
5988 }
5989
5990 if (Invalid)
5991 Anon->setInvalidDecl();
5992
5993 return Anon;
5994}
5995
5996Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5997 RecordDecl *Record) {
5998 assert(Record && "expected a record!");
5999
6000 // Mock up a declarator.
6001 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6002 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6003 assert(TInfo && "couldn't build declarator info for anonymous struct");
6004
6005 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6006 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6007
6008 // Create a declaration for this anonymous struct.
6009 NamedDecl *Anon =
6010 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6011 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6012 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6013 /*InitStyle=*/ICIS_NoInit);
6014 Anon->setImplicit();
6015
6016 // Add the anonymous struct object to the current context.
6017 CurContext->addDecl(D: Anon);
6018
6019 // Inject the members of the anonymous struct into the current
6020 // context and into the identifier resolver chain for name lookup
6021 // purposes.
6022 SmallVector<NamedDecl*, 2> Chain;
6023 Chain.push_back(Elt: Anon);
6024
6025 RecordDecl *RecordDef = Record->getDefinition();
6026 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6027 DiagID: diag::err_field_incomplete_or_sizeless) ||
6028 InjectAnonymousStructOrUnionMembers(
6029 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6030 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6031 Anon->setInvalidDecl();
6032 ParentDecl->setInvalidDecl();
6033 }
6034
6035 return Anon;
6036}
6037
6038DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6039 return GetNameFromUnqualifiedId(Name: D.getName());
6040}
6041
6042DeclarationNameInfo
6043Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6044 DeclarationNameInfo NameInfo;
6045 NameInfo.setLoc(Name.StartLocation);
6046
6047 switch (Name.getKind()) {
6048
6049 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6050 case UnqualifiedIdKind::IK_Identifier:
6051 NameInfo.setName(Name.Identifier);
6052 return NameInfo;
6053
6054 case UnqualifiedIdKind::IK_DeductionGuideName: {
6055 // C++ [temp.deduct.guide]p3:
6056 // The simple-template-id shall name a class template specialization.
6057 // The template-name shall be the same identifier as the template-name
6058 // of the simple-template-id.
6059 // These together intend to imply that the template-name shall name a
6060 // class template.
6061 // FIXME: template<typename T> struct X {};
6062 // template<typename T> using Y = X<T>;
6063 // Y(int) -> Y<int>;
6064 // satisfies these rules but does not name a class template.
6065 TemplateName TN = Name.TemplateName.get().get();
6066 auto *Template = TN.getAsTemplateDecl();
6067 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6068 Diag(Loc: Name.StartLocation,
6069 DiagID: diag::err_deduction_guide_name_not_class_template)
6070 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6071 if (Template)
6072 NoteTemplateLocation(Decl: *Template);
6073 return DeclarationNameInfo();
6074 }
6075
6076 NameInfo.setName(
6077 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6078 return NameInfo;
6079 }
6080
6081 case UnqualifiedIdKind::IK_OperatorFunctionId:
6082 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6083 Op: Name.OperatorFunctionId.Operator));
6084 NameInfo.setCXXOperatorNameRange(SourceRange(
6085 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6086 return NameInfo;
6087
6088 case UnqualifiedIdKind::IK_LiteralOperatorId:
6089 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6090 II: Name.Identifier));
6091 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6092 return NameInfo;
6093
6094 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6095 TypeSourceInfo *TInfo;
6096 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6097 if (Ty.isNull())
6098 return DeclarationNameInfo();
6099 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6100 Ty: Context.getCanonicalType(T: Ty)));
6101 NameInfo.setNamedTypeInfo(TInfo);
6102 return NameInfo;
6103 }
6104
6105 case UnqualifiedIdKind::IK_ConstructorName: {
6106 TypeSourceInfo *TInfo;
6107 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6108 if (Ty.isNull())
6109 return DeclarationNameInfo();
6110 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6111 Ty: Context.getCanonicalType(T: Ty)));
6112 NameInfo.setNamedTypeInfo(TInfo);
6113 return NameInfo;
6114 }
6115
6116 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6117 // In well-formed code, we can only have a constructor
6118 // template-id that refers to the current context, so go there
6119 // to find the actual type being constructed.
6120 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6121 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6122 return DeclarationNameInfo();
6123
6124 // Determine the type of the class being constructed.
6125 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6126
6127 // FIXME: Check two things: that the template-id names the same type as
6128 // CurClassType, and that the template-id does not occur when the name
6129 // was qualified.
6130
6131 NameInfo.setName(
6132 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6133 // FIXME: should we retrieve TypeSourceInfo?
6134 NameInfo.setNamedTypeInfo(nullptr);
6135 return NameInfo;
6136 }
6137
6138 case UnqualifiedIdKind::IK_DestructorName: {
6139 TypeSourceInfo *TInfo;
6140 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6141 if (Ty.isNull())
6142 return DeclarationNameInfo();
6143 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6144 Ty: Context.getCanonicalType(T: Ty)));
6145 NameInfo.setNamedTypeInfo(TInfo);
6146 return NameInfo;
6147 }
6148
6149 case UnqualifiedIdKind::IK_TemplateId: {
6150 TemplateName TName = Name.TemplateId->Template.get();
6151 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6152 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6153 }
6154
6155 } // switch (Name.getKind())
6156
6157 llvm_unreachable("Unknown name kind");
6158}
6159
6160static QualType getCoreType(QualType Ty) {
6161 do {
6162 if (Ty->isPointerOrReferenceType())
6163 Ty = Ty->getPointeeType();
6164 else if (Ty->isArrayType())
6165 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6166 else
6167 return Ty.withoutLocalFastQualifiers();
6168 } while (true);
6169}
6170
6171/// hasSimilarParameters - Determine whether the C++ functions Declaration
6172/// and Definition have "nearly" matching parameters. This heuristic is
6173/// used to improve diagnostics in the case where an out-of-line function
6174/// definition doesn't match any declaration within the class or namespace.
6175/// Also sets Params to the list of indices to the parameters that differ
6176/// between the declaration and the definition. If hasSimilarParameters
6177/// returns true and Params is empty, then all of the parameters match.
6178static bool hasSimilarParameters(ASTContext &Context,
6179 FunctionDecl *Declaration,
6180 FunctionDecl *Definition,
6181 SmallVectorImpl<unsigned> &Params) {
6182 Params.clear();
6183 if (Declaration->param_size() != Definition->param_size())
6184 return false;
6185 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6186 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6187 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6188
6189 // The parameter types are identical
6190 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6191 continue;
6192
6193 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6194 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6195 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6196 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6197
6198 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6199 (DeclTyName && DeclTyName == DefTyName))
6200 Params.push_back(Elt: Idx);
6201 else // The two parameters aren't even close
6202 return false;
6203 }
6204
6205 return true;
6206}
6207
6208/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6209/// declarator needs to be rebuilt in the current instantiation.
6210/// Any bits of declarator which appear before the name are valid for
6211/// consideration here. That's specifically the type in the decl spec
6212/// and the base type in any member-pointer chunks.
6213static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6214 DeclarationName Name) {
6215 // The types we specifically need to rebuild are:
6216 // - typenames, typeofs, and decltypes
6217 // - types which will become injected class names
6218 // Of course, we also need to rebuild any type referencing such a
6219 // type. It's safest to just say "dependent", but we call out a
6220 // few cases here.
6221
6222 DeclSpec &DS = D.getMutableDeclSpec();
6223 switch (DS.getTypeSpecType()) {
6224 case DeclSpec::TST_typename:
6225 case DeclSpec::TST_typeofType:
6226 case DeclSpec::TST_typeof_unqualType:
6227#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6228#include "clang/Basic/TransformTypeTraits.def"
6229 case DeclSpec::TST_atomic: {
6230 // Grab the type from the parser.
6231 TypeSourceInfo *TSI = nullptr;
6232 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6233 if (T.isNull() || !T->isInstantiationDependentType()) break;
6234
6235 // Make sure there's a type source info. This isn't really much
6236 // of a waste; most dependent types should have type source info
6237 // attached already.
6238 if (!TSI)
6239 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6240
6241 // Rebuild the type in the current instantiation.
6242 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6243 if (!TSI) return true;
6244
6245 // Store the new type back in the decl spec.
6246 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6247 DS.UpdateTypeRep(Rep: LocType);
6248 break;
6249 }
6250
6251 case DeclSpec::TST_decltype:
6252 case DeclSpec::TST_typeof_unqualExpr:
6253 case DeclSpec::TST_typeofExpr: {
6254 Expr *E = DS.getRepAsExpr();
6255 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6256 if (Result.isInvalid()) return true;
6257 DS.UpdateExprRep(Rep: Result.get());
6258 break;
6259 }
6260
6261 default:
6262 // Nothing to do for these decl specs.
6263 break;
6264 }
6265
6266 // It doesn't matter what order we do this in.
6267 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6268 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6269
6270 // The only type information in the declarator which can come
6271 // before the declaration name is the base type of a member
6272 // pointer.
6273 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6274 continue;
6275
6276 // Rebuild the scope specifier in-place.
6277 CXXScopeSpec &SS = Chunk.Mem.Scope();
6278 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6279 return true;
6280 }
6281
6282 return false;
6283}
6284
6285/// Returns true if the declaration is declared in a system header or from a
6286/// system macro.
6287static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6288 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6289 SM.isInSystemMacro(loc: D->getLocation());
6290}
6291
6292void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6293 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6294 // of system decl.
6295 if (D->getPreviousDecl() || D->isImplicit())
6296 return;
6297 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6298 if (Status != ReservedIdentifierStatus::NotReserved &&
6299 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6300 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6301 << D << static_cast<int>(Status);
6302 }
6303}
6304
6305Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6306 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6307
6308 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6309 // declaration only if the `bind_to_declaration` extension is set.
6310 SmallVector<FunctionDecl *, 4> Bases;
6311 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6312 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6313 TP: llvm::omp::TraitProperty::
6314 implementation_extension_bind_to_declaration))
6315 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6316 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6317
6318 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6319
6320 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6321 Dcl && Dcl->getDeclContext()->isFileContext())
6322 Dcl->setTopLevelDeclInObjCContainer();
6323
6324 if (!Bases.empty())
6325 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6326 Bases);
6327
6328 return Dcl;
6329}
6330
6331bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6332 DeclarationNameInfo NameInfo) {
6333 DeclarationName Name = NameInfo.getName();
6334
6335 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6336 while (Record && Record->isAnonymousStructOrUnion())
6337 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6338 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6339 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6340 return true;
6341 }
6342
6343 return false;
6344}
6345
6346bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6347 DeclarationName Name,
6348 SourceLocation Loc,
6349 TemplateIdAnnotation *TemplateId,
6350 bool IsMemberSpecialization) {
6351 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6352 "without nested-name-specifier");
6353 DeclContext *Cur = CurContext;
6354 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6355 Cur = Cur->getParent();
6356
6357 // If the user provided a superfluous scope specifier that refers back to the
6358 // class in which the entity is already declared, diagnose and ignore it.
6359 //
6360 // class X {
6361 // void X::f();
6362 // };
6363 //
6364 // Note, it was once ill-formed to give redundant qualification in all
6365 // contexts, but that rule was removed by DR482.
6366 if (Cur->Equals(DC)) {
6367 if (Cur->isRecord()) {
6368 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6369 : diag::err_member_extra_qualification)
6370 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6371 SS.clear();
6372 } else {
6373 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6374 }
6375 return false;
6376 }
6377
6378 // Check whether the qualifying scope encloses the scope of the original
6379 // declaration. For a template-id, we perform the checks in
6380 // CheckTemplateSpecializationScope.
6381 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6382 if (Cur->isRecord())
6383 Diag(Loc, DiagID: diag::err_member_qualification)
6384 << Name << SS.getRange();
6385 else if (isa<TranslationUnitDecl>(Val: DC))
6386 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6387 << Name << SS.getRange();
6388 else if (isa<FunctionDecl>(Val: Cur))
6389 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6390 << Name << SS.getRange();
6391 else if (isa<BlockDecl>(Val: Cur))
6392 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6393 << Name << SS.getRange();
6394 else if (isa<ExportDecl>(Val: Cur)) {
6395 if (!isa<NamespaceDecl>(Val: DC))
6396 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6397 << Name << SS.getRange();
6398 else
6399 // The cases that DC is not NamespaceDecl should be handled in
6400 // CheckRedeclarationExported.
6401 return false;
6402 } else
6403 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6404 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6405
6406 return true;
6407 }
6408
6409 if (Cur->isRecord()) {
6410 // Cannot qualify members within a class.
6411 Diag(Loc, DiagID: diag::err_member_qualification)
6412 << Name << SS.getRange();
6413 SS.clear();
6414
6415 // C++ constructors and destructors with incorrect scopes can break
6416 // our AST invariants by having the wrong underlying types. If
6417 // that's the case, then drop this declaration entirely.
6418 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6419 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6420 !Context.hasSameType(
6421 T1: Name.getCXXNameType(),
6422 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6423 return true;
6424
6425 return false;
6426 }
6427
6428 // C++23 [temp.names]p5:
6429 // The keyword template shall not appear immediately after a declarative
6430 // nested-name-specifier.
6431 //
6432 // First check the template-id (if any), and then check each component of the
6433 // nested-name-specifier in reverse order.
6434 //
6435 // FIXME: nested-name-specifiers in friend declarations are declarative,
6436 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6437 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6438 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6439 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6440
6441 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6442 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6443 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6444 SourceLocation TemplateKeywordLoc;
6445 switch (TL.getTypeLocClass()) {
6446 case TypeLoc::TemplateSpecialization: {
6447 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6448 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6449 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6450 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6451 << TST.getLocalSourceRange();
6452 break;
6453 }
6454 case TypeLoc::Decltype:
6455 case TypeLoc::PackIndexing: {
6456 const Type *T = TL.getTypePtr();
6457 // C++23 [expr.prim.id.qual]p2:
6458 // [...] A declarative nested-name-specifier shall not have a
6459 // computed-type-specifier.
6460 //
6461 // CWG2858 changed this from 'decltype-specifier' to
6462 // 'computed-type-specifier'.
6463 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6464 << T->isDecltypeType() << TL.getSourceRange();
6465 break;
6466 }
6467 case TypeLoc::DependentName:
6468 NextTL =
6469 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6470 break;
6471 default:
6472 break;
6473 }
6474 if (TemplateKeywordLoc.isValid())
6475 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6476 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6477 }
6478
6479 return false;
6480}
6481
6482NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6483 MultiTemplateParamsArg TemplateParamLists) {
6484 // TODO: consider using NameInfo for diagnostic.
6485 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6486 DeclarationName Name = NameInfo.getName();
6487
6488 // All of these full declarators require an identifier. If it doesn't have
6489 // one, the ParsedFreeStandingDeclSpec action should be used.
6490 if (D.isDecompositionDeclarator()) {
6491 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6492 } else if (!Name) {
6493 if (!D.isInvalidType()) // Reject this if we think it is valid.
6494 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6495 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6496 return nullptr;
6497 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6498 return nullptr;
6499
6500 DeclContext *DC = CurContext;
6501 if (D.getCXXScopeSpec().isInvalid())
6502 D.setInvalidType();
6503 else if (D.getCXXScopeSpec().isSet()) {
6504 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6505 UPPC: UPPC_DeclarationQualifier))
6506 return nullptr;
6507
6508 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6509 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6510 if (!DC || isa<EnumDecl>(Val: DC)) {
6511 // If we could not compute the declaration context, it's because the
6512 // declaration context is dependent but does not refer to a class,
6513 // class template, or class template partial specialization. Complain
6514 // and return early, to avoid the coming semantic disaster.
6515 Diag(Loc: D.getIdentifierLoc(),
6516 DiagID: diag::err_template_qualified_declarator_no_match)
6517 << D.getCXXScopeSpec().getScopeRep()
6518 << D.getCXXScopeSpec().getRange();
6519 return nullptr;
6520 }
6521 bool IsDependentContext = DC->isDependentContext();
6522
6523 if (!IsDependentContext &&
6524 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6525 return nullptr;
6526
6527 // If a class is incomplete, do not parse entities inside it.
6528 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6529 Diag(Loc: D.getIdentifierLoc(),
6530 DiagID: diag::err_member_def_undefined_record)
6531 << Name << DC << D.getCXXScopeSpec().getRange();
6532 return nullptr;
6533 }
6534 if (!D.getDeclSpec().isFriendSpecified()) {
6535 TemplateIdAnnotation *TemplateId =
6536 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6537 ? D.getName().TemplateId
6538 : nullptr;
6539 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6540 Loc: D.getIdentifierLoc(), TemplateId,
6541 /*IsMemberSpecialization=*/false)) {
6542 if (DC->isRecord())
6543 return nullptr;
6544
6545 D.setInvalidType();
6546 }
6547 }
6548
6549 // Check whether we need to rebuild the type of the given
6550 // declaration in the current instantiation.
6551 if (EnteringContext && IsDependentContext &&
6552 TemplateParamLists.size() != 0) {
6553 ContextRAII SavedContext(*this, DC);
6554 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6555 D.setInvalidType();
6556 }
6557 }
6558
6559 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6560 QualType R = TInfo->getType();
6561
6562 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6563 UPPC: UPPC_DeclarationType))
6564 D.setInvalidType();
6565
6566 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6567 forRedeclarationInCurContext());
6568
6569 // See if this is a redefinition of a variable in the same scope.
6570 if (!D.getCXXScopeSpec().isSet()) {
6571 bool IsLinkageLookup = false;
6572 bool CreateBuiltins = false;
6573
6574 // If the declaration we're planning to build will be a function
6575 // or object with linkage, then look for another declaration with
6576 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6577 //
6578 // If the declaration we're planning to build will be declared with
6579 // external linkage in the translation unit, create any builtin with
6580 // the same name.
6581 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6582 /* Do nothing*/;
6583 else if (CurContext->isFunctionOrMethod() &&
6584 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6585 R->isFunctionType())) {
6586 IsLinkageLookup = true;
6587 CreateBuiltins =
6588 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6589 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6590 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6591 CreateBuiltins = true;
6592
6593 if (IsLinkageLookup) {
6594 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6595 Previous.setRedeclarationKind(
6596 RedeclarationKind::ForExternalRedeclaration);
6597 }
6598
6599 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6600 } else { // Something like "int foo::x;"
6601 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6602
6603 // C++ [dcl.meaning]p1:
6604 // When the declarator-id is qualified, the declaration shall refer to a
6605 // previously declared member of the class or namespace to which the
6606 // qualifier refers (or, in the case of a namespace, of an element of the
6607 // inline namespace set of that namespace (7.3.1)) or to a specialization
6608 // thereof; [...]
6609 //
6610 // Note that we already checked the context above, and that we do not have
6611 // enough information to make sure that Previous contains the declaration
6612 // we want to match. For example, given:
6613 //
6614 // class X {
6615 // void f();
6616 // void f(float);
6617 // };
6618 //
6619 // void X::f(int) { } // ill-formed
6620 //
6621 // In this case, Previous will point to the overload set
6622 // containing the two f's declared in X, but neither of them
6623 // matches.
6624
6625 RemoveUsingDecls(R&: Previous);
6626 }
6627
6628 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6629 TPD && TPD->isTemplateParameter()) {
6630 // Older versions of clang allowed the names of function/variable templates
6631 // to shadow the names of their template parameters. For the compatibility
6632 // purposes we detect such cases and issue a default-to-error warning that
6633 // can be disabled with -Wno-strict-primary-template-shadow.
6634 if (!D.isInvalidType()) {
6635 bool AllowForCompatibility = false;
6636 if (Scope *DeclParent = S->getDeclParent();
6637 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6638 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6639 TemplateParamParent->isDeclScope(D: TPD);
6640 }
6641 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6642 SupportedForCompatibility: AllowForCompatibility);
6643 }
6644
6645 // Just pretend that we didn't see the previous declaration.
6646 Previous.clear();
6647 }
6648
6649 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6650 // Forget that the previous declaration is the injected-class-name.
6651 Previous.clear();
6652
6653 // In C++, the previous declaration we find might be a tag type
6654 // (class or enum). In this case, the new declaration will hide the
6655 // tag type. Note that this applies to functions, function templates, and
6656 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6657 if (Previous.isSingleTagDecl() &&
6658 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6659 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6660 Previous.clear();
6661
6662 // Check that there are no default arguments other than in the parameters
6663 // of a function declaration (C++ only).
6664 if (getLangOpts().CPlusPlus)
6665 CheckExtraCXXDefaultArguments(D);
6666
6667 /// Get the innermost enclosing declaration scope.
6668 S = S->getDeclParent();
6669
6670 NamedDecl *New;
6671
6672 bool AddToScope = true;
6673 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6674 if (TemplateParamLists.size()) {
6675 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6676 return nullptr;
6677 }
6678
6679 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6680 } else if (R->isFunctionType()) {
6681 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6682 TemplateParamLists,
6683 AddToScope);
6684 } else {
6685 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6686 AddToScope);
6687 }
6688
6689 if (!New)
6690 return nullptr;
6691
6692 warnOnCTypeHiddenInCPlusPlus(D: New);
6693
6694 // If this has an identifier and is not a function template specialization,
6695 // add it to the scope stack.
6696 if (New->getDeclName() && AddToScope)
6697 PushOnScopeChains(D: New, S);
6698
6699 if (OpenMP().isInOpenMPDeclareTargetContext())
6700 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6701
6702 return New;
6703}
6704
6705/// Helper method to turn variable array types into constant array
6706/// types in certain situations which would otherwise be errors (for
6707/// GCC compatibility).
6708static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6709 ASTContext &Context,
6710 bool &SizeIsNegative,
6711 llvm::APSInt &Oversized) {
6712 // This method tries to turn a variable array into a constant
6713 // array even when the size isn't an ICE. This is necessary
6714 // for compatibility with code that depends on gcc's buggy
6715 // constant expression folding, like struct {char x[(int)(char*)2];}
6716 SizeIsNegative = false;
6717 Oversized = 0;
6718
6719 if (T->isDependentType())
6720 return QualType();
6721
6722 QualifierCollector Qs;
6723 const Type *Ty = Qs.strip(type: T);
6724
6725 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6726 QualType Pointee = PTy->getPointeeType();
6727 QualType FixedType =
6728 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6729 Oversized);
6730 if (FixedType.isNull()) return FixedType;
6731 FixedType = Context.getPointerType(T: FixedType);
6732 return Qs.apply(Context, QT: FixedType);
6733 }
6734 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6735 QualType Inner = PTy->getInnerType();
6736 QualType FixedType =
6737 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6738 Oversized);
6739 if (FixedType.isNull()) return FixedType;
6740 FixedType = Context.getParenType(NamedType: FixedType);
6741 return Qs.apply(Context, QT: FixedType);
6742 }
6743
6744 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6745 if (!VLATy)
6746 return QualType();
6747
6748 QualType ElemTy = VLATy->getElementType();
6749 if (ElemTy->isVariablyModifiedType()) {
6750 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6751 SizeIsNegative, Oversized);
6752 if (ElemTy.isNull())
6753 return QualType();
6754 }
6755
6756 Expr::EvalResult Result;
6757 if (!VLATy->getSizeExpr() ||
6758 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6759 return QualType();
6760
6761 llvm::APSInt Res = Result.Val.getInt();
6762
6763 // Check whether the array size is negative.
6764 if (Res.isSigned() && Res.isNegative()) {
6765 SizeIsNegative = true;
6766 return QualType();
6767 }
6768
6769 // Check whether the array is too large to be addressed.
6770 unsigned ActiveSizeBits =
6771 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6772 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6773 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6774 : Res.getActiveBits();
6775 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6776 Oversized = std::move(Res);
6777 return QualType();
6778 }
6779
6780 QualType FoldedArrayType = Context.getConstantArrayType(
6781 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6782 return Qs.apply(Context, QT: FoldedArrayType);
6783}
6784
6785static void
6786FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6787 SrcTL = SrcTL.getUnqualifiedLoc();
6788 DstTL = DstTL.getUnqualifiedLoc();
6789 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6790 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6791 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6792 DstTL: DstPTL.getPointeeLoc());
6793 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6794 return;
6795 }
6796 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6797 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6798 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6799 DstTL: DstPTL.getInnerLoc());
6800 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6801 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6802 return;
6803 }
6804 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6805 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6806 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6807 TypeLoc DstElemTL = DstATL.getElementLoc();
6808 if (VariableArrayTypeLoc SrcElemATL =
6809 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6810 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6811 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6812 } else {
6813 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6814 }
6815 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6816 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6817 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6818}
6819
6820/// Helper method to turn variable array types into constant array
6821/// types in certain situations which would otherwise be errors (for
6822/// GCC compatibility).
6823static TypeSourceInfo*
6824TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6825 ASTContext &Context,
6826 bool &SizeIsNegative,
6827 llvm::APSInt &Oversized) {
6828 QualType FixedTy
6829 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6830 SizeIsNegative, Oversized);
6831 if (FixedTy.isNull())
6832 return nullptr;
6833 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6834 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6835 DstTL: FixedTInfo->getTypeLoc());
6836 return FixedTInfo;
6837}
6838
6839bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6840 QualType &T, SourceLocation Loc,
6841 unsigned FailedFoldDiagID) {
6842 bool SizeIsNegative;
6843 llvm::APSInt Oversized;
6844 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6845 TInfo, Context, SizeIsNegative, Oversized);
6846 if (FixedTInfo) {
6847 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6848 TInfo = FixedTInfo;
6849 T = FixedTInfo->getType();
6850 return true;
6851 }
6852
6853 if (SizeIsNegative)
6854 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6855 else if (Oversized.getBoolValue())
6856 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6857 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6858 /*UpperCase=*/false, /*InsertSeparators=*/true);
6859 else if (FailedFoldDiagID)
6860 Diag(Loc, DiagID: FailedFoldDiagID);
6861 return false;
6862}
6863
6864void
6865Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6866 if (!getLangOpts().CPlusPlus &&
6867 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6868 // Don't need to track declarations in the TU in C.
6869 return;
6870
6871 // Note that we have a locally-scoped external with this name.
6872 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6873}
6874
6875NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6876 // FIXME: We can have multiple results via __attribute__((overloadable)).
6877 auto Result = Context.getExternCContextDecl()->lookup(Name);
6878 return Result.empty() ? nullptr : *Result.begin();
6879}
6880
6881void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6882 // FIXME: We should probably indicate the identifier in question to avoid
6883 // confusion for constructs like "virtual int a(), b;"
6884 if (DS.isVirtualSpecified())
6885 Diag(Loc: DS.getVirtualSpecLoc(),
6886 DiagID: diag::err_virtual_non_function);
6887
6888 if (DS.hasExplicitSpecifier())
6889 Diag(Loc: DS.getExplicitSpecLoc(),
6890 DiagID: diag::err_explicit_non_function);
6891
6892 if (DS.isNoreturnSpecified())
6893 Diag(Loc: DS.getNoreturnSpecLoc(),
6894 DiagID: diag::err_noreturn_non_function);
6895}
6896
6897NamedDecl*
6898Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6899 TypeSourceInfo *TInfo, LookupResult &Previous) {
6900 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6901 if (D.getCXXScopeSpec().isSet()) {
6902 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6903 << D.getCXXScopeSpec().getRange();
6904 D.setInvalidType();
6905 // Pretend we didn't see the scope specifier.
6906 DC = CurContext;
6907 Previous.clear();
6908 }
6909
6910 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6911
6912 if (D.getDeclSpec().isInlineSpecified())
6913 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6914 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6915 ? diag::warn_ms_inline_non_function
6916 : diag::err_inline_non_function)
6917 << getLangOpts().CPlusPlus17;
6918 if (D.getDeclSpec().hasConstexprSpecifier())
6919 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6920 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6921
6922 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6923 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6924 Diag(Loc: D.getName().StartLocation,
6925 DiagID: diag::err_deduction_guide_invalid_specifier)
6926 << "typedef";
6927 else
6928 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6929 << D.getName().getSourceRange();
6930 return nullptr;
6931 }
6932
6933 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6934 if (!NewTD) return nullptr;
6935
6936 // Handle attributes prior to checking for duplicates in MergeVarDecl
6937 ProcessDeclAttributes(S, D: NewTD, PD: D);
6938
6939 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6940
6941 bool Redeclaration = D.isRedeclaration();
6942 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6943 D.setRedeclaration(Redeclaration);
6944 return ND;
6945}
6946
6947void
6948Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6949 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6950 // then it shall have block scope.
6951 // Note that variably modified types must be fixed before merging the decl so
6952 // that redeclarations will match.
6953 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6954 QualType T = TInfo->getType();
6955 if (T->isVariablyModifiedType()) {
6956 setFunctionHasBranchProtectedScope();
6957
6958 if (S->getFnParent() == nullptr) {
6959 bool SizeIsNegative;
6960 llvm::APSInt Oversized;
6961 TypeSourceInfo *FixedTInfo =
6962 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6963 SizeIsNegative,
6964 Oversized);
6965 if (FixedTInfo) {
6966 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6967 NewTD->setTypeSourceInfo(FixedTInfo);
6968 } else {
6969 if (SizeIsNegative)
6970 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6971 else if (T->isVariableArrayType())
6972 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6973 else if (Oversized.getBoolValue())
6974 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6975 << toString(I: Oversized, Radix: 10);
6976 else
6977 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6978 NewTD->setInvalidDecl();
6979 }
6980 }
6981 }
6982}
6983
6984NamedDecl*
6985Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6986 LookupResult &Previous, bool &Redeclaration) {
6987
6988 // Find the shadowed declaration before filtering for scope.
6989 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6990
6991 // Merge the decl with the existing one if appropriate. If the decl is
6992 // in an outer scope, it isn't the same thing.
6993 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6994 /*AllowInlineNamespace*/false);
6995 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6996 if (!Previous.empty()) {
6997 Redeclaration = true;
6998 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6999 } else {
7000 inferGslPointerAttribute(TD: NewTD);
7001 }
7002
7003 if (ShadowedDecl && !Redeclaration)
7004 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7005
7006 // If this is the C FILE type, notify the AST context.
7007 if (IdentifierInfo *II = NewTD->getIdentifier())
7008 if (!NewTD->isInvalidDecl() &&
7009 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7010 switch (II->getNotableIdentifierID()) {
7011 case tok::NotableIdentifierKind::FILE:
7012 Context.setFILEDecl(NewTD);
7013 break;
7014 case tok::NotableIdentifierKind::jmp_buf:
7015 Context.setjmp_bufDecl(NewTD);
7016 break;
7017 case tok::NotableIdentifierKind::sigjmp_buf:
7018 Context.setsigjmp_bufDecl(NewTD);
7019 break;
7020 case tok::NotableIdentifierKind::ucontext_t:
7021 Context.setucontext_tDecl(NewTD);
7022 break;
7023 case tok::NotableIdentifierKind::float_t:
7024 case tok::NotableIdentifierKind::double_t:
7025 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7026 break;
7027 default:
7028 break;
7029 }
7030 }
7031
7032 return NewTD;
7033}
7034
7035/// Determines whether the given declaration is an out-of-scope
7036/// previous declaration.
7037///
7038/// This routine should be invoked when name lookup has found a
7039/// previous declaration (PrevDecl) that is not in the scope where a
7040/// new declaration by the same name is being introduced. If the new
7041/// declaration occurs in a local scope, previous declarations with
7042/// linkage may still be considered previous declarations (C99
7043/// 6.2.2p4-5, C++ [basic.link]p6).
7044///
7045/// \param PrevDecl the previous declaration found by name
7046/// lookup
7047///
7048/// \param DC the context in which the new declaration is being
7049/// declared.
7050///
7051/// \returns true if PrevDecl is an out-of-scope previous declaration
7052/// for a new delcaration with the same name.
7053static bool
7054isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7055 ASTContext &Context) {
7056 if (!PrevDecl)
7057 return false;
7058
7059 if (!PrevDecl->hasLinkage())
7060 return false;
7061
7062 if (Context.getLangOpts().CPlusPlus) {
7063 // C++ [basic.link]p6:
7064 // If there is a visible declaration of an entity with linkage
7065 // having the same name and type, ignoring entities declared
7066 // outside the innermost enclosing namespace scope, the block
7067 // scope declaration declares that same entity and receives the
7068 // linkage of the previous declaration.
7069 DeclContext *OuterContext = DC->getRedeclContext();
7070 if (!OuterContext->isFunctionOrMethod())
7071 // This rule only applies to block-scope declarations.
7072 return false;
7073
7074 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7075 if (PrevOuterContext->isRecord())
7076 // We found a member function: ignore it.
7077 return false;
7078
7079 // Find the innermost enclosing namespace for the new and
7080 // previous declarations.
7081 OuterContext = OuterContext->getEnclosingNamespaceContext();
7082 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7083
7084 // The previous declaration is in a different namespace, so it
7085 // isn't the same function.
7086 if (!OuterContext->Equals(DC: PrevOuterContext))
7087 return false;
7088 }
7089
7090 return true;
7091}
7092
7093static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7094 CXXScopeSpec &SS = D.getCXXScopeSpec();
7095 if (!SS.isSet()) return;
7096 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7097}
7098
7099void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7100 LangAS ImplAS = LangAS::opencl_private;
7101 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7102 // __opencl_c_program_scope_global_variables feature, the address space
7103 // for a variable at program scope or a static or extern variable inside
7104 // a function are inferred to be __global.
7105 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7106 Var->hasGlobalStorage())
7107 ImplAS = LangAS::opencl_global;
7108 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7109}
7110
7111static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7112 // 'weak' only applies to declarations with external linkage.
7113 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7114 if (!ND.isExternallyVisible()) {
7115 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7116 ND.dropAttr<WeakAttr>();
7117 }
7118 }
7119}
7120
7121static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7122 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7123 if (ND.isExternallyVisible()) {
7124 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7125 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7126 }
7127 }
7128}
7129
7130static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7131 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7132 if (VD->hasInit()) {
7133 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7134 assert(VD->isThisDeclarationADefinition() &&
7135 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7136 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7137 VD->dropAttr<AliasAttr>();
7138 }
7139 }
7140 }
7141}
7142
7143static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7144 // 'selectany' only applies to externally visible variable declarations.
7145 // It does not apply to functions.
7146 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7147 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7148 S.Diag(Loc: Attr->getLocation(),
7149 DiagID: diag::err_attribute_selectany_non_extern_data);
7150 ND.dropAttr<SelectAnyAttr>();
7151 }
7152 }
7153}
7154
7155static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7156 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7157 if (!ND.isExternallyVisible())
7158 S.Diag(Loc: Attr->getLocation(),
7159 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7160 }
7161}
7162
7163static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7164 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7165 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7166 bool IsAnonymousNS = false;
7167 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7168 if (VD) {
7169 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7170 while (NS && !IsAnonymousNS) {
7171 IsAnonymousNS = NS->isAnonymousNamespace();
7172 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7173 }
7174 }
7175 // dll attributes require external linkage. Static locals may have external
7176 // linkage but still cannot be explicitly imported or exported.
7177 // In Microsoft mode, a variable defined in anonymous namespace must have
7178 // external linkage in order to be exported.
7179 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7180 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7181 (!AnonNSInMicrosoftMode &&
7182 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7183 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7184 << &ND << Attr;
7185 ND.setInvalidDecl();
7186 }
7187 }
7188}
7189
7190static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7191 // Check the attributes on the function type and function params, if any.
7192 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7193 FD = FD->getMostRecentDecl();
7194 // Don't declare this variable in the second operand of the for-statement;
7195 // GCC miscompiles that by ending its lifetime before evaluating the
7196 // third operand. See gcc.gnu.org/PR86769.
7197 AttributedTypeLoc ATL;
7198 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7199 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7200 TL = ATL.getModifiedLoc()) {
7201 // The [[lifetimebound]] attribute can be applied to the implicit object
7202 // parameter of a non-static member function (other than a ctor or dtor)
7203 // by applying it to the function type.
7204 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7205 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7206 int NoImplicitObjectError = -1;
7207 if (!MD)
7208 NoImplicitObjectError = 0;
7209 else if (MD->isStatic())
7210 NoImplicitObjectError = 1;
7211 else if (MD->isExplicitObjectMemberFunction())
7212 NoImplicitObjectError = 2;
7213 if (NoImplicitObjectError != -1) {
7214 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7215 << NoImplicitObjectError << A->getRange();
7216 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7217 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7218 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7219 } else if (MD->getReturnType()->isVoidType()) {
7220 S.Diag(
7221 Loc: MD->getLocation(),
7222 DiagID: diag::
7223 err_lifetimebound_implicit_object_parameter_void_return_type);
7224 }
7225 }
7226 }
7227
7228 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7229 const ParmVarDecl *P = FD->getParamDecl(i: I);
7230
7231 // The [[lifetimebound]] attribute can be applied to a function parameter
7232 // only if the function returns a value.
7233 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7234 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7235 S.Diag(Loc: A->getLocation(),
7236 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7237 }
7238 }
7239 }
7240 }
7241}
7242
7243static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7244 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7245 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7246}
7247
7248static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7249 // Ensure that an auto decl is deduced otherwise the checks below might cache
7250 // the wrong linkage.
7251 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7252
7253 checkWeakAttr(S, ND);
7254 checkWeakRefAttr(S, ND);
7255 checkAliasAttr(S, ND);
7256 checkSelectAnyAttr(S, ND);
7257 checkHybridPatchableAttr(S, ND);
7258 checkInheritableAttr(S, ND);
7259 checkLifetimeBoundAttr(S, ND);
7260}
7261
7262static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7263 NamedDecl *NewDecl,
7264 bool IsSpecialization,
7265 bool IsDefinition) {
7266 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7267 return;
7268
7269 bool IsTemplate = false;
7270 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7271 OldDecl = OldTD->getTemplatedDecl();
7272 IsTemplate = true;
7273 if (!IsSpecialization)
7274 IsDefinition = false;
7275 }
7276 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7277 NewDecl = NewTD->getTemplatedDecl();
7278 IsTemplate = true;
7279 }
7280
7281 if (!OldDecl || !NewDecl)
7282 return;
7283
7284 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7285 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7286 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7287 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7288
7289 // dllimport and dllexport are inheritable attributes so we have to exclude
7290 // inherited attribute instances.
7291 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7292 (NewExportAttr && !NewExportAttr->isInherited());
7293
7294 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7295 // the only exception being explicit specializations.
7296 // Implicitly generated declarations are also excluded for now because there
7297 // is no other way to switch these to use dllimport or dllexport.
7298 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7299
7300 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7301 // Allow with a warning for free functions and global variables.
7302 bool JustWarn = false;
7303 if (!OldDecl->isCXXClassMember()) {
7304 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7305 if (VD && !VD->getDescribedVarTemplate())
7306 JustWarn = true;
7307 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7308 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7309 JustWarn = true;
7310 }
7311
7312 // We cannot change a declaration that's been used because IR has already
7313 // been emitted. Dllimported functions will still work though (modulo
7314 // address equality) as they can use the thunk.
7315 if (OldDecl->isUsed())
7316 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7317 JustWarn = false;
7318
7319 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7320 : diag::err_attribute_dll_redeclaration;
7321 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7322 << NewDecl
7323 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7324 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7325 if (!JustWarn) {
7326 NewDecl->setInvalidDecl();
7327 return;
7328 }
7329 }
7330
7331 // A redeclaration is not allowed to drop a dllimport attribute, the only
7332 // exceptions being inline function definitions (except for function
7333 // templates), local extern declarations, qualified friend declarations or
7334 // special MSVC extension: in the last case, the declaration is treated as if
7335 // it were marked dllexport.
7336 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7337 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7338 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7339 // Ignore static data because out-of-line definitions are diagnosed
7340 // separately.
7341 IsStaticDataMember = VD->isStaticDataMember();
7342 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7343 VarDecl::DeclarationOnly;
7344 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7345 IsInline = FD->isInlined();
7346 IsQualifiedFriend = FD->getQualifier() &&
7347 FD->getFriendObjectKind() == Decl::FOK_Declared;
7348 }
7349
7350 if (OldImportAttr && !HasNewAttr &&
7351 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7352 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7353 if (IsMicrosoftABI && IsDefinition) {
7354 if (IsSpecialization) {
7355 S.Diag(
7356 Loc: NewDecl->getLocation(),
7357 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7358 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7359 NewDecl->dropAttr<DLLImportAttr>();
7360 } else {
7361 S.Diag(Loc: NewDecl->getLocation(),
7362 DiagID: diag::warn_redeclaration_without_import_attribute)
7363 << NewDecl;
7364 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7365 NewDecl->dropAttr<DLLImportAttr>();
7366 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7367 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7368 }
7369 } else if (IsMicrosoftABI && IsSpecialization) {
7370 assert(!IsDefinition);
7371 // MSVC allows this. Keep the inherited attribute.
7372 } else {
7373 S.Diag(Loc: NewDecl->getLocation(),
7374 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7375 << NewDecl << OldImportAttr;
7376 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7377 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7378 OldDecl->dropAttr<DLLImportAttr>();
7379 NewDecl->dropAttr<DLLImportAttr>();
7380 }
7381 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7382 // In MinGW, seeing a function declared inline drops the dllimport
7383 // attribute.
7384 OldDecl->dropAttr<DLLImportAttr>();
7385 NewDecl->dropAttr<DLLImportAttr>();
7386 S.Diag(Loc: NewDecl->getLocation(),
7387 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7388 << NewDecl << OldImportAttr;
7389 }
7390
7391 // A specialization of a class template member function is processed here
7392 // since it's a redeclaration. If the parent class is dllexport, the
7393 // specialization inherits that attribute. This doesn't happen automatically
7394 // since the parent class isn't instantiated until later.
7395 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7396 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7397 !NewImportAttr && !NewExportAttr) {
7398 if (const DLLExportAttr *ParentExportAttr =
7399 MD->getParent()->getAttr<DLLExportAttr>()) {
7400 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7401 NewAttr->setInherited(true);
7402 NewDecl->addAttr(A: NewAttr);
7403 }
7404 }
7405 }
7406}
7407
7408/// Given that we are within the definition of the given function,
7409/// will that definition behave like C99's 'inline', where the
7410/// definition is discarded except for optimization purposes?
7411static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7412 // Try to avoid calling GetGVALinkageForFunction.
7413
7414 // All cases of this require the 'inline' keyword.
7415 if (!FD->isInlined()) return false;
7416
7417 // This is only possible in C++ with the gnu_inline attribute.
7418 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7419 return false;
7420
7421 // Okay, go ahead and call the relatively-more-expensive function.
7422 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7423}
7424
7425/// Determine whether a variable is extern "C" prior to attaching
7426/// an initializer. We can't just call isExternC() here, because that
7427/// will also compute and cache whether the declaration is externally
7428/// visible, which might change when we attach the initializer.
7429///
7430/// This can only be used if the declaration is known to not be a
7431/// redeclaration of an internal linkage declaration.
7432///
7433/// For instance:
7434///
7435/// auto x = []{};
7436///
7437/// Attaching the initializer here makes this declaration not externally
7438/// visible, because its type has internal linkage.
7439///
7440/// FIXME: This is a hack.
7441template<typename T>
7442static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7443 if (S.getLangOpts().CPlusPlus) {
7444 // In C++, the overloadable attribute negates the effects of extern "C".
7445 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7446 return false;
7447
7448 // So do CUDA's host/device attributes.
7449 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7450 D->template hasAttr<CUDAHostAttr>()))
7451 return false;
7452 }
7453 return D->isExternC();
7454}
7455
7456static bool shouldConsiderLinkage(const VarDecl *VD) {
7457 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7458 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7459 isa<OMPDeclareMapperDecl>(Val: DC))
7460 return VD->hasExternalStorage();
7461 if (DC->isFileContext())
7462 return true;
7463 if (DC->isRecord())
7464 return false;
7465 if (DC->getDeclKind() == Decl::HLSLBuffer)
7466 return false;
7467
7468 if (isa<RequiresExprBodyDecl>(Val: DC))
7469 return false;
7470 llvm_unreachable("Unexpected context");
7471}
7472
7473static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7474 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7475 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7476 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7477 return true;
7478 if (DC->isRecord())
7479 return false;
7480 llvm_unreachable("Unexpected context");
7481}
7482
7483static bool hasParsedAttr(Scope *S, const Declarator &PD,
7484 ParsedAttr::Kind Kind) {
7485 // Check decl attributes on the DeclSpec.
7486 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7487 return true;
7488
7489 // Walk the declarator structure, checking decl attributes that were in a type
7490 // position to the decl itself.
7491 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7492 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7493 return true;
7494 }
7495
7496 // Finally, check attributes on the decl itself.
7497 return PD.getAttributes().hasAttribute(K: Kind) ||
7498 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7499}
7500
7501bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7502 if (!DC->isFunctionOrMethod())
7503 return false;
7504
7505 // If this is a local extern function or variable declared within a function
7506 // template, don't add it into the enclosing namespace scope until it is
7507 // instantiated; it might have a dependent type right now.
7508 if (DC->isDependentContext())
7509 return true;
7510
7511 // C++11 [basic.link]p7:
7512 // When a block scope declaration of an entity with linkage is not found to
7513 // refer to some other declaration, then that entity is a member of the
7514 // innermost enclosing namespace.
7515 //
7516 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7517 // semantically-enclosing namespace, not a lexically-enclosing one.
7518 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7519 DC = DC->getParent();
7520 return true;
7521}
7522
7523/// Returns true if given declaration has external C language linkage.
7524static bool isDeclExternC(const Decl *D) {
7525 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7526 return FD->isExternC();
7527 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7528 return VD->isExternC();
7529
7530 llvm_unreachable("Unknown type of decl!");
7531}
7532
7533/// Returns true if there hasn't been any invalid type diagnosed.
7534static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7535 DeclContext *DC = NewVD->getDeclContext();
7536 QualType R = NewVD->getType();
7537
7538 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7539 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7540 // argument.
7541 if (R->isImageType() || R->isPipeType()) {
7542 Se.Diag(Loc: NewVD->getLocation(),
7543 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7544 << R;
7545 NewVD->setInvalidDecl();
7546 return false;
7547 }
7548
7549 // OpenCL v1.2 s6.9.r:
7550 // The event type cannot be used to declare a program scope variable.
7551 // OpenCL v2.0 s6.9.q:
7552 // The clk_event_t and reserve_id_t types cannot be declared in program
7553 // scope.
7554 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7555 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7556 Se.Diag(Loc: NewVD->getLocation(),
7557 DiagID: diag::err_invalid_type_for_program_scope_var)
7558 << R;
7559 NewVD->setInvalidDecl();
7560 return false;
7561 }
7562 }
7563
7564 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7565 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7566 LO: Se.getLangOpts())) {
7567 QualType NR = R.getCanonicalType();
7568 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7569 NR->isReferenceType()) {
7570 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7571 NR->isFunctionReferenceType()) {
7572 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7573 << NR->isReferenceType();
7574 NewVD->setInvalidDecl();
7575 return false;
7576 }
7577 NR = NR->getPointeeType();
7578 }
7579 }
7580
7581 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7582 LO: Se.getLangOpts())) {
7583 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7584 // half array type (unless the cl_khr_fp16 extension is enabled).
7585 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7586 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7587 NewVD->setInvalidDecl();
7588 return false;
7589 }
7590 }
7591
7592 // OpenCL v1.2 s6.9.r:
7593 // The event type cannot be used with the __local, __constant and __global
7594 // address space qualifiers.
7595 if (R->isEventT()) {
7596 if (R.getAddressSpace() != LangAS::opencl_private) {
7597 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7598 NewVD->setInvalidDecl();
7599 return false;
7600 }
7601 }
7602
7603 if (R->isSamplerT()) {
7604 // OpenCL v1.2 s6.9.b p4:
7605 // The sampler type cannot be used with the __local and __global address
7606 // space qualifiers.
7607 if (R.getAddressSpace() == LangAS::opencl_local ||
7608 R.getAddressSpace() == LangAS::opencl_global) {
7609 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7610 NewVD->setInvalidDecl();
7611 }
7612
7613 // OpenCL v1.2 s6.12.14.1:
7614 // A global sampler must be declared with either the constant address
7615 // space qualifier or with the const qualifier.
7616 if (DC->isTranslationUnit() &&
7617 !(R.getAddressSpace() == LangAS::opencl_constant ||
7618 R.isConstQualified())) {
7619 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7620 NewVD->setInvalidDecl();
7621 }
7622 if (NewVD->isInvalidDecl())
7623 return false;
7624 }
7625
7626 return true;
7627}
7628
7629template <typename AttrTy>
7630static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7631 const TypedefNameDecl *TND = TT->getDecl();
7632 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7633 AttrTy *Clone = Attribute->clone(S.Context);
7634 Clone->setInherited(true);
7635 D->addAttr(A: Clone);
7636 }
7637}
7638
7639// This function emits warning and a corresponding note based on the
7640// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7641// declarations of an annotated type must be const qualified.
7642static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7643 QualType VarType = VD->getType().getCanonicalType();
7644
7645 // Ignore local declarations (for now) and those with const qualification.
7646 // TODO: Local variables should not be allowed if their type declaration has
7647 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7648 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7649 return;
7650
7651 if (VarType->isArrayType()) {
7652 // Retrieve element type for array declarations.
7653 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7654 }
7655
7656 const RecordDecl *RD = VarType->getAsRecordDecl();
7657
7658 // Check if the record declaration is present and if it has any attributes.
7659 if (RD == nullptr)
7660 return;
7661
7662 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7663 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7664 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7665 return;
7666 }
7667}
7668
7669void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7670 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7671 "NewD is not a function or variable");
7672
7673 if (PendingExportedNames.empty())
7674 return;
7675 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7676 if (getLangOpts().CPlusPlus && !FD->isExternC())
7677 return;
7678 }
7679 IdentifierInfo *IdentName = NewD->getIdentifier();
7680 if (IdentName == nullptr)
7681 return;
7682 auto PendingName = PendingExportedNames.find(Val: IdentName);
7683 if (PendingName != PendingExportedNames.end()) {
7684 auto &Label = PendingName->second;
7685 if (!Label.Used) {
7686 Label.Used = true;
7687 if (NewD->hasExternalFormalLinkage())
7688 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7689 else
7690 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7691 }
7692 }
7693}
7694
7695// Checks if VD is declared at global scope or with C language linkage.
7696static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7697 return Name.getAsIdentifierInfo() &&
7698 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7699 !VD->getDescribedVarTemplate() &&
7700 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7701 VD->isExternC());
7702}
7703
7704void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7705 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7706
7707 // Quickly return if the function does not have an `asm` attribute.
7708 if (E == nullptr)
7709 return;
7710
7711 // The parser guarantees this is a string.
7712 StringLiteral *SE = cast<StringLiteral>(Val: E);
7713 StringRef Label = SE->getString();
7714 QualType R = TInfo->getType();
7715 if (S->getFnParent() != nullptr) {
7716 switch (SC) {
7717 case SC_None:
7718 case SC_Auto:
7719 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7720 break;
7721 case SC_Register:
7722 // Local Named register
7723 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7724 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7725 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7726 break;
7727 case SC_Static:
7728 case SC_Extern:
7729 case SC_PrivateExtern:
7730 break;
7731 }
7732 } else if (SC == SC_Register) {
7733 // Global Named register
7734 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7735 const auto &TI = Context.getTargetInfo();
7736 bool HasSizeMismatch;
7737
7738 if (!TI.isValidGCCRegisterName(Name: Label))
7739 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7740 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7741 HasSizeMismatch))
7742 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7743 else if (HasSizeMismatch)
7744 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7745 }
7746
7747 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7748 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7749 DiagID: diag::err_asm_unsupported_register_type)
7750 << TInfo->getTypeLoc().getSourceRange();
7751 NewVD->setInvalidDecl(true);
7752 }
7753 }
7754}
7755
7756NamedDecl *Sema::ActOnVariableDeclarator(
7757 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7758 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7759 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7760 QualType R = TInfo->getType();
7761 DeclarationName Name = GetNameForDeclarator(D).getName();
7762
7763 IdentifierInfo *II = Name.getAsIdentifierInfo();
7764 bool IsPlaceholderVariable = false;
7765
7766 if (D.isDecompositionDeclarator()) {
7767 // Take the name of the first declarator as our name for diagnostic
7768 // purposes.
7769 auto &Decomp = D.getDecompositionDeclarator();
7770 if (!Decomp.bindings().empty()) {
7771 II = Decomp.bindings()[0].Name;
7772 Name = II;
7773 }
7774 } else if (!II) {
7775 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7776 return nullptr;
7777 }
7778
7779
7780 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7781 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7782 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7783 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7784
7785 IsPlaceholderVariable = true;
7786
7787 if (!Previous.empty()) {
7788 NamedDecl *PrevDecl = *Previous.begin();
7789 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7790 DC: DC->getRedeclContext());
7791 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7792 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7793 if (IsPlaceholderVariable)
7794 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7795 }
7796 }
7797 }
7798
7799 // dllimport globals without explicit storage class are treated as extern. We
7800 // have to change the storage class this early to get the right DeclContext.
7801 if (SC == SC_None && !DC->isRecord() &&
7802 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7803 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7804 SC = SC_Extern;
7805
7806 DeclContext *OriginalDC = DC;
7807 bool IsLocalExternDecl = SC == SC_Extern &&
7808 adjustContextForLocalExternDecl(DC);
7809
7810 if (SCSpec == DeclSpec::SCS_mutable) {
7811 // mutable can only appear on non-static class members, so it's always
7812 // an error here
7813 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7814 D.setInvalidType();
7815 SC = SC_None;
7816 }
7817
7818 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7819 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7820 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7821 // In C++11, the 'register' storage class specifier is deprecated.
7822 // Suppress the warning in system macros, it's used in macros in some
7823 // popular C system headers, such as in glibc's htonl() macro.
7824 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7825 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7826 : diag::warn_deprecated_register)
7827 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7828 }
7829
7830 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7831
7832 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7833 // C99 6.9p2: The storage-class specifiers auto and register shall not
7834 // appear in the declaration specifiers in an external declaration.
7835 // Global Register+Asm is a GNU extension we support.
7836 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7837 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7838 D.setInvalidType();
7839 }
7840 }
7841
7842 // If this variable has a VLA type and an initializer, try to
7843 // fold to a constant-sized type. This is otherwise invalid.
7844 if (D.hasInitializer() && R->isVariableArrayType())
7845 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7846 /*DiagID=*/FailedFoldDiagID: 0);
7847
7848 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7849 const AutoType *AT = TL.getTypePtr();
7850 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7851 }
7852
7853 bool IsMemberSpecialization = false;
7854 bool IsVariableTemplateSpecialization = false;
7855 bool IsPartialSpecialization = false;
7856 bool IsVariableTemplate = false;
7857 VarDecl *NewVD = nullptr;
7858 VarTemplateDecl *NewTemplate = nullptr;
7859 TemplateParameterList *TemplateParams = nullptr;
7860 if (!getLangOpts().CPlusPlus) {
7861 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7862 Id: II, T: R, TInfo, S: SC);
7863
7864 if (R->getContainedDeducedType())
7865 ParsingInitForAutoVars.insert(Ptr: NewVD);
7866
7867 if (D.isInvalidType())
7868 NewVD->setInvalidDecl();
7869
7870 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7871 NewVD->hasLocalStorage())
7872 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7873 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7874 } else {
7875 bool Invalid = false;
7876 // Match up the template parameter lists with the scope specifier, then
7877 // determine whether we have a template or a template specialization.
7878 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7879 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7880 SS: D.getCXXScopeSpec(),
7881 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7882 ? D.getName().TemplateId
7883 : nullptr,
7884 ParamLists: TemplateParamLists,
7885 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7886
7887 if (TemplateParams) {
7888 if (DC->isDependentContext()) {
7889 ContextRAII SavedContext(*this, DC);
7890 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7891 Invalid = true;
7892 }
7893
7894 if (!TemplateParams->size() &&
7895 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7896 // There is an extraneous 'template<>' for this variable. Complain
7897 // about it, but allow the declaration of the variable.
7898 Diag(Loc: TemplateParams->getTemplateLoc(),
7899 DiagID: diag::err_template_variable_noparams)
7900 << II
7901 << SourceRange(TemplateParams->getTemplateLoc(),
7902 TemplateParams->getRAngleLoc());
7903 TemplateParams = nullptr;
7904 } else {
7905 // Check that we can declare a template here.
7906 if (CheckTemplateDeclScope(S, TemplateParams))
7907 return nullptr;
7908
7909 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7910 // This is an explicit specialization or a partial specialization.
7911 IsVariableTemplateSpecialization = true;
7912 IsPartialSpecialization = TemplateParams->size() > 0;
7913 } else { // if (TemplateParams->size() > 0)
7914 // This is a template declaration.
7915 IsVariableTemplate = true;
7916
7917 // Only C++1y supports variable templates (N3651).
7918 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7919 }
7920 }
7921 } else {
7922 // Check that we can declare a member specialization here.
7923 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7924 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7925 return nullptr;
7926 assert((Invalid ||
7927 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7928 "should have a 'template<>' for this decl");
7929 }
7930
7931 bool IsExplicitSpecialization =
7932 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7933
7934 // C++ [temp.expl.spec]p2:
7935 // The declaration in an explicit-specialization shall not be an
7936 // export-declaration. An explicit specialization shall not use a
7937 // storage-class-specifier other than thread_local.
7938 //
7939 // We use the storage-class-specifier from DeclSpec because we may have
7940 // added implicit 'extern' for declarations with __declspec(dllimport)!
7941 if (SCSpec != DeclSpec::SCS_unspecified &&
7942 (IsExplicitSpecialization || IsMemberSpecialization)) {
7943 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7944 DiagID: diag::ext_explicit_specialization_storage_class)
7945 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7946 }
7947
7948 if (CurContext->isRecord()) {
7949 if (SC == SC_Static) {
7950 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7951 // Walk up the enclosing DeclContexts to check for any that are
7952 // incompatible with static data members.
7953 const DeclContext *FunctionOrMethod = nullptr;
7954 const CXXRecordDecl *AnonStruct = nullptr;
7955 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7956 if (Ctxt->isFunctionOrMethod()) {
7957 FunctionOrMethod = Ctxt;
7958 break;
7959 }
7960 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7961 if (ParentDecl && !ParentDecl->getDeclName()) {
7962 AnonStruct = ParentDecl;
7963 break;
7964 }
7965 }
7966 if (FunctionOrMethod) {
7967 // C++ [class.static.data]p5: A local class shall not have static
7968 // data members.
7969 Diag(Loc: D.getIdentifierLoc(),
7970 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7971 << Name << RD->getDeclName() << RD->getTagKind();
7972 Invalid = true;
7973 } else if (AnonStruct) {
7974 // C++ [class.static.data]p4: Unnamed classes and classes contained
7975 // directly or indirectly within unnamed classes shall not contain
7976 // static data members.
7977 Diag(Loc: D.getIdentifierLoc(),
7978 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7979 << Name << AnonStruct->getTagKind();
7980 Invalid = true;
7981 } else if (RD->isUnion()) {
7982 // C++98 [class.union]p1: If a union contains a static data member,
7983 // the program is ill-formed. C++11 drops this restriction.
7984 DiagCompat(Loc: D.getIdentifierLoc(),
7985 CompatDiagId: diag_compat::static_data_member_in_union)
7986 << Name;
7987 }
7988 }
7989 } else if (IsVariableTemplate || IsPartialSpecialization) {
7990 // There is no such thing as a member field template.
7991 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7992 << II << TemplateParams->getSourceRange();
7993 // Recover by pretending this is a static data member template.
7994 SC = SC_Static;
7995 }
7996 } else if (DC->isRecord()) {
7997 // This is an out-of-line definition of a static data member.
7998 switch (SC) {
7999 case SC_None:
8000 break;
8001 case SC_Static:
8002 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8003 DiagID: diag::err_static_out_of_line)
8004 << FixItHint::CreateRemoval(
8005 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8006 break;
8007 case SC_Auto:
8008 case SC_Register:
8009 case SC_Extern:
8010 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8011 // to names of variables declared in a block or to function parameters.
8012 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8013 // of class members
8014
8015 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8016 DiagID: diag::err_storage_class_for_static_member)
8017 << FixItHint::CreateRemoval(
8018 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8019 break;
8020 case SC_PrivateExtern:
8021 llvm_unreachable("C storage class in c++!");
8022 }
8023 }
8024
8025 if (IsVariableTemplateSpecialization) {
8026 SourceLocation TemplateKWLoc =
8027 TemplateParamLists.size() > 0
8028 ? TemplateParamLists[0]->getTemplateLoc()
8029 : SourceLocation();
8030 DeclResult Res = ActOnVarTemplateSpecialization(
8031 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8032 IsPartialSpecialization);
8033 if (Res.isInvalid())
8034 return nullptr;
8035 NewVD = cast<VarDecl>(Val: Res.get());
8036 AddToScope = false;
8037 } else if (D.isDecompositionDeclarator()) {
8038 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8039 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
8040 Bindings);
8041 } else
8042 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8043 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8044
8045 // If this is supposed to be a variable template, create it as such.
8046 if (IsVariableTemplate) {
8047 NewTemplate =
8048 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8049 Params: TemplateParams, Decl: NewVD);
8050 NewVD->setDescribedVarTemplate(NewTemplate);
8051 }
8052
8053 // If this decl has an auto type in need of deduction, make a note of the
8054 // Decl so we can diagnose uses of it in its own initializer.
8055 if (R->getContainedDeducedType())
8056 ParsingInitForAutoVars.insert(Ptr: NewVD);
8057
8058 if (D.isInvalidType() || Invalid) {
8059 NewVD->setInvalidDecl();
8060 if (NewTemplate)
8061 NewTemplate->setInvalidDecl();
8062 }
8063
8064 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8065
8066 // If we have any template parameter lists that don't directly belong to
8067 // the variable (matching the scope specifier), store them.
8068 // An explicit variable template specialization does not own any template
8069 // parameter lists.
8070 unsigned VDTemplateParamLists =
8071 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8072 if (TemplateParamLists.size() > VDTemplateParamLists)
8073 NewVD->setTemplateParameterListsInfo(
8074 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8075 }
8076
8077 if (D.getDeclSpec().isInlineSpecified()) {
8078 if (!getLangOpts().CPlusPlus) {
8079 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8080 << 0;
8081 } else if (CurContext->isFunctionOrMethod()) {
8082 // 'inline' is not allowed on block scope variable declaration.
8083 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8084 DiagID: diag::err_inline_declaration_block_scope) << Name
8085 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8086 } else {
8087 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8088 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8089 : diag::compat_pre_cxx17_inline_variable);
8090 NewVD->setInlineSpecified();
8091 }
8092 }
8093
8094 // Set the lexical context. If the declarator has a C++ scope specifier, the
8095 // lexical context will be different from the semantic context.
8096 NewVD->setLexicalDeclContext(CurContext);
8097 if (NewTemplate)
8098 NewTemplate->setLexicalDeclContext(CurContext);
8099
8100 if (IsLocalExternDecl) {
8101 if (D.isDecompositionDeclarator())
8102 for (auto *B : Bindings)
8103 B->setLocalExternDecl();
8104 else
8105 NewVD->setLocalExternDecl();
8106 }
8107
8108 bool EmitTLSUnsupportedError = false;
8109 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8110 // C++11 [dcl.stc]p4:
8111 // When thread_local is applied to a variable of block scope the
8112 // storage-class-specifier static is implied if it does not appear
8113 // explicitly.
8114 // Core issue: 'static' is not implied if the variable is declared
8115 // 'extern'.
8116 if (NewVD->hasLocalStorage() &&
8117 (SCSpec != DeclSpec::SCS_unspecified ||
8118 TSCS != DeclSpec::TSCS_thread_local ||
8119 !DC->isFunctionOrMethod()))
8120 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8121 DiagID: diag::err_thread_non_global)
8122 << DeclSpec::getSpecifierName(S: TSCS);
8123 else if (!Context.getTargetInfo().isTLSSupported()) {
8124 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8125 // Postpone error emission until we've collected attributes required to
8126 // figure out whether it's a host or device variable and whether the
8127 // error should be ignored.
8128 EmitTLSUnsupportedError = true;
8129 // We still need to mark the variable as TLS so it shows up in AST with
8130 // proper storage class for other tools to use even if we're not going
8131 // to emit any code for it.
8132 NewVD->setTSCSpec(TSCS);
8133 } else
8134 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8135 DiagID: diag::err_thread_unsupported);
8136 } else
8137 NewVD->setTSCSpec(TSCS);
8138 }
8139
8140 switch (D.getDeclSpec().getConstexprSpecifier()) {
8141 case ConstexprSpecKind::Unspecified:
8142 break;
8143
8144 case ConstexprSpecKind::Consteval:
8145 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8146 DiagID: diag::err_constexpr_wrong_decl_kind)
8147 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8148 [[fallthrough]];
8149
8150 case ConstexprSpecKind::Constexpr:
8151 NewVD->setConstexpr(true);
8152 // C++1z [dcl.spec.constexpr]p1:
8153 // A static data member declared with the constexpr specifier is
8154 // implicitly an inline variable.
8155 if (NewVD->isStaticDataMember() &&
8156 (getLangOpts().CPlusPlus17 ||
8157 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8158 NewVD->setImplicitlyInline();
8159 break;
8160
8161 case ConstexprSpecKind::Constinit:
8162 if (!NewVD->hasGlobalStorage())
8163 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8164 DiagID: diag::err_constinit_local_variable);
8165 else
8166 NewVD->addAttr(
8167 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8168 S: ConstInitAttr::Keyword_constinit));
8169 break;
8170 }
8171
8172 // C99 6.7.4p3
8173 // An inline definition of a function with external linkage shall
8174 // not contain a definition of a modifiable object with static or
8175 // thread storage duration...
8176 // We only apply this when the function is required to be defined
8177 // elsewhere, i.e. when the function is not 'extern inline'. Note
8178 // that a local variable with thread storage duration still has to
8179 // be marked 'static'. Also note that it's possible to get these
8180 // semantics in C++ using __attribute__((gnu_inline)).
8181 if (SC == SC_Static && S->getFnParent() != nullptr &&
8182 !NewVD->getType().isConstQualified()) {
8183 FunctionDecl *CurFD = getCurFunctionDecl();
8184 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8185 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8186 DiagID: diag::warn_static_local_in_extern_inline);
8187 MaybeSuggestAddingStaticToDecl(D: CurFD);
8188 }
8189 }
8190
8191 if (D.getDeclSpec().isModulePrivateSpecified()) {
8192 if (IsVariableTemplateSpecialization)
8193 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8194 << (IsPartialSpecialization ? 1 : 0)
8195 << FixItHint::CreateRemoval(
8196 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8197 else if (IsMemberSpecialization)
8198 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8199 << 2
8200 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8201 else if (NewVD->hasLocalStorage())
8202 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8203 << 0 << NewVD
8204 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8205 << FixItHint::CreateRemoval(
8206 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8207 else {
8208 NewVD->setModulePrivate();
8209 if (NewTemplate)
8210 NewTemplate->setModulePrivate();
8211 for (auto *B : Bindings)
8212 B->setModulePrivate();
8213 }
8214 }
8215
8216 if (getLangOpts().OpenCL) {
8217 deduceOpenCLAddressSpace(Var: NewVD);
8218
8219 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8220 if (TSC != TSCS_unspecified) {
8221 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8222 DiagID: diag::err_opencl_unknown_type_specifier)
8223 << getLangOpts().getOpenCLVersionString()
8224 << DeclSpec::getSpecifierName(S: TSC) << 1;
8225 NewVD->setInvalidDecl();
8226 }
8227 }
8228
8229 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8230 // address space if the table has local storage (semantic checks elsewhere
8231 // will produce an error anyway).
8232 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8233 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8234 !NewVD->hasLocalStorage()) {
8235 QualType Type = Context.getAddrSpaceQualType(
8236 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8237 NewVD->setType(Type);
8238 }
8239 }
8240
8241 LoadExternalExtnameUndeclaredIdentifiers();
8242
8243 if (Expr *E = D.getAsmLabel()) {
8244 // The parser guarantees this is a string.
8245 StringLiteral *SE = cast<StringLiteral>(Val: E);
8246 StringRef Label = SE->getString();
8247
8248 // Insert the asm attribute.
8249 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8250 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8251 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8252 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8253 if (I != ExtnameUndeclaredIdentifiers.end()) {
8254 if (isDeclExternC(D: NewVD)) {
8255 NewVD->addAttr(A: I->second);
8256 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8257 } else if (NewVD->getDeclContext()
8258 ->getRedeclContext()
8259 ->isTranslationUnit())
8260 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8261 << /*Variable*/ 1 << NewVD;
8262 }
8263 }
8264
8265 // Handle attributes prior to checking for duplicates in MergeVarDecl
8266 ProcessDeclAttributes(S, D: NewVD, PD: D);
8267
8268 if (getLangOpts().HLSL)
8269 HLSL().ActOnVariableDeclarator(VD: NewVD);
8270
8271 if (getLangOpts().OpenACC)
8272 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8273
8274 // FIXME: This is probably the wrong location to be doing this and we should
8275 // probably be doing this for more attributes (especially for function
8276 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8277 // the code to copy attributes would be generated by TableGen.
8278 if (R->isFunctionPointerType())
8279 if (const auto *TT = R->getAs<TypedefType>())
8280 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8281
8282 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8283 if (EmitTLSUnsupportedError &&
8284 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8285 (getLangOpts().OpenMPIsTargetDevice &&
8286 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8287 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8288 DiagID: diag::err_thread_unsupported);
8289
8290 if (EmitTLSUnsupportedError &&
8291 (LangOpts.SYCLIsDevice ||
8292 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8293 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8294 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8295 // storage [duration]."
8296 if (SC == SC_None && S->getFnParent() != nullptr &&
8297 (NewVD->hasAttr<CUDASharedAttr>() ||
8298 NewVD->hasAttr<CUDAConstantAttr>())) {
8299 NewVD->setStorageClass(SC_Static);
8300 }
8301 }
8302
8303 // Ensure that dllimport globals without explicit storage class are treated as
8304 // extern. The storage class is set above using parsed attributes. Now we can
8305 // check the VarDecl itself.
8306 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8307 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8308 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8309
8310 // In auto-retain/release, infer strong retension for variables of
8311 // retainable type.
8312 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8313 NewVD->setInvalidDecl();
8314
8315 // Check the ASM label here, as we need to know all other attributes of the
8316 // Decl first. Otherwise, we can't know if the asm label refers to the
8317 // host or device in a CUDA context. The device has other registers than
8318 // host and we must know where the function will be placed.
8319 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8320
8321 // Find the shadowed declaration before filtering for scope.
8322 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8323 ? getShadowedDeclaration(D: NewVD, R: Previous)
8324 : nullptr;
8325
8326 // Don't consider existing declarations that are in a different
8327 // scope and are out-of-semantic-context declarations (if the new
8328 // declaration has linkage).
8329 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8330 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8331 IsMemberSpecialization ||
8332 IsVariableTemplateSpecialization);
8333
8334 // Check whether the previous declaration is in the same block scope. This
8335 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8336 if (getLangOpts().CPlusPlus &&
8337 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8338 NewVD->setPreviousDeclInSameBlockScope(
8339 Previous.isSingleResult() && !Previous.isShadowed() &&
8340 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8341
8342 if (!getLangOpts().CPlusPlus) {
8343 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8344 } else {
8345 // If this is an explicit specialization of a static data member, check it.
8346 if (IsMemberSpecialization && !IsVariableTemplate &&
8347 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8348 CheckMemberSpecialization(Member: NewVD, Previous))
8349 NewVD->setInvalidDecl();
8350
8351 // Merge the decl with the existing one if appropriate.
8352 if (!Previous.empty()) {
8353 if (Previous.isSingleResult() &&
8354 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8355 D.getCXXScopeSpec().isSet()) {
8356 // The user tried to define a non-static data member
8357 // out-of-line (C++ [dcl.meaning]p1).
8358 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8359 << D.getCXXScopeSpec().getRange();
8360 Previous.clear();
8361 NewVD->setInvalidDecl();
8362 }
8363 } else if (D.getCXXScopeSpec().isSet() &&
8364 !IsVariableTemplateSpecialization) {
8365 // No previous declaration in the qualifying scope.
8366 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8367 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8368 << D.getCXXScopeSpec().getRange();
8369 NewVD->setInvalidDecl();
8370 }
8371
8372 if (!IsPlaceholderVariable)
8373 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8374
8375 // CheckVariableDeclaration will set NewVD as invalid if something is in
8376 // error like WebAssembly tables being declared as arrays with a non-zero
8377 // size, but then parsing continues and emits further errors on that line.
8378 // To avoid that we check here if it happened and return nullptr.
8379 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8380 return nullptr;
8381
8382 if (NewTemplate) {
8383 VarTemplateDecl *PrevVarTemplate =
8384 NewVD->getPreviousDecl()
8385 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8386 : nullptr;
8387
8388 // Check the template parameter list of this declaration, possibly
8389 // merging in the template parameter list from the previous variable
8390 // template declaration.
8391 if (CheckTemplateParameterList(
8392 NewParams: TemplateParams,
8393 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8394 : nullptr,
8395 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8396 DC->isDependentContext())
8397 ? TPC_ClassTemplateMember
8398 : TPC_Other))
8399 NewVD->setInvalidDecl();
8400 }
8401 }
8402
8403 if (IsMemberSpecialization) {
8404 if (NewTemplate && NewVD->getPreviousDecl()) {
8405 NewTemplate->setMemberSpecialization();
8406 } else if (IsPartialSpecialization) {
8407 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8408 ->setMemberSpecialization();
8409 }
8410 }
8411
8412 // Diagnose shadowed variables iff this isn't a redeclaration.
8413 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8414 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8415
8416 ProcessPragmaWeak(S, D: NewVD);
8417 ProcessPragmaExport(NewD: NewVD);
8418
8419 // If this is the first declaration of an extern C variable, update
8420 // the map of such variables.
8421 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8422 isIncompleteDeclExternC(S&: *this, D: NewVD))
8423 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8424
8425 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8426 MangleNumberingContext *MCtx;
8427 Decl *ManglingContextDecl;
8428 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8429 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8430 if (MCtx) {
8431 Context.setManglingNumber(
8432 ND: NewVD, Number: MCtx->getManglingNumber(
8433 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8434 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8435 }
8436 }
8437
8438 // Special handling of variable named 'main'.
8439 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8440 // C++ [basic.start.main]p3:
8441 // A program that declares
8442 // - a variable main at global scope, or
8443 // - an entity named main with C language linkage (in any namespace)
8444 // is ill-formed
8445 if (getLangOpts().CPlusPlus)
8446 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8447 << NewVD->isExternC();
8448
8449 // In C, and external-linkage variable named main results in undefined
8450 // behavior.
8451 else if (NewVD->hasExternalFormalLinkage())
8452 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8453 }
8454
8455 if (D.isRedeclaration() && !Previous.empty()) {
8456 NamedDecl *Prev = Previous.getRepresentativeDecl();
8457 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8458 IsDefinition: D.isFunctionDefinition());
8459 }
8460
8461 if (NewTemplate) {
8462 if (NewVD->isInvalidDecl())
8463 NewTemplate->setInvalidDecl();
8464 ActOnDocumentableDecl(D: NewTemplate);
8465 return NewTemplate;
8466 }
8467
8468 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8469 CompleteMemberSpecialization(Member: NewVD, Previous);
8470
8471 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8472
8473 return NewVD;
8474}
8475
8476/// Enum describing the %select options in diag::warn_decl_shadow.
8477enum ShadowedDeclKind {
8478 SDK_Local,
8479 SDK_Global,
8480 SDK_StaticMember,
8481 SDK_Field,
8482 SDK_Typedef,
8483 SDK_Using,
8484 SDK_StructuredBinding
8485};
8486
8487/// Determine what kind of declaration we're shadowing.
8488static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8489 const DeclContext *OldDC) {
8490 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8491 return SDK_Using;
8492 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8493 return SDK_Typedef;
8494 else if (isa<BindingDecl>(Val: ShadowedDecl))
8495 return SDK_StructuredBinding;
8496 else if (isa<RecordDecl>(Val: OldDC))
8497 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8498
8499 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8500}
8501
8502/// Return the location of the capture if the given lambda captures the given
8503/// variable \p VD, or an invalid source location otherwise.
8504static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8505 const ValueDecl *VD) {
8506 for (const Capture &Capture : LSI->Captures) {
8507 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8508 return Capture.getLocation();
8509 }
8510 return SourceLocation();
8511}
8512
8513static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8514 const LookupResult &R) {
8515 // Only diagnose if we're shadowing an unambiguous field or variable.
8516 if (R.getResultKind() != LookupResultKind::Found)
8517 return false;
8518
8519 // Return false if warning is ignored.
8520 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8521}
8522
8523NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8524 const LookupResult &R) {
8525 if (!shouldWarnIfShadowedDecl(Diags, R))
8526 return nullptr;
8527
8528 // Don't diagnose declarations at file scope.
8529 if (D->hasGlobalStorage() && !D->isStaticLocal())
8530 return nullptr;
8531
8532 NamedDecl *ShadowedDecl = R.getFoundDecl();
8533 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8534 : nullptr;
8535}
8536
8537NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8538 const LookupResult &R) {
8539 // Don't warn if typedef declaration is part of a class
8540 if (D->getDeclContext()->isRecord())
8541 return nullptr;
8542
8543 if (!shouldWarnIfShadowedDecl(Diags, R))
8544 return nullptr;
8545
8546 NamedDecl *ShadowedDecl = R.getFoundDecl();
8547 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8548}
8549
8550NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8551 const LookupResult &R) {
8552 if (!shouldWarnIfShadowedDecl(Diags, R))
8553 return nullptr;
8554
8555 NamedDecl *ShadowedDecl = R.getFoundDecl();
8556 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8557 : nullptr;
8558}
8559
8560void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8561 const LookupResult &R) {
8562 DeclContext *NewDC = D->getDeclContext();
8563
8564 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8565 if (const auto *MD =
8566 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8567 // Fields aren't shadowed in C++ static members or in member functions
8568 // with an explicit object parameter.
8569 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8570 return;
8571 }
8572 // Fields shadowed by constructor parameters are a special case. Usually
8573 // the constructor initializes the field with the parameter.
8574 if (isa<CXXConstructorDecl>(Val: NewDC))
8575 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8576 // Remember that this was shadowed so we can either warn about its
8577 // modification or its existence depending on warning settings.
8578 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8579 return;
8580 }
8581 }
8582
8583 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8584 if (shadowedVar->isExternC()) {
8585 // For shadowing external vars, make sure that we point to the global
8586 // declaration, not a locally scoped extern declaration.
8587 for (auto *I : shadowedVar->redecls())
8588 if (I->isFileVarDecl()) {
8589 ShadowedDecl = I;
8590 break;
8591 }
8592 }
8593
8594 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8595
8596 unsigned WarningDiag = diag::warn_decl_shadow;
8597 SourceLocation CaptureLoc;
8598 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8599 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8600 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8601 // Handle both VarDecl and BindingDecl in lambda contexts
8602 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8603 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8604 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8605 if (RD->getLambdaCaptureDefault() == LCD_None) {
8606 // Try to avoid warnings for lambdas with an explicit capture
8607 // list. Warn only when the lambda captures the shadowed decl
8608 // explicitly.
8609 CaptureLoc = getCaptureLocation(LSI, VD);
8610 if (CaptureLoc.isInvalid())
8611 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8612 } else {
8613 // Remember that this was shadowed so we can avoid the warning if
8614 // the shadowed decl isn't captured and the warning settings allow
8615 // it.
8616 cast<LambdaScopeInfo>(Val: getCurFunction())
8617 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8618 return;
8619 }
8620 }
8621 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8622 // If lambda can capture this, then emit default shadowing warning,
8623 // Otherwise it is not really a shadowing case since field is not
8624 // available in lambda's body.
8625 // At this point we don't know that lambda can capture this, so
8626 // remember that this was shadowed and delay until we know.
8627 cast<LambdaScopeInfo>(Val: getCurFunction())
8628 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8629 return;
8630 }
8631 }
8632 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8633 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8634 bool HasLocalStorage = false;
8635 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8636 HasLocalStorage = VD->hasLocalStorage();
8637 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8638 HasLocalStorage =
8639 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8640
8641 if (HasLocalStorage) {
8642 // A variable can't shadow a local variable or binding in an enclosing
8643 // scope, if they are separated by a non-capturing declaration
8644 // context.
8645 for (DeclContext *ParentDC = NewDC;
8646 ParentDC && !ParentDC->Equals(DC: OldDC);
8647 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8648 // Only block literals, captured statements, and lambda expressions
8649 // can capture; other scopes don't.
8650 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8651 !isLambdaCallOperator(DC: ParentDC))
8652 return;
8653 }
8654 }
8655 }
8656 }
8657 }
8658
8659 // Never warn about shadowing a placeholder variable.
8660 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8661 return;
8662
8663 // Only warn about certain kinds of shadowing for class members.
8664 if (NewDC) {
8665 // In particular, don't warn about shadowing non-class members.
8666 if (NewDC->isRecord() && !OldDC->isRecord())
8667 return;
8668
8669 // Skip shadowing check if we're in a class scope, dealing with an enum
8670 // constant in a different context.
8671 DeclContext *ReDC = NewDC->getRedeclContext();
8672 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8673 return;
8674
8675 // TODO: should we warn about static data members shadowing
8676 // static data members from base classes?
8677
8678 // TODO: don't diagnose for inaccessible shadowed members.
8679 // This is hard to do perfectly because we might friend the
8680 // shadowing context, but that's just a false negative.
8681 }
8682
8683 DeclarationName Name = R.getLookupName();
8684
8685 // Emit warning and note.
8686 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8687 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8688 if (!CaptureLoc.isInvalid())
8689 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8690 << Name << /*explicitly*/ 1;
8691 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8692}
8693
8694void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8695 for (const auto &Shadow : LSI->ShadowingDecls) {
8696 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8697 // Try to avoid the warning when the shadowed decl isn't captured.
8698 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8699 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8700 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8701 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8702 Diag(Loc: Shadow.VD->getLocation(),
8703 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8704 : diag::warn_decl_shadow)
8705 << Shadow.VD->getDeclName()
8706 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8707 if (CaptureLoc.isValid())
8708 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8709 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8710 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8711 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8712 Diag(Loc: Shadow.VD->getLocation(),
8713 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8714 : diag::warn_decl_shadow_uncaptured_local)
8715 << Shadow.VD->getDeclName()
8716 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8717 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8718 }
8719 }
8720}
8721
8722void Sema::CheckShadow(Scope *S, VarDecl *D) {
8723 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8724 return;
8725
8726 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8727 Sema::LookupOrdinaryName,
8728 RedeclarationKind::ForVisibleRedeclaration);
8729 LookupName(R, S);
8730 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8731 CheckShadow(D, ShadowedDecl, R);
8732}
8733
8734/// Check if 'E', which is an expression that is about to be modified, refers
8735/// to a constructor parameter that shadows a field.
8736void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8737 // Quickly ignore expressions that can't be shadowing ctor parameters.
8738 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8739 return;
8740 E = E->IgnoreParenImpCasts();
8741 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8742 if (!DRE)
8743 return;
8744 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8745 auto I = ShadowingDecls.find(Val: D);
8746 if (I == ShadowingDecls.end())
8747 return;
8748 const NamedDecl *ShadowedDecl = I->second;
8749 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8750 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8751 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8752 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8753
8754 // Avoid issuing multiple warnings about the same decl.
8755 ShadowingDecls.erase(I);
8756}
8757
8758/// Check for conflict between this global or extern "C" declaration and
8759/// previous global or extern "C" declarations. This is only used in C++.
8760template<typename T>
8761static bool checkGlobalOrExternCConflict(
8762 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8763 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8764 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8765
8766 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8767 // The common case: this global doesn't conflict with any extern "C"
8768 // declaration.
8769 return false;
8770 }
8771
8772 if (Prev) {
8773 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8774 // Both the old and new declarations have C language linkage. This is a
8775 // redeclaration.
8776 Previous.clear();
8777 Previous.addDecl(D: Prev);
8778 return true;
8779 }
8780
8781 // This is a global, non-extern "C" declaration, and there is a previous
8782 // non-global extern "C" declaration. Diagnose if this is a variable
8783 // declaration.
8784 if (!isa<VarDecl>(ND))
8785 return false;
8786 } else {
8787 // The declaration is extern "C". Check for any declaration in the
8788 // translation unit which might conflict.
8789 if (IsGlobal) {
8790 // We have already performed the lookup into the translation unit.
8791 IsGlobal = false;
8792 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8793 I != E; ++I) {
8794 if (isa<VarDecl>(Val: *I)) {
8795 Prev = *I;
8796 break;
8797 }
8798 }
8799 } else {
8800 DeclContext::lookup_result R =
8801 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8802 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8803 I != E; ++I) {
8804 if (isa<VarDecl>(Val: *I)) {
8805 Prev = *I;
8806 break;
8807 }
8808 // FIXME: If we have any other entity with this name in global scope,
8809 // the declaration is ill-formed, but that is a defect: it breaks the
8810 // 'stat' hack, for instance. Only variables can have mangled name
8811 // clashes with extern "C" declarations, so only they deserve a
8812 // diagnostic.
8813 }
8814 }
8815
8816 if (!Prev)
8817 return false;
8818 }
8819
8820 // Use the first declaration's location to ensure we point at something which
8821 // is lexically inside an extern "C" linkage-spec.
8822 assert(Prev && "should have found a previous declaration to diagnose");
8823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8824 Prev = FD->getFirstDecl();
8825 else
8826 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8827
8828 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8829 << IsGlobal << ND;
8830 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8831 << IsGlobal;
8832 return false;
8833}
8834
8835/// Apply special rules for handling extern "C" declarations. Returns \c true
8836/// if we have found that this is a redeclaration of some prior entity.
8837///
8838/// Per C++ [dcl.link]p6:
8839/// Two declarations [for a function or variable] with C language linkage
8840/// with the same name that appear in different scopes refer to the same
8841/// [entity]. An entity with C language linkage shall not be declared with
8842/// the same name as an entity in global scope.
8843template<typename T>
8844static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8845 LookupResult &Previous) {
8846 if (!S.getLangOpts().CPlusPlus) {
8847 // In C, when declaring a global variable, look for a corresponding 'extern'
8848 // variable declared in function scope. We don't need this in C++, because
8849 // we find local extern decls in the surrounding file-scope DeclContext.
8850 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8851 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8852 Previous.clear();
8853 Previous.addDecl(D: Prev);
8854 return true;
8855 }
8856 }
8857 return false;
8858 }
8859
8860 // A declaration in the translation unit can conflict with an extern "C"
8861 // declaration.
8862 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8863 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8864
8865 // An extern "C" declaration can conflict with a declaration in the
8866 // translation unit or can be a redeclaration of an extern "C" declaration
8867 // in another scope.
8868 if (isIncompleteDeclExternC(S,ND))
8869 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8870
8871 // Neither global nor extern "C": nothing to do.
8872 return false;
8873}
8874
8875static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8876 QualType T) {
8877 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8878 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8879 // any of its members, even recursively, shall not have an atomic type, or a
8880 // variably modified type, or a type that is volatile or restrict qualified.
8881 if (CanonT->isVariablyModifiedType()) {
8882 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8883 return true;
8884 }
8885
8886 // Arrays are qualified by their element type, so get the base type (this
8887 // works on non-arrays as well).
8888 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8889
8890 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8891 CanonT.isRestrictQualified()) {
8892 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8893 return true;
8894 }
8895
8896 if (CanonT->isRecordType()) {
8897 const RecordDecl *RD = CanonT->getAsRecordDecl();
8898 if (!RD->isInvalidDecl() &&
8899 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8900 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8901 }))
8902 return true;
8903 }
8904
8905 return false;
8906}
8907
8908void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8909 // If the decl is already known invalid, don't check it.
8910 if (NewVD->isInvalidDecl())
8911 return;
8912
8913 QualType T = NewVD->getType();
8914
8915 // Defer checking an 'auto' type until its initializer is attached.
8916 if (T->isUndeducedType())
8917 return;
8918
8919 if (NewVD->hasAttrs())
8920 CheckAlignasUnderalignment(D: NewVD);
8921
8922 if (T->isObjCObjectType()) {
8923 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8924 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8925 T = Context.getObjCObjectPointerType(OIT: T);
8926 NewVD->setType(T);
8927 }
8928
8929 // Emit an error if an address space was applied to decl with local storage.
8930 // This includes arrays of objects with address space qualifiers, but not
8931 // automatic variables that point to other address spaces.
8932 // ISO/IEC TR 18037 S5.1.2
8933 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8934 T.getAddressSpace() != LangAS::Default) {
8935 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8936 NewVD->setInvalidDecl();
8937 return;
8938 }
8939
8940 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8941 // scope.
8942 if (getLangOpts().OpenCLVersion == 120 &&
8943 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8944 LO: getLangOpts()) &&
8945 NewVD->isStaticLocal()) {
8946 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8947 NewVD->setInvalidDecl();
8948 return;
8949 }
8950
8951 if (getLangOpts().OpenCL) {
8952 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8953 return;
8954
8955 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8956 if (NewVD->hasAttr<BlocksAttr>()) {
8957 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8958 return;
8959 }
8960
8961 if (T->isBlockPointerType()) {
8962 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8963 // can't use 'extern' storage class.
8964 if (!T.isConstQualified()) {
8965 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8966 << 0 /*const*/;
8967 NewVD->setInvalidDecl();
8968 return;
8969 }
8970 if (NewVD->hasExternalStorage()) {
8971 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8972 NewVD->setInvalidDecl();
8973 return;
8974 }
8975 }
8976
8977 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8978 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8979 NewVD->hasExternalStorage()) {
8980 if (!T->isSamplerT() && !T->isDependentType() &&
8981 !(T.getAddressSpace() == LangAS::opencl_constant ||
8982 (T.getAddressSpace() == LangAS::opencl_global &&
8983 getOpenCLOptions().areProgramScopeVariablesSupported(
8984 Opts: getLangOpts())))) {
8985 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8986 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8987 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8988 << Scope << "global or constant";
8989 else
8990 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8991 << Scope << "constant";
8992 NewVD->setInvalidDecl();
8993 return;
8994 }
8995 } else {
8996 if (T.getAddressSpace() == LangAS::opencl_global) {
8997 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8998 << 1 /*is any function*/ << "global";
8999 NewVD->setInvalidDecl();
9000 return;
9001 }
9002 // When this extension is enabled, 'local' variables are permitted in
9003 // non-kernel functions and within nested scopes of kernel functions,
9004 // bypassing standard OpenCL address space restrictions.
9005 bool AllowFunctionScopeLocalVariables =
9006 T.getAddressSpace() == LangAS::opencl_local &&
9007 getOpenCLOptions().isAvailableOption(
9008 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9009 if (AllowFunctionScopeLocalVariables) {
9010 // Direct pass: No further diagnostics needed for this specific case.
9011 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9012 T.getAddressSpace() == LangAS::opencl_local) {
9013 FunctionDecl *FD = getCurFunctionDecl();
9014 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9015 // in functions.
9016 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9017 if (T.getAddressSpace() == LangAS::opencl_constant)
9018 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9019 << 0 /*non-kernel only*/ << "constant";
9020 else
9021 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9022 << 0 /*non-kernel only*/ << "local";
9023 NewVD->setInvalidDecl();
9024 return;
9025 }
9026 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9027 // in the outermost scope of a kernel function.
9028 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9029 if (!getCurScope()->isFunctionScope()) {
9030 if (T.getAddressSpace() == LangAS::opencl_constant)
9031 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9032 << "constant";
9033 else
9034 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9035 << "local";
9036 NewVD->setInvalidDecl();
9037 return;
9038 }
9039 }
9040 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9041 // If we are parsing a template we didn't deduce an addr
9042 // space yet.
9043 T.getAddressSpace() != LangAS::Default) {
9044 // Do not allow other address spaces on automatic variable.
9045 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9046 NewVD->setInvalidDecl();
9047 return;
9048 }
9049 }
9050 }
9051
9052 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9053 && !NewVD->hasAttr<BlocksAttr>()) {
9054 if (getLangOpts().getGC() != LangOptions::NonGC)
9055 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9056 else {
9057 assert(!getLangOpts().ObjCAutoRefCount);
9058 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9059 }
9060 }
9061
9062 // WebAssembly tables must be static with a zero length and can't be
9063 // declared within functions.
9064 if (T->isWebAssemblyTableType()) {
9065 if (getCurScope()->getParent()) { // Parent is null at top-level
9066 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9067 NewVD->setInvalidDecl();
9068 return;
9069 }
9070 if (NewVD->getStorageClass() != SC_Static) {
9071 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9072 NewVD->setInvalidDecl();
9073 return;
9074 }
9075 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9076 if (!ATy || ATy->getZExtSize() != 0) {
9077 Diag(Loc: NewVD->getLocation(),
9078 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9079 NewVD->setInvalidDecl();
9080 return;
9081 }
9082 }
9083
9084 // zero sized static arrays are not allowed in HIP device functions
9085 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9086 if (FunctionDecl *FD = getCurFunctionDecl();
9087 FD &&
9088 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9089 if (const ConstantArrayType *ArrayT =
9090 getASTContext().getAsConstantArrayType(T);
9091 ArrayT && ArrayT->isZeroSize()) {
9092 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9093 }
9094 }
9095 }
9096
9097 bool isVM = T->isVariablyModifiedType();
9098 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9099 NewVD->hasAttr<BlocksAttr>())
9100 setFunctionHasBranchProtectedScope();
9101
9102 if ((isVM && NewVD->hasLinkage()) ||
9103 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9104 bool SizeIsNegative;
9105 llvm::APSInt Oversized;
9106 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9107 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9108 QualType FixedT;
9109 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9110 FixedT = FixedTInfo->getType();
9111 else if (FixedTInfo) {
9112 // Type and type-as-written are canonically different. We need to fix up
9113 // both types separately.
9114 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9115 Oversized);
9116 }
9117 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9118 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9119 // FIXME: This won't give the correct result for
9120 // int a[10][n];
9121 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9122
9123 if (NewVD->isFileVarDecl())
9124 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9125 << SizeRange;
9126 else if (NewVD->isStaticLocal())
9127 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9128 << SizeRange;
9129 else
9130 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9131 << SizeRange;
9132 NewVD->setInvalidDecl();
9133 return;
9134 }
9135
9136 if (!FixedTInfo) {
9137 if (NewVD->isFileVarDecl())
9138 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9139 else
9140 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9141 NewVD->setInvalidDecl();
9142 return;
9143 }
9144
9145 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9146 NewVD->setType(FixedT);
9147 NewVD->setTypeSourceInfo(FixedTInfo);
9148 }
9149
9150 if (T->isVoidType()) {
9151 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9152 // of objects and functions.
9153 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9154 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9155 << T;
9156 NewVD->setInvalidDecl();
9157 return;
9158 }
9159 }
9160
9161 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9162 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9163 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9164 NewVD->setInvalidDecl();
9165 return;
9166 }
9167
9168 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9169 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9170 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9171 NewVD->setInvalidDecl();
9172 return;
9173 }
9174
9175 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9176 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9177 NewVD->setInvalidDecl();
9178 return;
9179 }
9180
9181 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9182 !T->isDependentType() &&
9183 RequireLiteralType(Loc: NewVD->getLocation(), T,
9184 DiagID: diag::err_constexpr_var_non_literal)) {
9185 NewVD->setInvalidDecl();
9186 return;
9187 }
9188
9189 // PPC MMA non-pointer types are not allowed as non-local variable types.
9190 if (Context.getTargetInfo().getTriple().isPPC64() &&
9191 !NewVD->isLocalVarDecl() &&
9192 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9193 NewVD->setInvalidDecl();
9194 return;
9195 }
9196
9197 // Check that SVE types are only used in functions with SVE available.
9198 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9199 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9200 llvm::StringMap<bool> CallerFeatureMap;
9201 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9202 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9203 FeatureMap: CallerFeatureMap)) {
9204 NewVD->setInvalidDecl();
9205 return;
9206 }
9207 }
9208
9209 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9210 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9211 llvm::StringMap<bool> CallerFeatureMap;
9212 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9213 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9214 FeatureMap: CallerFeatureMap);
9215 }
9216
9217 if (T.hasAddressSpace() &&
9218 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9219 NewVD->setInvalidDecl();
9220 return;
9221 }
9222}
9223
9224bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9225 CheckVariableDeclarationType(NewVD);
9226
9227 // If the decl is already known invalid, don't check it.
9228 if (NewVD->isInvalidDecl())
9229 return false;
9230
9231 // If we did not find anything by this name, look for a non-visible
9232 // extern "C" declaration with the same name.
9233 if (Previous.empty() &&
9234 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9235 Previous.setShadowed();
9236
9237 if (!Previous.empty()) {
9238 MergeVarDecl(New: NewVD, Previous);
9239 return true;
9240 }
9241 return false;
9242}
9243
9244bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9245 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9246
9247 // Look for methods in base classes that this method might override.
9248 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9249 /*DetectVirtual=*/false);
9250 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9251 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9252 DeclarationName Name = MD->getDeclName();
9253
9254 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9255 // We really want to find the base class destructor here.
9256 Name = Context.DeclarationNames.getCXXDestructorName(
9257 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9258 }
9259
9260 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9261 CXXMethodDecl *BaseMD =
9262 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9263 if (!BaseMD || !BaseMD->isVirtual() ||
9264 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9265 /*ConsiderCudaAttrs=*/true))
9266 continue;
9267 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9268 continue;
9269 if (Overridden.insert(Ptr: BaseMD).second) {
9270 MD->addOverriddenMethod(MD: BaseMD);
9271 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9272 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9273 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9274 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9275 }
9276
9277 // A method can only override one function from each base class. We
9278 // don't track indirectly overridden methods from bases of bases.
9279 return true;
9280 }
9281
9282 return false;
9283 };
9284
9285 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9286 return !Overridden.empty();
9287}
9288
9289namespace {
9290 // Struct for holding all of the extra arguments needed by
9291 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9292 struct ActOnFDArgs {
9293 Scope *S;
9294 Declarator &D;
9295 MultiTemplateParamsArg TemplateParamLists;
9296 bool AddToScope;
9297 };
9298} // end anonymous namespace
9299
9300namespace {
9301
9302// Callback to only accept typo corrections that have a non-zero edit distance.
9303// Also only accept corrections that have the same parent decl.
9304class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9305 public:
9306 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9307 CXXRecordDecl *Parent)
9308 : Context(Context), OriginalFD(TypoFD),
9309 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9310
9311 bool ValidateCandidate(const TypoCorrection &candidate) override {
9312 if (candidate.getEditDistance() == 0)
9313 return false;
9314
9315 SmallVector<unsigned, 1> MismatchedParams;
9316 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9317 CDeclEnd = candidate.end();
9318 CDecl != CDeclEnd; ++CDecl) {
9319 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9320
9321 if (FD && !FD->hasBody() &&
9322 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9323 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9324 CXXRecordDecl *Parent = MD->getParent();
9325 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9326 return true;
9327 } else if (!ExpectedParent) {
9328 return true;
9329 }
9330 }
9331 }
9332
9333 return false;
9334 }
9335
9336 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9337 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9338 }
9339
9340 private:
9341 ASTContext &Context;
9342 FunctionDecl *OriginalFD;
9343 CXXRecordDecl *ExpectedParent;
9344};
9345
9346} // end anonymous namespace
9347
9348void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9349 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9350}
9351
9352/// Generate diagnostics for an invalid function redeclaration.
9353///
9354/// This routine handles generating the diagnostic messages for an invalid
9355/// function redeclaration, including finding possible similar declarations
9356/// or performing typo correction if there are no previous declarations with
9357/// the same name.
9358///
9359/// Returns a NamedDecl iff typo correction was performed and substituting in
9360/// the new declaration name does not cause new errors.
9361static NamedDecl *DiagnoseInvalidRedeclaration(
9362 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9363 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9364 DeclarationName Name = NewFD->getDeclName();
9365 DeclContext *NewDC = NewFD->getDeclContext();
9366 SmallVector<unsigned, 1> MismatchedParams;
9367 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9368 TypoCorrection Correction;
9369 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9370 unsigned DiagMsg =
9371 IsLocalFriend ? diag::err_no_matching_local_friend :
9372 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9373 diag::err_member_decl_does_not_match;
9374 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9375 IsLocalFriend ? Sema::LookupLocalFriendName
9376 : Sema::LookupOrdinaryName,
9377 RedeclarationKind::ForVisibleRedeclaration);
9378
9379 NewFD->setInvalidDecl();
9380 if (IsLocalFriend)
9381 SemaRef.LookupName(R&: Prev, S);
9382 else
9383 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9384 assert(!Prev.isAmbiguous() &&
9385 "Cannot have an ambiguity in previous-declaration lookup");
9386 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9387 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9388 MD ? MD->getParent() : nullptr);
9389 if (!Prev.empty()) {
9390 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9391 Func != FuncEnd; ++Func) {
9392 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9393 if (FD &&
9394 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9395 // Add 1 to the index so that 0 can mean the mismatch didn't
9396 // involve a parameter
9397 unsigned ParamNum =
9398 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9399 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9400 }
9401 }
9402 // If the qualified name lookup yielded nothing, try typo correction
9403 } else if ((Correction = SemaRef.CorrectTypo(
9404 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9405 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9406 Mode: CorrectTypoKind::ErrorRecovery,
9407 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9408 // Set up everything for the call to ActOnFunctionDeclarator
9409 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9410 IdLoc: ExtraArgs.D.getIdentifierLoc());
9411 Previous.clear();
9412 Previous.setLookupName(Correction.getCorrection());
9413 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9414 CDeclEnd = Correction.end();
9415 CDecl != CDeclEnd; ++CDecl) {
9416 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9417 if (FD && !FD->hasBody() &&
9418 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9419 Previous.addDecl(D: FD);
9420 }
9421 }
9422 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9423
9424 NamedDecl *Result;
9425 // Retry building the function declaration with the new previous
9426 // declarations, and with errors suppressed.
9427 {
9428 // Trap errors.
9429 Sema::SFINAETrap Trap(SemaRef);
9430
9431 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9432 // pieces need to verify the typo-corrected C++ declaration and hopefully
9433 // eliminate the need for the parameter pack ExtraArgs.
9434 Result = SemaRef.ActOnFunctionDeclarator(
9435 S: ExtraArgs.S, D&: ExtraArgs.D,
9436 DC: Correction.getCorrectionDecl()->getDeclContext(),
9437 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9438 AddToScope&: ExtraArgs.AddToScope);
9439
9440 if (Trap.hasErrorOccurred())
9441 Result = nullptr;
9442 }
9443
9444 if (Result) {
9445 // Determine which correction we picked.
9446 Decl *Canonical = Result->getCanonicalDecl();
9447 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9448 I != E; ++I)
9449 if ((*I)->getCanonicalDecl() == Canonical)
9450 Correction.setCorrectionDecl(*I);
9451
9452 // Let Sema know about the correction.
9453 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9454 SemaRef.diagnoseTypo(
9455 Correction,
9456 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9457 ? diag::err_no_matching_local_friend_suggest
9458 : diag::err_member_decl_does_not_match_suggest)
9459 << Name << NewDC << IsDefinition);
9460 return Result;
9461 }
9462
9463 // Pretend the typo correction never occurred
9464 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9465 IdLoc: ExtraArgs.D.getIdentifierLoc());
9466 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9467 Previous.clear();
9468 Previous.setLookupName(Name);
9469 }
9470
9471 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9472 << Name << NewDC << IsDefinition << NewFD->getLocation();
9473
9474 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9475 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9476 CXXRecordDecl *RD = NewMD->getParent();
9477 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9478 << RD->getName() << RD->getLocation();
9479 }
9480
9481 bool NewFDisConst = NewMD && NewMD->isConst();
9482
9483 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9484 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9485 NearMatch != NearMatchEnd; ++NearMatch) {
9486 FunctionDecl *FD = NearMatch->first;
9487 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9488 bool FDisConst = MD && MD->isConst();
9489 bool IsMember = MD || !IsLocalFriend;
9490
9491 // FIXME: These notes are poorly worded for the local friend case.
9492 if (unsigned Idx = NearMatch->second) {
9493 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9494 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9495 if (Loc.isInvalid()) Loc = FD->getLocation();
9496 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9497 : diag::note_local_decl_close_param_match)
9498 << Idx << FDParam->getType()
9499 << NewFD->getParamDecl(i: Idx - 1)->getType();
9500 } else if (FDisConst != NewFDisConst) {
9501 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9502 DiagID: diag::note_member_def_close_const_match)
9503 << NewFDisConst << FD->getSourceRange().getEnd();
9504 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9505 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9506 Code: " const");
9507 else if (FTI.hasMethodTypeQualifiers() &&
9508 FTI.getConstQualifierLoc().isValid())
9509 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9510 } else {
9511 SemaRef.Diag(Loc: FD->getLocation(),
9512 DiagID: IsMember ? diag::note_member_def_close_match
9513 : diag::note_local_decl_close_match);
9514 }
9515 }
9516 return nullptr;
9517}
9518
9519static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9520 switch (D.getDeclSpec().getStorageClassSpec()) {
9521 default: llvm_unreachable("Unknown storage class!");
9522 case DeclSpec::SCS_auto:
9523 case DeclSpec::SCS_register:
9524 case DeclSpec::SCS_mutable:
9525 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9526 DiagID: diag::err_typecheck_sclass_func);
9527 D.getMutableDeclSpec().ClearStorageClassSpecs();
9528 D.setInvalidType();
9529 break;
9530 case DeclSpec::SCS_unspecified: break;
9531 case DeclSpec::SCS_extern:
9532 if (D.getDeclSpec().isExternInLinkageSpec())
9533 return SC_None;
9534 return SC_Extern;
9535 case DeclSpec::SCS_static: {
9536 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9537 // C99 6.7.1p5:
9538 // The declaration of an identifier for a function that has
9539 // block scope shall have no explicit storage-class specifier
9540 // other than extern
9541 // See also (C++ [dcl.stc]p4).
9542 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9543 DiagID: diag::err_static_block_func);
9544 break;
9545 } else
9546 return SC_Static;
9547 }
9548 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9549 }
9550
9551 // No explicit storage class has already been returned
9552 return SC_None;
9553}
9554
9555static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9556 DeclContext *DC, QualType &R,
9557 TypeSourceInfo *TInfo,
9558 StorageClass SC,
9559 bool &IsVirtualOkay) {
9560 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9561 DeclarationName Name = NameInfo.getName();
9562
9563 FunctionDecl *NewFD = nullptr;
9564 bool isInline = D.getDeclSpec().isInlineSpecified();
9565
9566 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9567 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9568 (SemaRef.getLangOpts().C23 &&
9569 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9570
9571 if (SemaRef.getLangOpts().C23)
9572 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9573 DiagID: diag::err_c23_constexpr_not_variable);
9574 else
9575 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9576 DiagID: diag::err_constexpr_wrong_decl_kind)
9577 << static_cast<int>(ConstexprKind);
9578 ConstexprKind = ConstexprSpecKind::Unspecified;
9579 D.getMutableDeclSpec().ClearConstexprSpec();
9580 }
9581
9582 if (!SemaRef.getLangOpts().CPlusPlus) {
9583 // Determine whether the function was written with a prototype. This is
9584 // true when:
9585 // - there is a prototype in the declarator, or
9586 // - the type R of the function is some kind of typedef or other non-
9587 // attributed reference to a type name (which eventually refers to a
9588 // function type). Note, we can't always look at the adjusted type to
9589 // check this case because attributes may cause a non-function
9590 // declarator to still have a function type. e.g.,
9591 // typedef void func(int a);
9592 // __attribute__((noreturn)) func other_func; // This has a prototype
9593 bool HasPrototype =
9594 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9595 (D.getDeclSpec().isTypeRep() &&
9596 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9597 ->isFunctionProtoType()) ||
9598 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9599 assert(
9600 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9601 "Strict prototypes are required");
9602
9603 NewFD = FunctionDecl::Create(
9604 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9605 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9606 ConstexprKind: ConstexprSpecKind::Unspecified,
9607 /*TrailingRequiresClause=*/{});
9608 if (D.isInvalidType())
9609 NewFD->setInvalidDecl();
9610
9611 return NewFD;
9612 }
9613
9614 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9615 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9616
9617 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9618
9619 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9620 // This is a C++ constructor declaration.
9621 assert(DC->isRecord() &&
9622 "Constructors can only be declared in a member context");
9623
9624 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9625 return CXXConstructorDecl::Create(
9626 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9627 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9628 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9629 Inherited: InheritedConstructor(), TrailingRequiresClause);
9630
9631 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9632 // This is a C++ destructor declaration.
9633 if (DC->isRecord()) {
9634 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9635 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9636 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9637 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9638 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9639 /*isImplicitlyDeclared=*/false, ConstexprKind,
9640 TrailingRequiresClause);
9641 // User defined destructors start as not selected if the class definition is still
9642 // not done.
9643 if (Record->isBeingDefined())
9644 NewDD->setIneligibleOrNotSelected(true);
9645
9646 // If the destructor needs an implicit exception specification, set it
9647 // now. FIXME: It'd be nice to be able to create the right type to start
9648 // with, but the type needs to reference the destructor declaration.
9649 if (SemaRef.getLangOpts().CPlusPlus11)
9650 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9651
9652 IsVirtualOkay = true;
9653 return NewDD;
9654
9655 } else {
9656 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9657 D.setInvalidType();
9658
9659 // Create a FunctionDecl to satisfy the function definition parsing
9660 // code path.
9661 return FunctionDecl::Create(
9662 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9663 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9664 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9665 }
9666
9667 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9668 if (!DC->isRecord()) {
9669 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9670 DiagID: diag::err_conv_function_not_member);
9671 return nullptr;
9672 }
9673
9674 SemaRef.CheckConversionDeclarator(D, R, SC);
9675 if (D.isInvalidType())
9676 return nullptr;
9677
9678 IsVirtualOkay = true;
9679 return CXXConversionDecl::Create(
9680 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9681 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9682 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9683 TrailingRequiresClause);
9684
9685 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9686 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9687 return nullptr;
9688 return CXXDeductionGuideDecl::Create(
9689 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9690 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9691 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9692 } else if (DC->isRecord()) {
9693 // If the name of the function is the same as the name of the record,
9694 // then this must be an invalid constructor that has a return type.
9695 // (The parser checks for a return type and makes the declarator a
9696 // constructor if it has no return type).
9697 if (Name.getAsIdentifierInfo() &&
9698 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9699 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9700 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9701 << SourceRange(D.getIdentifierLoc());
9702 return nullptr;
9703 }
9704
9705 // This is a C++ method declaration.
9706 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9707 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9708 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9709 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9710 IsVirtualOkay = !Ret->isStatic();
9711 return Ret;
9712 } else {
9713 bool isFriend =
9714 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9715 if (!isFriend && SemaRef.CurContext->isRecord())
9716 return nullptr;
9717
9718 // Determine whether the function was written with a
9719 // prototype. This true when:
9720 // - we're in C++ (where every function has a prototype),
9721 return FunctionDecl::Create(
9722 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9723 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9724 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9725 }
9726}
9727
9728enum OpenCLParamType {
9729 ValidKernelParam,
9730 PtrPtrKernelParam,
9731 PtrKernelParam,
9732 InvalidAddrSpacePtrKernelParam,
9733 InvalidKernelParam,
9734 RecordKernelParam
9735};
9736
9737static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9738 // Size dependent types are just typedefs to normal integer types
9739 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9740 // integers other than by their names.
9741 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9742
9743 // Remove typedefs one by one until we reach a typedef
9744 // for a size dependent type.
9745 QualType DesugaredTy = Ty;
9746 do {
9747 ArrayRef<StringRef> Names(SizeTypeNames);
9748 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9749 if (Names.end() != Match)
9750 return true;
9751
9752 Ty = DesugaredTy;
9753 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9754 } while (DesugaredTy != Ty);
9755
9756 return false;
9757}
9758
9759static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9760 if (PT->isDependentType())
9761 return InvalidKernelParam;
9762
9763 if (PT->isPointerOrReferenceType()) {
9764 QualType PointeeType = PT->getPointeeType();
9765 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9766 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9767 PointeeType.getAddressSpace() == LangAS::Default)
9768 return InvalidAddrSpacePtrKernelParam;
9769
9770 if (PointeeType->isPointerType()) {
9771 // This is a pointer to pointer parameter.
9772 // Recursively check inner type.
9773 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9774 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9775 ParamKind == InvalidKernelParam)
9776 return ParamKind;
9777
9778 // OpenCL v3.0 s6.11.a:
9779 // A restriction to pass pointers to pointers only applies to OpenCL C
9780 // v1.2 or below.
9781 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9782 return ValidKernelParam;
9783
9784 return PtrPtrKernelParam;
9785 }
9786
9787 // C++ for OpenCL v1.0 s2.4:
9788 // Moreover the types used in parameters of the kernel functions must be:
9789 // Standard layout types for pointer parameters. The same applies to
9790 // reference if an implementation supports them in kernel parameters.
9791 if (S.getLangOpts().OpenCLCPlusPlus &&
9792 !S.getOpenCLOptions().isAvailableOption(
9793 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9794 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9795 bool IsStandardLayoutType = true;
9796 if (CXXRec) {
9797 // If template type is not ODR-used its definition is only available
9798 // in the template definition not its instantiation.
9799 // FIXME: This logic doesn't work for types that depend on template
9800 // parameter (PR58590).
9801 if (!CXXRec->hasDefinition())
9802 CXXRec = CXXRec->getTemplateInstantiationPattern();
9803 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9804 IsStandardLayoutType = false;
9805 }
9806 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9807 !IsStandardLayoutType)
9808 return InvalidKernelParam;
9809 }
9810
9811 // OpenCL v1.2 s6.9.p:
9812 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9813 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9814 return ValidKernelParam;
9815
9816 return PtrKernelParam;
9817 }
9818
9819 // OpenCL v1.2 s6.9.k:
9820 // Arguments to kernel functions in a program cannot be declared with the
9821 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9822 // uintptr_t or a struct and/or union that contain fields declared to be one
9823 // of these built-in scalar types.
9824 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9825 return InvalidKernelParam;
9826
9827 if (PT->isImageType())
9828 return PtrKernelParam;
9829
9830 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9831 return InvalidKernelParam;
9832
9833 // OpenCL extension spec v1.2 s9.5:
9834 // This extension adds support for half scalar and vector types as built-in
9835 // types that can be used for arithmetic operations, conversions etc.
9836 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9837 PT->isHalfType())
9838 return InvalidKernelParam;
9839
9840 // Look into an array argument to check if it has a forbidden type.
9841 if (PT->isArrayType()) {
9842 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9843 // Call ourself to check an underlying type of an array. Since the
9844 // getPointeeOrArrayElementType returns an innermost type which is not an
9845 // array, this recursive call only happens once.
9846 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9847 }
9848
9849 // C++ for OpenCL v1.0 s2.4:
9850 // Moreover the types used in parameters of the kernel functions must be:
9851 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9852 // types) for parameters passed by value;
9853 if (S.getLangOpts().OpenCLCPlusPlus &&
9854 !S.getOpenCLOptions().isAvailableOption(
9855 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9856 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9857 return InvalidKernelParam;
9858
9859 if (PT->isRecordType())
9860 return RecordKernelParam;
9861
9862 return ValidKernelParam;
9863}
9864
9865static void checkIsValidOpenCLKernelParameter(
9866 Sema &S,
9867 Declarator &D,
9868 ParmVarDecl *Param,
9869 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9870 QualType PT = Param->getType();
9871
9872 // Cache the valid types we encounter to avoid rechecking structs that are
9873 // used again
9874 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9875 return;
9876
9877 switch (getOpenCLKernelParameterType(S, PT)) {
9878 case PtrPtrKernelParam:
9879 // OpenCL v3.0 s6.11.a:
9880 // A kernel function argument cannot be declared as a pointer to a pointer
9881 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9882 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9883 D.setInvalidType();
9884 return;
9885
9886 case InvalidAddrSpacePtrKernelParam:
9887 // OpenCL v1.0 s6.5:
9888 // __kernel function arguments declared to be a pointer of a type can point
9889 // to one of the following address spaces only : __global, __local or
9890 // __constant.
9891 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9892 D.setInvalidType();
9893 return;
9894
9895 // OpenCL v1.2 s6.9.k:
9896 // Arguments to kernel functions in a program cannot be declared with the
9897 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9898 // uintptr_t or a struct and/or union that contain fields declared to be
9899 // one of these built-in scalar types.
9900
9901 case InvalidKernelParam:
9902 // OpenCL v1.2 s6.8 n:
9903 // A kernel function argument cannot be declared
9904 // of event_t type.
9905 // Do not diagnose half type since it is diagnosed as invalid argument
9906 // type for any function elsewhere.
9907 if (!PT->isHalfType()) {
9908 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9909
9910 // Explain what typedefs are involved.
9911 const TypedefType *Typedef = nullptr;
9912 while ((Typedef = PT->getAs<TypedefType>())) {
9913 SourceLocation Loc = Typedef->getDecl()->getLocation();
9914 // SourceLocation may be invalid for a built-in type.
9915 if (Loc.isValid())
9916 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9917 PT = Typedef->desugar();
9918 }
9919 }
9920
9921 D.setInvalidType();
9922 return;
9923
9924 case PtrKernelParam:
9925 case ValidKernelParam:
9926 ValidTypes.insert(Ptr: PT.getTypePtr());
9927 return;
9928
9929 case RecordKernelParam:
9930 break;
9931 }
9932
9933 // Track nested structs we will inspect
9934 SmallVector<const Decl *, 4> VisitStack;
9935
9936 // Track where we are in the nested structs. Items will migrate from
9937 // VisitStack to HistoryStack as we do the DFS for bad field.
9938 SmallVector<const FieldDecl *, 4> HistoryStack;
9939 HistoryStack.push_back(Elt: nullptr);
9940
9941 // At this point we already handled everything except of a RecordType.
9942 assert(PT->isRecordType() && "Unexpected type.");
9943 const auto *PD = PT->castAsRecordDecl();
9944 VisitStack.push_back(Elt: PD);
9945 assert(VisitStack.back() && "First decl null?");
9946
9947 do {
9948 const Decl *Next = VisitStack.pop_back_val();
9949 if (!Next) {
9950 assert(!HistoryStack.empty());
9951 // Found a marker, we have gone up a level
9952 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9953 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9954
9955 continue;
9956 }
9957
9958 // Adds everything except the original parameter declaration (which is not a
9959 // field itself) to the history stack.
9960 const RecordDecl *RD;
9961 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9962 HistoryStack.push_back(Elt: Field);
9963
9964 QualType FieldTy = Field->getType();
9965 // Other field types (known to be valid or invalid) are handled while we
9966 // walk around RecordDecl::fields().
9967 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9968 "Unexpected type.");
9969 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9970
9971 RD = FieldRecTy->castAsRecordDecl();
9972 } else {
9973 RD = cast<RecordDecl>(Val: Next);
9974 }
9975
9976 // Add a null marker so we know when we've gone back up a level
9977 VisitStack.push_back(Elt: nullptr);
9978
9979 for (const auto *FD : RD->fields()) {
9980 QualType QT = FD->getType();
9981
9982 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9983 continue;
9984
9985 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9986 if (ParamType == ValidKernelParam)
9987 continue;
9988
9989 if (ParamType == RecordKernelParam) {
9990 VisitStack.push_back(Elt: FD);
9991 continue;
9992 }
9993
9994 // OpenCL v1.2 s6.9.p:
9995 // Arguments to kernel functions that are declared to be a struct or union
9996 // do not allow OpenCL objects to be passed as elements of the struct or
9997 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9998 // of SVM.
9999 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10000 ParamType == InvalidAddrSpacePtrKernelParam) {
10001 S.Diag(Loc: Param->getLocation(),
10002 DiagID: diag::err_record_with_pointers_kernel_param)
10003 << PT->isUnionType()
10004 << PT;
10005 } else {
10006 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10007 }
10008
10009 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10010 << PD->getDeclName();
10011
10012 // We have an error, now let's go back up through history and show where
10013 // the offending field came from
10014 for (ArrayRef<const FieldDecl *>::const_iterator
10015 I = HistoryStack.begin() + 1,
10016 E = HistoryStack.end();
10017 I != E; ++I) {
10018 const FieldDecl *OuterField = *I;
10019 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10020 << OuterField->getType();
10021 }
10022
10023 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10024 << QT->isPointerType()
10025 << QT;
10026 D.setInvalidType();
10027 return;
10028 }
10029 } while (!VisitStack.empty());
10030}
10031
10032/// Find the DeclContext in which a tag is implicitly declared if we see an
10033/// elaborated type specifier in the specified context, and lookup finds
10034/// nothing.
10035static DeclContext *getTagInjectionContext(DeclContext *DC) {
10036 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10037 DC = DC->getParent();
10038 return DC;
10039}
10040
10041/// Find the Scope in which a tag is implicitly declared if we see an
10042/// elaborated type specifier in the specified context, and lookup finds
10043/// nothing.
10044static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10045 while (S->isClassScope() ||
10046 (LangOpts.CPlusPlus &&
10047 S->isFunctionPrototypeScope()) ||
10048 ((S->getFlags() & Scope::DeclScope) == 0) ||
10049 (S->getEntity() && S->getEntity()->isTransparentContext()))
10050 S = S->getParent();
10051 return S;
10052}
10053
10054/// Determine whether a declaration matches a known function in namespace std.
10055static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10056 unsigned BuiltinID) {
10057 switch (BuiltinID) {
10058 case Builtin::BI__GetExceptionInfo:
10059 // No type checking whatsoever.
10060 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10061
10062 case Builtin::BIaddressof:
10063 case Builtin::BI__addressof:
10064 case Builtin::BIforward:
10065 case Builtin::BIforward_like:
10066 case Builtin::BImove:
10067 case Builtin::BImove_if_noexcept:
10068 case Builtin::BIas_const: {
10069 // Ensure that we don't treat the algorithm
10070 // OutputIt std::move(InputIt, InputIt, OutputIt)
10071 // as the builtin std::move.
10072 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10073 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10074 }
10075
10076 default:
10077 return false;
10078 }
10079}
10080
10081NamedDecl*
10082Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10083 TypeSourceInfo *TInfo, LookupResult &Previous,
10084 MultiTemplateParamsArg TemplateParamListsRef,
10085 bool &AddToScope) {
10086 QualType R = TInfo->getType();
10087
10088 assert(R->isFunctionType());
10089 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10090 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10091
10092 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10093 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10094 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10095 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10096 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10097 TemplateParamLists.back() = Invented;
10098 else
10099 TemplateParamLists.push_back(Elt: Invented);
10100 }
10101
10102 // TODO: consider using NameInfo for diagnostic.
10103 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10104 DeclarationName Name = NameInfo.getName();
10105 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10106
10107 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10108 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10109 DiagID: diag::err_invalid_thread)
10110 << DeclSpec::getSpecifierName(S: TSCS);
10111
10112 if (D.isFirstDeclarationOfMember())
10113 adjustMemberFunctionCC(
10114 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10115 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10116
10117 bool isFriend = false;
10118 FunctionTemplateDecl *FunctionTemplate = nullptr;
10119 bool isMemberSpecialization = false;
10120 bool isFunctionTemplateSpecialization = false;
10121
10122 bool HasExplicitTemplateArgs = false;
10123 TemplateArgumentListInfo TemplateArgs;
10124
10125 bool isVirtualOkay = false;
10126
10127 DeclContext *OriginalDC = DC;
10128 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10129
10130 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10131 IsVirtualOkay&: isVirtualOkay);
10132 if (!NewFD) return nullptr;
10133
10134 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10135 NewFD->setTopLevelDeclInObjCContainer();
10136
10137 // Set the lexical context. If this is a function-scope declaration, or has a
10138 // C++ scope specifier, or is the object of a friend declaration, the lexical
10139 // context will be different from the semantic context.
10140 NewFD->setLexicalDeclContext(CurContext);
10141
10142 if (IsLocalExternDecl)
10143 NewFD->setLocalExternDecl();
10144
10145 if (getLangOpts().CPlusPlus) {
10146 // The rules for implicit inlines changed in C++20 for methods and friends
10147 // with an in-class definition (when such a definition is not attached to
10148 // the global module). This does not affect declarations that are already
10149 // inline (whether explicitly or implicitly by being declared constexpr,
10150 // consteval, etc).
10151 // FIXME: We need a better way to separate C++ standard and clang modules.
10152 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10153 !NewFD->getOwningModule() ||
10154 NewFD->isFromGlobalModule() ||
10155 NewFD->getOwningModule()->isHeaderLikeModule();
10156 bool isInline = D.getDeclSpec().isInlineSpecified();
10157 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10158 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10159 isFriend = D.getDeclSpec().isFriendSpecified();
10160 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10161 // Pre-C++20 [class.friend]p5
10162 // A function can be defined in a friend declaration of a
10163 // class . . . . Such a function is implicitly inline.
10164 // Post C++20 [class.friend]p7
10165 // Such a function is implicitly an inline function if it is attached
10166 // to the global module.
10167 NewFD->setImplicitlyInline();
10168 }
10169
10170 // If this is a method defined in an __interface, and is not a constructor
10171 // or an overloaded operator, then set the pure flag (isVirtual will already
10172 // return true).
10173 if (const CXXRecordDecl *Parent =
10174 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10175 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10176 NewFD->setIsPureVirtual(true);
10177
10178 // C++ [class.union]p2
10179 // A union can have member functions, but not virtual functions.
10180 if (isVirtual && Parent->isUnion()) {
10181 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10182 NewFD->setInvalidDecl();
10183 }
10184 if ((Parent->isClass() || Parent->isStruct()) &&
10185 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10186 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10187 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10188 if (auto *Def = Parent->getDefinition())
10189 Def->setInitMethod(true);
10190 }
10191 }
10192
10193 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10194 isMemberSpecialization = false;
10195 isFunctionTemplateSpecialization = false;
10196 if (D.isInvalidType())
10197 NewFD->setInvalidDecl();
10198
10199 // Match up the template parameter lists with the scope specifier, then
10200 // determine whether we have a template or a template specialization.
10201 bool Invalid = false;
10202 TemplateIdAnnotation *TemplateId =
10203 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10204 ? D.getName().TemplateId
10205 : nullptr;
10206 TemplateParameterList *TemplateParams =
10207 MatchTemplateParametersToScopeSpecifier(
10208 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10209 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10210 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10211 if (TemplateParams) {
10212 // Check that we can declare a template here.
10213 if (CheckTemplateDeclScope(S, TemplateParams))
10214 NewFD->setInvalidDecl();
10215
10216 if (TemplateParams->size() > 0) {
10217 // This is a function template
10218
10219 // A destructor cannot be a template.
10220 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10221 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10222 NewFD->setInvalidDecl();
10223 // Function template with explicit template arguments.
10224 } else if (TemplateId) {
10225 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10226 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10227 NewFD->setInvalidDecl();
10228 }
10229
10230 // If we're adding a template to a dependent context, we may need to
10231 // rebuilding some of the types used within the template parameter list,
10232 // now that we know what the current instantiation is.
10233 if (DC->isDependentContext()) {
10234 ContextRAII SavedContext(*this, DC);
10235 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10236 Invalid = true;
10237 }
10238
10239 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10240 L: NewFD->getLocation(),
10241 Name, Params: TemplateParams,
10242 Decl: NewFD);
10243 FunctionTemplate->setLexicalDeclContext(CurContext);
10244 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10245
10246 // For source fidelity, store the other template param lists.
10247 if (TemplateParamLists.size() > 1) {
10248 NewFD->setTemplateParameterListsInfo(Context,
10249 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10250 .drop_back(N: 1));
10251 }
10252 } else {
10253 // This is a function template specialization.
10254 isFunctionTemplateSpecialization = true;
10255 // For source fidelity, store all the template param lists.
10256 if (TemplateParamLists.size() > 0)
10257 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10258
10259 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10260 if (isFriend) {
10261 // We want to remove the "template<>", found here.
10262 SourceRange RemoveRange = TemplateParams->getSourceRange();
10263
10264 // If we remove the template<> and the name is not a
10265 // template-id, we're actually silently creating a problem:
10266 // the friend declaration will refer to an untemplated decl,
10267 // and clearly the user wants a template specialization. So
10268 // we need to insert '<>' after the name.
10269 SourceLocation InsertLoc;
10270 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10271 InsertLoc = D.getName().getSourceRange().getEnd();
10272 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10273 }
10274
10275 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10276 << Name << RemoveRange
10277 << FixItHint::CreateRemoval(RemoveRange)
10278 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10279 Invalid = true;
10280
10281 // Recover by faking up an empty template argument list.
10282 HasExplicitTemplateArgs = true;
10283 TemplateArgs.setLAngleLoc(InsertLoc);
10284 TemplateArgs.setRAngleLoc(InsertLoc);
10285 }
10286 }
10287 } else {
10288 // Check that we can declare a template here.
10289 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10290 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10291 NewFD->setInvalidDecl();
10292
10293 // All template param lists were matched against the scope specifier:
10294 // this is NOT (an explicit specialization of) a template.
10295 if (TemplateParamLists.size() > 0)
10296 // For source fidelity, store all the template param lists.
10297 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10298
10299 // "friend void foo<>(int);" is an implicit specialization decl.
10300 if (isFriend && TemplateId)
10301 isFunctionTemplateSpecialization = true;
10302 }
10303
10304 // If this is a function template specialization and the unqualified-id of
10305 // the declarator-id is a template-id, convert the template argument list
10306 // into our AST format and check for unexpanded packs.
10307 if (isFunctionTemplateSpecialization && TemplateId) {
10308 HasExplicitTemplateArgs = true;
10309
10310 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10311 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10312 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10313 TemplateId->NumArgs);
10314 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10315
10316 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10317 // declaration of a function template partial specialization? Should we
10318 // consider the unexpanded pack context to be a partial specialization?
10319 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10320 if (DiagnoseUnexpandedParameterPack(
10321 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10322 : UPPC_ExplicitSpecialization))
10323 NewFD->setInvalidDecl();
10324 }
10325 }
10326
10327 if (Invalid) {
10328 NewFD->setInvalidDecl();
10329 if (FunctionTemplate)
10330 FunctionTemplate->setInvalidDecl();
10331 }
10332
10333 // C++ [dcl.fct.spec]p5:
10334 // The virtual specifier shall only be used in declarations of
10335 // nonstatic class member functions that appear within a
10336 // member-specification of a class declaration; see 10.3.
10337 //
10338 if (isVirtual && !NewFD->isInvalidDecl()) {
10339 if (!isVirtualOkay) {
10340 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10341 DiagID: diag::err_virtual_non_function);
10342 } else if (!CurContext->isRecord()) {
10343 // 'virtual' was specified outside of the class.
10344 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10345 DiagID: diag::err_virtual_out_of_class)
10346 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10347 } else if (NewFD->getDescribedFunctionTemplate()) {
10348 // C++ [temp.mem]p3:
10349 // A member function template shall not be virtual.
10350 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10351 DiagID: diag::err_virtual_member_function_template)
10352 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10353 } else {
10354 // Okay: Add virtual to the method.
10355 NewFD->setVirtualAsWritten(true);
10356 }
10357
10358 if (getLangOpts().CPlusPlus14 &&
10359 NewFD->getReturnType()->isUndeducedType())
10360 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10361 }
10362
10363 // C++ [dcl.fct.spec]p3:
10364 // The inline specifier shall not appear on a block scope function
10365 // declaration.
10366 if (isInline && !NewFD->isInvalidDecl()) {
10367 if (CurContext->isFunctionOrMethod()) {
10368 // 'inline' is not allowed on block scope function declaration.
10369 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10370 DiagID: diag::err_inline_declaration_block_scope) << Name
10371 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10372 }
10373 }
10374
10375 // C++ [dcl.fct.spec]p6:
10376 // The explicit specifier shall be used only in the declaration of a
10377 // constructor or conversion function within its class definition;
10378 // see 12.3.1 and 12.3.2.
10379 if (hasExplicit && !NewFD->isInvalidDecl() &&
10380 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10381 if (!CurContext->isRecord()) {
10382 // 'explicit' was specified outside of the class.
10383 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10384 DiagID: diag::err_explicit_out_of_class)
10385 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10386 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10387 !isa<CXXConversionDecl>(Val: NewFD)) {
10388 // 'explicit' was specified on a function that wasn't a constructor
10389 // or conversion function.
10390 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10391 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10392 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10393 }
10394 }
10395
10396 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10397 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10398 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10399 // are implicitly inline.
10400 NewFD->setImplicitlyInline();
10401
10402 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10403 // be either constructors or to return a literal type. Therefore,
10404 // destructors cannot be declared constexpr.
10405 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10406 (!getLangOpts().CPlusPlus20 ||
10407 ConstexprKind == ConstexprSpecKind::Consteval)) {
10408 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10409 << static_cast<int>(ConstexprKind);
10410 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10411 ? ConstexprSpecKind::Unspecified
10412 : ConstexprSpecKind::Constexpr);
10413 }
10414 // C++20 [dcl.constexpr]p2: An allocation function, or a
10415 // deallocation function shall not be declared with the consteval
10416 // specifier.
10417 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10418 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10419 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10420 DiagID: diag::err_invalid_consteval_decl_kind)
10421 << NewFD;
10422 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10423 }
10424 }
10425
10426 // If __module_private__ was specified, mark the function accordingly.
10427 if (D.getDeclSpec().isModulePrivateSpecified()) {
10428 if (isFunctionTemplateSpecialization) {
10429 SourceLocation ModulePrivateLoc
10430 = D.getDeclSpec().getModulePrivateSpecLoc();
10431 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10432 << 0
10433 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10434 } else {
10435 NewFD->setModulePrivate();
10436 if (FunctionTemplate)
10437 FunctionTemplate->setModulePrivate();
10438 }
10439 }
10440
10441 if (isFriend) {
10442 if (FunctionTemplate) {
10443 FunctionTemplate->setObjectOfFriendDecl();
10444 FunctionTemplate->setAccess(AS_public);
10445 }
10446 NewFD->setObjectOfFriendDecl();
10447 NewFD->setAccess(AS_public);
10448 }
10449
10450 // If a function is defined as defaulted or deleted, mark it as such now.
10451 // We'll do the relevant checks on defaulted / deleted functions later.
10452 switch (D.getFunctionDefinitionKind()) {
10453 case FunctionDefinitionKind::Declaration:
10454 case FunctionDefinitionKind::Definition:
10455 break;
10456
10457 case FunctionDefinitionKind::Defaulted:
10458 NewFD->setDefaulted();
10459 break;
10460
10461 case FunctionDefinitionKind::Deleted:
10462 NewFD->setDeletedAsWritten();
10463 break;
10464 }
10465
10466 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10467 D.isFunctionDefinition()) {
10468 // Pre C++20 [class.mfct]p2:
10469 // A member function may be defined (8.4) in its class definition, in
10470 // which case it is an inline member function (7.1.2)
10471 // Post C++20 [class.mfct]p1:
10472 // If a member function is attached to the global module and is defined
10473 // in its class definition, it is inline.
10474 NewFD->setImplicitlyInline();
10475 }
10476
10477 if (!isFriend && SC != SC_None) {
10478 // C++ [temp.expl.spec]p2:
10479 // The declaration in an explicit-specialization shall not be an
10480 // export-declaration. An explicit specialization shall not use a
10481 // storage-class-specifier other than thread_local.
10482 //
10483 // We diagnose friend declarations with storage-class-specifiers
10484 // elsewhere.
10485 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10486 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10487 DiagID: diag::ext_explicit_specialization_storage_class)
10488 << FixItHint::CreateRemoval(
10489 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10490 }
10491
10492 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10493 assert(isa<CXXMethodDecl>(NewFD) &&
10494 "Out-of-line member function should be a CXXMethodDecl");
10495 // C++ [class.static]p1:
10496 // A data or function member of a class may be declared static
10497 // in a class definition, in which case it is a static member of
10498 // the class.
10499
10500 // Complain about the 'static' specifier if it's on an out-of-line
10501 // member function definition.
10502
10503 // MSVC permits the use of a 'static' storage specifier on an
10504 // out-of-line member function template declaration and class member
10505 // template declaration (MSVC versions before 2015), warn about this.
10506 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10507 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10508 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10509 (getLangOpts().MSVCCompat &&
10510 NewFD->getDescribedFunctionTemplate()))
10511 ? diag::ext_static_out_of_line
10512 : diag::err_static_out_of_line)
10513 << FixItHint::CreateRemoval(
10514 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10515 }
10516 }
10517
10518 // C++11 [except.spec]p15:
10519 // A deallocation function with no exception-specification is treated
10520 // as if it were specified with noexcept(true).
10521 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10522 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10523 !FPT->hasExceptionSpec())
10524 NewFD->setType(Context.getFunctionType(
10525 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10526 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10527
10528 // C++20 [dcl.inline]/7
10529 // If an inline function or variable that is attached to a named module
10530 // is declared in a definition domain, it shall be defined in that
10531 // domain.
10532 // So, if the current declaration does not have a definition, we must
10533 // check at the end of the TU (or when the PMF starts) to see that we
10534 // have a definition at that point.
10535 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10536 NewFD->isInNamedModule()) {
10537 PendingInlineFuncDecls.insert(Ptr: NewFD);
10538 }
10539 }
10540
10541 // Filter out previous declarations that don't match the scope.
10542 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10543 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10544 isMemberSpecialization ||
10545 isFunctionTemplateSpecialization);
10546
10547 LoadExternalExtnameUndeclaredIdentifiers();
10548
10549 // Handle GNU asm-label extension (encoded as an attribute).
10550 if (Expr *E = D.getAsmLabel()) {
10551 // The parser guarantees this is a string.
10552 StringLiteral *SE = cast<StringLiteral>(Val: E);
10553 NewFD->addAttr(
10554 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10555 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10556 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10557 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10558 if (I != ExtnameUndeclaredIdentifiers.end()) {
10559 if (isDeclExternC(D: NewFD)) {
10560 NewFD->addAttr(A: I->second);
10561 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10562 } else if (NewFD->getDeclContext()
10563 ->getRedeclContext()
10564 ->isTranslationUnit())
10565 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10566 << /*Variable*/0 << NewFD;
10567 }
10568 }
10569
10570 // Copy the parameter declarations from the declarator D to the function
10571 // declaration NewFD, if they are available. First scavenge them into Params.
10572 SmallVector<ParmVarDecl*, 16> Params;
10573 unsigned FTIIdx;
10574 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10575 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10576
10577 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10578 // function that takes no arguments, not a function that takes a
10579 // single void argument.
10580 // We let through "const void" here because Sema::GetTypeForDeclarator
10581 // already checks for that case.
10582 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10583 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10584 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10585 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10586 Param->setDeclContext(NewFD);
10587 Params.push_back(Elt: Param);
10588
10589 if (Param->isInvalidDecl())
10590 NewFD->setInvalidDecl();
10591 }
10592 }
10593
10594 if (!getLangOpts().CPlusPlus) {
10595 // In C, find all the tag declarations from the prototype and move them
10596 // into the function DeclContext. Remove them from the surrounding tag
10597 // injection context of the function, which is typically but not always
10598 // the TU.
10599 DeclContext *PrototypeTagContext =
10600 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10601 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10602 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10603
10604 // We don't want to reparent enumerators. Look at their parent enum
10605 // instead.
10606 if (!TD) {
10607 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10608 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10609 }
10610 if (!TD)
10611 continue;
10612 DeclContext *TagDC = TD->getLexicalDeclContext();
10613 if (!TagDC->containsDecl(D: TD))
10614 continue;
10615 TagDC->removeDecl(D: TD);
10616 TD->setDeclContext(NewFD);
10617 NewFD->addDecl(D: TD);
10618
10619 // Preserve the lexical DeclContext if it is not the surrounding tag
10620 // injection context of the FD. In this example, the semantic context of
10621 // E will be f and the lexical context will be S, while both the
10622 // semantic and lexical contexts of S will be f:
10623 // void f(struct S { enum E { a } f; } s);
10624 if (TagDC != PrototypeTagContext)
10625 TD->setLexicalDeclContext(TagDC);
10626 }
10627 }
10628 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10629 // When we're declaring a function with a typedef, typeof, etc as in the
10630 // following example, we'll need to synthesize (unnamed)
10631 // parameters for use in the declaration.
10632 //
10633 // @code
10634 // typedef void fn(int);
10635 // fn f;
10636 // @endcode
10637
10638 // Synthesize a parameter for each argument type.
10639 for (const auto &AI : FT->param_types()) {
10640 ParmVarDecl *Param =
10641 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10642 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10643 Params.push_back(Elt: Param);
10644 }
10645 } else {
10646 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10647 "Should not need args for typedef of non-prototype fn");
10648 }
10649
10650 // Finally, we know we have the right number of parameters, install them.
10651 NewFD->setParams(Params);
10652
10653 // If this declarator is a declaration and not a definition, its parameters
10654 // will not be pushed onto a scope chain. That means we will not issue any
10655 // reserved identifier warnings for the declaration, but we will for the
10656 // definition. Handle those here.
10657 if (!D.isFunctionDefinition()) {
10658 for (const ParmVarDecl *PVD : Params)
10659 warnOnReservedIdentifier(D: PVD);
10660 }
10661
10662 if (D.getDeclSpec().isNoreturnSpecified())
10663 NewFD->addAttr(
10664 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10665
10666 // Functions returning a variably modified type violate C99 6.7.5.2p2
10667 // because all functions have linkage.
10668 if (!NewFD->isInvalidDecl() &&
10669 NewFD->getReturnType()->isVariablyModifiedType()) {
10670 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10671 NewFD->setInvalidDecl();
10672 }
10673
10674 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10675 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10676 !NewFD->hasAttr<SectionAttr>())
10677 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10678 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10679 Range: PragmaClangTextSection.PragmaLocation));
10680
10681 // Apply an implicit SectionAttr if #pragma code_seg is active.
10682 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10683 !NewFD->hasAttr<SectionAttr>()) {
10684 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10685 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10686 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10687 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10688 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10689 ASTContext::PSF_Read,
10690 TheDecl: NewFD))
10691 NewFD->dropAttr<SectionAttr>();
10692 }
10693
10694 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10695 // active.
10696 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10697 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10698 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10699 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10700
10701 // Apply an implicit CodeSegAttr from class declspec or
10702 // apply an implicit SectionAttr from #pragma code_seg if active.
10703 if (!NewFD->hasAttr<CodeSegAttr>()) {
10704 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10705 IsDefinition: D.isFunctionDefinition())) {
10706 NewFD->addAttr(A: SAttr);
10707 }
10708 }
10709
10710 // Handle attributes.
10711 ProcessDeclAttributes(S, D: NewFD, PD: D);
10712 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10713 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10714 !NewTVA->isDefaultVersion() &&
10715 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10716 // Don't add to scope fmv functions declarations if fmv disabled
10717 AddToScope = false;
10718 return NewFD;
10719 }
10720
10721 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10722 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10723 // type.
10724 //
10725 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10726 // type declaration will generate a compilation error.
10727 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10728 if (AddressSpace != LangAS::Default) {
10729 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10730 NewFD->setInvalidDecl();
10731 }
10732 }
10733
10734 if (!getLangOpts().CPlusPlus) {
10735 // Perform semantic checking on the function declaration.
10736 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10737 CheckMain(FD: NewFD, D: D.getDeclSpec());
10738
10739 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10740 CheckMSVCRTEntryPoint(FD: NewFD);
10741
10742 if (!NewFD->isInvalidDecl())
10743 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10744 IsMemberSpecialization: isMemberSpecialization,
10745 DeclIsDefn: D.isFunctionDefinition()));
10746 else if (!Previous.empty())
10747 // Recover gracefully from an invalid redeclaration.
10748 D.setRedeclaration(true);
10749 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10750 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10751 "previous declaration set still overloaded");
10752
10753 // Diagnose no-prototype function declarations with calling conventions that
10754 // don't support variadic calls. Only do this in C and do it after merging
10755 // possibly prototyped redeclarations.
10756 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10757 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10758 CallingConv CC = FT->getExtInfo().getCC();
10759 if (!supportsVariadicCall(CC)) {
10760 // Windows system headers sometimes accidentally use stdcall without
10761 // (void) parameters, so we relax this to a warning.
10762 int DiagID =
10763 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10764 Diag(Loc: NewFD->getLocation(), DiagID)
10765 << FunctionType::getNameForCallConv(CC);
10766 }
10767 }
10768
10769 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10770 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10771 checkNonTrivialCUnion(
10772 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10773 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10774 } else {
10775 // C++11 [replacement.functions]p3:
10776 // The program's definitions shall not be specified as inline.
10777 //
10778 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10779 //
10780 // Suppress the diagnostic if the function is __attribute__((used)), since
10781 // that forces an external definition to be emitted.
10782 if (D.getDeclSpec().isInlineSpecified() &&
10783 NewFD->isReplaceableGlobalAllocationFunction() &&
10784 !NewFD->hasAttr<UsedAttr>())
10785 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10786 DiagID: diag::ext_operator_new_delete_declared_inline)
10787 << NewFD->getDeclName();
10788
10789 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10790 // C++20 [dcl.decl.general]p4:
10791 // The optional requires-clause in an init-declarator or
10792 // member-declarator shall be present only if the declarator declares a
10793 // templated function.
10794 //
10795 // C++20 [temp.pre]p8:
10796 // An entity is templated if it is
10797 // - a template,
10798 // - an entity defined or created in a templated entity,
10799 // - a member of a templated entity,
10800 // - an enumerator for an enumeration that is a templated entity, or
10801 // - the closure type of a lambda-expression appearing in the
10802 // declaration of a templated entity.
10803 //
10804 // [Note 6: A local class, a local or block variable, or a friend
10805 // function defined in a templated entity is a templated entity.
10806 // — end note]
10807 //
10808 // A templated function is a function template or a function that is
10809 // templated. A templated class is a class template or a class that is
10810 // templated. A templated variable is a variable template or a variable
10811 // that is templated.
10812 if (!FunctionTemplate) {
10813 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10814 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10815 // An explicit specialization shall not have a trailing
10816 // requires-clause unless it declares a function template.
10817 //
10818 // Since a friend function template specialization cannot be
10819 // definition, and since a non-template friend declaration with a
10820 // trailing requires-clause must be a definition, we diagnose
10821 // friend function template specializations with trailing
10822 // requires-clauses on the same path as explicit specializations
10823 // even though they aren't necessarily prohibited by the same
10824 // language rule.
10825 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10826 << isFriend;
10827 } else if (isFriend && NewFD->isTemplated() &&
10828 !D.isFunctionDefinition()) {
10829 // C++ [temp.friend]p9:
10830 // A non-template friend declaration with a requires-clause shall be
10831 // a definition.
10832 Diag(Loc: NewFD->getBeginLoc(),
10833 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10834 NewFD->setInvalidDecl();
10835 } else if (!NewFD->isTemplated() ||
10836 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10837 Diag(Loc: TRC->getBeginLoc(),
10838 DiagID: diag::err_constrained_non_templated_function);
10839 }
10840 }
10841 }
10842
10843 // We do not add HD attributes to specializations here because
10844 // they may have different constexpr-ness compared to their
10845 // templates and, after maybeAddHostDeviceAttrs() is applied,
10846 // may end up with different effective targets. Instead, a
10847 // specialization inherits its target attributes from its template
10848 // in the CheckFunctionTemplateSpecialization() call below.
10849 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10850 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10851
10852 // Handle explicit specializations of function templates
10853 // and friend function declarations with an explicit
10854 // template argument list.
10855 if (isFunctionTemplateSpecialization) {
10856 bool isDependentSpecialization = false;
10857 if (isFriend) {
10858 // For friend function specializations, this is a dependent
10859 // specialization if its semantic context is dependent, its
10860 // type is dependent, or if its template-id is dependent.
10861 isDependentSpecialization =
10862 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10863 (HasExplicitTemplateArgs &&
10864 TemplateSpecializationType::
10865 anyInstantiationDependentTemplateArguments(
10866 Args: TemplateArgs.arguments()));
10867 assert((!isDependentSpecialization ||
10868 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10869 "dependent friend function specialization without template "
10870 "args");
10871 } else {
10872 // For class-scope explicit specializations of function templates,
10873 // if the lexical context is dependent, then the specialization
10874 // is dependent.
10875 isDependentSpecialization =
10876 CurContext->isRecord() && CurContext->isDependentContext();
10877 }
10878
10879 TemplateArgumentListInfo *ExplicitTemplateArgs =
10880 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10881 if (isDependentSpecialization) {
10882 // If it's a dependent specialization, it may not be possible
10883 // to determine the primary template (for explicit specializations)
10884 // or befriended declaration (for friends) until the enclosing
10885 // template is instantiated. In such cases, we store the declarations
10886 // found by name lookup and defer resolution until instantiation.
10887 if (CheckDependentFunctionTemplateSpecialization(
10888 FD: NewFD, ExplicitTemplateArgs, Previous))
10889 NewFD->setInvalidDecl();
10890 } else if (!NewFD->isInvalidDecl()) {
10891 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10892 Previous))
10893 NewFD->setInvalidDecl();
10894 }
10895 } else if (isMemberSpecialization && !FunctionTemplate) {
10896 if (CheckMemberSpecialization(Member: NewFD, Previous))
10897 NewFD->setInvalidDecl();
10898 }
10899
10900 // Perform semantic checking on the function declaration.
10901 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10902 CheckMain(FD: NewFD, D: D.getDeclSpec());
10903
10904 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10905 CheckMSVCRTEntryPoint(FD: NewFD);
10906
10907 if (!NewFD->isInvalidDecl())
10908 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10909 IsMemberSpecialization: isMemberSpecialization,
10910 DeclIsDefn: D.isFunctionDefinition()));
10911 else if (!Previous.empty())
10912 // Recover gracefully from an invalid redeclaration.
10913 D.setRedeclaration(true);
10914
10915 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10916 !D.isRedeclaration() ||
10917 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10918 "previous declaration set still overloaded");
10919
10920 NamedDecl *PrincipalDecl = (FunctionTemplate
10921 ? cast<NamedDecl>(Val: FunctionTemplate)
10922 : NewFD);
10923
10924 if (isFriend && NewFD->getPreviousDecl()) {
10925 AccessSpecifier Access = AS_public;
10926 if (!NewFD->isInvalidDecl())
10927 Access = NewFD->getPreviousDecl()->getAccess();
10928
10929 NewFD->setAccess(Access);
10930 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10931 }
10932
10933 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10934 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10935 PrincipalDecl->setNonMemberOperator();
10936
10937 // If we have a function template, check the template parameter
10938 // list. This will check and merge default template arguments.
10939 if (FunctionTemplate) {
10940 FunctionTemplateDecl *PrevTemplate =
10941 FunctionTemplate->getPreviousDecl();
10942 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10943 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10944 : nullptr,
10945 TPC: D.getDeclSpec().isFriendSpecified()
10946 ? (D.isFunctionDefinition()
10947 ? TPC_FriendFunctionTemplateDefinition
10948 : TPC_FriendFunctionTemplate)
10949 : (D.getCXXScopeSpec().isSet() &&
10950 DC && DC->isRecord() &&
10951 DC->isDependentContext())
10952 ? TPC_ClassTemplateMember
10953 : TPC_FunctionTemplate);
10954 }
10955
10956 if (NewFD->isInvalidDecl()) {
10957 // Ignore all the rest of this.
10958 } else if (!D.isRedeclaration()) {
10959 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10960 .AddToScope: AddToScope };
10961 // Fake up an access specifier if it's supposed to be a class member.
10962 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10963 NewFD->setAccess(AS_public);
10964
10965 // Qualified decls generally require a previous declaration.
10966 if (D.getCXXScopeSpec().isSet()) {
10967 // ...with the major exception of templated-scope or
10968 // dependent-scope friend declarations.
10969
10970 // TODO: we currently also suppress this check in dependent
10971 // contexts because (1) the parameter depth will be off when
10972 // matching friend templates and (2) we might actually be
10973 // selecting a friend based on a dependent factor. But there
10974 // are situations where these conditions don't apply and we
10975 // can actually do this check immediately.
10976 //
10977 // Unless the scope is dependent, it's always an error if qualified
10978 // redeclaration lookup found nothing at all. Diagnose that now;
10979 // nothing will diagnose that error later.
10980 if (isFriend &&
10981 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10982 (!Previous.empty() && CurContext->isDependentContext()))) {
10983 // ignore these
10984 } else if (NewFD->isCPUDispatchMultiVersion() ||
10985 NewFD->isCPUSpecificMultiVersion()) {
10986 // ignore this, we allow the redeclaration behavior here to create new
10987 // versions of the function.
10988 } else {
10989 // The user tried to provide an out-of-line definition for a
10990 // function that is a member of a class or namespace, but there
10991 // was no such member function declared (C++ [class.mfct]p2,
10992 // C++ [namespace.memdef]p2). For example:
10993 //
10994 // class X {
10995 // void f() const;
10996 // };
10997 //
10998 // void X::f() { } // ill-formed
10999 //
11000 // Complain about this problem, and attempt to suggest close
11001 // matches (e.g., those that differ only in cv-qualifiers and
11002 // whether the parameter types are references).
11003
11004 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11005 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11006 AddToScope = ExtraArgs.AddToScope;
11007 return Result;
11008 }
11009 }
11010
11011 // Unqualified local friend declarations are required to resolve
11012 // to something.
11013 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11014 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11015 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11016 AddToScope = ExtraArgs.AddToScope;
11017 return Result;
11018 }
11019 }
11020 } else if (!D.isFunctionDefinition() &&
11021 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11022 !isFriend && !isFunctionTemplateSpecialization &&
11023 !isMemberSpecialization) {
11024 // An out-of-line member function declaration must also be a
11025 // definition (C++ [class.mfct]p2).
11026 // Note that this is not the case for explicit specializations of
11027 // function templates or member functions of class templates, per
11028 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11029 // extension for compatibility with old SWIG code which likes to
11030 // generate them.
11031 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11032 << D.getCXXScopeSpec().getRange();
11033 }
11034 }
11035
11036 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11037 // Any top level function could potentially be specified as an entry.
11038 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11039 HLSL().ActOnTopLevelFunction(FD: NewFD);
11040
11041 if (NewFD->hasAttr<HLSLShaderAttr>())
11042 HLSL().CheckEntryPoint(FD: NewFD);
11043 }
11044
11045 // If this is the first declaration of a library builtin function, add
11046 // attributes as appropriate.
11047 if (!D.isRedeclaration()) {
11048 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11049 if (unsigned BuiltinID = II->getBuiltinID()) {
11050 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11051 if (!InStdNamespace &&
11052 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11053 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11054 // Validate the type matches unless this builtin is specified as
11055 // matching regardless of its declared type.
11056 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11057 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11058 } else {
11059 ASTContext::GetBuiltinTypeError Error;
11060 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11061 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11062
11063 if (!Error && !BuiltinType.isNull() &&
11064 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11065 T: NewFD->getType(), U: BuiltinType))
11066 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11067 }
11068 }
11069 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11070 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11071 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11072 }
11073 }
11074 }
11075 }
11076
11077 ProcessPragmaWeak(S, D: NewFD);
11078 ProcessPragmaExport(NewD: NewFD);
11079 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11080
11081 AddKnownFunctionAttributes(FD: NewFD);
11082 // The above can add the format attribute for known builtin/library functions
11083 // which is required by the modular_format attribute, thus
11084 // validate modular_format now after those attributes have been added.
11085 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11086
11087 if (NewFD->hasAttr<OverloadableAttr>() &&
11088 !NewFD->getType()->getAs<FunctionProtoType>()) {
11089 Diag(Loc: NewFD->getLocation(),
11090 DiagID: diag::err_attribute_overloadable_no_prototype)
11091 << NewFD;
11092 NewFD->dropAttr<OverloadableAttr>();
11093 }
11094
11095 // If there's a #pragma GCC visibility in scope, and this isn't a class
11096 // member, set the visibility of this function.
11097 if (!DC->isRecord() && NewFD->isExternallyVisible())
11098 AddPushedVisibilityAttribute(RD: NewFD);
11099
11100 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11101 // marking the function.
11102 ObjC().AddCFAuditedAttribute(D: NewFD);
11103
11104 // If this is a function definition, check if we have to apply any
11105 // attributes (i.e. optnone and no_builtin) due to a pragma.
11106 if (D.isFunctionDefinition()) {
11107 AddRangeBasedOptnone(FD: NewFD);
11108 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11109 AddSectionMSAllocText(FD: NewFD);
11110 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11111 }
11112
11113 // If this is the first declaration of an extern C variable, update
11114 // the map of such variables.
11115 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11116 isIncompleteDeclExternC(S&: *this, D: NewFD))
11117 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11118
11119 // Set this FunctionDecl's range up to the right paren.
11120 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11121
11122 if (D.isRedeclaration() && !Previous.empty()) {
11123 NamedDecl *Prev = Previous.getRepresentativeDecl();
11124 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11125 IsSpecialization: isMemberSpecialization ||
11126 isFunctionTemplateSpecialization,
11127 IsDefinition: D.isFunctionDefinition());
11128 }
11129
11130 if (getLangOpts().CUDA) {
11131 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11132 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11133 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11134 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11135 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11136 << CUDA().getConfigureFuncName();
11137 Context.setcudaConfigureCallDecl(NewFD);
11138 }
11139 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11140 !NewFD->isInvalidDecl() &&
11141 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11142 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11143 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11144 << CUDA().getConfigureFuncName();
11145 Context.setcudaGetParameterBufferDecl(NewFD);
11146 }
11147 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11148 !NewFD->isInvalidDecl() &&
11149 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11150 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11151 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11152 << CUDA().getConfigureFuncName();
11153 Context.setcudaLaunchDeviceDecl(NewFD);
11154 }
11155 }
11156 }
11157
11158 MarkUnusedFileScopedDecl(D: NewFD);
11159
11160 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11161 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11162 if (SC == SC_Static) {
11163 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11164 D.setInvalidType();
11165 }
11166
11167 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11168 if (!NewFD->getReturnType()->isVoidType()) {
11169 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11170 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11171 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11172 : FixItHint());
11173 D.setInvalidType();
11174 }
11175
11176 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11177 for (auto *Param : NewFD->parameters())
11178 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11179
11180 if (getLangOpts().OpenCLCPlusPlus) {
11181 if (DC->isRecord()) {
11182 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11183 D.setInvalidType();
11184 }
11185 if (FunctionTemplate) {
11186 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11187 D.setInvalidType();
11188 }
11189 }
11190 }
11191
11192 if (getLangOpts().CPlusPlus) {
11193 // Precalculate whether this is a friend function template with a constraint
11194 // that depends on an enclosing template, per [temp.friend]p9.
11195 if (isFriend && FunctionTemplate &&
11196 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11197 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11198
11199 // C++ [temp.friend]p9:
11200 // A friend function template with a constraint that depends on a
11201 // template parameter from an enclosing template shall be a definition.
11202 if (!D.isFunctionDefinition()) {
11203 Diag(Loc: NewFD->getBeginLoc(),
11204 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11205 NewFD->setInvalidDecl();
11206 }
11207 }
11208
11209 if (FunctionTemplate) {
11210 if (NewFD->isInvalidDecl())
11211 FunctionTemplate->setInvalidDecl();
11212 return FunctionTemplate;
11213 }
11214
11215 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11216 CompleteMemberSpecialization(Member: NewFD, Previous);
11217 }
11218
11219 for (const ParmVarDecl *Param : NewFD->parameters()) {
11220 QualType PT = Param->getType();
11221
11222 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11223 // types.
11224 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11225 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11226 QualType ElemTy = PipeTy->getElementType();
11227 if (ElemTy->isPointerOrReferenceType()) {
11228 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11229 D.setInvalidType();
11230 }
11231 }
11232 }
11233 // WebAssembly tables can't be used as function parameters.
11234 if (Context.getTargetInfo().getTriple().isWasm()) {
11235 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11236 Diag(Loc: Param->getTypeSpecStartLoc(),
11237 DiagID: diag::err_wasm_table_as_function_parameter);
11238 D.setInvalidType();
11239 }
11240 }
11241 }
11242
11243 // Diagnose availability attributes. Availability cannot be used on functions
11244 // that are run during load/unload.
11245 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11246 if (NewFD->hasAttr<ConstructorAttr>()) {
11247 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11248 << 1;
11249 NewFD->dropAttr<AvailabilityAttr>();
11250 }
11251 if (NewFD->hasAttr<DestructorAttr>()) {
11252 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11253 << 2;
11254 NewFD->dropAttr<AvailabilityAttr>();
11255 }
11256 }
11257
11258 // Diagnose no_builtin attribute on function declaration that are not a
11259 // definition.
11260 // FIXME: We should really be doing this in
11261 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11262 // the FunctionDecl and at this point of the code
11263 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11264 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11265 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11266 switch (D.getFunctionDefinitionKind()) {
11267 case FunctionDefinitionKind::Defaulted:
11268 case FunctionDefinitionKind::Deleted:
11269 Diag(Loc: NBA->getLocation(),
11270 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11271 << NBA->getSpelling();
11272 break;
11273 case FunctionDefinitionKind::Declaration:
11274 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11275 << NBA->getSpelling();
11276 break;
11277 case FunctionDefinitionKind::Definition:
11278 break;
11279 }
11280
11281 // Similar to no_builtin logic above, at this point of the code
11282 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11283 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11284 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11285 !NewFD->isInvalidDecl() &&
11286 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11287 ExternalDeclarations.push_back(Elt: NewFD);
11288
11289 // Used for a warning on the 'next' declaration when used with a
11290 // `routine(name)`.
11291 if (getLangOpts().OpenACC)
11292 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11293
11294 return NewFD;
11295}
11296
11297/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11298/// when __declspec(code_seg) "is applied to a class, all member functions of
11299/// the class and nested classes -- this includes compiler-generated special
11300/// member functions -- are put in the specified segment."
11301/// The actual behavior is a little more complicated. The Microsoft compiler
11302/// won't check outer classes if there is an active value from #pragma code_seg.
11303/// The CodeSeg is always applied from the direct parent but only from outer
11304/// classes when the #pragma code_seg stack is empty. See:
11305/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11306/// available since MS has removed the page.
11307static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11308 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11309 if (!Method)
11310 return nullptr;
11311 const CXXRecordDecl *Parent = Method->getParent();
11312 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11313 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11314 NewAttr->setImplicit(true);
11315 return NewAttr;
11316 }
11317
11318 // The Microsoft compiler won't check outer classes for the CodeSeg
11319 // when the #pragma code_seg stack is active.
11320 if (S.CodeSegStack.CurrentValue)
11321 return nullptr;
11322
11323 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11324 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11325 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11326 NewAttr->setImplicit(true);
11327 return NewAttr;
11328 }
11329 }
11330 return nullptr;
11331}
11332
11333Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11334 bool IsDefinition) {
11335 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11336 return A;
11337 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11338 CodeSegStack.CurrentValue)
11339 return SectionAttr::CreateImplicit(
11340 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11341 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11342 return nullptr;
11343}
11344
11345bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11346 QualType NewT, QualType OldT) {
11347 if (!NewD->getLexicalDeclContext()->isDependentContext())
11348 return true;
11349
11350 // For dependently-typed local extern declarations and friends, we can't
11351 // perform a correct type check in general until instantiation:
11352 //
11353 // int f();
11354 // template<typename T> void g() { T f(); }
11355 //
11356 // (valid if g() is only instantiated with T = int).
11357 if (NewT->isDependentType() &&
11358 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11359 return false;
11360
11361 // Similarly, if the previous declaration was a dependent local extern
11362 // declaration, we don't really know its type yet.
11363 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11364 return false;
11365
11366 return true;
11367}
11368
11369bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11370 if (!D->getLexicalDeclContext()->isDependentContext())
11371 return true;
11372
11373 // Don't chain dependent friend function definitions until instantiation, to
11374 // permit cases like
11375 //
11376 // void func();
11377 // template<typename T> class C1 { friend void func() {} };
11378 // template<typename T> class C2 { friend void func() {} };
11379 //
11380 // ... which is valid if only one of C1 and C2 is ever instantiated.
11381 //
11382 // FIXME: This need only apply to function definitions. For now, we proxy
11383 // this by checking for a file-scope function. We do not want this to apply
11384 // to friend declarations nominating member functions, because that gets in
11385 // the way of access checks.
11386 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11387 return false;
11388
11389 auto *VD = dyn_cast<ValueDecl>(Val: D);
11390 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11391 return !VD || !PrevVD ||
11392 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11393 OldT: PrevVD->getType());
11394}
11395
11396/// Check the target or target_version attribute of the function for
11397/// MultiVersion validity.
11398///
11399/// Returns true if there was an error, false otherwise.
11400static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11401 const auto *TA = FD->getAttr<TargetAttr>();
11402 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11403
11404 assert((TA || TVA) && "Expecting target or target_version attribute");
11405
11406 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11407 enum ErrType { Feature = 0, Architecture = 1 };
11408
11409 if (TA) {
11410 ParsedTargetAttr ParseInfo =
11411 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11412 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11413 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11414 << Architecture << ParseInfo.CPU;
11415 return true;
11416 }
11417 for (const auto &Feat : ParseInfo.Features) {
11418 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11419 if (Feat[0] == '-') {
11420 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11421 << Feature << ("no-" + BareFeat);
11422 return true;
11423 }
11424
11425 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11426 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11427 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11428 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11429 << Feature << BareFeat;
11430 return true;
11431 }
11432 }
11433 }
11434
11435 if (TVA) {
11436 llvm::SmallVector<StringRef, 8> Feats;
11437 ParsedTargetAttr ParseInfo;
11438 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11439 ParseInfo =
11440 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11441 for (auto &Feat : ParseInfo.Features)
11442 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11443 } else {
11444 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11445 TVA->getFeatures(Out&: Feats);
11446 }
11447 for (const auto &Feat : Feats) {
11448 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11449 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11450 << Feature << Feat;
11451 return true;
11452 }
11453 }
11454 }
11455 return false;
11456}
11457
11458// Provide a white-list of attributes that are allowed to be combined with
11459// multiversion functions.
11460static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11461 MultiVersionKind MVKind) {
11462 // Note: this list/diagnosis must match the list in
11463 // checkMultiversionAttributesAllSame.
11464 switch (Kind) {
11465 default:
11466 return false;
11467 case attr::ArmLocallyStreaming:
11468 return MVKind == MultiVersionKind::TargetVersion ||
11469 MVKind == MultiVersionKind::TargetClones;
11470 case attr::Used:
11471 return MVKind == MultiVersionKind::Target;
11472 case attr::NonNull:
11473 case attr::NoThrow:
11474 return true;
11475 }
11476}
11477
11478static bool checkNonMultiVersionCompatAttributes(Sema &S,
11479 const FunctionDecl *FD,
11480 const FunctionDecl *CausedFD,
11481 MultiVersionKind MVKind) {
11482 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11483 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11484 << static_cast<unsigned>(MVKind) << A;
11485 if (CausedFD)
11486 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11487 return true;
11488 };
11489
11490 for (const Attr *A : FD->attrs()) {
11491 switch (A->getKind()) {
11492 case attr::CPUDispatch:
11493 case attr::CPUSpecific:
11494 if (MVKind != MultiVersionKind::CPUDispatch &&
11495 MVKind != MultiVersionKind::CPUSpecific)
11496 return Diagnose(S, A);
11497 break;
11498 case attr::Target:
11499 if (MVKind != MultiVersionKind::Target)
11500 return Diagnose(S, A);
11501 break;
11502 case attr::TargetVersion:
11503 if (MVKind != MultiVersionKind::TargetVersion &&
11504 MVKind != MultiVersionKind::TargetClones)
11505 return Diagnose(S, A);
11506 break;
11507 case attr::TargetClones:
11508 if (MVKind != MultiVersionKind::TargetClones &&
11509 MVKind != MultiVersionKind::TargetVersion)
11510 return Diagnose(S, A);
11511 break;
11512 default:
11513 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11514 return Diagnose(S, A);
11515 break;
11516 }
11517 }
11518 return false;
11519}
11520
11521bool Sema::areMultiversionVariantFunctionsCompatible(
11522 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11523 const PartialDiagnostic &NoProtoDiagID,
11524 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11525 const PartialDiagnosticAt &NoSupportDiagIDAt,
11526 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11527 bool ConstexprSupported, bool CLinkageMayDiffer) {
11528 enum DoesntSupport {
11529 FuncTemplates = 0,
11530 VirtFuncs = 1,
11531 DeducedReturn = 2,
11532 Constructors = 3,
11533 Destructors = 4,
11534 DeletedFuncs = 5,
11535 DefaultedFuncs = 6,
11536 ConstexprFuncs = 7,
11537 ConstevalFuncs = 8,
11538 Lambda = 9,
11539 };
11540 enum Different {
11541 CallingConv = 0,
11542 ReturnType = 1,
11543 ConstexprSpec = 2,
11544 InlineSpec = 3,
11545 Linkage = 4,
11546 LanguageLinkage = 5,
11547 };
11548
11549 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11550 !OldFD->getType()->getAs<FunctionProtoType>()) {
11551 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11552 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11553 return true;
11554 }
11555
11556 if (NoProtoDiagID.getDiagID() != 0 &&
11557 !NewFD->getType()->getAs<FunctionProtoType>())
11558 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11559
11560 if (!TemplatesSupported &&
11561 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11562 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11563 << FuncTemplates;
11564
11565 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11566 if (NewCXXFD->isVirtual())
11567 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11568 << VirtFuncs;
11569
11570 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11571 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11572 << Constructors;
11573
11574 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11575 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11576 << Destructors;
11577 }
11578
11579 if (NewFD->isDeleted())
11580 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11581 << DeletedFuncs;
11582
11583 if (NewFD->isDefaulted())
11584 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11585 << DefaultedFuncs;
11586
11587 if (!ConstexprSupported && NewFD->isConstexpr())
11588 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11589 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11590
11591 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11592 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11593 QualType NewReturnType = NewType->getReturnType();
11594
11595 if (NewReturnType->isUndeducedType())
11596 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11597 << DeducedReturn;
11598
11599 // Ensure the return type is identical.
11600 if (OldFD) {
11601 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11602 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11603 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11604 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11605
11606 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11607 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11608
11609 bool ArmStreamingCCMismatched = false;
11610 if (OldFPT && NewFPT) {
11611 unsigned Diff =
11612 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11613 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11614 // cannot be mixed.
11615 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11616 FunctionType::SME_PStateSMCompatibleMask))
11617 ArmStreamingCCMismatched = true;
11618 }
11619
11620 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11621 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11622
11623 QualType OldReturnType = OldType->getReturnType();
11624
11625 if (OldReturnType != NewReturnType)
11626 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11627
11628 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11629 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11630
11631 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11632 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11633
11634 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11635 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11636
11637 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11638 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11639
11640 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11641 NewLoc: NewFD->getLocation()))
11642 return true;
11643 }
11644 return false;
11645}
11646
11647static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11648 const FunctionDecl *NewFD,
11649 bool CausesMV,
11650 MultiVersionKind MVKind) {
11651 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11652 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11653 if (OldFD)
11654 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11655 return true;
11656 }
11657
11658 bool IsCPUSpecificCPUDispatchMVKind =
11659 MVKind == MultiVersionKind::CPUDispatch ||
11660 MVKind == MultiVersionKind::CPUSpecific;
11661
11662 if (CausesMV && OldFD &&
11663 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11664 return true;
11665
11666 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11667 return true;
11668
11669 // Only allow transition to MultiVersion if it hasn't been used.
11670 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11671 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11672 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11673 return true;
11674 }
11675
11676 return S.areMultiversionVariantFunctionsCompatible(
11677 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11678 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11679 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11680 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11681 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11682 << static_cast<unsigned>(MVKind)),
11683 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11684 S.PDiag(DiagID: diag::err_multiversion_diff)),
11685 /*TemplatesSupported=*/false,
11686 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11687 /*CLinkageMayDiffer=*/false);
11688}
11689
11690/// Check the validity of a multiversion function declaration that is the
11691/// first of its kind. Also sets the multiversion'ness' of the function itself.
11692///
11693/// This sets NewFD->isInvalidDecl() to true if there was an error.
11694///
11695/// Returns true if there was an error, false otherwise.
11696static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11697 MultiVersionKind MVKind = FD->getMultiVersionKind();
11698 assert(MVKind != MultiVersionKind::None &&
11699 "Function lacks multiversion attribute");
11700 const auto *TA = FD->getAttr<TargetAttr>();
11701 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11702 // The target attribute only causes MV if this declaration is the default,
11703 // otherwise it is treated as a normal function.
11704 if (TA && !TA->isDefaultVersion())
11705 return false;
11706
11707 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11708 FD->setInvalidDecl();
11709 return true;
11710 }
11711
11712 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11713 FD->setInvalidDecl();
11714 return true;
11715 }
11716
11717 FD->setIsMultiVersion();
11718 return false;
11719}
11720
11721static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11722 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11723 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11724 return true;
11725 }
11726
11727 return false;
11728}
11729
11730static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11731 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11732 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11733 return;
11734
11735 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11736 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11737
11738 if (MVKindTo == MultiVersionKind::None &&
11739 (MVKindFrom == MultiVersionKind::TargetVersion ||
11740 MVKindFrom == MultiVersionKind::TargetClones))
11741 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11742 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11743}
11744
11745static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11746 FunctionDecl *NewFD,
11747 bool &Redeclaration,
11748 NamedDecl *&OldDecl,
11749 LookupResult &Previous) {
11750 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11751
11752 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11753 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11754 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11755 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11756
11757 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11758
11759 // The definitions should be allowed in any order. If we have discovered
11760 // a new target version and the preceeding was the default, then add the
11761 // corresponding attribute to it.
11762 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11763
11764 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11765 // to change, this is a simple redeclaration.
11766 if (NewTA && !NewTA->isDefaultVersion() &&
11767 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11768 return false;
11769
11770 // Otherwise, this decl causes MultiVersioning.
11771 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11772 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11773 : MultiVersionKind::Target)) {
11774 NewFD->setInvalidDecl();
11775 return true;
11776 }
11777
11778 if (CheckMultiVersionValue(S, FD: NewFD)) {
11779 NewFD->setInvalidDecl();
11780 return true;
11781 }
11782
11783 // If this is 'default', permit the forward declaration.
11784 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11785 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11786 Redeclaration = true;
11787 OldDecl = OldFD;
11788 OldFD->setIsMultiVersion();
11789 NewFD->setIsMultiVersion();
11790 return false;
11791 }
11792
11793 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11794 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11795 NewFD->setInvalidDecl();
11796 return true;
11797 }
11798
11799 if (NewTA) {
11800 ParsedTargetAttr OldParsed =
11801 S.getASTContext().getTargetInfo().parseTargetAttr(
11802 Str: OldTA->getFeaturesStr());
11803 llvm::sort(C&: OldParsed.Features);
11804 ParsedTargetAttr NewParsed =
11805 S.getASTContext().getTargetInfo().parseTargetAttr(
11806 Str: NewTA->getFeaturesStr());
11807 // Sort order doesn't matter, it just needs to be consistent.
11808 llvm::sort(C&: NewParsed.Features);
11809 if (OldParsed == NewParsed) {
11810 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11811 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11812 NewFD->setInvalidDecl();
11813 return true;
11814 }
11815 }
11816
11817 for (const auto *FD : OldFD->redecls()) {
11818 const auto *CurTA = FD->getAttr<TargetAttr>();
11819 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11820 // We allow forward declarations before ANY multiversioning attributes, but
11821 // nothing after the fact.
11822 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11823 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11824 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11825 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11826 << (NewTA ? 0 : 2);
11827 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11828 NewFD->setInvalidDecl();
11829 return true;
11830 }
11831 }
11832
11833 OldFD->setIsMultiVersion();
11834 NewFD->setIsMultiVersion();
11835 Redeclaration = false;
11836 OldDecl = nullptr;
11837 Previous.clear();
11838 return false;
11839}
11840
11841static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11842 MultiVersionKind OldKind = Old->getMultiVersionKind();
11843 MultiVersionKind NewKind = New->getMultiVersionKind();
11844
11845 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11846 NewKind == MultiVersionKind::None)
11847 return true;
11848
11849 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11850 switch (OldKind) {
11851 case MultiVersionKind::TargetVersion:
11852 return NewKind == MultiVersionKind::TargetClones;
11853 case MultiVersionKind::TargetClones:
11854 return NewKind == MultiVersionKind::TargetVersion;
11855 default:
11856 return false;
11857 }
11858 } else {
11859 switch (OldKind) {
11860 case MultiVersionKind::CPUDispatch:
11861 return NewKind == MultiVersionKind::CPUSpecific;
11862 case MultiVersionKind::CPUSpecific:
11863 return NewKind == MultiVersionKind::CPUDispatch;
11864 default:
11865 return false;
11866 }
11867 }
11868}
11869
11870/// Check the validity of a new function declaration being added to an existing
11871/// multiversioned declaration collection.
11872static bool CheckMultiVersionAdditionalDecl(
11873 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11874 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11875 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11876 LookupResult &Previous) {
11877
11878 // Disallow mixing of multiversioning types.
11879 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11880 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11881 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11882 NewFD->setInvalidDecl();
11883 return true;
11884 }
11885
11886 // Add the default target_version attribute if it's missing.
11887 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11888 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11889
11890 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11891 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11892 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11893 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11894
11895 ParsedTargetAttr NewParsed;
11896 if (NewTA) {
11897 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11898 Str: NewTA->getFeaturesStr());
11899 llvm::sort(C&: NewParsed.Features);
11900 }
11901 llvm::SmallVector<StringRef, 8> NewFeats;
11902 if (NewTVA) {
11903 NewTVA->getFeatures(Out&: NewFeats);
11904 llvm::sort(C&: NewFeats);
11905 }
11906
11907 bool UseMemberUsingDeclRules =
11908 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11909
11910 bool MayNeedOverloadableChecks =
11911 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11912
11913 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11914 // of a previous member of the MultiVersion set.
11915 for (NamedDecl *ND : Previous) {
11916 FunctionDecl *CurFD = ND->getAsFunction();
11917 if (!CurFD || CurFD->isInvalidDecl())
11918 continue;
11919 if (MayNeedOverloadableChecks &&
11920 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11921 continue;
11922
11923 switch (NewMVKind) {
11924 case MultiVersionKind::None:
11925 assert(OldMVKind == MultiVersionKind::TargetClones &&
11926 "Only target_clones can be omitted in subsequent declarations");
11927 break;
11928 case MultiVersionKind::Target: {
11929 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11930 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11931 NewFD->setIsMultiVersion();
11932 Redeclaration = true;
11933 OldDecl = ND;
11934 return false;
11935 }
11936
11937 ParsedTargetAttr CurParsed =
11938 S.getASTContext().getTargetInfo().parseTargetAttr(
11939 Str: CurTA->getFeaturesStr());
11940 llvm::sort(C&: CurParsed.Features);
11941 if (CurParsed == NewParsed) {
11942 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11943 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11944 NewFD->setInvalidDecl();
11945 return true;
11946 }
11947 break;
11948 }
11949 case MultiVersionKind::TargetVersion: {
11950 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11951 if (CurTVA->getName() == NewTVA->getName()) {
11952 NewFD->setIsMultiVersion();
11953 Redeclaration = true;
11954 OldDecl = ND;
11955 return false;
11956 }
11957 llvm::SmallVector<StringRef, 8> CurFeats;
11958 CurTVA->getFeatures(Out&: CurFeats);
11959 llvm::sort(C&: CurFeats);
11960
11961 if (CurFeats == NewFeats) {
11962 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11963 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11964 NewFD->setInvalidDecl();
11965 return true;
11966 }
11967 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11968 // Default
11969 if (NewFeats.empty())
11970 break;
11971
11972 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11973 llvm::SmallVector<StringRef, 8> CurFeats;
11974 CurClones->getFeatures(Out&: CurFeats, Index: I);
11975 llvm::sort(C&: CurFeats);
11976
11977 if (CurFeats == NewFeats) {
11978 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11979 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11980 NewFD->setInvalidDecl();
11981 return true;
11982 }
11983 }
11984 }
11985 break;
11986 }
11987 case MultiVersionKind::TargetClones: {
11988 assert(NewClones && "MultiVersionKind does not match attribute type");
11989 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11990 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11991 !std::equal(first1: CurClones->featuresStrs_begin(),
11992 last1: CurClones->featuresStrs_end(),
11993 first2: NewClones->featuresStrs_begin())) {
11994 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11995 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11996 NewFD->setInvalidDecl();
11997 return true;
11998 }
11999 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12000 llvm::SmallVector<StringRef, 8> CurFeats;
12001 CurTVA->getFeatures(Out&: CurFeats);
12002 llvm::sort(C&: CurFeats);
12003
12004 // Default
12005 if (CurFeats.empty())
12006 break;
12007
12008 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12009 NewFeats.clear();
12010 NewClones->getFeatures(Out&: NewFeats, Index: I);
12011 llvm::sort(C&: NewFeats);
12012
12013 if (CurFeats == NewFeats) {
12014 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12015 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12016 NewFD->setInvalidDecl();
12017 return true;
12018 }
12019 }
12020 break;
12021 }
12022 Redeclaration = true;
12023 OldDecl = CurFD;
12024 NewFD->setIsMultiVersion();
12025 return false;
12026 }
12027 case MultiVersionKind::CPUSpecific:
12028 case MultiVersionKind::CPUDispatch: {
12029 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12030 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12031 // Handle CPUDispatch/CPUSpecific versions.
12032 // Only 1 CPUDispatch function is allowed, this will make it go through
12033 // the redeclaration errors.
12034 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12035 CurFD->hasAttr<CPUDispatchAttr>()) {
12036 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12037 std::equal(
12038 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12039 first2: NewCPUDisp->cpus_begin(),
12040 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12041 return Cur->getName() == New->getName();
12042 })) {
12043 NewFD->setIsMultiVersion();
12044 Redeclaration = true;
12045 OldDecl = ND;
12046 return false;
12047 }
12048
12049 // If the declarations don't match, this is an error condition.
12050 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12051 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12052 NewFD->setInvalidDecl();
12053 return true;
12054 }
12055 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12056 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12057 std::equal(
12058 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12059 first2: NewCPUSpec->cpus_begin(),
12060 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12061 return Cur->getName() == New->getName();
12062 })) {
12063 NewFD->setIsMultiVersion();
12064 Redeclaration = true;
12065 OldDecl = ND;
12066 return false;
12067 }
12068
12069 // Only 1 version of CPUSpecific is allowed for each CPU.
12070 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12071 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12072 if (CurII == NewII) {
12073 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12074 << NewII;
12075 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12076 NewFD->setInvalidDecl();
12077 return true;
12078 }
12079 }
12080 }
12081 }
12082 break;
12083 }
12084 }
12085 }
12086
12087 // Redeclarations of a target_clones function may omit the attribute, in which
12088 // case it will be inherited during declaration merging.
12089 if (NewMVKind == MultiVersionKind::None &&
12090 OldMVKind == MultiVersionKind::TargetClones) {
12091 NewFD->setIsMultiVersion();
12092 Redeclaration = true;
12093 OldDecl = OldFD;
12094 return false;
12095 }
12096
12097 // Else, this is simply a non-redecl case. Checking the 'value' is only
12098 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12099 // handled in the attribute adding step.
12100 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12101 NewFD->setInvalidDecl();
12102 return true;
12103 }
12104
12105 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12106 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12107 NewFD->setInvalidDecl();
12108 return true;
12109 }
12110
12111 // Permit forward declarations in the case where these two are compatible.
12112 if (!OldFD->isMultiVersion()) {
12113 OldFD->setIsMultiVersion();
12114 NewFD->setIsMultiVersion();
12115 Redeclaration = true;
12116 OldDecl = OldFD;
12117 return false;
12118 }
12119
12120 NewFD->setIsMultiVersion();
12121 Redeclaration = false;
12122 OldDecl = nullptr;
12123 Previous.clear();
12124 return false;
12125}
12126
12127/// Check the validity of a mulitversion function declaration.
12128/// Also sets the multiversion'ness' of the function itself.
12129///
12130/// This sets NewFD->isInvalidDecl() to true if there was an error.
12131///
12132/// Returns true if there was an error, false otherwise.
12133static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12134 bool &Redeclaration, NamedDecl *&OldDecl,
12135 LookupResult &Previous) {
12136 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12137
12138 // Check if FMV is disabled.
12139 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12140 return false;
12141
12142 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12143 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12144 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12145 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12146 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12147 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12148
12149 // Main isn't allowed to become a multiversion function, however it IS
12150 // permitted to have 'main' be marked with the 'target' optimization hint,
12151 // for 'target_version' only default is allowed.
12152 if (NewFD->isMain()) {
12153 if (MVKind != MultiVersionKind::None &&
12154 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12155 !(MVKind == MultiVersionKind::TargetVersion &&
12156 NewTVA->isDefaultVersion())) {
12157 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12158 NewFD->setInvalidDecl();
12159 return true;
12160 }
12161 return false;
12162 }
12163
12164 // Target attribute on AArch64 is not used for multiversioning
12165 if (NewTA && TI.getTriple().isAArch64())
12166 return false;
12167
12168 // Target attribute on RISCV is not used for multiversioning
12169 if (NewTA && TI.getTriple().isRISCV())
12170 return false;
12171
12172 if (!OldDecl || !OldDecl->getAsFunction() ||
12173 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12174 DC: NewFD->getDeclContext()->getRedeclContext())) {
12175 // If there's no previous declaration, AND this isn't attempting to cause
12176 // multiversioning, this isn't an error condition.
12177 if (MVKind == MultiVersionKind::None)
12178 return false;
12179 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12180 }
12181
12182 FunctionDecl *OldFD = OldDecl->getAsFunction();
12183
12184 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12185 return false;
12186
12187 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12188 // for target_clones and target_version.
12189 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12190 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12191 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12192 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12193 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12194 NewFD->setInvalidDecl();
12195 return true;
12196 }
12197
12198 if (!OldFD->isMultiVersion()) {
12199 switch (MVKind) {
12200 case MultiVersionKind::Target:
12201 case MultiVersionKind::TargetVersion:
12202 return CheckDeclarationCausesMultiVersioning(
12203 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12204 case MultiVersionKind::TargetClones:
12205 if (OldFD->isUsed(CheckUsedAttr: false)) {
12206 NewFD->setInvalidDecl();
12207 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12208 }
12209 OldFD->setIsMultiVersion();
12210 break;
12211
12212 case MultiVersionKind::CPUDispatch:
12213 case MultiVersionKind::CPUSpecific:
12214 case MultiVersionKind::None:
12215 break;
12216 }
12217 }
12218
12219 // At this point, we have a multiversion function decl (in OldFD) AND an
12220 // appropriate attribute in the current function decl (unless it's allowed to
12221 // omit the attribute). Resolve that these are still compatible with previous
12222 // declarations.
12223 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12224 NewCPUSpec, NewClones, Redeclaration,
12225 OldDecl, Previous);
12226}
12227
12228static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12229 bool IsPure = NewFD->hasAttr<PureAttr>();
12230 bool IsConst = NewFD->hasAttr<ConstAttr>();
12231
12232 // If there are no pure or const attributes, there's nothing to check.
12233 if (!IsPure && !IsConst)
12234 return;
12235
12236 // If the function is marked both pure and const, we retain the const
12237 // attribute because it makes stronger guarantees than the pure attribute, and
12238 // we drop the pure attribute explicitly to prevent later confusion about
12239 // semantics.
12240 if (IsPure && IsConst) {
12241 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12242 NewFD->dropAttrs<PureAttr>();
12243 }
12244
12245 // Constructors and destructors are functions which return void, so are
12246 // handled here as well.
12247 if (NewFD->getReturnType()->isVoidType()) {
12248 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12249 << IsConst;
12250 NewFD->dropAttrs<PureAttr, ConstAttr>();
12251 }
12252}
12253
12254bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12255 LookupResult &Previous,
12256 bool IsMemberSpecialization,
12257 bool DeclIsDefn) {
12258 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12259 "Variably modified return types are not handled here");
12260
12261 // Determine whether the type of this function should be merged with
12262 // a previous visible declaration. This never happens for functions in C++,
12263 // and always happens in C if the previous declaration was visible.
12264 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12265 !Previous.isShadowed();
12266
12267 bool Redeclaration = false;
12268 NamedDecl *OldDecl = nullptr;
12269 bool MayNeedOverloadableChecks = false;
12270
12271 inferLifetimeCaptureByAttribute(FD: NewFD);
12272 // Merge or overload the declaration with an existing declaration of
12273 // the same name, if appropriate.
12274 if (!Previous.empty()) {
12275 // Determine whether NewFD is an overload of PrevDecl or
12276 // a declaration that requires merging. If it's an overload,
12277 // there's no more work to do here; we'll just add the new
12278 // function to the scope.
12279 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12280 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12281 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12282 Redeclaration = true;
12283 OldDecl = Candidate;
12284 }
12285 } else {
12286 MayNeedOverloadableChecks = true;
12287 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12288 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12289 case OverloadKind::Match:
12290 Redeclaration = true;
12291 break;
12292
12293 case OverloadKind::NonFunction:
12294 Redeclaration = true;
12295 break;
12296
12297 case OverloadKind::Overload:
12298 Redeclaration = false;
12299 break;
12300 }
12301 }
12302 }
12303
12304 // Check for a previous extern "C" declaration with this name.
12305 if (!Redeclaration &&
12306 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12307 if (!Previous.empty()) {
12308 // This is an extern "C" declaration with the same name as a previous
12309 // declaration, and thus redeclares that entity...
12310 Redeclaration = true;
12311 OldDecl = Previous.getFoundDecl();
12312 MergeTypeWithPrevious = false;
12313
12314 // ... except in the presence of __attribute__((overloadable)).
12315 if (OldDecl->hasAttr<OverloadableAttr>() ||
12316 NewFD->hasAttr<OverloadableAttr>()) {
12317 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12318 MayNeedOverloadableChecks = true;
12319 Redeclaration = false;
12320 OldDecl = nullptr;
12321 }
12322 }
12323 }
12324 }
12325
12326 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12327 return Redeclaration;
12328
12329 // PPC MMA non-pointer types are not allowed as function return types.
12330 if (Context.getTargetInfo().getTriple().isPPC64() &&
12331 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12332 NewFD->setInvalidDecl();
12333 }
12334
12335 CheckConstPureAttributesUsage(S&: *this, NewFD);
12336
12337 // C++ [dcl.spec.auto.general]p12:
12338 // Return type deduction for a templated function with a placeholder in its
12339 // declared type occurs when the definition is instantiated even if the
12340 // function body contains a return statement with a non-type-dependent
12341 // operand.
12342 //
12343 // C++ [temp.dep.expr]p3:
12344 // An id-expression is type-dependent if it is a template-id that is not a
12345 // concept-id and is dependent; or if its terminal name is:
12346 // - [...]
12347 // - associated by name lookup with one or more declarations of member
12348 // functions of a class that is the current instantiation declared with a
12349 // return type that contains a placeholder type,
12350 // - [...]
12351 //
12352 // If this is a templated function with a placeholder in its return type,
12353 // make the placeholder type dependent since it won't be deduced until the
12354 // definition is instantiated. We do this here because it needs to happen
12355 // for implicitly instantiated member functions/member function templates.
12356 if (getLangOpts().CPlusPlus14 &&
12357 (NewFD->isDependentContext() &&
12358 NewFD->getReturnType()->isUndeducedType())) {
12359 const FunctionProtoType *FPT =
12360 NewFD->getType()->castAs<FunctionProtoType>();
12361 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12362 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12363 EPI: FPT->getExtProtoInfo()));
12364 }
12365
12366 // C++11 [dcl.constexpr]p8:
12367 // A constexpr specifier for a non-static member function that is not
12368 // a constructor declares that member function to be const.
12369 //
12370 // This needs to be delayed until we know whether this is an out-of-line
12371 // definition of a static member function.
12372 //
12373 // This rule is not present in C++1y, so we produce a backwards
12374 // compatibility warning whenever it happens in C++11.
12375 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12376 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12377 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12378 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12379 CXXMethodDecl *OldMD = nullptr;
12380 if (OldDecl)
12381 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12382 if (!OldMD || !OldMD->isStatic()) {
12383 const FunctionProtoType *FPT =
12384 MD->getType()->castAs<FunctionProtoType>();
12385 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12386 EPI.TypeQuals.addConst();
12387 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12388 Args: FPT->getParamTypes(), EPI));
12389
12390 // Warn that we did this, if we're not performing template instantiation.
12391 // In that case, we'll have warned already when the template was defined.
12392 if (!inTemplateInstantiation()) {
12393 SourceLocation AddConstLoc;
12394 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12395 .IgnoreParens().getAs<FunctionTypeLoc>())
12396 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12397
12398 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12399 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12400 }
12401 }
12402 }
12403
12404 if (Redeclaration) {
12405 // NewFD and OldDecl represent declarations that need to be
12406 // merged.
12407 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12408 NewDeclIsDefn: DeclIsDefn)) {
12409 NewFD->setInvalidDecl();
12410 return Redeclaration;
12411 }
12412
12413 Previous.clear();
12414 Previous.addDecl(D: OldDecl);
12415
12416 if (FunctionTemplateDecl *OldTemplateDecl =
12417 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12418 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12419 FunctionTemplateDecl *NewTemplateDecl
12420 = NewFD->getDescribedFunctionTemplate();
12421 assert(NewTemplateDecl && "Template/non-template mismatch");
12422
12423 // The call to MergeFunctionDecl above may have created some state in
12424 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12425 // can add it as a redeclaration.
12426 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12427
12428 NewFD->setPreviousDeclaration(OldFD);
12429 if (NewFD->isCXXClassMember()) {
12430 NewFD->setAccess(OldTemplateDecl->getAccess());
12431 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12432 }
12433
12434 // If this is an explicit specialization of a member that is a function
12435 // template, mark it as a member specialization.
12436 if (IsMemberSpecialization &&
12437 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12438 NewTemplateDecl->setMemberSpecialization();
12439 assert(OldTemplateDecl->isMemberSpecialization());
12440 // Explicit specializations of a member template do not inherit deleted
12441 // status from the parent member template that they are specializing.
12442 if (OldFD->isDeleted()) {
12443 // FIXME: This assert will not hold in the presence of modules.
12444 assert(OldFD->getCanonicalDecl() == OldFD);
12445 // FIXME: We need an update record for this AST mutation.
12446 OldFD->setDeletedAsWritten(D: false);
12447 }
12448 }
12449
12450 } else {
12451 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12452 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12453 // This needs to happen first so that 'inline' propagates.
12454 NewFD->setPreviousDeclaration(OldFD);
12455 if (NewFD->isCXXClassMember())
12456 NewFD->setAccess(OldFD->getAccess());
12457 }
12458 }
12459 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12460 !NewFD->getAttr<OverloadableAttr>()) {
12461 assert((Previous.empty() ||
12462 llvm::any_of(Previous,
12463 [](const NamedDecl *ND) {
12464 return ND->hasAttr<OverloadableAttr>();
12465 })) &&
12466 "Non-redecls shouldn't happen without overloadable present");
12467
12468 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12469 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12470 return FD && !FD->hasAttr<OverloadableAttr>();
12471 });
12472
12473 if (OtherUnmarkedIter != Previous.end()) {
12474 Diag(Loc: NewFD->getLocation(),
12475 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12476 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12477 DiagID: diag::note_attribute_overloadable_prev_overload)
12478 << false;
12479
12480 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12481 }
12482 }
12483
12484 if (LangOpts.OpenMP)
12485 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12486
12487 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12488 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12489
12490 if (NewFD->hasAttr<SYCLExternalAttr>())
12491 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12492
12493 // Semantic checking for this function declaration (in isolation).
12494
12495 if (getLangOpts().CPlusPlus) {
12496 // C++-specific checks.
12497 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12498 CheckConstructor(Constructor);
12499 } else if (CXXDestructorDecl *Destructor =
12500 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12501 // We check here for invalid destructor names.
12502 // If we have a friend destructor declaration that is dependent, we can't
12503 // diagnose right away because cases like this are still valid:
12504 // template <class T> struct A { friend T::X::~Y(); };
12505 // struct B { struct Y { ~Y(); }; using X = Y; };
12506 // template struct A<B>;
12507 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12508 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12509 CanQualType ClassType =
12510 Context.getCanonicalTagType(TD: Destructor->getParent());
12511
12512 DeclarationName Name =
12513 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12514 if (NewFD->getDeclName() != Name) {
12515 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12516 NewFD->setInvalidDecl();
12517 return Redeclaration;
12518 }
12519 }
12520 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12521 if (auto *TD = Guide->getDescribedFunctionTemplate())
12522 CheckDeductionGuideTemplate(TD);
12523
12524 // A deduction guide is not on the list of entities that can be
12525 // explicitly specialized.
12526 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12527 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12528 << /*explicit specialization*/ 1;
12529 }
12530
12531 // Find any virtual functions that this function overrides.
12532 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12533 if (!Method->isFunctionTemplateSpecialization() &&
12534 !Method->getDescribedFunctionTemplate() &&
12535 Method->isCanonicalDecl()) {
12536 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12537 }
12538 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12539 // C++2a [class.virtual]p6
12540 // A virtual method shall not have a requires-clause.
12541 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12542 DiagID: diag::err_constrained_virtual_method);
12543
12544 if (Method->isStatic())
12545 checkThisInStaticMemberFunctionType(Method);
12546 }
12547
12548 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12549 ActOnConversionDeclarator(Conversion);
12550
12551 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12552 if (NewFD->isOverloadedOperator() &&
12553 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12554 NewFD->setInvalidDecl();
12555 return Redeclaration;
12556 }
12557
12558 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12559 if (NewFD->getLiteralIdentifier() &&
12560 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12561 NewFD->setInvalidDecl();
12562 return Redeclaration;
12563 }
12564
12565 // In C++, check default arguments now that we have merged decls. Unless
12566 // the lexical context is the class, because in this case this is done
12567 // during delayed parsing anyway.
12568 if (!CurContext->isRecord())
12569 CheckCXXDefaultArguments(FD: NewFD);
12570
12571 // If this function is declared as being extern "C", then check to see if
12572 // the function returns a UDT (class, struct, or union type) that is not C
12573 // compatible, and if it does, warn the user.
12574 // But, issue any diagnostic on the first declaration only.
12575 if (Previous.empty() && NewFD->isExternC()) {
12576 QualType R = NewFD->getReturnType();
12577 if (R->isIncompleteType() && !R->isVoidType())
12578 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12579 << NewFD << R;
12580 else if (!R.isPODType(Context) && !R->isVoidType() &&
12581 !R->isObjCObjectPointerType())
12582 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12583 }
12584
12585 // C++1z [dcl.fct]p6:
12586 // [...] whether the function has a non-throwing exception-specification
12587 // [is] part of the function type
12588 //
12589 // This results in an ABI break between C++14 and C++17 for functions whose
12590 // declared type includes an exception-specification in a parameter or
12591 // return type. (Exception specifications on the function itself are OK in
12592 // most cases, and exception specifications are not permitted in most other
12593 // contexts where they could make it into a mangling.)
12594 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12595 auto HasNoexcept = [&](QualType T) -> bool {
12596 // Strip off declarator chunks that could be between us and a function
12597 // type. We don't need to look far, exception specifications are very
12598 // restricted prior to C++17.
12599 if (auto *RT = T->getAs<ReferenceType>())
12600 T = RT->getPointeeType();
12601 else if (T->isAnyPointerType())
12602 T = T->getPointeeType();
12603 else if (auto *MPT = T->getAs<MemberPointerType>())
12604 T = MPT->getPointeeType();
12605 if (auto *FPT = T->getAs<FunctionProtoType>())
12606 if (FPT->isNothrow())
12607 return true;
12608 return false;
12609 };
12610
12611 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12612 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12613 for (QualType T : FPT->param_types())
12614 AnyNoexcept |= HasNoexcept(T);
12615 if (AnyNoexcept)
12616 Diag(Loc: NewFD->getLocation(),
12617 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12618 << NewFD;
12619 }
12620
12621 if (!Redeclaration && LangOpts.CUDA) {
12622 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12623 for (auto *Parm : NewFD->parameters()) {
12624 if (!Parm->getType()->isDependentType() &&
12625 Parm->hasAttr<CUDAGridConstantAttr>() &&
12626 !(IsKernel && Parm->getType().isConstQualified()))
12627 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12628 DiagID: diag::err_cuda_grid_constant_not_allowed);
12629 }
12630 CUDA().checkTargetOverload(NewFD, Previous);
12631 }
12632 }
12633
12634 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12635 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12636
12637 return Redeclaration;
12638}
12639
12640void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12641 // [basic.start.main]p3
12642 // The main function shall not be declared with C linkage-specification.
12643 if (FD->isExternCContext())
12644 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12645
12646 // C++11 [basic.start.main]p3:
12647 // A program that [...] declares main to be inline, static or
12648 // constexpr is ill-formed.
12649 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12650 // appear in a declaration of main.
12651 // static main is not an error under C99, but we should warn about it.
12652 // We accept _Noreturn main as an extension.
12653 if (FD->getStorageClass() == SC_Static)
12654 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12655 ? diag::err_static_main : diag::warn_static_main)
12656 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12657 if (FD->isInlineSpecified())
12658 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12659 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12660 if (DS.isNoreturnSpecified()) {
12661 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12662 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12663 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12664 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12665 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12666 }
12667 if (FD->isConstexpr()) {
12668 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12669 << FD->isConsteval()
12670 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12671 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12672 }
12673
12674 if (getLangOpts().OpenCL) {
12675 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12676 << FD->hasAttr<DeviceKernelAttr>();
12677 FD->setInvalidDecl();
12678 return;
12679 }
12680
12681 if (FD->hasAttr<SYCLExternalAttr>()) {
12682 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12683 << FD->getAttr<SYCLExternalAttr>();
12684 FD->setInvalidDecl();
12685 return;
12686 }
12687
12688 // Functions named main in hlsl are default entries, but don't have specific
12689 // signatures they are required to conform to.
12690 if (getLangOpts().HLSL)
12691 return;
12692
12693 QualType T = FD->getType();
12694 assert(T->isFunctionType() && "function decl is not of function type");
12695 const FunctionType* FT = T->castAs<FunctionType>();
12696
12697 // Set default calling convention for main()
12698 if (FT->getCallConv() != CC_C) {
12699 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12700 FD->setType(QualType(FT, 0));
12701 T = Context.getCanonicalType(T: FD->getType());
12702 }
12703
12704 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12705 // In C with GNU extensions we allow main() to have non-integer return
12706 // type, but we should warn about the extension, and we disable the
12707 // implicit-return-zero rule.
12708
12709 // GCC in C mode accepts qualified 'int'.
12710 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12711 FD->setHasImplicitReturnZero(true);
12712 else {
12713 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12714 SourceRange RTRange = FD->getReturnTypeSourceRange();
12715 if (RTRange.isValid())
12716 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12717 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12718 }
12719 } else {
12720 // In C and C++, main magically returns 0 if you fall off the end;
12721 // set the flag which tells us that.
12722 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12723
12724 // All the standards say that main() should return 'int'.
12725 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12726 FD->setHasImplicitReturnZero(true);
12727 else {
12728 // Otherwise, this is just a flat-out error.
12729 SourceRange RTRange = FD->getReturnTypeSourceRange();
12730 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12731 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12732 : FixItHint());
12733 FD->setInvalidDecl(true);
12734 }
12735
12736 // [basic.start.main]p3:
12737 // A program that declares a function main that belongs to the global scope
12738 // and is attached to a named module is ill-formed.
12739 if (FD->isInNamedModule()) {
12740 const SourceLocation start = FD->getTypeSpecStartLoc();
12741 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12742 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12743 }
12744 }
12745
12746 // Treat protoless main() as nullary.
12747 if (isa<FunctionNoProtoType>(Val: FT)) return;
12748
12749 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12750 unsigned nparams = FTP->getNumParams();
12751 assert(FD->getNumParams() == nparams);
12752
12753 bool HasExtraParameters = (nparams > 3);
12754
12755 if (FTP->isVariadic()) {
12756 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12757 // FIXME: if we had information about the location of the ellipsis, we
12758 // could add a FixIt hint to remove it as a parameter.
12759 }
12760
12761 // Darwin passes an undocumented fourth argument of type char**. If
12762 // other platforms start sprouting these, the logic below will start
12763 // getting shifty.
12764 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12765 HasExtraParameters = false;
12766
12767 if (HasExtraParameters) {
12768 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12769 FD->setInvalidDecl(true);
12770 nparams = 3;
12771 }
12772
12773 // FIXME: a lot of the following diagnostics would be improved
12774 // if we had some location information about types.
12775
12776 QualType CharPP =
12777 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12778 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12779
12780 for (unsigned i = 0; i < nparams; ++i) {
12781 QualType AT = FTP->getParamType(i);
12782
12783 bool mismatch = true;
12784
12785 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12786 mismatch = false;
12787 else if (Expected[i] == CharPP) {
12788 // As an extension, the following forms are okay:
12789 // char const **
12790 // char const * const *
12791 // char * const *
12792
12793 QualifierCollector qs;
12794 const PointerType* PT;
12795 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12796 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12797 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12798 T2: Context.CharTy)) {
12799 qs.removeConst();
12800 mismatch = !qs.empty();
12801 }
12802 }
12803
12804 if (mismatch) {
12805 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12806 // TODO: suggest replacing given type with expected type
12807 FD->setInvalidDecl(true);
12808 }
12809 }
12810
12811 if (nparams == 1 && !FD->isInvalidDecl()) {
12812 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12813 }
12814
12815 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12816 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12817 FD->setInvalidDecl();
12818 }
12819}
12820
12821static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12822
12823 // Default calling convention for main and wmain is __cdecl
12824 if (FD->getName() == "main" || FD->getName() == "wmain")
12825 return false;
12826
12827 // Default calling convention for MinGW and Cygwin is __cdecl
12828 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12829 if (T.isOSCygMing())
12830 return false;
12831
12832 // Default calling convention for WinMain, wWinMain and DllMain
12833 // is __stdcall on 32 bit Windows
12834 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12835 return true;
12836
12837 return false;
12838}
12839
12840void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12841 QualType T = FD->getType();
12842 assert(T->isFunctionType() && "function decl is not of function type");
12843 const FunctionType *FT = T->castAs<FunctionType>();
12844
12845 // Set an implicit return of 'zero' if the function can return some integral,
12846 // enumeration, pointer or nullptr type.
12847 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12848 FT->getReturnType()->isAnyPointerType() ||
12849 FT->getReturnType()->isNullPtrType())
12850 // DllMain is exempt because a return value of zero means it failed.
12851 if (FD->getName() != "DllMain")
12852 FD->setHasImplicitReturnZero(true);
12853
12854 // Explicitly specified calling conventions are applied to MSVC entry points
12855 if (!hasExplicitCallingConv(T)) {
12856 if (isDefaultStdCall(FD, S&: *this)) {
12857 if (FT->getCallConv() != CC_X86StdCall) {
12858 FT = Context.adjustFunctionType(
12859 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12860 FD->setType(QualType(FT, 0));
12861 }
12862 } else if (FT->getCallConv() != CC_C) {
12863 FT = Context.adjustFunctionType(Fn: FT,
12864 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12865 FD->setType(QualType(FT, 0));
12866 }
12867 }
12868
12869 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12870 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12871 FD->setInvalidDecl();
12872 }
12873}
12874
12875bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12876 // FIXME: Need strict checking. In C89, we need to check for
12877 // any assignment, increment, decrement, function-calls, or
12878 // commas outside of a sizeof. In C99, it's the same list,
12879 // except that the aforementioned are allowed in unevaluated
12880 // expressions. Everything else falls under the
12881 // "may accept other forms of constant expressions" exception.
12882 //
12883 // Regular C++ code will not end up here (exceptions: language extensions,
12884 // OpenCL C++ etc), so the constant expression rules there don't matter.
12885 if (Init->isValueDependent()) {
12886 assert(Init->containsErrors() &&
12887 "Dependent code should only occur in error-recovery path.");
12888 return true;
12889 }
12890 const Expr *Culprit;
12891 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
12892 return false;
12893
12894 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12895 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Val: Culprit)) {
12896
12897 // For collection literals iterate the elements to highlight which one is
12898 // the offender.
12899 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Val: Init)) {
12900 for (auto *Elm : ALE->elements()) {
12901 if (!Elm->isConstantInitializer(Ctx&: Context)) {
12902 Diag(Loc: Elm->getExprLoc(),
12903 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12904 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
12905 return true;
12906 }
12907 }
12908 }
12909
12910 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Val: Init)) {
12911 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12912 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
12913
12914 // Check that the key is a string literal and is constant.
12915 if (!isa<ObjCStringLiteral>(Val: Elm.Key) ||
12916 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
12917 Diag(Loc: Elm.Key->getExprLoc(),
12918 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12919 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
12920 return true;
12921 }
12922
12923 if (!Elm.Value->isConstantInitializer(Ctx&: Context)) {
12924 Diag(Loc: Elm.Value->getExprLoc(),
12925 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12926 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
12927 return true;
12928 }
12929 }
12930 }
12931
12932 Diag(Loc: Culprit->getExprLoc(),
12933 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12934 << ObjC().CheckLiteralKind(FromE: Init) << Culprit->getSourceRange();
12935 return true;
12936 }
12937
12938 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12939 return true;
12940}
12941
12942namespace {
12943 // Visits an initialization expression to see if OrigDecl is evaluated in
12944 // its own initialization and throws a warning if it does.
12945 class SelfReferenceChecker
12946 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12947 Sema &S;
12948 Decl *OrigDecl;
12949 bool isRecordType;
12950 bool isPODType;
12951 bool isReferenceType;
12952 bool isInCXXOperatorCall;
12953
12954 bool isInitList;
12955 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12956
12957 public:
12958 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12959
12960 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12961 S(S), OrigDecl(OrigDecl) {
12962 isPODType = false;
12963 isRecordType = false;
12964 isReferenceType = false;
12965 isInCXXOperatorCall = false;
12966 isInitList = false;
12967 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12968 isPODType = VD->getType().isPODType(Context: S.Context);
12969 isRecordType = VD->getType()->isRecordType();
12970 isReferenceType = VD->getType()->isReferenceType();
12971 }
12972 }
12973
12974 // For most expressions, just call the visitor. For initializer lists,
12975 // track the index of the field being initialized since fields are
12976 // initialized in order allowing use of previously initialized fields.
12977 void CheckExpr(Expr *E) {
12978 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12979 if (!InitList) {
12980 Visit(S: E);
12981 return;
12982 }
12983
12984 // Track and increment the index here.
12985 isInitList = true;
12986 InitFieldIndex.push_back(Elt: 0);
12987 for (auto *Child : InitList->children()) {
12988 CheckExpr(E: cast<Expr>(Val: Child));
12989 ++InitFieldIndex.back();
12990 }
12991 InitFieldIndex.pop_back();
12992 }
12993
12994 // Returns true if MemberExpr is checked and no further checking is needed.
12995 // Returns false if additional checking is required.
12996 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12997 llvm::SmallVector<FieldDecl*, 4> Fields;
12998 Expr *Base = E;
12999 bool ReferenceField = false;
13000
13001 // Get the field members used.
13002 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13003 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13004 if (!FD)
13005 return false;
13006 Fields.push_back(Elt: FD);
13007 if (FD->getType()->isReferenceType())
13008 ReferenceField = true;
13009 Base = ME->getBase()->IgnoreParenImpCasts();
13010 }
13011
13012 // Keep checking only if the base Decl is the same.
13013 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13014 if (!DRE || DRE->getDecl() != OrigDecl)
13015 return false;
13016
13017 // A reference field can be bound to an unininitialized field.
13018 if (CheckReference && !ReferenceField)
13019 return true;
13020
13021 // Convert FieldDecls to their index number.
13022 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13023 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13024 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13025
13026 // See if a warning is needed by checking the first difference in index
13027 // numbers. If field being used has index less than the field being
13028 // initialized, then the use is safe.
13029 for (auto UsedIter = UsedFieldIndex.begin(),
13030 UsedEnd = UsedFieldIndex.end(),
13031 OrigIter = InitFieldIndex.begin(),
13032 OrigEnd = InitFieldIndex.end();
13033 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13034 if (*UsedIter < *OrigIter)
13035 return true;
13036 if (*UsedIter > *OrigIter)
13037 break;
13038 }
13039
13040 // TODO: Add a different warning which will print the field names.
13041 HandleDeclRefExpr(DRE);
13042 return true;
13043 }
13044
13045 // For most expressions, the cast is directly above the DeclRefExpr.
13046 // For conditional operators, the cast can be outside the conditional
13047 // operator if both expressions are DeclRefExpr's.
13048 void HandleValue(Expr *E) {
13049 E = E->IgnoreParens();
13050 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13051 HandleDeclRefExpr(DRE);
13052 return;
13053 }
13054
13055 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13056 Visit(S: CO->getCond());
13057 HandleValue(E: CO->getTrueExpr());
13058 HandleValue(E: CO->getFalseExpr());
13059 return;
13060 }
13061
13062 if (BinaryConditionalOperator *BCO =
13063 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13064 Visit(S: BCO->getCond());
13065 HandleValue(E: BCO->getFalseExpr());
13066 return;
13067 }
13068
13069 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13070 if (Expr *SE = OVE->getSourceExpr())
13071 HandleValue(E: SE);
13072 return;
13073 }
13074
13075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13076 if (BO->getOpcode() == BO_Comma) {
13077 Visit(S: BO->getLHS());
13078 HandleValue(E: BO->getRHS());
13079 return;
13080 }
13081 }
13082
13083 if (isa<MemberExpr>(Val: E)) {
13084 if (isInitList) {
13085 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13086 CheckReference: false /*CheckReference*/))
13087 return;
13088 }
13089
13090 Expr *Base = E->IgnoreParenImpCasts();
13091 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13092 // Check for static member variables and don't warn on them.
13093 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13094 return;
13095 Base = ME->getBase()->IgnoreParenImpCasts();
13096 }
13097 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13098 HandleDeclRefExpr(DRE);
13099 return;
13100 }
13101
13102 Visit(S: E);
13103 }
13104
13105 // Reference types not handled in HandleValue are handled here since all
13106 // uses of references are bad, not just r-value uses.
13107 void VisitDeclRefExpr(DeclRefExpr *E) {
13108 if (isReferenceType)
13109 HandleDeclRefExpr(DRE: E);
13110 }
13111
13112 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13113 if (E->getCastKind() == CK_LValueToRValue) {
13114 HandleValue(E: E->getSubExpr());
13115 return;
13116 }
13117
13118 Inherited::VisitImplicitCastExpr(S: E);
13119 }
13120
13121 void VisitMemberExpr(MemberExpr *E) {
13122 if (isInitList) {
13123 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13124 return;
13125 }
13126
13127 // Don't warn on arrays since they can be treated as pointers.
13128 if (E->getType()->canDecayToPointerType()) return;
13129
13130 // Warn when a non-static method call is followed by non-static member
13131 // field accesses, which is followed by a DeclRefExpr.
13132 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13133 bool Warn = (MD && !MD->isStatic());
13134 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13135 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13136 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13137 Warn = false;
13138 Base = ME->getBase()->IgnoreParenImpCasts();
13139 }
13140
13141 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13142 if (Warn)
13143 HandleDeclRefExpr(DRE);
13144 return;
13145 }
13146
13147 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13148 // Visit that expression.
13149 Visit(S: Base);
13150 }
13151
13152 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13153 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13154 Expr *Callee = E->getCallee();
13155
13156 if (isa<UnresolvedLookupExpr>(Val: Callee))
13157 return Inherited::VisitCXXOperatorCallExpr(S: E);
13158
13159 Visit(S: Callee);
13160 for (auto Arg: E->arguments())
13161 HandleValue(E: Arg->IgnoreParenImpCasts());
13162 }
13163
13164 void VisitLambdaExpr(LambdaExpr *E) {
13165 if (!isInCXXOperatorCall) {
13166 Inherited::VisitLambdaExpr(LE: E);
13167 return;
13168 }
13169
13170 for (Expr *Init : E->capture_inits())
13171 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13172 HandleDeclRefExpr(DRE);
13173 else if (Init)
13174 Visit(S: Init);
13175 }
13176
13177 void VisitUnaryOperator(UnaryOperator *E) {
13178 // For POD record types, addresses of its own members are well-defined.
13179 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13180 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13181 if (!isPODType)
13182 HandleValue(E: E->getSubExpr());
13183 return;
13184 }
13185
13186 if (E->isIncrementDecrementOp()) {
13187 HandleValue(E: E->getSubExpr());
13188 return;
13189 }
13190
13191 Inherited::VisitUnaryOperator(S: E);
13192 }
13193
13194 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13195
13196 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13197 if (E->getConstructor()->isCopyConstructor()) {
13198 Expr *ArgExpr = E->getArg(Arg: 0);
13199 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13200 if (ILE->getNumInits() == 1)
13201 ArgExpr = ILE->getInit(Init: 0);
13202 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13203 if (ICE->getCastKind() == CK_NoOp)
13204 ArgExpr = ICE->getSubExpr();
13205 HandleValue(E: ArgExpr);
13206 return;
13207 }
13208 Inherited::VisitCXXConstructExpr(S: E);
13209 }
13210
13211 void VisitCallExpr(CallExpr *E) {
13212 // Treat std::move as a use.
13213 if (E->isCallToStdMove()) {
13214 HandleValue(E: E->getArg(Arg: 0));
13215 return;
13216 }
13217
13218 Inherited::VisitCallExpr(CE: E);
13219 }
13220
13221 void VisitBinaryOperator(BinaryOperator *E) {
13222 if (E->isCompoundAssignmentOp()) {
13223 HandleValue(E: E->getLHS());
13224 Visit(S: E->getRHS());
13225 return;
13226 }
13227
13228 Inherited::VisitBinaryOperator(S: E);
13229 }
13230
13231 // A custom visitor for BinaryConditionalOperator is needed because the
13232 // regular visitor would check the condition and true expression separately
13233 // but both point to the same place giving duplicate diagnostics.
13234 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13235 Visit(S: E->getCond());
13236 Visit(S: E->getFalseExpr());
13237 }
13238
13239 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13240 Decl* ReferenceDecl = DRE->getDecl();
13241 if (OrigDecl != ReferenceDecl) return;
13242 unsigned diag;
13243 if (isReferenceType) {
13244 diag = diag::warn_uninit_self_reference_in_reference_init;
13245 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13246 diag = diag::warn_static_self_reference_in_init;
13247 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13248 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13249 DRE->getDecl()->getType()->isRecordType()) {
13250 diag = diag::warn_uninit_self_reference_in_init;
13251 } else {
13252 // Local variables will be handled by the CFG analysis.
13253 return;
13254 }
13255
13256 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13257 PD: S.PDiag(DiagID: diag)
13258 << DRE->getDecl() << OrigDecl->getLocation()
13259 << DRE->getSourceRange());
13260 }
13261 };
13262
13263 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13264 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13265 bool DirectInit) {
13266 // Parameters arguments are occassionially constructed with itself,
13267 // for instance, in recursive functions. Skip them.
13268 if (isa<ParmVarDecl>(Val: OrigDecl))
13269 return;
13270
13271 // Skip checking for file-scope constexpr variables - constant evaluation
13272 // will produce appropriate errors without needing runtime diagnostics.
13273 // Local constexpr should still emit runtime warnings.
13274 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13275 VD && VD->isConstexpr() && VD->isFileVarDecl())
13276 return;
13277
13278 E = E->IgnoreParens();
13279
13280 // Skip checking T a = a where T is not a record or reference type.
13281 // Doing so is a way to silence uninitialized warnings.
13282 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13283 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13284 if (ICE->getCastKind() == CK_LValueToRValue)
13285 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13286 if (DRE->getDecl() == OrigDecl)
13287 return;
13288
13289 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13290 }
13291} // end anonymous namespace
13292
13293namespace {
13294 // Simple wrapper to add the name of a variable or (if no variable is
13295 // available) a DeclarationName into a diagnostic.
13296 struct VarDeclOrName {
13297 VarDecl *VDecl;
13298 DeclarationName Name;
13299
13300 friend const Sema::SemaDiagnosticBuilder &
13301 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13302 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13303 }
13304 };
13305} // end anonymous namespace
13306
13307QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13308 DeclarationName Name, QualType Type,
13309 TypeSourceInfo *TSI,
13310 SourceRange Range, bool DirectInit,
13311 Expr *Init) {
13312 bool IsInitCapture = !VDecl;
13313 assert((!VDecl || !VDecl->isInitCapture()) &&
13314 "init captures are expected to be deduced prior to initialization");
13315
13316 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13317
13318 DeducedType *Deduced = Type->getContainedDeducedType();
13319 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13320
13321 // Diagnose auto array declarations in C23, unless it's a supported extension.
13322 if (getLangOpts().C23 && Type->isArrayType() &&
13323 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13324 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13325 << (int)Deduced->getContainedAutoType()->getKeyword()
13326 << /*in array decl*/ 23 << Range;
13327 return QualType();
13328 }
13329
13330 // C++11 [dcl.spec.auto]p3
13331 if (!Init) {
13332 assert(VDecl && "no init for init capture deduction?");
13333
13334 // Except for class argument deduction, and then for an initializing
13335 // declaration only, i.e. no static at class scope or extern.
13336 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13337 VDecl->hasExternalStorage() ||
13338 VDecl->isStaticDataMember()) {
13339 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13340 << VDecl->getDeclName() << Type;
13341 return QualType();
13342 }
13343 }
13344
13345 ArrayRef<Expr*> DeduceInits;
13346 if (Init)
13347 DeduceInits = Init;
13348
13349 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13350 if (DirectInit && PL)
13351 DeduceInits = PL->exprs();
13352
13353 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13354 assert(VDecl && "non-auto type for init capture deduction?");
13355 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13356 InitializationKind Kind = InitializationKind::CreateForInit(
13357 Loc: VDecl->getLocation(), DirectInit, Init);
13358 // FIXME: Initialization should not be taking a mutable list of inits.
13359 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13360 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13361 Init: InitsCopy);
13362 }
13363
13364 if (DirectInit) {
13365 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13366 DeduceInits = IL->inits();
13367 }
13368
13369 // Deduction only works if we have exactly one source expression.
13370 if (DeduceInits.empty()) {
13371 // It isn't possible to write this directly, but it is possible to
13372 // end up in this situation with "auto x(some_pack...);"
13373 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13374 ? diag::err_init_capture_no_expression
13375 : diag::err_auto_var_init_no_expression)
13376 << VN << Type << Range;
13377 return QualType();
13378 }
13379
13380 if (DeduceInits.size() > 1) {
13381 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13382 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13383 : diag::err_auto_var_init_multiple_expressions)
13384 << VN << Type << Range;
13385 return QualType();
13386 }
13387
13388 Expr *DeduceInit = DeduceInits[0];
13389 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13390 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13391 ? diag::err_init_capture_paren_braces
13392 : diag::err_auto_var_init_paren_braces)
13393 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13394 return QualType();
13395 }
13396
13397 // Expressions default to 'id' when we're in a debugger.
13398 bool DefaultedAnyToId = false;
13399 if (getLangOpts().DebuggerCastResultToId &&
13400 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13401 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13402 if (Result.isInvalid()) {
13403 return QualType();
13404 }
13405 Init = Result.get();
13406 DefaultedAnyToId = true;
13407 }
13408
13409 // C++ [dcl.decomp]p1:
13410 // If the assignment-expression [...] has array type A and no ref-qualifier
13411 // is present, e has type cv A
13412 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13413 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13414 DeduceInit->getType()->isConstantArrayType())
13415 return Context.getQualifiedType(T: DeduceInit->getType(),
13416 Qs: Type.getQualifiers());
13417
13418 QualType DeducedType;
13419 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13420 TemplateDeductionResult Result =
13421 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13422 if (Result != TemplateDeductionResult::Success &&
13423 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13424 if (!IsInitCapture)
13425 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13426 else if (isa<InitListExpr>(Val: Init))
13427 Diag(Loc: Range.getBegin(),
13428 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13429 << VN
13430 << (DeduceInit->getType().isNull() ? TSI->getType()
13431 : DeduceInit->getType())
13432 << DeduceInit->getSourceRange();
13433 else
13434 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13435 << VN << TSI->getType()
13436 << (DeduceInit->getType().isNull() ? TSI->getType()
13437 : DeduceInit->getType())
13438 << DeduceInit->getSourceRange();
13439 }
13440
13441 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13442 // 'id' instead of a specific object type prevents most of our usual
13443 // checks.
13444 // We only want to warn outside of template instantiations, though:
13445 // inside a template, the 'id' could have come from a parameter.
13446 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13447 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13448 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13449 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13450 }
13451
13452 return DeducedType;
13453}
13454
13455bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13456 Expr *Init) {
13457 assert(!Init || !Init->containsErrors());
13458 QualType DeducedType = deduceVarTypeFromInitializer(
13459 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13460 Range: VDecl->getSourceRange(), DirectInit, Init);
13461 if (DeducedType.isNull()) {
13462 VDecl->setInvalidDecl();
13463 return true;
13464 }
13465
13466 VDecl->setType(DeducedType);
13467 assert(VDecl->isLinkageValid());
13468
13469 // In ARC, infer lifetime.
13470 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13471 VDecl->setInvalidDecl();
13472
13473 if (getLangOpts().OpenCL)
13474 deduceOpenCLAddressSpace(Var: VDecl);
13475
13476 if (getLangOpts().HLSL)
13477 HLSL().deduceAddressSpace(Decl: VDecl);
13478
13479 // If this is a redeclaration, check that the type we just deduced matches
13480 // the previously declared type.
13481 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13482 // We never need to merge the type, because we cannot form an incomplete
13483 // array of auto, nor deduce such a type.
13484 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13485 }
13486
13487 // Check the deduced type is valid for a variable declaration.
13488 CheckVariableDeclarationType(NewVD: VDecl);
13489 return VDecl->isInvalidDecl();
13490}
13491
13492void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13493 SourceLocation Loc) {
13494 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13495 Init = EWC->getSubExpr();
13496
13497 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13498 Init = CE->getSubExpr();
13499
13500 QualType InitType = Init->getType();
13501 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13502 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13503 "shouldn't be called if type doesn't have a non-trivial C struct");
13504 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13505 for (auto *I : ILE->inits()) {
13506 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13507 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13508 continue;
13509 SourceLocation SL = I->getExprLoc();
13510 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13511 }
13512 return;
13513 }
13514
13515 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13516 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13517 checkNonTrivialCUnion(QT: InitType, Loc,
13518 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13519 NonTrivialKind: NTCUK_Init);
13520 } else {
13521 // Assume all other explicit initializers involving copying some existing
13522 // object.
13523 // TODO: ignore any explicit initializers where we can guarantee
13524 // copy-elision.
13525 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13526 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13527 NonTrivialKind: NTCUK_Copy);
13528 }
13529}
13530
13531namespace {
13532
13533bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13534 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13535 // in the source code or implicitly by the compiler if it is in a union
13536 // defined in a system header and has non-trivial ObjC ownership
13537 // qualifications. We don't want those fields to participate in determining
13538 // whether the containing union is non-trivial.
13539 return FD->hasAttr<UnavailableAttr>();
13540}
13541
13542struct DiagNonTrivalCUnionDefaultInitializeVisitor
13543 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13544 void> {
13545 using Super =
13546 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13547 void>;
13548
13549 DiagNonTrivalCUnionDefaultInitializeVisitor(
13550 QualType OrigTy, SourceLocation OrigLoc,
13551 NonTrivialCUnionContext UseContext, Sema &S)
13552 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13553
13554 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13555 const FieldDecl *FD, bool InNonTrivialUnion) {
13556 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13557 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13558 Args&: InNonTrivialUnion);
13559 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13560 }
13561
13562 void visitARCStrong(QualType QT, const FieldDecl *FD,
13563 bool InNonTrivialUnion) {
13564 if (InNonTrivialUnion)
13565 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13566 << 1 << 0 << QT << FD->getName();
13567 }
13568
13569 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13570 if (InNonTrivialUnion)
13571 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13572 << 1 << 0 << QT << FD->getName();
13573 }
13574
13575 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13576 const auto *RD = QT->castAsRecordDecl();
13577 if (RD->isUnion()) {
13578 if (OrigLoc.isValid()) {
13579 bool IsUnion = false;
13580 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13581 IsUnion = OrigRD->isUnion();
13582 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13583 << 0 << OrigTy << IsUnion << UseContext;
13584 // Reset OrigLoc so that this diagnostic is emitted only once.
13585 OrigLoc = SourceLocation();
13586 }
13587 InNonTrivialUnion = true;
13588 }
13589
13590 if (InNonTrivialUnion)
13591 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13592 << 0 << 0 << QT.getUnqualifiedType() << "";
13593
13594 for (const FieldDecl *FD : RD->fields())
13595 if (!shouldIgnoreForRecordTriviality(FD))
13596 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13597 }
13598
13599 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13600
13601 // The non-trivial C union type or the struct/union type that contains a
13602 // non-trivial C union.
13603 QualType OrigTy;
13604 SourceLocation OrigLoc;
13605 NonTrivialCUnionContext UseContext;
13606 Sema &S;
13607};
13608
13609struct DiagNonTrivalCUnionDestructedTypeVisitor
13610 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13611 using Super =
13612 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13613
13614 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13615 SourceLocation OrigLoc,
13616 NonTrivialCUnionContext UseContext,
13617 Sema &S)
13618 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13619
13620 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13621 const FieldDecl *FD, bool InNonTrivialUnion) {
13622 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13623 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13624 Args&: InNonTrivialUnion);
13625 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13626 }
13627
13628 void visitARCStrong(QualType QT, const FieldDecl *FD,
13629 bool InNonTrivialUnion) {
13630 if (InNonTrivialUnion)
13631 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13632 << 1 << 1 << QT << FD->getName();
13633 }
13634
13635 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13636 if (InNonTrivialUnion)
13637 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13638 << 1 << 1 << QT << FD->getName();
13639 }
13640
13641 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13642 const auto *RD = QT->castAsRecordDecl();
13643 if (RD->isUnion()) {
13644 if (OrigLoc.isValid()) {
13645 bool IsUnion = false;
13646 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13647 IsUnion = OrigRD->isUnion();
13648 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13649 << 1 << OrigTy << IsUnion << UseContext;
13650 // Reset OrigLoc so that this diagnostic is emitted only once.
13651 OrigLoc = SourceLocation();
13652 }
13653 InNonTrivialUnion = true;
13654 }
13655
13656 if (InNonTrivialUnion)
13657 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13658 << 0 << 1 << QT.getUnqualifiedType() << "";
13659
13660 for (const FieldDecl *FD : RD->fields())
13661 if (!shouldIgnoreForRecordTriviality(FD))
13662 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13663 }
13664
13665 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13666 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13667 bool InNonTrivialUnion) {}
13668
13669 // The non-trivial C union type or the struct/union type that contains a
13670 // non-trivial C union.
13671 QualType OrigTy;
13672 SourceLocation OrigLoc;
13673 NonTrivialCUnionContext UseContext;
13674 Sema &S;
13675};
13676
13677struct DiagNonTrivalCUnionCopyVisitor
13678 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13679 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13680
13681 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13682 NonTrivialCUnionContext UseContext, Sema &S)
13683 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13684
13685 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13686 const FieldDecl *FD, bool InNonTrivialUnion) {
13687 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13688 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13689 Args&: InNonTrivialUnion);
13690 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13691 }
13692
13693 void visitARCStrong(QualType QT, const FieldDecl *FD,
13694 bool InNonTrivialUnion) {
13695 if (InNonTrivialUnion)
13696 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13697 << 1 << 2 << QT << FD->getName();
13698 }
13699
13700 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13701 if (InNonTrivialUnion)
13702 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13703 << 1 << 2 << QT << FD->getName();
13704 }
13705
13706 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13707 const auto *RD = QT->castAsRecordDecl();
13708 if (RD->isUnion()) {
13709 if (OrigLoc.isValid()) {
13710 bool IsUnion = false;
13711 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13712 IsUnion = OrigRD->isUnion();
13713 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13714 << 2 << OrigTy << IsUnion << UseContext;
13715 // Reset OrigLoc so that this diagnostic is emitted only once.
13716 OrigLoc = SourceLocation();
13717 }
13718 InNonTrivialUnion = true;
13719 }
13720
13721 if (InNonTrivialUnion)
13722 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13723 << 0 << 2 << QT.getUnqualifiedType() << "";
13724
13725 for (const FieldDecl *FD : RD->fields())
13726 if (!shouldIgnoreForRecordTriviality(FD))
13727 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13728 }
13729
13730 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13731 if (InNonTrivialUnion)
13732 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13733 << 1 << 2 << QT << FD->getName();
13734 }
13735
13736 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13737 const FieldDecl *FD, bool InNonTrivialUnion) {}
13738 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13739 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13740 bool InNonTrivialUnion) {}
13741
13742 // The non-trivial C union type or the struct/union type that contains a
13743 // non-trivial C union.
13744 QualType OrigTy;
13745 SourceLocation OrigLoc;
13746 NonTrivialCUnionContext UseContext;
13747 Sema &S;
13748};
13749
13750} // namespace
13751
13752void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13753 NonTrivialCUnionContext UseContext,
13754 unsigned NonTrivialKind) {
13755 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13756 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13757 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13758 "shouldn't be called if type doesn't have a non-trivial C union");
13759
13760 if ((NonTrivialKind & NTCUK_Init) &&
13761 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13762 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13763 .visit(FT: QT, Args: nullptr, Args: false);
13764 if ((NonTrivialKind & NTCUK_Destruct) &&
13765 QT.hasNonTrivialToPrimitiveDestructCUnion())
13766 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13767 .visit(FT: QT, Args: nullptr, Args: false);
13768 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13769 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13770 .visit(FT: QT, Args: nullptr, Args: false);
13771}
13772
13773bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13774 const VarDecl *Dcl) {
13775 if (!getLangOpts().CPlusPlus)
13776 return false;
13777
13778 // We only need to warn if the definition is in a header file, so wait to
13779 // diagnose until we've seen the definition.
13780 if (!Dcl->isThisDeclarationADefinition())
13781 return false;
13782
13783 // If an object is defined in a source file, its definition can't get
13784 // duplicated since it will never appear in more than one TU.
13785 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13786 return false;
13787
13788 // If the variable we're looking at is a static local, then we actually care
13789 // about the properties of the function containing it.
13790 const ValueDecl *Target = Dcl;
13791 // VarDecls and FunctionDecls have different functions for checking
13792 // inline-ness, and whether they were originally templated, so we have to
13793 // call the appropriate functions manually.
13794 bool TargetIsInline = Dcl->isInline();
13795 bool TargetWasTemplated =
13796 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13797
13798 // Update the Target and TargetIsInline property if necessary
13799 if (Dcl->isStaticLocal()) {
13800 const DeclContext *Ctx = Dcl->getDeclContext();
13801 if (!Ctx)
13802 return false;
13803
13804 const FunctionDecl *FunDcl =
13805 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13806 if (!FunDcl)
13807 return false;
13808
13809 Target = FunDcl;
13810 // IsInlined() checks for the C++ inline property
13811 TargetIsInline = FunDcl->isInlined();
13812 TargetWasTemplated =
13813 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13814 }
13815
13816 // Non-inline functions/variables can only legally appear in one TU
13817 // unless they were part of a template. Unfortunately, making complex
13818 // template instantiations visible is infeasible in practice, since
13819 // everything the template depends on also has to be visible. To avoid
13820 // giving impractical-to-fix warnings, don't warn if we're inside
13821 // something that was templated, even on inline stuff.
13822 if (!TargetIsInline || TargetWasTemplated)
13823 return false;
13824
13825 // If the object isn't hidden, the dynamic linker will prevent duplication.
13826 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13827
13828 // The target is "hidden" (from the dynamic linker) if:
13829 // 1. On posix, it has hidden visibility, or
13830 // 2. On windows, it has no import/export annotation, and neither does the
13831 // class which directly contains it.
13832 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13833 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13834 return false;
13835
13836 // If the variable isn't directly annotated, check to see if it's a member
13837 // of an annotated class.
13838 const CXXRecordDecl *Ctx =
13839 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13840 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13841 return false;
13842
13843 } else if (Lnk.getVisibility() != HiddenVisibility) {
13844 // Posix case
13845 return false;
13846 }
13847
13848 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13849 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13850 return false;
13851
13852 return true;
13853}
13854
13855// Determine whether the object seems mutable for the purpose of diagnosing
13856// possible unique object duplication, i.e. non-const-qualified, and
13857// not an always-constant type like a function.
13858// Not perfect: doesn't account for mutable members, for example, or
13859// elements of container types.
13860// For nested pointers, any individual level being non-const is sufficient.
13861static bool looksMutable(QualType T, const ASTContext &Ctx) {
13862 T = T.getNonReferenceType();
13863 if (T->isFunctionType())
13864 return false;
13865 if (!T.isConstant(Ctx))
13866 return true;
13867 if (T->isPointerType())
13868 return looksMutable(T: T->getPointeeType(), Ctx);
13869 return false;
13870}
13871
13872void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13873 // If this object has external linkage and hidden visibility, it might be
13874 // duplicated when built into a shared library, which causes problems if it's
13875 // mutable (since the copies won't be in sync) or its initialization has side
13876 // effects (since it will run once per copy instead of once globally).
13877
13878 // Don't diagnose if we're inside a template, because it's not practical to
13879 // fix the warning in most cases.
13880 if (!VD->isTemplated() &&
13881 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13882
13883 QualType Type = VD->getType();
13884 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13885 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13886 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13887 }
13888
13889 // To keep false positives low, only warn if we're certain that the
13890 // initializer has side effects. Don't warn on operator new, since a mutable
13891 // pointer will trigger the previous warning, and an immutable pointer
13892 // getting duplicated just results in a little extra memory usage.
13893 const Expr *Init = VD->getAnyInitializer();
13894 if (Init &&
13895 Init->HasSideEffects(Ctx: VD->getASTContext(),
13896 /*IncludePossibleEffects=*/false) &&
13897 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13898 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13899 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13900 }
13901 }
13902}
13903
13904void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13905 llvm::scope_exit ResetDeclForInitializer([this]() {
13906 if (!this->ExprEvalContexts.empty())
13907 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13908 });
13909
13910 // If there is no declaration, there was an error parsing it. Just ignore
13911 // the initializer.
13912 if (!RealDecl) {
13913 return;
13914 }
13915
13916 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13917 if (!Method->isInvalidDecl()) {
13918 // Pure-specifiers are handled in ActOnPureSpecifier.
13919 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13920 << Method->getDeclName() << Init->getSourceRange();
13921 Method->setInvalidDecl();
13922 }
13923 return;
13924 }
13925
13926 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13927 if (!VDecl) {
13928 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13929 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13930 RealDecl->setInvalidDecl();
13931 return;
13932 }
13933
13934 if (VDecl->isInvalidDecl()) {
13935 ExprResult Recovery =
13936 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13937 if (Expr *E = Recovery.get())
13938 VDecl->setInit(E);
13939 return;
13940 }
13941
13942 // __amdgpu_feature_predicate_t cannot be initialised
13943 if (VDecl->getType().getDesugaredType(Context) ==
13944 Context.AMDGPUFeaturePredicateTy) {
13945 Diag(Loc: VDecl->getLocation(),
13946 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
13947 << VDecl;
13948 VDecl->setInvalidDecl();
13949 return;
13950 }
13951
13952 // WebAssembly tables can't be used to initialise a variable.
13953 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13954 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13955 VDecl->setInvalidDecl();
13956 return;
13957 }
13958
13959 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13960 if (VDecl->getType()->isUndeducedType()) {
13961 if (Init->containsErrors()) {
13962 // Invalidate the decl as we don't know the type for recovery-expr yet.
13963 RealDecl->setInvalidDecl();
13964 VDecl->setInit(Init);
13965 return;
13966 }
13967
13968 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
13969 assert(VDecl->isInvalidDecl() &&
13970 "decl should be invalidated when deduce fails");
13971 if (auto *RecoveryExpr =
13972 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
13973 .get())
13974 VDecl->setInit(RecoveryExpr);
13975 return;
13976 }
13977 }
13978
13979 this->CheckAttributesOnDeducedType(D: RealDecl);
13980
13981 // we don't initialize groupshared variables so warn and return
13982 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
13983 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
13984 return;
13985 }
13986
13987 // dllimport cannot be used on variable definitions.
13988 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13989 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13990 VDecl->setInvalidDecl();
13991 return;
13992 }
13993
13994 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13995 // the identifier has external or internal linkage, the declaration shall
13996 // have no initializer for the identifier.
13997 // C++14 [dcl.init]p5 is the same restriction for C++.
13998 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13999 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14000 VDecl->setInvalidDecl();
14001 return;
14002 }
14003
14004 if (!VDecl->getType()->isDependentType()) {
14005 // A definition must end up with a complete type, which means it must be
14006 // complete with the restriction that an array type might be completed by
14007 // the initializer; note that later code assumes this restriction.
14008 QualType BaseDeclType = VDecl->getType();
14009 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14010 BaseDeclType = Array->getElementType();
14011 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14012 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14013 RealDecl->setInvalidDecl();
14014 return;
14015 }
14016
14017 // The variable can not have an abstract class type.
14018 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14019 DiagID: diag::err_abstract_type_in_decl,
14020 Args: AbstractVariableType))
14021 VDecl->setInvalidDecl();
14022 }
14023
14024 // C++ [module.import/6]
14025 // ...
14026 // A header unit shall not contain a definition of a non-inline function or
14027 // variable whose name has external linkage.
14028 //
14029 // We choose to allow weak & selectany definitions, as they are common in
14030 // headers, and have semantics similar to inline definitions which are allowed
14031 // in header units.
14032 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14033 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14034 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14035 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14036 !VDecl->getInstantiatedFromStaticDataMember() &&
14037 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14038 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14039 VDecl->setInvalidDecl();
14040 }
14041
14042 // If adding the initializer will turn this declaration into a definition,
14043 // and we already have a definition for this variable, diagnose or otherwise
14044 // handle the situation.
14045 if (VarDecl *Def = VDecl->getDefinition())
14046 if (Def != VDecl &&
14047 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14048 !VDecl->isThisDeclarationADemotedDefinition() &&
14049 checkVarDeclRedefinition(Old: Def, New: VDecl))
14050 return;
14051
14052 if (getLangOpts().CPlusPlus) {
14053 // C++ [class.static.data]p4
14054 // If a static data member is of const integral or const
14055 // enumeration type, its declaration in the class definition can
14056 // specify a constant-initializer which shall be an integral
14057 // constant expression (5.19). In that case, the member can appear
14058 // in integral constant expressions. The member shall still be
14059 // defined in a namespace scope if it is used in the program and the
14060 // namespace scope definition shall not contain an initializer.
14061 //
14062 // We already performed a redefinition check above, but for static
14063 // data members we also need to check whether there was an in-class
14064 // declaration with an initializer.
14065 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14066 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14067 << VDecl->getDeclName();
14068 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14069 DiagID: diag::note_previous_initializer)
14070 << 0;
14071 return;
14072 }
14073
14074 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14075 VDecl->setInvalidDecl();
14076 return;
14077 }
14078 }
14079
14080 // If the variable has an initializer and local storage, check whether
14081 // anything jumps over the initialization.
14082 if (VDecl->hasLocalStorage())
14083 setFunctionHasBranchProtectedScope();
14084
14085 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14086 // a kernel function cannot be initialized."
14087 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14088 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14089 VDecl->setInvalidDecl();
14090 return;
14091 }
14092
14093 // The LoaderUninitialized attribute acts as a definition (of undef).
14094 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14095 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14096 VDecl->setInvalidDecl();
14097 return;
14098 }
14099
14100 if (getLangOpts().HLSL)
14101 if (!HLSL().handleInitialization(VDecl, Init))
14102 return;
14103
14104 // Get the decls type and save a reference for later, since
14105 // CheckInitializerTypes may change it.
14106 QualType DclT = VDecl->getType(), SavT = DclT;
14107
14108 // Expressions default to 'id' when we're in a debugger
14109 // and we are assigning it to a variable of Objective-C pointer type.
14110 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14111 Init->getType() == Context.UnknownAnyTy) {
14112 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14113 if (!Result.isUsable()) {
14114 VDecl->setInvalidDecl();
14115 return;
14116 }
14117 Init = Result.get();
14118 }
14119
14120 // Perform the initialization.
14121 bool InitializedFromParenListExpr = false;
14122 bool IsParenListInit = false;
14123 if (!VDecl->isInvalidDecl()) {
14124 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14125 InitializationKind Kind = InitializationKind::CreateForInit(
14126 Loc: VDecl->getLocation(), DirectInit, Init);
14127
14128 MultiExprArg Args = Init;
14129 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14130 Args =
14131 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14132 InitializedFromParenListExpr = true;
14133 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14134 Args = CXXDirectInit->getInitExprs();
14135 InitializedFromParenListExpr = true;
14136 }
14137
14138 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14139 /*TopLevelOfInitList=*/false,
14140 /*TreatUnavailableAsInvalid=*/false);
14141 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14142 if (!Result.isUsable()) {
14143 // If the provided initializer fails to initialize the var decl,
14144 // we attach a recovery expr for better recovery.
14145 auto RecoveryExpr =
14146 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14147 if (RecoveryExpr.get())
14148 VDecl->setInit(RecoveryExpr.get());
14149 // In general, for error recovery purposes, the initializer doesn't play
14150 // part in the valid bit of the declaration. There are a few exceptions:
14151 // 1) if the var decl has a deduced auto type, and the type cannot be
14152 // deduced by an invalid initializer;
14153 // 2) if the var decl is a decomposition decl with a non-deduced type,
14154 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14155 // Case 1) was already handled elsewhere.
14156 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14157 VDecl->setInvalidDecl();
14158 return;
14159 }
14160
14161 Init = Result.getAs<Expr>();
14162 IsParenListInit = !InitSeq.steps().empty() &&
14163 InitSeq.step_begin()->Kind ==
14164 InitializationSequence::SK_ParenthesizedListInit;
14165 QualType VDeclType = VDecl->getType();
14166 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14167 !VDeclType->isDependentType() &&
14168 Context.getAsIncompleteArrayType(T: VDeclType) &&
14169 Context.getAsIncompleteArrayType(T: Init->getType())) {
14170 // Bail out if it is not possible to deduce array size from the
14171 // initializer.
14172 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14173 << VDeclType;
14174 VDecl->setInvalidDecl();
14175 return;
14176 }
14177 }
14178
14179 // Check for self-references within variable initializers.
14180 // Variables declared within a function/method body (except for references)
14181 // are handled by a dataflow analysis.
14182 // This is undefined behavior in C++, but valid in C.
14183 if (getLangOpts().CPlusPlus)
14184 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14185 VDecl->getType()->isReferenceType())
14186 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14187
14188 // If the type changed, it means we had an incomplete type that was
14189 // completed by the initializer. For example:
14190 // int ary[] = { 1, 3, 5 };
14191 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14192 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14193 VDecl->setType(DclT);
14194
14195 if (!VDecl->isInvalidDecl()) {
14196 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14197
14198 if (VDecl->hasAttr<BlocksAttr>())
14199 ObjC().checkRetainCycles(Var: VDecl, Init);
14200
14201 // It is safe to assign a weak reference into a strong variable.
14202 // Although this code can still have problems:
14203 // id x = self.weakProp;
14204 // id y = self.weakProp;
14205 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14206 // paths through the function. This should be revisited if
14207 // -Wrepeated-use-of-weak is made flow-sensitive.
14208 if (FunctionScopeInfo *FSI = getCurFunction())
14209 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14210 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14211 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14212 Loc: Init->getBeginLoc()))
14213 FSI->markSafeWeakUse(E: Init);
14214 }
14215
14216 // The initialization is usually a full-expression.
14217 //
14218 // FIXME: If this is a braced initialization of an aggregate, it is not
14219 // an expression, and each individual field initializer is a separate
14220 // full-expression. For instance, in:
14221 //
14222 // struct Temp { ~Temp(); };
14223 // struct S { S(Temp); };
14224 // struct T { S a, b; } t = { Temp(), Temp() }
14225 //
14226 // we should destroy the first Temp before constructing the second.
14227
14228 // Set context flag for OverflowBehaviorType initialization analysis
14229 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14230 true);
14231 ExprResult Result =
14232 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14233 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14234 if (!Result.isUsable()) {
14235 VDecl->setInvalidDecl();
14236 return;
14237 }
14238 Init = Result.get();
14239
14240 // Attach the initializer to the decl.
14241 VDecl->setInit(Init);
14242
14243 if (VDecl->isLocalVarDecl()) {
14244 // Don't check the initializer if the declaration is malformed.
14245 if (VDecl->isInvalidDecl()) {
14246 // do nothing
14247
14248 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14249 // This is true even in C++ for OpenCL.
14250 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14251 CheckForConstantInitializer(Init);
14252
14253 // Otherwise, C++ does not restrict the initializer.
14254 } else if (getLangOpts().CPlusPlus) {
14255 // do nothing
14256
14257 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14258 // static storage duration shall be constant expressions or string literals.
14259 } else if (VDecl->getStorageClass() == SC_Static) {
14260 // Avoid evaluating the initializer twice for constexpr variables. It will
14261 // be evaluated later.
14262 if (!VDecl->isConstexpr())
14263 CheckForConstantInitializer(Init);
14264
14265 // C89 is stricter than C99 for aggregate initializers.
14266 // C89 6.5.7p3: All the expressions [...] in an initializer list
14267 // for an object that has aggregate or union type shall be
14268 // constant expressions.
14269 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14270 isa<InitListExpr>(Val: Init)) {
14271 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14272 }
14273
14274 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14275 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14276 if (VDecl->hasLocalStorage())
14277 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14278 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14279 VDecl->getLexicalDeclContext()->isRecord()) {
14280 // This is an in-class initialization for a static data member, e.g.,
14281 //
14282 // struct S {
14283 // static const int value = 17;
14284 // };
14285
14286 // C++ [class.mem]p4:
14287 // A member-declarator can contain a constant-initializer only
14288 // if it declares a static member (9.4) of const integral or
14289 // const enumeration type, see 9.4.2.
14290 //
14291 // C++11 [class.static.data]p3:
14292 // If a non-volatile non-inline const static data member is of integral
14293 // or enumeration type, its declaration in the class definition can
14294 // specify a brace-or-equal-initializer in which every initializer-clause
14295 // that is an assignment-expression is a constant expression. A static
14296 // data member of literal type can be declared in the class definition
14297 // with the constexpr specifier; if so, its declaration shall specify a
14298 // brace-or-equal-initializer in which every initializer-clause that is
14299 // an assignment-expression is a constant expression.
14300
14301 // Do nothing on dependent types.
14302 if (DclT->isDependentType()) {
14303
14304 // Allow any 'static constexpr' members, whether or not they are of literal
14305 // type. We separately check that every constexpr variable is of literal
14306 // type.
14307 } else if (VDecl->isConstexpr()) {
14308
14309 // Require constness.
14310 } else if (!DclT.isConstQualified()) {
14311 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14312 << Init->getSourceRange();
14313 VDecl->setInvalidDecl();
14314
14315 // We allow integer constant expressions in all cases.
14316 } else if (DclT->isIntegralOrEnumerationType()) {
14317 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14318 // In C++11, a non-constexpr const static data member with an
14319 // in-class initializer cannot be volatile.
14320 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14321
14322 // We allow foldable floating-point constants as an extension.
14323 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14324 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14325 // it anyway and provide a fixit to add the 'constexpr'.
14326 if (getLangOpts().CPlusPlus11) {
14327 Diag(Loc: VDecl->getLocation(),
14328 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14329 << DclT << Init->getSourceRange();
14330 Diag(Loc: VDecl->getBeginLoc(),
14331 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14332 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14333 } else {
14334 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14335 << DclT << Init->getSourceRange();
14336
14337 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14338 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14339 << Init->getSourceRange();
14340 VDecl->setInvalidDecl();
14341 }
14342 }
14343
14344 // Suggest adding 'constexpr' in C++11 for literal types.
14345 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14346 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14347 << DclT << Init->getSourceRange()
14348 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14349 VDecl->setConstexpr(true);
14350
14351 } else {
14352 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14353 << DclT << Init->getSourceRange();
14354 VDecl->setInvalidDecl();
14355 }
14356 } else if (VDecl->isFileVarDecl()) {
14357 // In C, extern is typically used to avoid tentative definitions when
14358 // declaring variables in headers, but adding an initializer makes it a
14359 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14360 // In C++, extern is often used to give implicitly static const variables
14361 // external linkage, so don't warn in that case. If selectany is present,
14362 // this might be header code intended for C and C++ inclusion, so apply the
14363 // C++ rules.
14364 if (VDecl->getStorageClass() == SC_Extern &&
14365 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14366 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14367 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14368 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14369 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14370
14371 // In Microsoft C++ mode, a const variable defined in namespace scope has
14372 // external linkage by default if the variable is declared with
14373 // __declspec(dllexport).
14374 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14375 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14376 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14377 VDecl->setStorageClass(SC_Extern);
14378
14379 // C99 6.7.8p4. All file scoped initializers need to be constant.
14380 // Avoid duplicate diagnostics for constexpr variables.
14381 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14382 !VDecl->isConstexpr())
14383 CheckForConstantInitializer(Init);
14384 }
14385
14386 QualType InitType = Init->getType();
14387 if (!InitType.isNull() &&
14388 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14389 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14390 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14391
14392 // We will represent direct-initialization similarly to copy-initialization:
14393 // int x(1); -as-> int x = 1;
14394 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14395 //
14396 // Clients that want to distinguish between the two forms, can check for
14397 // direct initializer using VarDecl::getInitStyle().
14398 // A major benefit is that clients that don't particularly care about which
14399 // exactly form was it (like the CodeGen) can handle both cases without
14400 // special case code.
14401
14402 // C++ 8.5p11:
14403 // The form of initialization (using parentheses or '=') matters
14404 // when the entity being initialized has class type.
14405 if (InitializedFromParenListExpr) {
14406 assert(DirectInit && "Call-style initializer must be direct init.");
14407 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14408 : VarDecl::CallInit);
14409 } else if (DirectInit) {
14410 // This must be list-initialization. No other way is direct-initialization.
14411 VDecl->setInitStyle(VarDecl::ListInit);
14412 }
14413
14414 if (LangOpts.OpenMP &&
14415 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14416 VDecl->isFileVarDecl())
14417 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14418 CheckCompleteVariableDeclaration(VD: VDecl);
14419
14420 if (LangOpts.OpenACC && !InitType.isNull())
14421 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14422}
14423
14424void Sema::ActOnInitializerError(Decl *D) {
14425 // Our main concern here is re-establishing invariants like "a
14426 // variable's type is either dependent or complete".
14427 if (!D || D->isInvalidDecl()) return;
14428
14429 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14430 if (!VD) return;
14431
14432 // Bindings are not usable if we can't make sense of the initializer.
14433 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14434 for (auto *BD : DD->bindings())
14435 BD->setInvalidDecl();
14436
14437 // Auto types are meaningless if we can't make sense of the initializer.
14438 if (VD->getType()->isUndeducedType()) {
14439 D->setInvalidDecl();
14440 return;
14441 }
14442
14443 QualType Ty = VD->getType();
14444 if (Ty->isDependentType()) return;
14445
14446 // Require a complete type.
14447 if (RequireCompleteType(Loc: VD->getLocation(),
14448 T: Context.getBaseElementType(QT: Ty),
14449 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14450 VD->setInvalidDecl();
14451 return;
14452 }
14453
14454 // Require a non-abstract type.
14455 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14456 DiagID: diag::err_abstract_type_in_decl,
14457 Args: AbstractVariableType)) {
14458 VD->setInvalidDecl();
14459 return;
14460 }
14461
14462 // Don't bother complaining about constructors or destructors,
14463 // though.
14464}
14465
14466void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14467 // If there is no declaration, there was an error parsing it. Just ignore it.
14468 if (!RealDecl)
14469 return;
14470
14471 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14472 QualType Type = Var->getType();
14473
14474 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14475 Diag(Loc: Var->getLocation(),
14476 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14477 << Var;
14478 Var->setInvalidDecl();
14479 return;
14480 }
14481 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14482 if (isa<DecompositionDecl>(Val: RealDecl)) {
14483 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14484 Var->setInvalidDecl();
14485 return;
14486 }
14487
14488 if (Type->isUndeducedType() &&
14489 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14490 return;
14491
14492 this->CheckAttributesOnDeducedType(D: RealDecl);
14493
14494 // C++11 [class.static.data]p3: A static data member can be declared with
14495 // the constexpr specifier; if so, its declaration shall specify
14496 // a brace-or-equal-initializer.
14497 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14498 // the definition of a variable [...] or the declaration of a static data
14499 // member.
14500 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14501 !Var->isThisDeclarationADemotedDefinition()) {
14502 if (Var->isStaticDataMember()) {
14503 // C++1z removes the relevant rule; the in-class declaration is always
14504 // a definition there.
14505 if (!getLangOpts().CPlusPlus17 &&
14506 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14507 Diag(Loc: Var->getLocation(),
14508 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14509 << Var;
14510 Var->setInvalidDecl();
14511 return;
14512 }
14513 } else {
14514 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14515 Var->setInvalidDecl();
14516 return;
14517 }
14518 }
14519
14520 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14521 // be initialized.
14522 if (!Var->isInvalidDecl() &&
14523 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14524 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14525 bool HasConstExprDefaultConstructor = false;
14526 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14527 for (auto *Ctor : RD->ctors()) {
14528 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14529 Ctor->getMethodQualifiers().getAddressSpace() ==
14530 LangAS::opencl_constant) {
14531 HasConstExprDefaultConstructor = true;
14532 }
14533 }
14534 }
14535 if (!HasConstExprDefaultConstructor) {
14536 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14537 Var->setInvalidDecl();
14538 return;
14539 }
14540 }
14541
14542 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14543 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14544 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14545 Var->setInvalidDecl();
14546 return;
14547 }
14548
14549 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14550 if (Var->getStorageClass() == SC_Extern) {
14551 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14552 << Var;
14553 Var->setInvalidDecl();
14554 return;
14555 }
14556 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14557 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14558 Var->setInvalidDecl();
14559 return;
14560 }
14561 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14562 if (!RD->hasTrivialDefaultConstructor()) {
14563 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14564 Var->setInvalidDecl();
14565 return;
14566 }
14567 }
14568 // The declaration is uninitialized, no need for further checks.
14569 return;
14570 }
14571
14572 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14573 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14574 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14575 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14576 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14577 NonTrivialKind: NTCUK_Init);
14578
14579 switch (DefKind) {
14580 case VarDecl::Definition:
14581 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14582 break;
14583
14584 // We have an out-of-line definition of a static data member
14585 // that has an in-class initializer, so we type-check this like
14586 // a declaration.
14587 //
14588 [[fallthrough]];
14589
14590 case VarDecl::DeclarationOnly:
14591 // It's only a declaration.
14592
14593 // Block scope. C99 6.7p7: If an identifier for an object is
14594 // declared with no linkage (C99 6.2.2p6), the type for the
14595 // object shall be complete.
14596 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14597 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14598 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14599 DiagID: diag::err_typecheck_decl_incomplete_type))
14600 Var->setInvalidDecl();
14601
14602 // Make sure that the type is not abstract.
14603 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14604 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14605 DiagID: diag::err_abstract_type_in_decl,
14606 Args: AbstractVariableType))
14607 Var->setInvalidDecl();
14608 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14609 Var->getStorageClass() == SC_PrivateExtern) {
14610 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14611 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14612 }
14613
14614 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14615 !Var->isInvalidDecl())
14616 ExternalDeclarations.push_back(Elt: Var);
14617
14618 return;
14619
14620 case VarDecl::TentativeDefinition:
14621 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14622 // object that has file scope without an initializer, and without a
14623 // storage-class specifier or with the storage-class specifier "static",
14624 // constitutes a tentative definition. Note: A tentative definition with
14625 // external linkage is valid (C99 6.2.2p5).
14626 if (!Var->isInvalidDecl()) {
14627 if (const IncompleteArrayType *ArrayT
14628 = Context.getAsIncompleteArrayType(T: Type)) {
14629 if (RequireCompleteSizedType(
14630 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14631 DiagID: diag::err_array_incomplete_or_sizeless_type))
14632 Var->setInvalidDecl();
14633 }
14634 if (Var->getStorageClass() == SC_Static) {
14635 // C99 6.9.2p3: If the declaration of an identifier for an object is
14636 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14637 // declared type shall not be an incomplete type.
14638 // NOTE: code such as the following
14639 // static struct s;
14640 // struct s { int a; };
14641 // is accepted by gcc. Hence here we issue a warning instead of
14642 // an error and we do not invalidate the static declaration.
14643 // NOTE: to avoid multiple warnings, only check the first declaration.
14644 if (Var->isFirstDecl())
14645 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14646 DiagID: diag::ext_typecheck_decl_incomplete_type,
14647 Args: Type->isArrayType());
14648 }
14649 }
14650
14651 // Record the tentative definition; we're done.
14652 if (!Var->isInvalidDecl())
14653 TentativeDefinitions.push_back(LocalValue: Var);
14654 return;
14655 }
14656
14657 // Provide a specific diagnostic for uninitialized variable definitions
14658 // with incomplete array type, unless it is a global unbounded HLSL resource
14659 // array.
14660 if (Type->isIncompleteArrayType() &&
14661 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14662 Type->isHLSLResourceRecordArray())) {
14663 if (Var->isConstexpr())
14664 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14665 << Var;
14666 else
14667 Diag(Loc: Var->getLocation(),
14668 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14669 Var->setInvalidDecl();
14670 return;
14671 }
14672
14673 // Provide a specific diagnostic for uninitialized variable
14674 // definitions with reference type.
14675 if (Type->isReferenceType()) {
14676 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14677 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14678 return;
14679 }
14680
14681 // Do not attempt to type-check the default initializer for a
14682 // variable with dependent type.
14683 if (Type->isDependentType())
14684 return;
14685
14686 if (Var->isInvalidDecl())
14687 return;
14688
14689 if (!Var->hasAttr<AliasAttr>()) {
14690 if (RequireCompleteType(Loc: Var->getLocation(),
14691 T: Context.getBaseElementType(QT: Type),
14692 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14693 Var->setInvalidDecl();
14694 return;
14695 }
14696 } else {
14697 return;
14698 }
14699
14700 // The variable can not have an abstract class type.
14701 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14702 DiagID: diag::err_abstract_type_in_decl,
14703 Args: AbstractVariableType)) {
14704 Var->setInvalidDecl();
14705 return;
14706 }
14707
14708 // In C, if the definition is const-qualified and has no initializer, it
14709 // is left uninitialized unless it has static or thread storage duration.
14710 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14711 unsigned DiagID = diag::warn_default_init_const_unsafe;
14712 if (Var->getStorageDuration() == SD_Static ||
14713 Var->getStorageDuration() == SD_Thread)
14714 DiagID = diag::warn_default_init_const;
14715
14716 bool EmitCppCompat = !Diags.isIgnored(
14717 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14718 Loc: Var->getLocation());
14719
14720 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14721 }
14722
14723 // Check for jumps past the implicit initializer. C++0x
14724 // clarifies that this applies to a "variable with automatic
14725 // storage duration", not a "local variable".
14726 // C++11 [stmt.dcl]p3
14727 // A program that jumps from a point where a variable with automatic
14728 // storage duration is not in scope to a point where it is in scope is
14729 // ill-formed unless the variable has scalar type, class type with a
14730 // trivial default constructor and a trivial destructor, a cv-qualified
14731 // version of one of these types, or an array of one of the preceding
14732 // types and is declared without an initializer.
14733 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14734 if (const auto *CXXRecord =
14735 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14736 // Mark the function (if we're in one) for further checking even if the
14737 // looser rules of C++11 do not require such checks, so that we can
14738 // diagnose incompatibilities with C++98.
14739 if (!CXXRecord->isPOD())
14740 setFunctionHasBranchProtectedScope();
14741 }
14742 }
14743 // In OpenCL, we can't initialize objects in the __local address space,
14744 // even implicitly, so don't synthesize an implicit initializer.
14745 if (getLangOpts().OpenCL &&
14746 Var->getType().getAddressSpace() == LangAS::opencl_local)
14747 return;
14748
14749 // Handle HLSL uninitialized decls
14750 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14751 return;
14752
14753 // HLSL input & push-constant variables are expected to be externally
14754 // initialized, even when marked `static`.
14755 if (getLangOpts().HLSL &&
14756 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14757 return;
14758
14759 // C++03 [dcl.init]p9:
14760 // If no initializer is specified for an object, and the
14761 // object is of (possibly cv-qualified) non-POD class type (or
14762 // array thereof), the object shall be default-initialized; if
14763 // the object is of const-qualified type, the underlying class
14764 // type shall have a user-declared default
14765 // constructor. Otherwise, if no initializer is specified for
14766 // a non- static object, the object and its subobjects, if
14767 // any, have an indeterminate initial value); if the object
14768 // or any of its subobjects are of const-qualified type, the
14769 // program is ill-formed.
14770 // C++0x [dcl.init]p11:
14771 // If no initializer is specified for an object, the object is
14772 // default-initialized; [...].
14773 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14774 InitializationKind Kind
14775 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14776
14777 InitializationSequence InitSeq(*this, Entity, Kind, {});
14778 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14779
14780 if (Init.get()) {
14781 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14782 // This is important for template substitution.
14783 Var->setInitStyle(VarDecl::CallInit);
14784 } else if (Init.isInvalid()) {
14785 // If default-init fails, attach a recovery-expr initializer to track
14786 // that initialization was attempted and failed.
14787 auto RecoveryExpr =
14788 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14789 if (RecoveryExpr.get())
14790 Var->setInit(RecoveryExpr.get());
14791 }
14792
14793 CheckCompleteVariableDeclaration(VD: Var);
14794 }
14795}
14796
14797void Sema::ActOnCXXForRangeDecl(Decl *D) {
14798 // If there is no declaration, there was an error parsing it. Ignore it.
14799 if (!D)
14800 return;
14801
14802 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14803 if (!VD) {
14804 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14805 D->setInvalidDecl();
14806 return;
14807 }
14808
14809 VD->setCXXForRangeDecl(true);
14810
14811 // for-range-declaration cannot be given a storage class specifier.
14812 int Error = -1;
14813 switch (VD->getStorageClass()) {
14814 case SC_None:
14815 break;
14816 case SC_Extern:
14817 Error = 0;
14818 break;
14819 case SC_Static:
14820 Error = 1;
14821 break;
14822 case SC_PrivateExtern:
14823 Error = 2;
14824 break;
14825 case SC_Auto:
14826 Error = 3;
14827 break;
14828 case SC_Register:
14829 Error = 4;
14830 break;
14831 }
14832
14833 // for-range-declaration cannot be given a storage class specifier con't.
14834 switch (VD->getTSCSpec()) {
14835 case TSCS_thread_local:
14836 Error = 6;
14837 break;
14838 case TSCS___thread:
14839 case TSCS__Thread_local:
14840 case TSCS_unspecified:
14841 break;
14842 }
14843
14844 if (Error != -1) {
14845 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14846 << VD << Error;
14847 D->setInvalidDecl();
14848 }
14849}
14850
14851StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14852 IdentifierInfo *Ident,
14853 ParsedAttributes &Attrs) {
14854 // C++1y [stmt.iter]p1:
14855 // A range-based for statement of the form
14856 // for ( for-range-identifier : for-range-initializer ) statement
14857 // is equivalent to
14858 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14859 DeclSpec DS(Attrs.getPool().getFactory());
14860
14861 const char *PrevSpec;
14862 unsigned DiagID;
14863 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14864 Policy: getPrintingPolicy());
14865
14866 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14867 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14868 D.takeAttributesAppending(attrs&: Attrs);
14869
14870 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14871 EndLoc: IdentLoc);
14872 Decl *Var = ActOnDeclarator(S, D);
14873 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14874 FinalizeDeclaration(D: Var);
14875 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14876 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14877 : IdentLoc);
14878}
14879
14880void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
14881 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
14882 return;
14883 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
14884 QualType MethodType = MD->getType();
14885 QualType AttributedType =
14886 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
14887 TypeLocBuilder TLB;
14888 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14889 TLB.pushFullCopy(L: TSI->getTypeLoc());
14890 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
14891 TyLoc.setAttr(Attr);
14892 MD->setType(AttributedType);
14893 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
14894}
14895
14896void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14897 if (var->isInvalidDecl()) return;
14898
14899 CUDA().MaybeAddConstantAttr(VD: var);
14900
14901 if (getLangOpts().OpenCL) {
14902 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14903 // initialiser
14904 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14905 !var->hasInit()) {
14906 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14907 << 1 /*Init*/;
14908 var->setInvalidDecl();
14909 return;
14910 }
14911 }
14912
14913 // In Objective-C, don't allow jumps past the implicit initialization of a
14914 // local retaining variable.
14915 if (getLangOpts().ObjC &&
14916 var->hasLocalStorage()) {
14917 switch (var->getType().getObjCLifetime()) {
14918 case Qualifiers::OCL_None:
14919 case Qualifiers::OCL_ExplicitNone:
14920 case Qualifiers::OCL_Autoreleasing:
14921 break;
14922
14923 case Qualifiers::OCL_Weak:
14924 case Qualifiers::OCL_Strong:
14925 setFunctionHasBranchProtectedScope();
14926 break;
14927 }
14928 }
14929
14930 if (var->hasLocalStorage() &&
14931 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14932 setFunctionHasBranchProtectedScope();
14933
14934 // Warn about externally-visible variables being defined without a
14935 // prior declaration. We only want to do this for global
14936 // declarations, but we also specifically need to avoid doing it for
14937 // class members because the linkage of an anonymous class can
14938 // change if it's later given a typedef name.
14939 if (var->isThisDeclarationADefinition() &&
14940 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14941 var->isExternallyVisible() && var->hasLinkage() &&
14942 !var->isInline() && !var->getDescribedVarTemplate() &&
14943 var->getStorageClass() != SC_Register &&
14944 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14945 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14946 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14947 Loc: var->getLocation())) {
14948 // Find a previous declaration that's not a definition.
14949 VarDecl *prev = var->getPreviousDecl();
14950 while (prev && prev->isThisDeclarationADefinition())
14951 prev = prev->getPreviousDecl();
14952
14953 if (!prev) {
14954 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14955 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14956 << /* variable */ 0;
14957 }
14958 }
14959
14960 // Cache the result of checking for constant initialization.
14961 std::optional<bool> CacheHasConstInit;
14962 const Expr *CacheCulprit = nullptr;
14963 auto checkConstInit = [&]() mutable {
14964 const Expr *Init = var->getInit();
14965 if (Init->isInstantiationDependent())
14966 return true;
14967
14968 if (!CacheHasConstInit)
14969 CacheHasConstInit = var->getInit()->isConstantInitializer(
14970 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14971 return *CacheHasConstInit;
14972 };
14973
14974 if (var->getTLSKind() == VarDecl::TLS_Static) {
14975 if (var->getType().isDestructedType()) {
14976 // GNU C++98 edits for __thread, [basic.start.term]p3:
14977 // The type of an object with thread storage duration shall not
14978 // have a non-trivial destructor.
14979 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14980 if (getLangOpts().CPlusPlus11)
14981 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14982 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14983 if (!checkConstInit()) {
14984 // GNU C++98 edits for __thread, [basic.start.init]p4:
14985 // An object of thread storage duration shall not require dynamic
14986 // initialization.
14987 // FIXME: Need strict checking here.
14988 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14989 << CacheCulprit->getSourceRange();
14990 if (getLangOpts().CPlusPlus11)
14991 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14992 }
14993 }
14994 }
14995
14996
14997 if (!var->getType()->isStructureType() && var->hasInit() &&
14998 isa<InitListExpr>(Val: var->getInit())) {
14999 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15000 unsigned NumInits = ILE->getNumInits();
15001 if (NumInits > 2)
15002 for (unsigned I = 0; I < NumInits; ++I) {
15003 const auto *Init = ILE->getInit(Init: I);
15004 if (!Init)
15005 break;
15006 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15007 if (!SL)
15008 break;
15009
15010 unsigned NumConcat = SL->getNumConcatenated();
15011 // Diagnose missing comma in string array initialization.
15012 // Do not warn when all the elements in the initializer are concatenated
15013 // together. Do not warn for macros too.
15014 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15015 bool OnlyOneMissingComma = true;
15016 for (unsigned J = I + 1; J < NumInits; ++J) {
15017 const auto *Init = ILE->getInit(Init: J);
15018 if (!Init)
15019 break;
15020 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15021 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15022 OnlyOneMissingComma = false;
15023 break;
15024 }
15025 }
15026
15027 if (OnlyOneMissingComma) {
15028 SmallVector<FixItHint, 1> Hints;
15029 for (unsigned i = 0; i < NumConcat - 1; ++i)
15030 Hints.push_back(Elt: FixItHint::CreateInsertion(
15031 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15032
15033 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15034 DiagID: diag::warn_concatenated_literal_array_init)
15035 << Hints;
15036 Diag(Loc: SL->getBeginLoc(),
15037 DiagID: diag::note_concatenated_string_literal_silence);
15038 }
15039 // In any case, stop now.
15040 break;
15041 }
15042 }
15043 }
15044
15045
15046 QualType type = var->getType();
15047
15048 if (var->hasAttr<BlocksAttr>())
15049 getCurFunction()->addByrefBlockVar(VD: var);
15050
15051 Expr *Init = var->getInit();
15052 bool GlobalStorage = var->hasGlobalStorage();
15053 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15054 QualType baseType = Context.getBaseElementType(QT: type);
15055 bool HasConstInit = true;
15056
15057 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15058 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15059 << var;
15060
15061 // Check whether the initializer is sufficiently constant.
15062 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15063 !type->isDependentType() && Init && !Init->isValueDependent() &&
15064 (GlobalStorage || var->isConstexpr() ||
15065 var->mightBeUsableInConstantExpressions(C: Context))) {
15066 // If this variable might have a constant initializer or might be usable in
15067 // constant expressions, check whether or not it actually is now. We can't
15068 // do this lazily, because the result might depend on things that change
15069 // later, such as which constexpr functions happen to be defined.
15070 SmallVector<PartialDiagnosticAt, 8> Notes;
15071 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15072 // Prior to C++11, in contexts where a constant initializer is required,
15073 // the set of valid constant initializers is described by syntactic rules
15074 // in [expr.const]p2-6.
15075 // FIXME: Stricter checking for these rules would be useful for constinit /
15076 // -Wglobal-constructors.
15077 HasConstInit = checkConstInit();
15078
15079 // Compute and cache the constant value, and remember that we have a
15080 // constant initializer.
15081 if (HasConstInit) {
15082 if (var->isStaticDataMember() && !var->isInline() &&
15083 var->getLexicalDeclContext()->isRecord() &&
15084 type->isIntegralOrEnumerationType()) {
15085 // In C++98, in-class initialization for a static data member must
15086 // be an integer constant expression.
15087 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15088 Diag(Loc: Init->getExprLoc(),
15089 DiagID: diag::ext_in_class_initializer_non_constant)
15090 << Init->getSourceRange();
15091 }
15092 }
15093 (void)var->checkForConstantInitialization(Notes);
15094 Notes.clear();
15095 } else if (CacheCulprit) {
15096 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15097 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15098 Notes.back().second << CacheCulprit->getSourceRange();
15099 }
15100 } else {
15101 // Evaluate the initializer to see if it's a constant initializer.
15102 HasConstInit = var->checkForConstantInitialization(Notes);
15103 }
15104
15105 if (HasConstInit) {
15106 // FIXME: Consider replacing the initializer with a ConstantExpr.
15107 } else if (var->isConstexpr()) {
15108 SourceLocation DiagLoc = var->getLocation();
15109 // If the note doesn't add any useful information other than a source
15110 // location, fold it into the primary diagnostic.
15111 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15112 diag::note_invalid_subexpr_in_const_expr) {
15113 DiagLoc = Notes[0].first;
15114 Notes.clear();
15115 }
15116 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15117 << var << Init->getSourceRange();
15118 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15119 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15120 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15121 auto *Attr = var->getAttr<ConstInitAttr>();
15122 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15123 << Init->getSourceRange();
15124 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15125 << Attr->getRange() << Attr->isConstinit();
15126 for (auto &it : Notes)
15127 Diag(Loc: it.first, PD: it.second);
15128 } else if (var->isStaticDataMember() && !var->isInline() &&
15129 var->getLexicalDeclContext()->isRecord()) {
15130 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15131 << Init->getSourceRange();
15132 for (auto &it : Notes)
15133 Diag(Loc: it.first, PD: it.second);
15134 var->setInvalidDecl();
15135 } else if (IsGlobal &&
15136 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15137 Loc: var->getLocation())) {
15138 // Warn about globals which don't have a constant initializer. Don't
15139 // warn about globals with a non-trivial destructor because we already
15140 // warned about them.
15141 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15142 if (!(RD && !RD->hasTrivialDestructor())) {
15143 // checkConstInit() here permits trivial default initialization even in
15144 // C++11 onwards, where such an initializer is not a constant initializer
15145 // but nonetheless doesn't require a global constructor.
15146 if (!checkConstInit())
15147 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15148 << Init->getSourceRange();
15149 }
15150 }
15151 }
15152
15153 // Apply section attributes and pragmas to global variables.
15154 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15155 !inTemplateInstantiation()) {
15156 PragmaStack<StringLiteral *> *Stack = nullptr;
15157 int SectionFlags = ASTContext::PSF_Read;
15158 bool MSVCEnv =
15159 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15160 std::optional<QualType::NonConstantStorageReason> Reason;
15161 if (HasConstInit &&
15162 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15163 Stack = &ConstSegStack;
15164 } else {
15165 SectionFlags |= ASTContext::PSF_Write;
15166 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15167 }
15168 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15169 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15170 SectionFlags |= ASTContext::PSF_Implicit;
15171 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15172 } else if (Stack->CurrentValue) {
15173 if (Stack != &ConstSegStack && MSVCEnv &&
15174 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15175 var->getType().isConstQualified()) {
15176 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15177 NonConstNonReferenceType) &&
15178 "This case should've already been handled elsewhere");
15179 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15180 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15181 ? QualType::NonConstantStorageReason::NonTrivialCtor
15182 : *Reason);
15183 }
15184 SectionFlags |= ASTContext::PSF_Implicit;
15185 auto SectionName = Stack->CurrentValue->getString();
15186 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15187 Range: Stack->CurrentPragmaLocation,
15188 S: SectionAttr::Declspec_allocate));
15189 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15190 var->dropAttr<SectionAttr>();
15191 }
15192
15193 // Apply the init_seg attribute if this has an initializer. If the
15194 // initializer turns out to not be dynamic, we'll end up ignoring this
15195 // attribute.
15196 if (CurInitSeg && var->getInit())
15197 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15198 Range: CurInitSegLoc));
15199 }
15200
15201 // All the following checks are C++ only.
15202 if (!getLangOpts().CPlusPlus) {
15203 // If this variable must be emitted, add it as an initializer for the
15204 // current module.
15205 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15206 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15207 return;
15208 }
15209
15210 DiagnoseUniqueObjectDuplication(VD: var);
15211
15212 // Require the destructor.
15213 if (!type->isDependentType())
15214 if (auto *RD = baseType->getAsCXXRecordDecl())
15215 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15216
15217 // If this variable must be emitted, add it as an initializer for the current
15218 // module.
15219 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty() &&
15220 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15221 // For named modules, we may only emit non discardable variables.
15222 !isDiscardableGVALinkage(L: Context.GetGVALinkageForVariable(VD: var))))
15223 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15224
15225 // Build the bindings if this is a structured binding declaration.
15226 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15227 CheckCompleteDecompositionDeclaration(DD);
15228}
15229
15230void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15231 assert(VD->isStaticLocal());
15232
15233 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15234
15235 // Find outermost function when VD is in lambda function.
15236 while (FD && !getDLLAttr(D: FD) &&
15237 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15238 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15239 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15240 }
15241
15242 if (!FD)
15243 return;
15244
15245 // Static locals inherit dll attributes from their function.
15246 if (Attr *A = getDLLAttr(D: FD)) {
15247 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15248 NewAttr->setInherited(true);
15249 VD->addAttr(A: NewAttr);
15250 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15251 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15252 NewAttr->setInherited(true);
15253 VD->addAttr(A: NewAttr);
15254
15255 // Export this function to enforce exporting this static variable even
15256 // if it is not used in this compilation unit.
15257 if (!FD->hasAttr<DLLExportAttr>())
15258 FD->addAttr(A: NewAttr);
15259
15260 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15261 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15262 NewAttr->setInherited(true);
15263 VD->addAttr(A: NewAttr);
15264 }
15265}
15266
15267void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15268 assert(VD->getTLSKind());
15269
15270 // Perform TLS alignment check here after attributes attached to the variable
15271 // which may affect the alignment have been processed. Only perform the check
15272 // if the target has a maximum TLS alignment (zero means no constraints).
15273 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15274 // Protect the check so that it's not performed on dependent types and
15275 // dependent alignments (we can't determine the alignment in that case).
15276 if (!VD->hasDependentAlignment()) {
15277 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15278 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15279 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15280 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15281 << (unsigned)MaxAlignChars.getQuantity();
15282 }
15283 }
15284 }
15285}
15286
15287void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15288 // Note that we are no longer parsing the initializer for this declaration.
15289 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15290
15291 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15292 if (!VD)
15293 return;
15294
15295 // Emit any deferred warnings for the variable's initializer, even if the
15296 // variable is invalid
15297 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15298
15299 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15300 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15301 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15302 if (PragmaClangBSSSection.Valid)
15303 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15304 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15305 Range: PragmaClangBSSSection.PragmaLocation));
15306 if (PragmaClangDataSection.Valid)
15307 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15308 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15309 Range: PragmaClangDataSection.PragmaLocation));
15310 if (PragmaClangRodataSection.Valid)
15311 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15312 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15313 Range: PragmaClangRodataSection.PragmaLocation));
15314 if (PragmaClangRelroSection.Valid)
15315 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15316 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15317 Range: PragmaClangRelroSection.PragmaLocation));
15318 }
15319
15320 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15321 for (auto *BD : DD->bindings()) {
15322 FinalizeDeclaration(ThisDecl: BD);
15323 }
15324 }
15325
15326 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15327 K: BuiltinCountedByRefKind::Initializer);
15328
15329 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15330
15331 if (VD->isStaticLocal())
15332 CheckStaticLocalForDllExport(VD);
15333
15334 if (VD->getTLSKind())
15335 CheckThreadLocalForLargeAlignment(VD);
15336
15337 // Perform check for initializers of device-side global variables.
15338 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15339 // 7.5). We must also apply the same checks to all __shared__
15340 // variables whether they are local or not. CUDA also allows
15341 // constant initializers for __constant__ and __device__ variables.
15342 if (getLangOpts().CUDA)
15343 CUDA().checkAllowedInitializer(VD);
15344
15345 // Grab the dllimport or dllexport attribute off of the VarDecl.
15346 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15347
15348 // Imported static data members cannot be defined out-of-line.
15349 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15350 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15351 VD->isThisDeclarationADefinition()) {
15352 // We allow definitions of dllimport class template static data members
15353 // with a warning.
15354 CXXRecordDecl *Context =
15355 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15356 bool IsClassTemplateMember =
15357 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15358 Context->getDescribedClassTemplate();
15359
15360 Diag(Loc: VD->getLocation(),
15361 DiagID: IsClassTemplateMember
15362 ? diag::warn_attribute_dllimport_static_field_definition
15363 : diag::err_attribute_dllimport_static_field_definition);
15364 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15365 if (!IsClassTemplateMember)
15366 VD->setInvalidDecl();
15367 }
15368 }
15369
15370 // dllimport/dllexport variables cannot be thread local, their TLS index
15371 // isn't exported with the variable.
15372 if (DLLAttr && VD->getTLSKind()) {
15373 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15374 if (F && getDLLAttr(D: F)) {
15375 assert(VD->isStaticLocal());
15376 // But if this is a static local in a dlimport/dllexport function, the
15377 // function will never be inlined, which means the var would never be
15378 // imported, so having it marked import/export is safe.
15379 } else {
15380 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15381 << DLLAttr;
15382 VD->setInvalidDecl();
15383 }
15384 }
15385
15386 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15387 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15388 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15389 << Attr;
15390 VD->dropAttr<UsedAttr>();
15391 }
15392 }
15393 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15394 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15395 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15396 << Attr;
15397 VD->dropAttr<RetainAttr>();
15398 }
15399 }
15400
15401 const DeclContext *DC = VD->getDeclContext();
15402 // If there's a #pragma GCC visibility in scope, and this isn't a class
15403 // member, set the visibility of this variable.
15404 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15405 AddPushedVisibilityAttribute(RD: VD);
15406
15407 // FIXME: Warn on unused var template partial specializations.
15408 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15409 MarkUnusedFileScopedDecl(D: VD);
15410
15411 // Now we have parsed the initializer and can update the table of magic
15412 // tag values.
15413 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15414 !VD->getType()->isIntegralOrEnumerationType())
15415 return;
15416
15417 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15418 const Expr *MagicValueExpr = VD->getInit();
15419 if (!MagicValueExpr) {
15420 continue;
15421 }
15422 std::optional<llvm::APSInt> MagicValueInt;
15423 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15424 Diag(Loc: I->getRange().getBegin(),
15425 DiagID: diag::err_type_tag_for_datatype_not_ice)
15426 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15427 continue;
15428 }
15429 if (MagicValueInt->getActiveBits() > 64) {
15430 Diag(Loc: I->getRange().getBegin(),
15431 DiagID: diag::err_type_tag_for_datatype_too_large)
15432 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15433 continue;
15434 }
15435 uint64_t MagicValue = MagicValueInt->getZExtValue();
15436 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15437 MagicValue,
15438 Type: I->getMatchingCType(),
15439 LayoutCompatible: I->getLayoutCompatible(),
15440 MustBeNull: I->getMustBeNull());
15441 }
15442}
15443
15444static bool hasDeducedAuto(DeclaratorDecl *DD) {
15445 auto *VD = dyn_cast<VarDecl>(Val: DD);
15446 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15447}
15448
15449Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15450 ArrayRef<Decl *> Group) {
15451 SmallVector<Decl*, 8> Decls;
15452
15453 if (DS.isTypeSpecOwned())
15454 Decls.push_back(Elt: DS.getRepAsDecl());
15455
15456 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15457 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15458 bool DiagnosedMultipleDecomps = false;
15459 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15460 bool DiagnosedNonDeducedAuto = false;
15461
15462 for (Decl *D : Group) {
15463 if (!D)
15464 continue;
15465 // Check if the Decl has been declared in '#pragma omp declare target'
15466 // directive and has static storage duration.
15467 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15468 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15469 VD->hasGlobalStorage())
15470 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15471 // For declarators, there are some additional syntactic-ish checks we need
15472 // to perform.
15473 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15474 if (!FirstDeclaratorInGroup)
15475 FirstDeclaratorInGroup = DD;
15476 if (!FirstDecompDeclaratorInGroup)
15477 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15478 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15479 !hasDeducedAuto(DD))
15480 FirstNonDeducedAutoInGroup = DD;
15481
15482 if (FirstDeclaratorInGroup != DD) {
15483 // A decomposition declaration cannot be combined with any other
15484 // declaration in the same group.
15485 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15486 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15487 DiagID: diag::err_decomp_decl_not_alone)
15488 << FirstDeclaratorInGroup->getSourceRange()
15489 << DD->getSourceRange();
15490 DiagnosedMultipleDecomps = true;
15491 }
15492
15493 // A declarator that uses 'auto' in any way other than to declare a
15494 // variable with a deduced type cannot be combined with any other
15495 // declarator in the same group.
15496 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15497 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15498 DiagID: diag::err_auto_non_deduced_not_alone)
15499 << FirstNonDeducedAutoInGroup->getType()
15500 ->hasAutoForTrailingReturnType()
15501 << FirstDeclaratorInGroup->getSourceRange()
15502 << DD->getSourceRange();
15503 DiagnosedNonDeducedAuto = true;
15504 }
15505 }
15506 }
15507
15508 Decls.push_back(Elt: D);
15509 }
15510
15511 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15512 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15513 handleTagNumbering(Tag, TagScope: S);
15514 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15515 getLangOpts().CPlusPlus)
15516 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15517 }
15518 }
15519
15520 return BuildDeclaratorGroup(Group: Decls);
15521}
15522
15523Sema::DeclGroupPtrTy
15524Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15525 // C++14 [dcl.spec.auto]p7: (DR1347)
15526 // If the type that replaces the placeholder type is not the same in each
15527 // deduction, the program is ill-formed.
15528 if (Group.size() > 1) {
15529 QualType Deduced;
15530 VarDecl *DeducedDecl = nullptr;
15531 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15532 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15533 if (!D || D->isInvalidDecl())
15534 break;
15535 DeducedType *DT = D->getType()->getContainedDeducedType();
15536 if (!DT || DT->getDeducedType().isNull())
15537 continue;
15538 if (Deduced.isNull()) {
15539 Deduced = DT->getDeducedType();
15540 DeducedDecl = D;
15541 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15542 auto *AT = dyn_cast<AutoType>(Val: DT);
15543 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15544 DiagID: diag::err_auto_different_deductions)
15545 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15546 << DeducedDecl->getDeclName() << DT->getDeducedType()
15547 << D->getDeclName();
15548 if (DeducedDecl->hasInit())
15549 Dia << DeducedDecl->getInit()->getSourceRange();
15550 if (D->getInit())
15551 Dia << D->getInit()->getSourceRange();
15552 D->setInvalidDecl();
15553 break;
15554 }
15555 }
15556 }
15557
15558 ActOnDocumentableDecls(Group);
15559
15560 return DeclGroupPtrTy::make(
15561 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15562}
15563
15564void Sema::ActOnDocumentableDecl(Decl *D) {
15565 ActOnDocumentableDecls(Group: D);
15566}
15567
15568void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15569 // Don't parse the comment if Doxygen diagnostics are ignored.
15570 if (Group.empty() || !Group[0])
15571 return;
15572
15573 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15574 Loc: Group[0]->getLocation()) &&
15575 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15576 Loc: Group[0]->getLocation()))
15577 return;
15578
15579 if (Group.size() >= 2) {
15580 // This is a decl group. Normally it will contain only declarations
15581 // produced from declarator list. But in case we have any definitions or
15582 // additional declaration references:
15583 // 'typedef struct S {} S;'
15584 // 'typedef struct S *S;'
15585 // 'struct S *pS;'
15586 // FinalizeDeclaratorGroup adds these as separate declarations.
15587 Decl *MaybeTagDecl = Group[0];
15588 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15589 Group = Group.slice(N: 1);
15590 }
15591 }
15592
15593 // FIXME: We assume every Decl in the group is in the same file.
15594 // This is false when preprocessor constructs the group from decls in
15595 // different files (e. g. macros or #include).
15596 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15597}
15598
15599void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15600 // Check that there are no default arguments inside the type of this
15601 // parameter.
15602 if (getLangOpts().CPlusPlus)
15603 CheckExtraCXXDefaultArguments(D);
15604
15605 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15606 if (D.getCXXScopeSpec().isSet()) {
15607 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15608 << D.getCXXScopeSpec().getRange();
15609 }
15610
15611 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15612 // simple identifier except [...irrelevant cases...].
15613 switch (D.getName().getKind()) {
15614 case UnqualifiedIdKind::IK_Identifier:
15615 break;
15616
15617 case UnqualifiedIdKind::IK_OperatorFunctionId:
15618 case UnqualifiedIdKind::IK_ConversionFunctionId:
15619 case UnqualifiedIdKind::IK_LiteralOperatorId:
15620 case UnqualifiedIdKind::IK_ConstructorName:
15621 case UnqualifiedIdKind::IK_DestructorName:
15622 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15623 case UnqualifiedIdKind::IK_DeductionGuideName:
15624 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15625 << GetNameForDeclarator(D).getName();
15626 break;
15627
15628 case UnqualifiedIdKind::IK_TemplateId:
15629 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15630 // GetNameForDeclarator would not produce a useful name in this case.
15631 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15632 break;
15633 }
15634}
15635
15636void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15637 // This only matters in C.
15638 if (getLangOpts().CPlusPlus)
15639 return;
15640
15641 // This only matters if the declaration has a type.
15642 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15643 if (!VD)
15644 return;
15645
15646 // Get the type, this only matters for tag types.
15647 QualType QT = VD->getType();
15648 const auto *TD = QT->getAsTagDecl();
15649 if (!TD)
15650 return;
15651
15652 // Check if the tag declaration is lexically declared somewhere different
15653 // from the lexical declaration of the given object, then it will be hidden
15654 // in C++ and we should warn on it.
15655 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15656 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15657 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15658 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15659 }
15660}
15661
15662static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15663 SourceLocation ExplicitThisLoc) {
15664 if (!ExplicitThisLoc.isValid())
15665 return;
15666 assert(S.getLangOpts().CPlusPlus &&
15667 "explicit parameter in non-cplusplus mode");
15668 if (!S.getLangOpts().CPlusPlus23)
15669 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15670 << P->getSourceRange();
15671
15672 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15673 // parameter pack.
15674 if (P->isParameterPack()) {
15675 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15676 << P->getSourceRange();
15677 return;
15678 }
15679 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15680 if (LambdaScopeInfo *LSI = S.getCurLambda())
15681 LSI->ExplicitObjectParameter = P;
15682}
15683
15684Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15685 SourceLocation ExplicitThisLoc) {
15686 const DeclSpec &DS = D.getDeclSpec();
15687
15688 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15689 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15690 // except for the special case of a single unnamed parameter of type void
15691 // with no storage class specifier, no type qualifier, and no following
15692 // ellipsis terminator.
15693 // Clang applies the C2y rules for 'register void' in all C language modes,
15694 // same as GCC, because it's questionable what that could possibly mean.
15695
15696 // C++03 [dcl.stc]p2 also permits 'auto'.
15697 StorageClass SC = SC_None;
15698 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15699 SC = SC_Register;
15700 // In C++11, the 'register' storage class specifier is deprecated.
15701 // In C++17, it is not allowed, but we tolerate it as an extension.
15702 if (getLangOpts().CPlusPlus11) {
15703 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15704 ? diag::ext_register_storage_class
15705 : diag::warn_deprecated_register)
15706 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15707 } else if (!getLangOpts().CPlusPlus &&
15708 DS.getTypeSpecType() == DeclSpec::TST_void &&
15709 D.getNumTypeObjects() == 0) {
15710 Diag(Loc: DS.getStorageClassSpecLoc(),
15711 DiagID: diag::err_invalid_storage_class_in_func_decl)
15712 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15713 D.getMutableDeclSpec().ClearStorageClassSpecs();
15714 }
15715 } else if (getLangOpts().CPlusPlus &&
15716 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15717 SC = SC_Auto;
15718 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15719 Diag(Loc: DS.getStorageClassSpecLoc(),
15720 DiagID: diag::err_invalid_storage_class_in_func_decl);
15721 D.getMutableDeclSpec().ClearStorageClassSpecs();
15722 }
15723
15724 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15725 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15726 << DeclSpec::getSpecifierName(S: TSCS);
15727 if (DS.isInlineSpecified())
15728 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15729 << getLangOpts().CPlusPlus17;
15730 if (DS.hasConstexprSpecifier())
15731 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15732 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15733
15734 DiagnoseFunctionSpecifiers(DS);
15735
15736 CheckFunctionOrTemplateParamDeclarator(S, D);
15737
15738 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15739 QualType parmDeclType = TInfo->getType();
15740
15741 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15742 const IdentifierInfo *II = D.getIdentifier();
15743 if (II) {
15744 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15745 RedeclarationKind::ForVisibleRedeclaration);
15746 LookupName(R, S);
15747 if (!R.empty()) {
15748 NamedDecl *PrevDecl = *R.begin();
15749 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15750 // Maybe we will complain about the shadowed template parameter.
15751 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15752 // Just pretend that we didn't see the previous declaration.
15753 PrevDecl = nullptr;
15754 }
15755 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15756 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15757 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15758 // Recover by removing the name
15759 II = nullptr;
15760 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15761 D.setInvalidType(true);
15762 }
15763 }
15764 }
15765
15766 // Incomplete resource arrays are not allowed as function parameters in HLSL
15767 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15768 parmDeclType->isHLSLResourceRecordArray()) {
15769 Diag(Loc: D.getIdentifierLoc(),
15770 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15771 D.setInvalidType(true);
15772 }
15773
15774 // Temporarily put parameter variables in the translation unit, not
15775 // the enclosing context. This prevents them from accidentally
15776 // looking like class members in C++.
15777 ParmVarDecl *New =
15778 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15779 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15780
15781 if (D.isInvalidType())
15782 New->setInvalidDecl();
15783
15784 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15785
15786 assert(S->isFunctionPrototypeScope());
15787 assert(S->getFunctionPrototypeDepth() >= 1);
15788 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15789 parameterIndex: S->getNextFunctionPrototypeIndex());
15790
15791 warnOnCTypeHiddenInCPlusPlus(D: New);
15792
15793 // Add the parameter declaration into this scope.
15794 S->AddDecl(D: New);
15795 if (II)
15796 IdResolver.AddDecl(D: New);
15797
15798 ProcessDeclAttributes(S, D: New, PD: D);
15799
15800 if (D.getDeclSpec().isModulePrivateSpecified())
15801 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15802 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15803 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15804
15805 if (New->hasAttr<BlocksAttr>())
15806 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
15807 << diag::NotAllowedBlockVarReason::NonlocalVariable;
15808
15809 New->deduceParmAddressSpace(Ctxt: Context);
15810
15811 return New;
15812}
15813
15814ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15815 SourceLocation Loc,
15816 QualType T) {
15817 /* FIXME: setting StartLoc == Loc.
15818 Would it be worth to modify callers so as to provide proper source
15819 location for the unnamed parameters, embedding the parameter's type? */
15820 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15821 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15822 S: SC_None, DefArg: nullptr);
15823 Param->setImplicit();
15824 return Param;
15825}
15826
15827void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15828 // Don't diagnose unused-parameter errors in template instantiations; we
15829 // will already have done so in the template itself.
15830 if (inTemplateInstantiation())
15831 return;
15832
15833 for (const ParmVarDecl *Parameter : Parameters) {
15834 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15835 !Parameter->hasAttr<UnusedAttr>() &&
15836 !Parameter->getIdentifier()->isPlaceholder()) {
15837 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15838 << Parameter->getDeclName();
15839 }
15840 }
15841}
15842
15843void Sema::DiagnoseSizeOfParametersAndReturnValue(
15844 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15845 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15846 return;
15847
15848 // Warn if the return value is pass-by-value and larger than the specified
15849 // threshold.
15850 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15851 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15852 if (Size > LangOpts.NumLargeByValueCopy)
15853 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15854 }
15855
15856 // Warn if any parameter is pass-by-value and larger than the specified
15857 // threshold.
15858 for (const ParmVarDecl *Parameter : Parameters) {
15859 QualType T = Parameter->getType();
15860 if (T->isDependentType() || !T.isPODType(Context))
15861 continue;
15862 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15863 if (Size > LangOpts.NumLargeByValueCopy)
15864 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15865 << Parameter << Size;
15866 }
15867}
15868
15869ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15870 SourceLocation NameLoc,
15871 const IdentifierInfo *Name, QualType T,
15872 TypeSourceInfo *TSInfo, StorageClass SC) {
15873 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15874 if (getLangOpts().ObjCAutoRefCount &&
15875 T.getObjCLifetime() == Qualifiers::OCL_None &&
15876 T->isObjCLifetimeType()) {
15877
15878 Qualifiers::ObjCLifetime lifetime;
15879
15880 // Special cases for arrays:
15881 // - if it's const, use __unsafe_unretained
15882 // - otherwise, it's an error
15883 if (T->isArrayType()) {
15884 if (!T.isConstQualified()) {
15885 if (DelayedDiagnostics.shouldDelayDiagnostics())
15886 DelayedDiagnostics.add(
15887 diag: sema::DelayedDiagnostic::makeForbiddenType(
15888 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15889 else
15890 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15891 << TSInfo->getTypeLoc().getSourceRange();
15892 }
15893 lifetime = Qualifiers::OCL_ExplicitNone;
15894 } else {
15895 lifetime = T->getObjCARCImplicitLifetime();
15896 }
15897 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15898 }
15899
15900 if (getLangOpts().OpenCL) {
15901 assert(!isa<DecayedType>(T));
15902 if (T->isArrayType() && !T.hasAddressSpace()) {
15903 QualType ET = Context.getAsArrayType(T)->getElementType();
15904 if (!ET.hasAddressSpace()) {
15905 // Add the private address space to the contents of the pointer when a
15906 // pointer parameter is declared as an array and not declared.
15907 LangAS ImplAS = LangAS::opencl_private;
15908 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
15909 T = QualType(Context.getAsArrayType(T), 0);
15910 }
15911 }
15912 }
15913
15914 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15915 T: Context.getAdjustedParameterType(T),
15916 TInfo: TSInfo, S: SC, DefArg: nullptr);
15917
15918 // Make a note if we created a new pack in the scope of a lambda, so that
15919 // we know that references to that pack must also be expanded within the
15920 // lambda scope.
15921 if (New->isParameterPack())
15922 if (auto *CSI = getEnclosingLambdaOrBlock())
15923 CSI->LocalPacks.push_back(Elt: New);
15924
15925 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15926 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15927 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15928 UseContext: NonTrivialCUnionContext::FunctionParam,
15929 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15930
15931 // Parameter declarators cannot be interface types. All ObjC objects are
15932 // passed by reference.
15933 if (T->isObjCObjectType()) {
15934 SourceLocation TypeEndLoc =
15935 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15936 Diag(Loc: NameLoc,
15937 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15938 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15939 T = Context.getObjCObjectPointerType(OIT: T);
15940 New->setType(T);
15941 }
15942
15943 // __ptrauth is forbidden on parameters.
15944 if (T.getPointerAuth()) {
15945 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15946 New->setInvalidDecl();
15947 }
15948
15949 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15950 // duration shall not be qualified by an address-space qualifier."
15951 // Since all parameters have automatic store duration, they can not have
15952 // an address space.
15953 if (T.getAddressSpace() != LangAS::Default &&
15954 // OpenCL allows function arguments declared to be an array of a type
15955 // to be qualified with an address space.
15956 !(getLangOpts().OpenCL &&
15957 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15958 // WebAssembly allows reference types as parameters. Funcref in particular
15959 // lives in a different address space.
15960 !(T->isFunctionPointerType() &&
15961 T.getAddressSpace() == LangAS::wasm_funcref) &&
15962 // HLSL allows function arguments to be qualified with an address space
15963 // if the groupshared annotation is used.
15964 !(getLangOpts().HLSL &&
15965 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
15966 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15967 New->setInvalidDecl();
15968 }
15969
15970 // PPC MMA non-pointer types are not allowed as function argument types.
15971 if (Context.getTargetInfo().getTriple().isPPC64() &&
15972 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15973 New->setInvalidDecl();
15974 }
15975
15976 return New;
15977}
15978
15979void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15980 SourceLocation LocAfterDecls) {
15981 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15982
15983 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15984 // in the declaration list shall have at least one declarator, those
15985 // declarators shall only declare identifiers from the identifier list, and
15986 // every identifier in the identifier list shall be declared.
15987 //
15988 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15989 // identifiers it names shall be declared in the declaration list."
15990 //
15991 // This is why we only diagnose in C99 and later. Note, the other conditions
15992 // listed are checked elsewhere.
15993 if (!FTI.hasPrototype) {
15994 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15995 --i;
15996 if (FTI.Params[i].Param == nullptr) {
15997 if (getLangOpts().C99) {
15998 SmallString<256> Code;
15999 llvm::raw_svector_ostream(Code)
16000 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16001 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16002 << FTI.Params[i].Ident
16003 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16004 }
16005
16006 // Implicitly declare the argument as type 'int' for lack of a better
16007 // type.
16008 AttributeFactory attrs;
16009 DeclSpec DS(attrs);
16010 const char* PrevSpec; // unused
16011 unsigned DiagID; // unused
16012 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16013 DiagID, Policy: Context.getPrintingPolicy());
16014 // Use the identifier location for the type source range.
16015 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16016 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16017 Declarator ParamD(DS, ParsedAttributesView::none(),
16018 DeclaratorContext::KNRTypeList);
16019 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16020 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16021 }
16022 }
16023 }
16024}
16025
16026Decl *
16027Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16028 MultiTemplateParamsArg TemplateParameterLists,
16029 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16030 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16031 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16032 Scope *ParentScope = FnBodyScope->getParent();
16033
16034 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16035 // we define a non-templated function definition, we will create a declaration
16036 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16037 // The base function declaration will have the equivalent of an `omp declare
16038 // variant` annotation which specifies the mangled definition as a
16039 // specialization function under the OpenMP context defined as part of the
16040 // `omp begin declare variant`.
16041 SmallVector<FunctionDecl *, 4> Bases;
16042 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16043 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16044 S: ParentScope, D, TemplateParameterLists, Bases);
16045
16046 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16047 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16048 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16049
16050 if (!Bases.empty())
16051 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16052 Bases);
16053
16054 return Dcl;
16055}
16056
16057void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16058 Consumer.HandleInlineFunctionDefinition(D);
16059}
16060
16061static bool FindPossiblePrototype(const FunctionDecl *FD,
16062 const FunctionDecl *&PossiblePrototype) {
16063 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16064 Prev = Prev->getPreviousDecl()) {
16065 // Ignore any declarations that occur in function or method
16066 // scope, because they aren't visible from the header.
16067 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16068 continue;
16069
16070 PossiblePrototype = Prev;
16071 return Prev->getType()->isFunctionProtoType();
16072 }
16073 return false;
16074}
16075
16076static bool
16077ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16078 const FunctionDecl *&PossiblePrototype) {
16079 // Don't warn about invalid declarations.
16080 if (FD->isInvalidDecl())
16081 return false;
16082
16083 // Or declarations that aren't global.
16084 if (!FD->isGlobal())
16085 return false;
16086
16087 // Don't warn about C++ member functions.
16088 if (isa<CXXMethodDecl>(Val: FD))
16089 return false;
16090
16091 // Don't warn about 'main'.
16092 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16093 if (IdentifierInfo *II = FD->getIdentifier())
16094 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16095 return false;
16096
16097 if (FD->isMSVCRTEntryPoint())
16098 return false;
16099
16100 // Don't warn about inline functions.
16101 if (FD->isInlined())
16102 return false;
16103
16104 // Don't warn about function templates.
16105 if (FD->getDescribedFunctionTemplate())
16106 return false;
16107
16108 // Don't warn about function template specializations.
16109 if (FD->isFunctionTemplateSpecialization())
16110 return false;
16111
16112 // Don't warn for OpenCL kernels.
16113 if (FD->hasAttr<DeviceKernelAttr>())
16114 return false;
16115
16116 // Don't warn on explicitly deleted functions.
16117 if (FD->isDeleted())
16118 return false;
16119
16120 // Don't warn on implicitly local functions (such as having local-typed
16121 // parameters).
16122 if (!FD->isExternallyVisible())
16123 return false;
16124
16125 // If we were able to find a potential prototype, don't warn.
16126 if (FindPossiblePrototype(FD, PossiblePrototype))
16127 return false;
16128
16129 return true;
16130}
16131
16132void
16133Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16134 const FunctionDecl *EffectiveDefinition,
16135 SkipBodyInfo *SkipBody) {
16136 const FunctionDecl *Definition = EffectiveDefinition;
16137 if (!Definition &&
16138 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16139 return;
16140
16141 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16142 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16143 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16144 // A merged copy of the same function, instantiated as a member of
16145 // the same class, is OK.
16146 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16147 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16148 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16149 return;
16150 }
16151 }
16152 }
16153
16154 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16155 return;
16156
16157 // Don't emit an error when this is redefinition of a typo-corrected
16158 // definition.
16159 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16160 return;
16161
16162 bool DefinitionVisible = false;
16163 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16164 (Definition->getFormalLinkage() == Linkage::Internal ||
16165 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16166 !Definition->getTemplateParameterLists().empty())) {
16167 SkipBody->ShouldSkip = true;
16168 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16169 if (!DefinitionVisible) {
16170 if (auto *TD = Definition->getDescribedFunctionTemplate())
16171 makeMergedDefinitionVisible(ND: TD);
16172 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16173 }
16174 return;
16175 }
16176
16177 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16178 Definition->getStorageClass() == SC_Extern)
16179 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16180 << FD << getLangOpts().CPlusPlus;
16181 else
16182 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16183
16184 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16185 FD->setInvalidDecl();
16186}
16187
16188LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16189 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16190
16191 LambdaScopeInfo *LSI = PushLambdaScope();
16192 LSI->CallOperator = CallOperator;
16193 LSI->Lambda = LambdaClass;
16194 LSI->ReturnType = CallOperator->getReturnType();
16195 // When this function is called in situation where the context of the call
16196 // operator is not entered, we set AfterParameterList to false, so that
16197 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16198 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16199 // where we would set the CurContext to the lambda operator before
16200 // substituting into it. In this case the flag needs to be true such that
16201 // tryCaptureVariable can correctly handle potential captures thereof.
16202 LSI->AfterParameterList = CurContext == CallOperator;
16203
16204 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16205 // used at the point of dealing with potential captures.
16206 //
16207 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16208 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16209 // associated. (Technically, we could recover that list from their
16210 // instantiation patterns, but for now, the GLTemplateParameterList seems
16211 // unnecessary in these cases.)
16212 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16213 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16214 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16215
16216 if (LCD == LCD_None)
16217 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16218 else if (LCD == LCD_ByCopy)
16219 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16220 else if (LCD == LCD_ByRef)
16221 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16222 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16223
16224 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16225 LSI->Mutable = !CallOperator->isConst();
16226 if (CallOperator->isExplicitObjectMemberFunction())
16227 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16228
16229 // Add the captures to the LSI so they can be noted as already
16230 // captured within tryCaptureVar.
16231 auto I = LambdaClass->field_begin();
16232 for (const auto &C : LambdaClass->captures()) {
16233 if (C.capturesVariable()) {
16234 ValueDecl *VD = C.getCapturedVar();
16235 if (VD->isInitCapture())
16236 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16237 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16238 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16239 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16240 /*EllipsisLoc*/C.isPackExpansion()
16241 ? C.getEllipsisLoc() : SourceLocation(),
16242 CaptureType: I->getType(), /*Invalid*/false);
16243
16244 } else if (C.capturesThis()) {
16245 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16246 ByCopy: C.getCaptureKind() == LCK_StarThis);
16247 } else {
16248 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16249 CaptureType: I->getType());
16250 }
16251 ++I;
16252 }
16253 return LSI;
16254}
16255
16256Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16257 SkipBodyInfo *SkipBody,
16258 FnBodyKind BodyKind) {
16259 if (!D) {
16260 // Parsing the function declaration failed in some way. Push on a fake scope
16261 // anyway so we can try to parse the function body.
16262 PushFunctionScope();
16263 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16264 return D;
16265 }
16266
16267 FunctionDecl *FD = nullptr;
16268
16269 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16270 FD = FunTmpl->getTemplatedDecl();
16271 else
16272 FD = cast<FunctionDecl>(Val: D);
16273
16274 // Do not push if it is a lambda because one is already pushed when building
16275 // the lambda in ActOnStartOfLambdaDefinition().
16276 if (!isLambdaCallOperator(DC: FD))
16277 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16278 FD);
16279
16280 // Check for defining attributes before the check for redefinition.
16281 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16282 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16283 FD->dropAttr<AliasAttr>();
16284 FD->setInvalidDecl();
16285 }
16286 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16287 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16288 FD->dropAttr<IFuncAttr>();
16289 FD->setInvalidDecl();
16290 }
16291 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16292 if (Context.getTargetInfo().getTriple().isAArch64() &&
16293 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16294 !Attr->isDefaultVersion()) {
16295 // If function multi versioning disabled skip parsing function body
16296 // defined with non-default target_version attribute
16297 if (SkipBody)
16298 SkipBody->ShouldSkip = true;
16299 return nullptr;
16300 }
16301 }
16302
16303 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16304 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16305 Ctor->isDefaultConstructor() &&
16306 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16307 // If this is an MS ABI dllexport default constructor, instantiate any
16308 // default arguments.
16309 InstantiateDefaultCtorDefaultArgs(Ctor);
16310 }
16311 }
16312
16313 // See if this is a redefinition. If 'will have body' (or similar) is already
16314 // set, then these checks were already performed when it was set.
16315 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16316 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16317 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16318
16319 // If we're skipping the body, we're done. Don't enter the scope.
16320 if (SkipBody && SkipBody->ShouldSkip)
16321 return D;
16322 }
16323
16324 // Mark this function as "will have a body eventually". This lets users to
16325 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16326 // this function.
16327 FD->setWillHaveBody();
16328
16329 // If we are instantiating a generic lambda call operator, push
16330 // a LambdaScopeInfo onto the function stack. But use the information
16331 // that's already been calculated (ActOnLambdaExpr) to prime the current
16332 // LambdaScopeInfo.
16333 // When the template operator is being specialized, the LambdaScopeInfo,
16334 // has to be properly restored so that tryCaptureVariable doesn't try
16335 // and capture any new variables. In addition when calculating potential
16336 // captures during transformation of nested lambdas, it is necessary to
16337 // have the LSI properly restored.
16338 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16339 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16340 // specialized.
16341 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16342 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16343 << /*specialization*/ 0;
16344 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16345 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16346
16347 FD->setInvalidDecl();
16348 PushFunctionScope();
16349 } else {
16350 assert(inTemplateInstantiation() &&
16351 "There should be an active template instantiation on the stack "
16352 "when instantiating a generic lambda!");
16353 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16354 }
16355 } else {
16356 // Enter a new function scope
16357 PushFunctionScope();
16358 }
16359
16360 // Builtin functions cannot be defined.
16361 if (unsigned BuiltinID = FD->getBuiltinID()) {
16362 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16363 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16364 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16365 FD->setInvalidDecl();
16366 }
16367 }
16368
16369 // The return type of a function definition must be complete (C99 6.9.1p3).
16370 // C++23 [dcl.fct.def.general]/p2
16371 // The type of [...] the return for a function definition
16372 // shall not be a (possibly cv-qualified) class type that is incomplete
16373 // or abstract within the function body unless the function is deleted.
16374 QualType ResultType = FD->getReturnType();
16375 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16376 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16377 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16378 DiagID: diag::err_func_def_incomplete_result) ||
16379 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16380 DiagID: diag::err_abstract_type_in_decl,
16381 Args: AbstractReturnType)))
16382 FD->setInvalidDecl();
16383
16384 if (FnBodyScope)
16385 PushDeclContext(S: FnBodyScope, DC: FD);
16386
16387 // Check the validity of our function parameters
16388 if (BodyKind != FnBodyKind::Delete)
16389 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16390 /*CheckParameterNames=*/true);
16391
16392 // Add non-parameter declarations already in the function to the current
16393 // scope.
16394 if (FnBodyScope) {
16395 for (Decl *NPD : FD->decls()) {
16396 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16397 if (!NonParmDecl)
16398 continue;
16399 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16400 "parameters should not be in newly created FD yet");
16401
16402 // If the decl has a name, make it accessible in the current scope.
16403 if (NonParmDecl->getDeclName())
16404 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16405
16406 // Similarly, dive into enums and fish their constants out, making them
16407 // accessible in this scope.
16408 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16409 for (auto *EI : ED->enumerators())
16410 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16411 }
16412 }
16413 }
16414
16415 // Introduce our parameters into the function scope
16416 for (auto *Param : FD->parameters()) {
16417 Param->setOwningFunction(FD);
16418
16419 // If this has an identifier, add it to the scope stack.
16420 if (Param->getIdentifier() && FnBodyScope) {
16421 CheckShadow(S: FnBodyScope, D: Param);
16422
16423 PushOnScopeChains(D: Param, S: FnBodyScope);
16424 }
16425 }
16426
16427 // C++ [module.import/6]
16428 // ...
16429 // A header unit shall not contain a definition of a non-inline function or
16430 // variable whose name has external linkage.
16431 //
16432 // Deleted and Defaulted functions are implicitly inline (but the
16433 // inline state is not set at this point, so check the BodyKind explicitly).
16434 // We choose to allow weak & selectany definitions, as they are common in
16435 // headers, and have semantics similar to inline definitions which are allowed
16436 // in header units.
16437 // FIXME: Consider an alternate location for the test where the inlined()
16438 // state is complete.
16439 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16440 !FD->isInvalidDecl() && !FD->isInlined() &&
16441 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16442 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16443 !FD->isTemplateInstantiation() &&
16444 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16445 assert(FD->isThisDeclarationADefinition());
16446 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16447 FD->setInvalidDecl();
16448 }
16449
16450 // Ensure that the function's exception specification is instantiated.
16451 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16452 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16453
16454 // dllimport cannot be applied to non-inline function definitions.
16455 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16456 !FD->isTemplateInstantiation()) {
16457 assert(!FD->hasAttr<DLLExportAttr>());
16458 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16459 FD->setInvalidDecl();
16460 return D;
16461 }
16462
16463 // Some function attributes (like OptimizeNoneAttr) need actions before
16464 // parsing body started.
16465 applyFunctionAttributesBeforeParsingBody(FD: D);
16466
16467 // We want to attach documentation to original Decl (which might be
16468 // a function template).
16469 ActOnDocumentableDecl(D);
16470 if (getCurLexicalContext()->isObjCContainer() &&
16471 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16472 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16473 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16474
16475 maybeAddDeclWithEffects(D: FD);
16476
16477 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16478 FnBodyScope) {
16479 // An implicit call expression is synthesized for functions declared with
16480 // the sycl_kernel_entry_point attribute. The call may resolve to a
16481 // function template, a member function template, or a call operator
16482 // of a variable template depending on the results of unqualified lookup
16483 // for 'sycl_kernel_launch' from the beginning of the function body.
16484 // Performing that lookup requires the stack of parsing scopes active
16485 // when the definition is parsed and is thus done here; the result is
16486 // cached in FunctionScopeInfo and used to synthesize the (possibly
16487 // unresolved) call expression after the function body has been parsed.
16488 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16489 if (!SKEPAttr->isInvalidAttr()) {
16490 ExprResult LaunchIdExpr =
16491 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16492 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16493 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16494 // treated as an error in the definition of 'FD'; treating it as an error
16495 // of the declaration would affect overload resolution which would
16496 // potentially result in additional errors. If construction of
16497 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16498 // a null pointer value below; that is expected.
16499 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16500 }
16501 }
16502
16503 return D;
16504}
16505
16506void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16507 if (!FD || FD->isInvalidDecl())
16508 return;
16509 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16510 FD = TD->getTemplatedDecl();
16511 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16512 FPOptionsOverride FPO;
16513 FPO.setDisallowOptimizations();
16514 CurFPFeatures.applyChanges(FPO);
16515 FpPragmaStack.CurrentValue =
16516 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16517 }
16518}
16519
16520void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16521 ReturnStmt **Returns = Scope->Returns.data();
16522
16523 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16524 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16525 if (!NRVOCandidate->isNRVOVariable()) {
16526 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16527 DiagID: diag::warn_not_eliding_copy_on_return);
16528 Returns[I]->setNRVOCandidate(nullptr);
16529 }
16530 }
16531 }
16532}
16533
16534bool Sema::canDelayFunctionBody(const Declarator &D) {
16535 // We can't delay parsing the body of a constexpr function template (yet).
16536 if (D.getDeclSpec().hasConstexprSpecifier())
16537 return false;
16538
16539 // We can't delay parsing the body of a function template with a deduced
16540 // return type (yet).
16541 if (D.getDeclSpec().hasAutoTypeSpec()) {
16542 // If the placeholder introduces a non-deduced trailing return type,
16543 // we can still delay parsing it.
16544 if (D.getNumTypeObjects()) {
16545 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16546 if (Outer.Kind == DeclaratorChunk::Function &&
16547 Outer.Fun.hasTrailingReturnType()) {
16548 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16549 return Ty.isNull() || !Ty->isUndeducedType();
16550 }
16551 }
16552 return false;
16553 }
16554
16555 return true;
16556}
16557
16558bool Sema::canSkipFunctionBody(Decl *D) {
16559 // We cannot skip the body of a function (or function template) which is
16560 // constexpr, since we may need to evaluate its body in order to parse the
16561 // rest of the file.
16562 // We cannot skip the body of a function with an undeduced return type,
16563 // because any callers of that function need to know the type.
16564 if (const FunctionDecl *FD = D->getAsFunction()) {
16565 if (FD->isConstexpr())
16566 return false;
16567 // We can't simply call Type::isUndeducedType here, because inside template
16568 // auto can be deduced to a dependent type, which is not considered
16569 // "undeduced".
16570 if (FD->getReturnType()->getContainedDeducedType())
16571 return false;
16572 }
16573 return Consumer.shouldSkipFunctionBody(D);
16574}
16575
16576Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16577 if (!Decl)
16578 return nullptr;
16579 if (FunctionDecl *FD = Decl->getAsFunction())
16580 FD->setHasSkippedBody();
16581 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16582 MD->setHasSkippedBody();
16583 return Decl;
16584}
16585
16586/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16587/// body.
16588class ExitFunctionBodyRAII {
16589public:
16590 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16591 ~ExitFunctionBodyRAII() {
16592 if (!IsLambda)
16593 S.PopExpressionEvaluationContext();
16594 }
16595
16596private:
16597 Sema &S;
16598 bool IsLambda = false;
16599};
16600
16601static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16602 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16603
16604 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16605 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16606 if (!Inserted)
16607 return It->second;
16608
16609 bool R = false;
16610 const BlockDecl *CurBD = BD;
16611
16612 do {
16613 R = !CurBD->doesNotEscape();
16614 if (R)
16615 break;
16616 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16617 } while (CurBD);
16618
16619 return It->second = R;
16620 };
16621
16622 // If the location where 'self' is implicitly retained is inside a escaping
16623 // block, emit a diagnostic.
16624 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16625 S.ImplicitlyRetainedSelfLocs)
16626 if (IsOrNestedInEscapingBlock(P.second))
16627 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16628 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16629}
16630
16631static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16632 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16633 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16634}
16635
16636bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16637 return methodHasName(FD, Name: "get_return_object");
16638}
16639
16640bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16641 return FD->isStatic() &&
16642 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16643}
16644
16645void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16646 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16647 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16648 return;
16649 // Allow some_promise_type::get_return_object().
16650 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16651 return;
16652 if (!FD->hasAttr<CoroWrapperAttr>())
16653 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16654}
16655
16656Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16657 bool RetainFunctionScopeInfo) {
16658 FunctionScopeInfo *FSI = getCurFunction();
16659 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16660
16661 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16662 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16663
16664 SourceLocation AnalysisLoc;
16665 if (Body)
16666 AnalysisLoc = Body->getEndLoc();
16667 else if (FD)
16668 AnalysisLoc = FD->getEndLoc();
16669 sema::AnalysisBasedWarnings::Policy WP =
16670 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16671 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16672
16673 // If we skip function body, we can't tell if a function is a coroutine.
16674 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16675 if (FSI->isCoroutine())
16676 CheckCompletedCoroutineBody(FD, Body);
16677 else
16678 CheckCoroutineWrapper(FD);
16679 }
16680
16681 // Diagnose invalid SYCL kernel entry point function declarations
16682 // and build SYCLKernelCallStmts for valid ones.
16683 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16684 SYCLKernelEntryPointAttr *SKEPAttr =
16685 FD->getAttr<SYCLKernelEntryPointAttr>();
16686 if (FD->isDefaulted()) {
16687 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16688 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16689 SKEPAttr->setInvalidAttr();
16690 } else if (FD->isDeleted()) {
16691 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16692 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16693 SKEPAttr->setInvalidAttr();
16694 } else if (FSI->isCoroutine()) {
16695 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16696 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16697 SKEPAttr->setInvalidAttr();
16698 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16699 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16700 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16701 SKEPAttr->setInvalidAttr();
16702 }
16703
16704 // Build an unresolved SYCL kernel call statement for a function template,
16705 // validate that a SYCL kernel call statement was instantiated for an
16706 // (implicit or explicit) instantiation of a function template, or otherwise
16707 // build a (resolved) SYCL kernel call statement for a non-templated
16708 // function or an explicit specialization.
16709 if (Body && !SKEPAttr->isInvalidAttr()) {
16710 StmtResult SR;
16711 if (FD->isTemplateInstantiation()) {
16712 // The function body should already be a SYCLKernelCallStmt in this
16713 // case, but might not be if there were previous errors.
16714 SR = Body;
16715 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16716 // If name lookup for a template named sycl_kernel_launch failed
16717 // earlier, don't try to build a SYCL kernel call statement as that
16718 // would cause additional errors to be issued; just proceed with the
16719 // original function body.
16720 SR = Body;
16721 } else if (FD->isTemplated()) {
16722 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16723 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16724 } else {
16725 SR = SYCL().BuildSYCLKernelCallStmt(
16726 FD, Body: cast<CompoundStmt>(Val: Body),
16727 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16728 }
16729 // If construction of the replacement body fails, just continue with the
16730 // original function body. An early error return here is not valid; the
16731 // current declaration context and function scopes must be popped before
16732 // returning.
16733 if (SR.isUsable())
16734 Body = SR.get();
16735 }
16736 }
16737
16738 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16739 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16740 if (FD->isDeletedAsWritten())
16741 Diag(Loc: SEAttr->getLocation(),
16742 DiagID: diag::err_sycl_external_invalid_deleted_function)
16743 << SEAttr;
16744 }
16745
16746 {
16747 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16748 // one is already popped when finishing the lambda in BuildLambdaExpr().
16749 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16750 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16751 if (FD) {
16752 // The function body and the DefaultedOrDeletedInfo, if present, use
16753 // the same storage; don't overwrite the latter if the former is null
16754 // (the body is initialised to null anyway, so even if the latter isn't
16755 // present, this would still be a no-op).
16756 if (Body)
16757 FD->setBody(Body);
16758 FD->setWillHaveBody(false);
16759
16760 if (getLangOpts().CPlusPlus14) {
16761 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16762 FD->getReturnType()->isUndeducedType()) {
16763 // For a function with a deduced result type to return void,
16764 // the result type as written must be 'auto' or 'decltype(auto)',
16765 // possibly cv-qualified or constrained, but not ref-qualified.
16766 if (!FD->getReturnType()->getAs<AutoType>()) {
16767 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16768 << FD->getReturnType();
16769 FD->setInvalidDecl();
16770 } else {
16771 // Falling off the end of the function is the same as 'return;'.
16772 Expr *Dummy = nullptr;
16773 if (DeduceFunctionTypeFromReturnExpr(
16774 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16775 AT: FD->getReturnType()->getAs<AutoType>()))
16776 FD->setInvalidDecl();
16777 }
16778 }
16779 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16780 // In C++11, we don't use 'auto' deduction rules for lambda call
16781 // operators because we don't support return type deduction.
16782 auto *LSI = getCurLambda();
16783 if (LSI->HasImplicitReturnType) {
16784 deduceClosureReturnType(CSI&: *LSI);
16785
16786 // C++11 [expr.prim.lambda]p4:
16787 // [...] if there are no return statements in the compound-statement
16788 // [the deduced type is] the type void
16789 QualType RetType =
16790 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16791
16792 // Update the return type to the deduced type.
16793 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16794 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16795 EPI: Proto->getExtProtoInfo()));
16796 }
16797 }
16798
16799 // If the function implicitly returns zero (like 'main') or is naked,
16800 // don't complain about missing return statements.
16801 // Clang implicitly returns 0 in C89 mode, but that's considered an
16802 // extension. The check is necessary to ensure the expected extension
16803 // warning is emitted in C89 mode.
16804 if ((FD->hasImplicitReturnZero() &&
16805 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16806 FD->hasAttr<NakedAttr>())
16807 WP.disableCheckFallThrough();
16808
16809 // MSVC permits the use of pure specifier (=0) on function definition,
16810 // defined at class scope, warn about this non-standard construct.
16811 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16812 !FD->isOutOfLine())
16813 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16814
16815 if (!FD->isInvalidDecl()) {
16816 // Don't diagnose unused parameters of defaulted, deleted or naked
16817 // functions.
16818 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16819 !FD->hasAttr<NakedAttr>())
16820 DiagnoseUnusedParameters(Parameters: FD->parameters());
16821 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16822 ReturnTy: FD->getReturnType(), D: FD);
16823
16824 // If this is a structor, we need a vtable.
16825 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16826 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16827 else if (CXXDestructorDecl *Destructor =
16828 dyn_cast<CXXDestructorDecl>(Val: FD))
16829 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16830
16831 // Try to apply the named return value optimization. We have to check
16832 // if we can do this here because lambdas keep return statements around
16833 // to deduce an implicit return type.
16834 if (FD->getReturnType()->isRecordType() &&
16835 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16836 computeNRVO(Body, Scope: FSI);
16837 }
16838
16839 // GNU warning -Wmissing-prototypes:
16840 // Warn if a global function is defined without a previous
16841 // prototype declaration. This warning is issued even if the
16842 // definition itself provides a prototype. The aim is to detect
16843 // global functions that fail to be declared in header files.
16844 const FunctionDecl *PossiblePrototype = nullptr;
16845 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16846 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16847
16848 if (PossiblePrototype) {
16849 // We found a declaration that is not a prototype,
16850 // but that could be a zero-parameter prototype
16851 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16852 TypeLoc TL = TI->getTypeLoc();
16853 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16854 Diag(Loc: PossiblePrototype->getLocation(),
16855 DiagID: diag::note_declaration_not_a_prototype)
16856 << (FD->getNumParams() != 0)
16857 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16858 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16859 : FixItHint{});
16860 }
16861 } else {
16862 // Returns true if the token beginning at this Loc is `const`.
16863 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16864 const LangOptions &LangOpts) {
16865 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16866 if (LocInfo.first.isInvalid())
16867 return false;
16868
16869 bool Invalid = false;
16870 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16871 if (Invalid)
16872 return false;
16873
16874 if (LocInfo.second > Buffer.size())
16875 return false;
16876
16877 const char *LexStart = Buffer.data() + LocInfo.second;
16878 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16879
16880 return StartTok.consume_front(Prefix: "const") &&
16881 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16882 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16883 };
16884
16885 auto findBeginLoc = [&]() {
16886 // If the return type has `const` qualifier, we want to insert
16887 // `static` before `const` (and not before the typename).
16888 if ((FD->getReturnType()->isAnyPointerType() &&
16889 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16890 FD->getReturnType().isConstQualified()) {
16891 // But only do this if we can determine where the `const` is.
16892
16893 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16894 getLangOpts()))
16895
16896 return FD->getBeginLoc();
16897 }
16898 return FD->getTypeSpecStartLoc();
16899 };
16900 Diag(Loc: FD->getTypeSpecStartLoc(),
16901 DiagID: diag::note_static_for_internal_linkage)
16902 << /* function */ 1
16903 << (FD->getStorageClass() == SC_None
16904 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16905 : FixItHint{});
16906 }
16907 }
16908
16909 // We might not have found a prototype because we didn't wish to warn on
16910 // the lack of a missing prototype. Try again without the checks for
16911 // whether we want to warn on the missing prototype.
16912 if (!PossiblePrototype)
16913 (void)FindPossiblePrototype(FD, PossiblePrototype);
16914
16915 // If the function being defined does not have a prototype, then we may
16916 // need to diagnose it as changing behavior in C23 because we now know
16917 // whether the function accepts arguments or not. This only handles the
16918 // case where the definition has no prototype but does have parameters
16919 // and either there is no previous potential prototype, or the previous
16920 // potential prototype also has no actual prototype. This handles cases
16921 // like:
16922 // void f(); void f(a) int a; {}
16923 // void g(a) int a; {}
16924 // See MergeFunctionDecl() for other cases of the behavior change
16925 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16926 // type without a prototype.
16927 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16928 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16929 !PossiblePrototype->isImplicit()))) {
16930 // The function definition has parameters, so this will change behavior
16931 // in C23. If there is a possible prototype, it comes before the
16932 // function definition.
16933 // FIXME: The declaration may have already been diagnosed as being
16934 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16935 // there's no way to test for the "changes behavior" condition in
16936 // SemaType.cpp when forming the declaration's function type. So, we do
16937 // this awkward dance instead.
16938 //
16939 // If we have a possible prototype and it declares a function with a
16940 // prototype, we don't want to diagnose it; if we have a possible
16941 // prototype and it has no prototype, it may have already been
16942 // diagnosed in SemaType.cpp as deprecated depending on whether
16943 // -Wstrict-prototypes is enabled. If we already warned about it being
16944 // deprecated, add a note that it also changes behavior. If we didn't
16945 // warn about it being deprecated (because the diagnostic is not
16946 // enabled), warn now that it is deprecated and changes behavior.
16947
16948 // This K&R C function definition definitely changes behavior in C23,
16949 // so diagnose it.
16950 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16951 << /*definition*/ 1 << /* not supported in C23 */ 0;
16952
16953 // If we have a possible prototype for the function which is a user-
16954 // visible declaration, we already tested that it has no prototype.
16955 // This will change behavior in C23. This gets a warning rather than a
16956 // note because it's the same behavior-changing problem as with the
16957 // definition.
16958 if (PossiblePrototype)
16959 Diag(Loc: PossiblePrototype->getLocation(),
16960 DiagID: diag::warn_non_prototype_changes_behavior)
16961 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16962 << /*definition*/ 1;
16963 }
16964
16965 // Warn on CPUDispatch with an actual body.
16966 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16967 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16968 if (!CmpndBody->body_empty())
16969 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16970 DiagID: diag::warn_dispatch_body_ignored);
16971
16972 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16973 const CXXMethodDecl *KeyFunction;
16974 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16975 MD->isVirtual() &&
16976 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16977 MD == KeyFunction->getCanonicalDecl()) {
16978 // Update the key-function state if necessary for this ABI.
16979 if (FD->isInlined() &&
16980 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16981 Context.setNonKeyFunction(MD);
16982
16983 // If the newly-chosen key function is already defined, then we
16984 // need to mark the vtable as used retroactively.
16985 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16986 const FunctionDecl *Definition;
16987 if (KeyFunction && KeyFunction->isDefined(Definition))
16988 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16989 } else {
16990 // We just defined they key function; mark the vtable as used.
16991 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16992 }
16993 }
16994 }
16995
16996 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16997 "Function parsing confused");
16998 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16999 assert(MD == getCurMethodDecl() && "Method parsing confused");
17000 MD->setBody(Body);
17001 if (!MD->isInvalidDecl()) {
17002 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17003 ReturnTy: MD->getReturnType(), D: MD);
17004
17005 if (Body)
17006 computeNRVO(Body, Scope: FSI);
17007 }
17008 if (FSI->ObjCShouldCallSuper) {
17009 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17010 << MD->getSelector().getAsString();
17011 FSI->ObjCShouldCallSuper = false;
17012 }
17013 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17014 const ObjCMethodDecl *InitMethod = nullptr;
17015 bool isDesignated =
17016 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17017 assert(isDesignated && InitMethod);
17018 (void)isDesignated;
17019
17020 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17021 auto IFace = MD->getClassInterface();
17022 if (!IFace)
17023 return false;
17024 auto SuperD = IFace->getSuperClass();
17025 if (!SuperD)
17026 return false;
17027 return SuperD->getIdentifier() ==
17028 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17029 };
17030 // Don't issue this warning for unavailable inits or direct subclasses
17031 // of NSObject.
17032 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17033 Diag(Loc: MD->getLocation(),
17034 DiagID: diag::warn_objc_designated_init_missing_super_call);
17035 Diag(Loc: InitMethod->getLocation(),
17036 DiagID: diag::note_objc_designated_init_marked_here);
17037 }
17038 FSI->ObjCWarnForNoDesignatedInitChain = false;
17039 }
17040 if (FSI->ObjCWarnForNoInitDelegation) {
17041 // Don't issue this warning for unavailable inits.
17042 if (!MD->isUnavailable())
17043 Diag(Loc: MD->getLocation(),
17044 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17045 FSI->ObjCWarnForNoInitDelegation = false;
17046 }
17047
17048 diagnoseImplicitlyRetainedSelf(S&: *this);
17049 } else {
17050 // Parsing the function declaration failed in some way. Pop the fake scope
17051 // we pushed on.
17052 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17053 return nullptr;
17054 }
17055
17056 if (Body) {
17057 if (FSI->HasPotentialAvailabilityViolations)
17058 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17059 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17060 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17061 }
17062
17063 assert(!FSI->ObjCShouldCallSuper &&
17064 "This should only be set for ObjC methods, which should have been "
17065 "handled in the block above.");
17066
17067 // Verify and clean out per-function state.
17068 if (Body && (!FD || !FD->isDefaulted())) {
17069 // C++ constructors that have function-try-blocks can't have return
17070 // statements in the handlers of that block. (C++ [except.handle]p14)
17071 // Verify this.
17072 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17073 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17074
17075 // Verify that gotos and switch cases don't jump into scopes illegally.
17076 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17077 DiagnoseInvalidJumps(Body);
17078
17079 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17080 if (!Destructor->getParent()->isDependentType())
17081 CheckDestructor(Destructor);
17082
17083 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17084 Record: Destructor->getParent());
17085 }
17086
17087 // If any errors have occurred, clear out any temporaries that may have
17088 // been leftover. This ensures that these temporaries won't be picked up
17089 // for deletion in some later function.
17090 if (hasUncompilableErrorOccurred() ||
17091 hasAnyUnrecoverableErrorsInThisFunction() ||
17092 getDiagnostics().getSuppressAllDiagnostics()) {
17093 DiscardCleanupsInEvaluationContext();
17094 }
17095 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17096 // Since the body is valid, issue any analysis-based warnings that are
17097 // enabled.
17098 ActivePolicy = &WP;
17099 }
17100
17101 if (!IsInstantiation && FD &&
17102 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17103 !FD->isInvalidDecl() &&
17104 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17105 FD->setInvalidDecl();
17106
17107 if (FD && FD->hasAttr<NakedAttr>()) {
17108 for (const Stmt *S : Body->children()) {
17109 // Allow local register variables without initializer as they don't
17110 // require prologue.
17111 bool RegisterVariables = false;
17112 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17113 for (const auto *Decl : DS->decls()) {
17114 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17115 RegisterVariables =
17116 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17117 if (!RegisterVariables)
17118 break;
17119 }
17120 }
17121 }
17122 if (RegisterVariables)
17123 continue;
17124 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17125 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17126 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17127 FD->setInvalidDecl();
17128 break;
17129 }
17130 }
17131 }
17132
17133 assert(ExprCleanupObjects.size() ==
17134 ExprEvalContexts.back().NumCleanupObjects &&
17135 "Leftover temporaries in function");
17136 assert(!Cleanup.exprNeedsCleanups() &&
17137 "Unaccounted cleanups in function");
17138 assert(MaybeODRUseExprs.empty() &&
17139 "Leftover expressions for odr-use checking");
17140 }
17141 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17142 // the declaration context below. Otherwise, we're unable to transform
17143 // 'this' expressions when transforming immediate context functions.
17144
17145 if (FD)
17146 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17147
17148 if (!IsInstantiation)
17149 PopDeclContext();
17150
17151 if (!RetainFunctionScopeInfo)
17152 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17153 // If any errors have occurred, clear out any temporaries that may have
17154 // been leftover. This ensures that these temporaries won't be picked up for
17155 // deletion in some later function.
17156 if (hasUncompilableErrorOccurred()) {
17157 DiscardCleanupsInEvaluationContext();
17158 }
17159
17160 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17161 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17162 auto ES = getEmissionStatus(Decl: FD);
17163 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17164 ES == Sema::FunctionEmissionStatus::Unknown)
17165 DeclsToCheckForDeferredDiags.insert(X: FD);
17166 }
17167
17168 if (FD && !FD->isDeleted())
17169 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17170
17171 return dcl;
17172}
17173
17174/// When we finish delayed parsing of an attribute, we must attach it to the
17175/// relevant Decl.
17176void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17177 ParsedAttributes &Attrs) {
17178 // Always attach attributes to the underlying decl.
17179 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17180 D = TD->getTemplatedDecl();
17181 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17182 ProcessAPINotes(D);
17183
17184 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17185 if (Method->isStatic())
17186 checkThisInStaticMemberFunctionAttributes(Method);
17187}
17188
17189NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17190 IdentifierInfo &II, Scope *S) {
17191 // It is not valid to implicitly define a function in C23.
17192 assert(LangOpts.implicitFunctionsAllowed() &&
17193 "Implicit function declarations aren't allowed in this language mode");
17194
17195 // Find the scope in which the identifier is injected and the corresponding
17196 // DeclContext.
17197 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17198 // In that case, we inject the declaration into the translation unit scope
17199 // instead.
17200 Scope *BlockScope = S;
17201 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17202 BlockScope = BlockScope->getParent();
17203
17204 // Loop until we find a DeclContext that is either a function/method or the
17205 // translation unit, which are the only two valid places to implicitly define
17206 // a function. This avoids accidentally defining the function within a tag
17207 // declaration, for example.
17208 Scope *ContextScope = BlockScope;
17209 while (!ContextScope->getEntity() ||
17210 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17211 !ContextScope->getEntity()->isTranslationUnit()))
17212 ContextScope = ContextScope->getParent();
17213 ContextRAII SavedContext(*this, ContextScope->getEntity());
17214
17215 // Before we produce a declaration for an implicitly defined
17216 // function, see whether there was a locally-scoped declaration of
17217 // this name as a function or variable. If so, use that
17218 // (non-visible) declaration, and complain about it.
17219 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17220 if (ExternCPrev) {
17221 // We still need to inject the function into the enclosing block scope so
17222 // that later (non-call) uses can see it.
17223 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17224
17225 // C89 footnote 38:
17226 // If in fact it is not defined as having type "function returning int",
17227 // the behavior is undefined.
17228 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17229 !Context.typesAreCompatible(
17230 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17231 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17232 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17233 << ExternCPrev << !getLangOpts().C99;
17234 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17235 return ExternCPrev;
17236 }
17237 }
17238
17239 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17240 unsigned diag_id;
17241 if (II.getName().starts_with(Prefix: "__builtin_"))
17242 diag_id = diag::warn_builtin_unknown;
17243 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17244 else if (getLangOpts().C99)
17245 diag_id = diag::ext_implicit_function_decl_c99;
17246 else
17247 diag_id = diag::warn_implicit_function_decl;
17248
17249 TypoCorrection Corrected;
17250 // Because typo correction is expensive, only do it if the implicit
17251 // function declaration is going to be treated as an error.
17252 //
17253 // Perform the correction before issuing the main diagnostic, as some
17254 // consumers use typo-correction callbacks to enhance the main diagnostic.
17255 if (S && !ExternCPrev &&
17256 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17257 DeclFilterCCC<FunctionDecl> CCC{};
17258 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17259 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17260 }
17261
17262 Diag(Loc, DiagID: diag_id) << &II;
17263 if (Corrected) {
17264 // If the correction is going to suggest an implicitly defined function,
17265 // skip the correction as not being a particularly good idea.
17266 bool Diagnose = true;
17267 if (const auto *D = Corrected.getCorrectionDecl())
17268 Diagnose = !D->isImplicit();
17269 if (Diagnose)
17270 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17271 /*ErrorRecovery*/ false);
17272 }
17273
17274 // If we found a prior declaration of this function, don't bother building
17275 // another one. We've already pushed that one into scope, so there's nothing
17276 // more to do.
17277 if (ExternCPrev)
17278 return ExternCPrev;
17279
17280 // Set a Declarator for the implicit definition: int foo();
17281 const char *Dummy;
17282 AttributeFactory attrFactory;
17283 DeclSpec DS(attrFactory);
17284 unsigned DiagID;
17285 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17286 Policy: Context.getPrintingPolicy());
17287 (void)Error; // Silence warning.
17288 assert(!Error && "Error setting up implicit decl!");
17289 SourceLocation NoLoc;
17290 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17291 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17292 /*IsAmbiguous=*/false,
17293 /*LParenLoc=*/NoLoc,
17294 /*Params=*/nullptr,
17295 /*NumParams=*/0,
17296 /*EllipsisLoc=*/NoLoc,
17297 /*RParenLoc=*/NoLoc,
17298 /*RefQualifierIsLvalueRef=*/true,
17299 /*RefQualifierLoc=*/NoLoc,
17300 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17301 /*ESpecRange=*/SourceRange(),
17302 /*Exceptions=*/nullptr,
17303 /*ExceptionRanges=*/nullptr,
17304 /*NumExceptions=*/0,
17305 /*NoexceptExpr=*/nullptr,
17306 /*ExceptionSpecTokens=*/nullptr,
17307 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17308 TheDeclarator&: D),
17309 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17310 D.SetIdentifier(Id: &II, IdLoc: Loc);
17311
17312 // Insert this function into the enclosing block scope.
17313 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17314 FD->setImplicit();
17315
17316 AddKnownFunctionAttributes(FD);
17317
17318 return FD;
17319}
17320
17321void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17322 FunctionDecl *FD) {
17323 if (FD->isInvalidDecl())
17324 return;
17325
17326 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17327 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17328 return;
17329
17330 UnsignedOrNone AlignmentParam = std::nullopt;
17331 bool IsNothrow = false;
17332 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17333 return;
17334
17335 // C++2a [basic.stc.dynamic.allocation]p4:
17336 // An allocation function that has a non-throwing exception specification
17337 // indicates failure by returning a null pointer value. Any other allocation
17338 // function never returns a null pointer value and indicates failure only by
17339 // throwing an exception [...]
17340 //
17341 // However, -fcheck-new invalidates this possible assumption, so don't add
17342 // NonNull when that is enabled.
17343 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17344 !getLangOpts().CheckNew)
17345 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17346
17347 // C++2a [basic.stc.dynamic.allocation]p2:
17348 // An allocation function attempts to allocate the requested amount of
17349 // storage. [...] If the request succeeds, the value returned by a
17350 // replaceable allocation function is a [...] pointer value p0 different
17351 // from any previously returned value p1 [...]
17352 //
17353 // However, this particular information is being added in codegen,
17354 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17355
17356 // C++2a [basic.stc.dynamic.allocation]p2:
17357 // An allocation function attempts to allocate the requested amount of
17358 // storage. If it is successful, it returns the address of the start of a
17359 // block of storage whose length in bytes is at least as large as the
17360 // requested size.
17361 if (!FD->hasAttr<AllocSizeAttr>()) {
17362 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17363 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17364 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17365 }
17366
17367 // C++2a [basic.stc.dynamic.allocation]p3:
17368 // For an allocation function [...], the pointer returned on a successful
17369 // call shall represent the address of storage that is aligned as follows:
17370 // (3.1) If the allocation function takes an argument of type
17371 // std​::​align_­val_­t, the storage will have the alignment
17372 // specified by the value of this argument.
17373 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17374 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17375 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17376 }
17377
17378 // FIXME:
17379 // C++2a [basic.stc.dynamic.allocation]p3:
17380 // For an allocation function [...], the pointer returned on a successful
17381 // call shall represent the address of storage that is aligned as follows:
17382 // (3.2) Otherwise, if the allocation function is named operator new[],
17383 // the storage is aligned for any object that does not have
17384 // new-extended alignment ([basic.align]) and is no larger than the
17385 // requested size.
17386 // (3.3) Otherwise, the storage is aligned for any object that does not
17387 // have new-extended alignment and is of the requested size.
17388}
17389
17390void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17391 if (FD->isInvalidDecl())
17392 return;
17393
17394 // If this is a built-in function, map its builtin attributes to
17395 // actual attributes.
17396 if (unsigned BuiltinID = FD->getBuiltinID()) {
17397 // Handle printf-formatting attributes.
17398 unsigned FormatIdx;
17399 bool HasVAListArg;
17400 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17401 if (!FD->hasAttr<FormatAttr>()) {
17402 const char *fmt = "printf";
17403 unsigned int NumParams = FD->getNumParams();
17404 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17405 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17406 fmt = "NSString";
17407 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17408 Type: &Context.Idents.get(Name: fmt),
17409 FormatIdx: FormatIdx+1,
17410 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17411 Range: FD->getLocation()));
17412 }
17413 }
17414 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17415 HasVAListArg)) {
17416 if (!FD->hasAttr<FormatAttr>())
17417 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17418 Type: &Context.Idents.get(Name: "scanf"),
17419 FormatIdx: FormatIdx+1,
17420 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17421 Range: FD->getLocation()));
17422 }
17423
17424 // Handle automatically recognized callbacks.
17425 SmallVector<int, 4> Encoding;
17426 if (!FD->hasAttr<CallbackAttr>() &&
17427 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17428 FD->addAttr(A: CallbackAttr::CreateImplicit(
17429 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17430
17431 // Mark const if we don't care about errno and/or floating point exceptions
17432 // that are the only thing preventing the function from being const. This
17433 // allows IRgen to use LLVM intrinsics for such functions.
17434 bool NoExceptions =
17435 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17436 bool ConstWithoutErrnoAndExceptions =
17437 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17438 bool ConstWithoutExceptions =
17439 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17440 if (!FD->hasAttr<ConstAttr>() &&
17441 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17442 (!ConstWithoutErrnoAndExceptions ||
17443 (!getLangOpts().MathErrno && NoExceptions)) &&
17444 (!ConstWithoutExceptions || NoExceptions))
17445 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17446
17447 // We make "fma" on GNU or Windows const because we know it does not set
17448 // errno in those environments even though it could set errno based on the
17449 // C standard.
17450 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17451 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17452 !FD->hasAttr<ConstAttr>()) {
17453 switch (BuiltinID) {
17454 case Builtin::BI__builtin_fma:
17455 case Builtin::BI__builtin_fmaf:
17456 case Builtin::BI__builtin_fmal:
17457 case Builtin::BIfma:
17458 case Builtin::BIfmaf:
17459 case Builtin::BIfmal:
17460 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17461 break;
17462 default:
17463 break;
17464 }
17465 }
17466
17467 SmallVector<int, 4> Indxs;
17468 Builtin::Info::NonNullMode OptMode;
17469 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17470 !FD->hasAttr<NonNullAttr>()) {
17471 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17472 for (int I : Indxs) {
17473 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17474 QualType T = PVD->getType();
17475 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17476 PVD->setType(T);
17477 }
17478 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17479 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17480 for (int I : Indxs)
17481 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17482 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17483 ArgsSize: ParamIndxs.size()));
17484 }
17485 }
17486 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17487 !FD->hasAttr<ReturnsTwiceAttr>())
17488 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17489 Range: FD->getLocation()));
17490 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17491 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17492 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17493 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17494 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17495 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17496 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17497 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17498 // Add the appropriate attribute, depending on the CUDA compilation mode
17499 // and which target the builtin belongs to. For example, during host
17500 // compilation, aux builtins are __device__, while the rest are __host__.
17501 if (getLangOpts().CUDAIsDevice !=
17502 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17503 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17504 else
17505 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17506 }
17507
17508 // Add known guaranteed alignment for allocation functions.
17509 switch (BuiltinID) {
17510 case Builtin::BImemalign:
17511 case Builtin::BIaligned_alloc:
17512 if (!FD->hasAttr<AllocAlignAttr>())
17513 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17514 Range: FD->getLocation()));
17515 break;
17516 default:
17517 break;
17518 }
17519
17520 // Add allocsize attribute for allocation functions.
17521 switch (BuiltinID) {
17522 case Builtin::BIcalloc:
17523 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17524 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17525 break;
17526 case Builtin::BImemalign:
17527 case Builtin::BIaligned_alloc:
17528 case Builtin::BIrealloc:
17529 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17530 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17531 break;
17532 case Builtin::BImalloc:
17533 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17534 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17535 break;
17536 default:
17537 break;
17538 }
17539 }
17540
17541 LazyProcessLifetimeCaptureByParams(FD);
17542 inferLifetimeBoundAttribute(FD);
17543 inferLifetimeCaptureByAttribute(FD);
17544 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17545
17546 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17547 // throw, add an implicit nothrow attribute to any extern "C" function we come
17548 // across.
17549 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17550 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17551 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17552 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17553 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17554 }
17555
17556 IdentifierInfo *Name = FD->getIdentifier();
17557 if (!Name)
17558 return;
17559 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17560 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17561 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17562 LinkageSpecLanguageIDs::C)) {
17563 // Okay: this could be a libc/libm/Objective-C function we know
17564 // about.
17565 } else
17566 return;
17567
17568 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17569 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17570 // target-specific builtins, perhaps?
17571 if (!FD->hasAttr<FormatAttr>())
17572 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17573 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17574 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17575 Range: FD->getLocation()));
17576 }
17577
17578 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17579 // We already have a __builtin___CFStringMakeConstantString,
17580 // but builds that use -fno-constant-cfstrings don't go through that.
17581 if (!FD->hasAttr<FormatArgAttr>())
17582 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17583 Range: FD->getLocation()));
17584 }
17585}
17586
17587TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17588 TypeSourceInfo *TInfo) {
17589 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17590 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17591
17592 if (!TInfo) {
17593 assert(D.isInvalidType() && "no declarator info for valid type");
17594 TInfo = Context.getTrivialTypeSourceInfo(T);
17595 }
17596
17597 // Scope manipulation handled by caller.
17598 TypedefDecl *NewTD =
17599 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17600 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17601
17602 // Bail out immediately if we have an invalid declaration.
17603 if (D.isInvalidType()) {
17604 NewTD->setInvalidDecl();
17605 return NewTD;
17606 }
17607
17608 if (D.getDeclSpec().isModulePrivateSpecified()) {
17609 if (CurContext->isFunctionOrMethod())
17610 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17611 << 2 << NewTD
17612 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17613 << FixItHint::CreateRemoval(
17614 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17615 else
17616 NewTD->setModulePrivate();
17617 }
17618
17619 // C++ [dcl.typedef]p8:
17620 // If the typedef declaration defines an unnamed class (or
17621 // enum), the first typedef-name declared by the declaration
17622 // to be that class type (or enum type) is used to denote the
17623 // class type (or enum type) for linkage purposes only.
17624 // We need to check whether the type was declared in the declaration.
17625 switch (D.getDeclSpec().getTypeSpecType()) {
17626 case TST_enum:
17627 case TST_struct:
17628 case TST_interface:
17629 case TST_union:
17630 case TST_class: {
17631 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17632 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17633 break;
17634 }
17635
17636 default:
17637 break;
17638 }
17639
17640 return NewTD;
17641}
17642
17643bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17644 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17645 QualType T = TI->getType();
17646
17647 if (T->isDependentType())
17648 return false;
17649
17650 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17651 // integral type; any cv-qualification is ignored.
17652 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17653 // non-atomic version of the type specified by the type specifiers in the
17654 // specifier qualifier list.
17655 // Because of how odd C's rule is, we'll let the user know that operations
17656 // involving the enumeration type will be non-atomic.
17657 if (T->isAtomicType())
17658 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17659
17660 Qualifiers Q = T.getQualifiers();
17661 std::optional<unsigned> QualSelect;
17662 if (Q.hasConst() && Q.hasVolatile())
17663 QualSelect = diag::CVQualList::Both;
17664 else if (Q.hasConst())
17665 QualSelect = diag::CVQualList::Const;
17666 else if (Q.hasVolatile())
17667 QualSelect = diag::CVQualList::Volatile;
17668
17669 if (QualSelect)
17670 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17671
17672 T = T.getAtomicUnqualifiedType();
17673
17674 // This doesn't use 'isIntegralType' despite the error message mentioning
17675 // integral type because isIntegralType would also allow enum types in C.
17676 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17677 if (BT->isInteger())
17678 return false;
17679
17680 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17681 << T << T->isBitIntType();
17682}
17683
17684bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17685 QualType EnumUnderlyingTy, bool IsFixed,
17686 const EnumDecl *Prev) {
17687 if (IsScoped != Prev->isScoped()) {
17688 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17689 << Prev->isScoped();
17690 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17691 return true;
17692 }
17693
17694 if (IsFixed && Prev->isFixed()) {
17695 if (!EnumUnderlyingTy->isDependentType() &&
17696 !Prev->getIntegerType()->isDependentType() &&
17697 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17698 T2: Prev->getIntegerType())) {
17699 // TODO: Highlight the underlying type of the redeclaration.
17700 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17701 << EnumUnderlyingTy << Prev->getIntegerType();
17702 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17703 << Prev->getIntegerTypeRange();
17704 return true;
17705 }
17706 } else if (IsFixed != Prev->isFixed()) {
17707 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17708 << Prev->isFixed();
17709 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17710 return true;
17711 }
17712
17713 return false;
17714}
17715
17716/// Get diagnostic %select index for tag kind for
17717/// redeclaration diagnostic message.
17718/// WARNING: Indexes apply to particular diagnostics only!
17719///
17720/// \returns diagnostic %select index.
17721static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17722 switch (Tag) {
17723 case TagTypeKind::Struct:
17724 return 0;
17725 case TagTypeKind::Interface:
17726 return 1;
17727 case TagTypeKind::Class:
17728 return 2;
17729 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17730 }
17731}
17732
17733/// Determine if tag kind is a class-key compatible with
17734/// class for redeclaration (class, struct, or __interface).
17735///
17736/// \returns true iff the tag kind is compatible.
17737static bool isClassCompatTagKind(TagTypeKind Tag)
17738{
17739 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17740 Tag == TagTypeKind::Interface;
17741}
17742
17743NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17744 if (isa<TypedefDecl>(Val: PrevDecl))
17745 return NonTagKind::Typedef;
17746 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17747 return NonTagKind::TypeAlias;
17748 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17749 return NonTagKind::Template;
17750 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17751 return NonTagKind::TypeAliasTemplate;
17752 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17753 return NonTagKind::TemplateTemplateArgument;
17754 switch (TTK) {
17755 case TagTypeKind::Struct:
17756 case TagTypeKind::Interface:
17757 case TagTypeKind::Class:
17758 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17759 : NonTagKind::NonStruct;
17760 case TagTypeKind::Union:
17761 return NonTagKind::NonUnion;
17762 case TagTypeKind::Enum:
17763 return NonTagKind::NonEnum;
17764 }
17765 llvm_unreachable("invalid TTK");
17766}
17767
17768bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17769 TagTypeKind NewTag, bool isDefinition,
17770 SourceLocation NewTagLoc,
17771 const IdentifierInfo *Name) {
17772 // C++ [dcl.type.elab]p3:
17773 // The class-key or enum keyword present in the
17774 // elaborated-type-specifier shall agree in kind with the
17775 // declaration to which the name in the elaborated-type-specifier
17776 // refers. This rule also applies to the form of
17777 // elaborated-type-specifier that declares a class-name or
17778 // friend class since it can be construed as referring to the
17779 // definition of the class. Thus, in any
17780 // elaborated-type-specifier, the enum keyword shall be used to
17781 // refer to an enumeration (7.2), the union class-key shall be
17782 // used to refer to a union (clause 9), and either the class or
17783 // struct class-key shall be used to refer to a class (clause 9)
17784 // declared using the class or struct class-key.
17785 TagTypeKind OldTag = Previous->getTagKind();
17786 if (OldTag != NewTag &&
17787 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17788 return false;
17789
17790 // Tags are compatible, but we might still want to warn on mismatched tags.
17791 // Non-class tags can't be mismatched at this point.
17792 if (!isClassCompatTagKind(Tag: NewTag))
17793 return true;
17794
17795 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17796 // by our warning analysis. We don't want to warn about mismatches with (eg)
17797 // declarations in system headers that are designed to be specialized, but if
17798 // a user asks us to warn, we should warn if their code contains mismatched
17799 // declarations.
17800 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17801 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17802 Loc);
17803 };
17804 if (IsIgnoredLoc(NewTagLoc))
17805 return true;
17806
17807 auto IsIgnored = [&](const TagDecl *Tag) {
17808 return IsIgnoredLoc(Tag->getLocation());
17809 };
17810 while (IsIgnored(Previous)) {
17811 Previous = Previous->getPreviousDecl();
17812 if (!Previous)
17813 return true;
17814 OldTag = Previous->getTagKind();
17815 }
17816
17817 bool isTemplate = false;
17818 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17819 isTemplate = Record->getDescribedClassTemplate();
17820
17821 if (inTemplateInstantiation()) {
17822 if (OldTag != NewTag) {
17823 // In a template instantiation, do not offer fix-its for tag mismatches
17824 // since they usually mess up the template instead of fixing the problem.
17825 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17826 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17827 << getRedeclDiagFromTagKind(Tag: OldTag);
17828 // FIXME: Note previous location?
17829 }
17830 return true;
17831 }
17832
17833 if (isDefinition) {
17834 // On definitions, check all previous tags and issue a fix-it for each
17835 // one that doesn't match the current tag.
17836 if (Previous->getDefinition()) {
17837 // Don't suggest fix-its for redefinitions.
17838 return true;
17839 }
17840
17841 bool previousMismatch = false;
17842 for (const TagDecl *I : Previous->redecls()) {
17843 if (I->getTagKind() != NewTag) {
17844 // Ignore previous declarations for which the warning was disabled.
17845 if (IsIgnored(I))
17846 continue;
17847
17848 if (!previousMismatch) {
17849 previousMismatch = true;
17850 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17851 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17852 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17853 }
17854 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17855 << getRedeclDiagFromTagKind(Tag: NewTag)
17856 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17857 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17858 }
17859 }
17860 return true;
17861 }
17862
17863 // Identify the prevailing tag kind: this is the kind of the definition (if
17864 // there is a non-ignored definition), or otherwise the kind of the prior
17865 // (non-ignored) declaration.
17866 const TagDecl *PrevDef = Previous->getDefinition();
17867 if (PrevDef && IsIgnored(PrevDef))
17868 PrevDef = nullptr;
17869 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17870 if (Redecl->getTagKind() != NewTag) {
17871 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17872 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17873 << getRedeclDiagFromTagKind(Tag: OldTag);
17874 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17875
17876 // If there is a previous definition, suggest a fix-it.
17877 if (PrevDef) {
17878 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17879 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17880 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17881 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17882 }
17883 }
17884
17885 return true;
17886}
17887
17888/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17889/// from an outer enclosing namespace or file scope inside a friend declaration.
17890/// This should provide the commented out code in the following snippet:
17891/// namespace N {
17892/// struct X;
17893/// namespace M {
17894/// struct Y { friend struct /*N::*/ X; };
17895/// }
17896/// }
17897static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17898 SourceLocation NameLoc) {
17899 // While the decl is in a namespace, do repeated lookup of that name and see
17900 // if we get the same namespace back. If we do not, continue until
17901 // translation unit scope, at which point we have a fully qualified NNS.
17902 SmallVector<IdentifierInfo *, 4> Namespaces;
17903 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17904 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17905 // This tag should be declared in a namespace, which can only be enclosed by
17906 // other namespaces. Bail if there's an anonymous namespace in the chain.
17907 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17908 if (!Namespace || Namespace->isAnonymousNamespace())
17909 return FixItHint();
17910 IdentifierInfo *II = Namespace->getIdentifier();
17911 Namespaces.push_back(Elt: II);
17912 NamedDecl *Lookup = SemaRef.LookupSingleName(
17913 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17914 if (Lookup == Namespace)
17915 break;
17916 }
17917
17918 // Once we have all the namespaces, reverse them to go outermost first, and
17919 // build an NNS.
17920 SmallString<64> Insertion;
17921 llvm::raw_svector_ostream OS(Insertion);
17922 if (DC->isTranslationUnit())
17923 OS << "::";
17924 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17925 for (auto *II : Namespaces)
17926 OS << II->getName() << "::";
17927 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17928}
17929
17930/// Determine whether a tag originally declared in context \p OldDC can
17931/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17932/// found a declaration in \p OldDC as a previous decl, perhaps through a
17933/// using-declaration).
17934static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17935 DeclContext *NewDC) {
17936 OldDC = OldDC->getRedeclContext();
17937 NewDC = NewDC->getRedeclContext();
17938
17939 if (OldDC->Equals(DC: NewDC))
17940 return true;
17941
17942 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17943 // encloses the other).
17944 if (S.getLangOpts().MSVCCompat &&
17945 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17946 return true;
17947
17948 return false;
17949}
17950
17951DeclResult
17952Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17953 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17954 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17955 SourceLocation ModulePrivateLoc,
17956 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17957 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17958 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17959 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17960 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17961 // If this is not a definition, it must have a name.
17962 IdentifierInfo *OrigName = Name;
17963 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17964 "Nameless record must be a definition!");
17965 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17966
17967 OwnedDecl = false;
17968 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17969 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17970
17971 // FIXME: Check member specializations more carefully.
17972 bool isMemberSpecialization = false;
17973 bool IsInjectedClassName = false;
17974 bool Invalid = false;
17975
17976 // We only need to do this matching if we have template parameters
17977 // or a scope specifier, which also conveniently avoids this work
17978 // for non-C++ cases.
17979 if (TemplateParameterLists.size() > 0 ||
17980 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17981 TemplateParameterList *TemplateParams =
17982 MatchTemplateParametersToScopeSpecifier(
17983 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17984 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17985
17986 // C++23 [dcl.type.elab] p2:
17987 // If an elaborated-type-specifier is the sole constituent of a
17988 // declaration, the declaration is ill-formed unless it is an explicit
17989 // specialization, an explicit instantiation or it has one of the
17990 // following forms: [...]
17991 // C++23 [dcl.enum] p1:
17992 // If the enum-head-name of an opaque-enum-declaration contains a
17993 // nested-name-specifier, the declaration shall be an explicit
17994 // specialization.
17995 //
17996 // FIXME: Class template partial specializations can be forward declared
17997 // per CWG2213, but the resolution failed to allow qualified forward
17998 // declarations. This is almost certainly unintentional, so we allow them.
17999 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18000 !isMemberSpecialization)
18001 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18002 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18003
18004 if (TemplateParams) {
18005 if (Kind == TagTypeKind::Enum) {
18006 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18007 return true;
18008 }
18009
18010 if (TemplateParams->size() > 0) {
18011 // This is a declaration or definition of a class template (which may
18012 // be a member of another template).
18013
18014 if (Invalid)
18015 return true;
18016
18017 OwnedDecl = false;
18018 DeclResult Result = CheckClassTemplate(
18019 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18020 AS, ModulePrivateLoc,
18021 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18022 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18023 return Result.get();
18024 } else {
18025 // The "template<>" header is extraneous.
18026 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18027 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18028 isMemberSpecialization = true;
18029 }
18030 }
18031
18032 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18033 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18034 return true;
18035 }
18036
18037 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18038 // C++23 [dcl.type.elab]p4:
18039 // If an elaborated-type-specifier appears with the friend specifier as
18040 // an entire member-declaration, the member-declaration shall have one
18041 // of the following forms:
18042 // friend class-key nested-name-specifier(opt) identifier ;
18043 // friend class-key simple-template-id ;
18044 // friend class-key nested-name-specifier template(opt)
18045 // simple-template-id ;
18046 //
18047 // Since enum is not a class-key, so declarations like "friend enum E;"
18048 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18049 // invalid, most implementations accept so we issue a pedantic warning.
18050 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18051 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18052 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18053 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18054 << (ScopedEnum + ScopedEnumUsesClassTag);
18055 }
18056
18057 // Figure out the underlying type if this a enum declaration. We need to do
18058 // this early, because it's needed to detect if this is an incompatible
18059 // redeclaration.
18060 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18061 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18062
18063 if (Kind == TagTypeKind::Enum) {
18064 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18065 Invalid) {
18066 // No underlying type explicitly specified, or we failed to parse the
18067 // type, default to int.
18068 EnumUnderlying = Context.IntTy.getTypePtr();
18069 } else if (UnderlyingType.get()) {
18070 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18071 // integral type; any cv-qualification is ignored.
18072 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18073 // unqualified, non-atomic version of the type specified by the type
18074 // specifiers in the specifier qualifier list.
18075 TypeSourceInfo *TI = nullptr;
18076 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18077 EnumUnderlying = TI;
18078
18079 if (CheckEnumUnderlyingType(TI))
18080 // Recover by falling back to int.
18081 EnumUnderlying = Context.IntTy.getTypePtr();
18082
18083 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18084 UPPC: UPPC_FixedUnderlyingType))
18085 EnumUnderlying = Context.IntTy.getTypePtr();
18086
18087 // If the underlying type is atomic, we need to adjust the type before
18088 // continuing. This only happens in the case we stored a TypeSourceInfo
18089 // into EnumUnderlying because the other cases are error recovery up to
18090 // this point. But because it's not possible to gin up a TypeSourceInfo
18091 // for a non-atomic type from an atomic one, we'll store into the Type
18092 // field instead. FIXME: it would be nice to have an easy way to get a
18093 // derived TypeSourceInfo which strips qualifiers including the weird
18094 // ones like _Atomic where it forms a different type.
18095 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18096 TI && TI->getType()->isAtomicType())
18097 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18098
18099 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18100 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18101 // of 'int'. However, if this is an unfixed forward declaration, don't set
18102 // the underlying type unless the user enables -fms-compatibility. This
18103 // makes unfixed forward declared enums incomplete and is more conforming.
18104 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18105 EnumUnderlying = Context.IntTy.getTypePtr();
18106 }
18107 }
18108
18109 DeclContext *SearchDC = CurContext;
18110 DeclContext *DC = CurContext;
18111 bool isStdBadAlloc = false;
18112 bool isStdAlignValT = false;
18113
18114 RedeclarationKind Redecl = forRedeclarationInCurContext();
18115 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18116 Redecl = RedeclarationKind::NotForRedeclaration;
18117
18118 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18119 /// implemented asks for structural equivalence checking, the returned decl
18120 /// here is passed back to the parser, allowing the tag body to be parsed.
18121 auto createTagFromNewDecl = [&]() -> TagDecl * {
18122 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18123 // If there is an identifier, use the location of the identifier as the
18124 // location of the decl, otherwise use the location of the struct/union
18125 // keyword.
18126 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18127 TagDecl *New = nullptr;
18128
18129 if (Kind == TagTypeKind::Enum) {
18130 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18131 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18132 // If this is an undefined enum, bail.
18133 if (TUK != TagUseKind::Definition && !Invalid)
18134 return nullptr;
18135 if (EnumUnderlying) {
18136 EnumDecl *ED = cast<EnumDecl>(Val: New);
18137 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18138 ED->setIntegerTypeSourceInfo(TI);
18139 else
18140 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18141 QualType EnumTy = ED->getIntegerType();
18142 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18143 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18144 : EnumTy);
18145 }
18146 } else { // struct/union
18147 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18148 PrevDecl: nullptr);
18149 }
18150
18151 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18152 // Add alignment attributes if necessary; these attributes are checked
18153 // when the ASTContext lays out the structure.
18154 //
18155 // It is important for implementing the correct semantics that this
18156 // happen here (in ActOnTag). The #pragma pack stack is
18157 // maintained as a result of parser callbacks which can occur at
18158 // many points during the parsing of a struct declaration (because
18159 // the #pragma tokens are effectively skipped over during the
18160 // parsing of the struct).
18161 if (TUK == TagUseKind::Definition &&
18162 (!SkipBody || !SkipBody->ShouldSkip)) {
18163 if (LangOpts.HLSL)
18164 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18165 AddAlignmentAttributesForRecord(RD);
18166 AddMsStructLayoutForRecord(RD);
18167 }
18168 }
18169 New->setLexicalDeclContext(CurContext);
18170 return New;
18171 };
18172
18173 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18174 if (Name && SS.isNotEmpty()) {
18175 // We have a nested-name tag ('struct foo::bar').
18176
18177 // Check for invalid 'foo::'.
18178 if (SS.isInvalid()) {
18179 Name = nullptr;
18180 goto CreateNewDecl;
18181 }
18182
18183 // If this is a friend or a reference to a class in a dependent
18184 // context, don't try to make a decl for it.
18185 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18186 DC = computeDeclContext(SS, EnteringContext: false);
18187 if (!DC) {
18188 IsDependent = true;
18189 return true;
18190 }
18191 } else {
18192 DC = computeDeclContext(SS, EnteringContext: true);
18193 if (!DC) {
18194 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18195 << SS.getRange();
18196 return true;
18197 }
18198 }
18199
18200 if (RequireCompleteDeclContext(SS, DC))
18201 return true;
18202
18203 SearchDC = DC;
18204 // Look-up name inside 'foo::'.
18205 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18206
18207 if (Previous.isAmbiguous())
18208 return true;
18209
18210 if (Previous.empty()) {
18211 // Name lookup did not find anything. However, if the
18212 // nested-name-specifier refers to the current instantiation,
18213 // and that current instantiation has any dependent base
18214 // classes, we might find something at instantiation time: treat
18215 // this as a dependent elaborated-type-specifier.
18216 // But this only makes any sense for reference-like lookups.
18217 if (Previous.wasNotFoundInCurrentInstantiation() &&
18218 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18219 IsDependent = true;
18220 return true;
18221 }
18222
18223 // A tag 'foo::bar' must already exist.
18224 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18225 << Kind << Name << DC << SS.getRange();
18226 Name = nullptr;
18227 Invalid = true;
18228 goto CreateNewDecl;
18229 }
18230 } else if (Name) {
18231 // C++14 [class.mem]p14:
18232 // If T is the name of a class, then each of the following shall have a
18233 // name different from T:
18234 // -- every member of class T that is itself a type
18235 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18236 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18237 return true;
18238
18239 // If this is a named struct, check to see if there was a previous forward
18240 // declaration or definition.
18241 // FIXME: We're looking into outer scopes here, even when we
18242 // shouldn't be. Doing so can result in ambiguities that we
18243 // shouldn't be diagnosing.
18244 LookupName(R&: Previous, S);
18245
18246 // When declaring or defining a tag, ignore ambiguities introduced
18247 // by types using'ed into this scope.
18248 if (Previous.isAmbiguous() &&
18249 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18250 LookupResult::Filter F = Previous.makeFilter();
18251 while (F.hasNext()) {
18252 NamedDecl *ND = F.next();
18253 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18254 DC: SearchDC->getRedeclContext()))
18255 F.erase();
18256 }
18257 F.done();
18258 }
18259
18260 // C++11 [namespace.memdef]p3:
18261 // If the name in a friend declaration is neither qualified nor
18262 // a template-id and the declaration is a function or an
18263 // elaborated-type-specifier, the lookup to determine whether
18264 // the entity has been previously declared shall not consider
18265 // any scopes outside the innermost enclosing namespace.
18266 //
18267 // MSVC doesn't implement the above rule for types, so a friend tag
18268 // declaration may be a redeclaration of a type declared in an enclosing
18269 // scope. They do implement this rule for friend functions.
18270 //
18271 // Does it matter that this should be by scope instead of by
18272 // semantic context?
18273 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18274 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18275 LookupResult::Filter F = Previous.makeFilter();
18276 bool FriendSawTagOutsideEnclosingNamespace = false;
18277 while (F.hasNext()) {
18278 NamedDecl *ND = F.next();
18279 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18280 if (DC->isFileContext() &&
18281 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18282 if (getLangOpts().MSVCCompat)
18283 FriendSawTagOutsideEnclosingNamespace = true;
18284 else
18285 F.erase();
18286 }
18287 }
18288 F.done();
18289
18290 // Diagnose this MSVC extension in the easy case where lookup would have
18291 // unambiguously found something outside the enclosing namespace.
18292 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18293 NamedDecl *ND = Previous.getFoundDecl();
18294 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18295 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18296 }
18297 }
18298
18299 // Note: there used to be some attempt at recovery here.
18300 if (Previous.isAmbiguous())
18301 return true;
18302
18303 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18304 // FIXME: This makes sure that we ignore the contexts associated
18305 // with C structs, unions, and enums when looking for a matching
18306 // tag declaration or definition. See the similar lookup tweak
18307 // in Sema::LookupName; is there a better way to deal with this?
18308 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18309 SearchDC = SearchDC->getParent();
18310 } else if (getLangOpts().CPlusPlus) {
18311 // Inside ObjCContainer want to keep it as a lexical decl context but go
18312 // past it (most often to TranslationUnit) to find the semantic decl
18313 // context.
18314 while (isa<ObjCContainerDecl>(Val: SearchDC))
18315 SearchDC = SearchDC->getParent();
18316 }
18317 } else if (getLangOpts().CPlusPlus) {
18318 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18319 // TagDecl the same way as we skip it for named TagDecl.
18320 while (isa<ObjCContainerDecl>(Val: SearchDC))
18321 SearchDC = SearchDC->getParent();
18322 }
18323
18324 if (Previous.isSingleResult() &&
18325 Previous.getFoundDecl()->isTemplateParameter()) {
18326 // Maybe we will complain about the shadowed template parameter.
18327 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18328 // Just pretend that we didn't see the previous declaration.
18329 Previous.clear();
18330 }
18331
18332 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18333 DC->Equals(DC: getStdNamespace())) {
18334 if (Name->isStr(Str: "bad_alloc")) {
18335 // This is a declaration of or a reference to "std::bad_alloc".
18336 isStdBadAlloc = true;
18337
18338 // If std::bad_alloc has been implicitly declared (but made invisible to
18339 // name lookup), fill in this implicit declaration as the previous
18340 // declaration, so that the declarations get chained appropriately.
18341 if (Previous.empty() && StdBadAlloc)
18342 Previous.addDecl(D: getStdBadAlloc());
18343 } else if (Name->isStr(Str: "align_val_t")) {
18344 isStdAlignValT = true;
18345 if (Previous.empty() && StdAlignValT)
18346 Previous.addDecl(D: getStdAlignValT());
18347 }
18348 }
18349
18350 // If we didn't find a previous declaration, and this is a reference
18351 // (or friend reference), move to the correct scope. In C++, we
18352 // also need to do a redeclaration lookup there, just in case
18353 // there's a shadow friend decl.
18354 if (Name && Previous.empty() &&
18355 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18356 IsTemplateParamOrArg)) {
18357 if (Invalid) goto CreateNewDecl;
18358 assert(SS.isEmpty());
18359
18360 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18361 // C++ [basic.scope.pdecl]p5:
18362 // -- for an elaborated-type-specifier of the form
18363 //
18364 // class-key identifier
18365 //
18366 // if the elaborated-type-specifier is used in the
18367 // decl-specifier-seq or parameter-declaration-clause of a
18368 // function defined in namespace scope, the identifier is
18369 // declared as a class-name in the namespace that contains
18370 // the declaration; otherwise, except as a friend
18371 // declaration, the identifier is declared in the smallest
18372 // non-class, non-function-prototype scope that contains the
18373 // declaration.
18374 //
18375 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18376 // C structs and unions.
18377 //
18378 // It is an error in C++ to declare (rather than define) an enum
18379 // type, including via an elaborated type specifier. We'll
18380 // diagnose that later; for now, declare the enum in the same
18381 // scope as we would have picked for any other tag type.
18382 //
18383 // GNU C also supports this behavior as part of its incomplete
18384 // enum types extension, while GNU C++ does not.
18385 //
18386 // Find the context where we'll be declaring the tag.
18387 // FIXME: We would like to maintain the current DeclContext as the
18388 // lexical context,
18389 SearchDC = getTagInjectionContext(DC: SearchDC);
18390
18391 // Find the scope where we'll be declaring the tag.
18392 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18393 } else {
18394 assert(TUK == TagUseKind::Friend);
18395 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18396
18397 // C++ [namespace.memdef]p3:
18398 // If a friend declaration in a non-local class first declares a
18399 // class or function, the friend class or function is a member of
18400 // the innermost enclosing namespace.
18401 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18402 : SearchDC->getEnclosingNamespaceContext();
18403 }
18404
18405 // In C++, we need to do a redeclaration lookup to properly
18406 // diagnose some problems.
18407 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18408 // hidden declaration so that we don't get ambiguity errors when using a
18409 // type declared by an elaborated-type-specifier. In C that is not correct
18410 // and we should instead merge compatible types found by lookup.
18411 if (getLangOpts().CPlusPlus) {
18412 // FIXME: This can perform qualified lookups into function contexts,
18413 // which are meaningless.
18414 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18415 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18416 } else {
18417 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18418 LookupName(R&: Previous, S);
18419 }
18420 }
18421
18422 // If we have a known previous declaration to use, then use it.
18423 if (Previous.empty() && SkipBody && SkipBody->Previous)
18424 Previous.addDecl(D: SkipBody->Previous);
18425
18426 if (!Previous.empty()) {
18427 NamedDecl *PrevDecl = Previous.getFoundDecl();
18428 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18429
18430 // It's okay to have a tag decl in the same scope as a typedef
18431 // which hides a tag decl in the same scope. Finding this
18432 // with a redeclaration lookup can only actually happen in C++.
18433 //
18434 // This is also okay for elaborated-type-specifiers, which is
18435 // technically forbidden by the current standard but which is
18436 // okay according to the likely resolution of an open issue;
18437 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18438 if (getLangOpts().CPlusPlus) {
18439 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18440 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18441 if (Tag->getDeclName() == Name &&
18442 Tag->getDeclContext()->getRedeclContext()
18443 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18444 PrevDecl = Tag;
18445 Previous.clear();
18446 Previous.addDecl(D: Tag);
18447 Previous.resolveKind();
18448 }
18449 }
18450 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18451 TUK == TagUseKind::Reference && RD &&
18452 RD->isInjectedClassName()) {
18453 // If lookup found the injected class name, the previous declaration is
18454 // the class being injected into.
18455 PrevDecl = cast<TagDecl>(Val: RD->getDeclContext());
18456 Previous.clear();
18457 Previous.addDecl(D: PrevDecl);
18458 Previous.resolveKind();
18459 IsInjectedClassName = true;
18460 }
18461 }
18462
18463 // If this is a redeclaration of a using shadow declaration, it must
18464 // declare a tag in the same context. In MSVC mode, we allow a
18465 // redefinition if either context is within the other.
18466 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18467 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18468 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18469 TUK != TagUseKind::Friend &&
18470 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18471 !(OldTag && isAcceptableTagRedeclContext(
18472 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18473 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18474 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18475 DiagID: diag::note_using_decl_target);
18476 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18477 << 0;
18478 // Recover by ignoring the old declaration.
18479 Previous.clear();
18480 goto CreateNewDecl;
18481 }
18482 }
18483
18484 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18485 // If this is a use of a previous tag, or if the tag is already declared
18486 // in the same scope (so that the definition/declaration completes or
18487 // rementions the tag), reuse the decl.
18488 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18489 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18490 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18491 // Make sure that this wasn't declared as an enum and now used as a
18492 // struct or something similar.
18493 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18494 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18495 Name)) {
18496 bool SafeToContinue =
18497 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18498 Kind != TagTypeKind::Enum);
18499 if (SafeToContinue)
18500 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18501 << Name
18502 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18503 Code: PrevTagDecl->getKindName());
18504 else
18505 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18506 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18507
18508 if (SafeToContinue)
18509 Kind = PrevTagDecl->getTagKind();
18510 else {
18511 // Recover by making this an anonymous redefinition.
18512 Name = nullptr;
18513 Previous.clear();
18514 Invalid = true;
18515 }
18516 }
18517
18518 if (Kind == TagTypeKind::Enum &&
18519 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18520 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18521 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18522 return PrevTagDecl;
18523
18524 QualType EnumUnderlyingTy;
18525 if (TypeSourceInfo *TI =
18526 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18527 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18528 else if (const Type *T =
18529 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18530 EnumUnderlyingTy = QualType(T, 0);
18531
18532 // All conflicts with previous declarations are recovered by
18533 // returning the previous declaration, unless this is a definition,
18534 // in which case we want the caller to bail out.
18535 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18536 IsScoped: ScopedEnum, EnumUnderlyingTy,
18537 IsFixed, Prev: PrevEnum))
18538 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18539 }
18540
18541 // C++11 [class.mem]p1:
18542 // A member shall not be declared twice in the member-specification,
18543 // except that a nested class or member class template can be declared
18544 // and then later defined.
18545 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18546 S->isDeclScope(D: PrevDecl)) {
18547 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18548 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18549 }
18550
18551 // C++ [class.local]p3:
18552 // A class nested within a local class is a local class. A member of
18553 // a local class X shall be declared only in the definition of X or,
18554 // if the member is a nested class, in the nearest enclosing block
18555 // scope of X.
18556 if (TUK == TagUseKind::Definition && SS.isValid()) {
18557 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18558 while (const auto *ParentClass =
18559 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18560 OutermostClass = ParentClass;
18561
18562 if (OutermostClass->isLocalClass() &&
18563 !S->isDeclScope(D: OutermostClass)) {
18564 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18565 << Name << OutermostClass;
18566 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18567 << OutermostClass;
18568 }
18569 }
18570 }
18571
18572 if (!Invalid) {
18573 // If this is a use, just return the declaration we found, unless
18574 // we have attributes.
18575 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18576 if (!Attrs.empty()) {
18577 // FIXME: Diagnose these attributes. For now, we create a new
18578 // declaration to hold them.
18579 } else if (TUK == TagUseKind::Reference &&
18580 (PrevTagDecl->getFriendObjectKind() ==
18581 Decl::FOK_Undeclared ||
18582 PrevDecl->getOwningModule() != getCurrentModule()) &&
18583 SS.isEmpty()) {
18584 // This declaration is a reference to an existing entity, but
18585 // has different visibility from that entity: it either makes
18586 // a friend visible or it makes a type visible in a new module.
18587 // In either case, create a new declaration. We only do this if
18588 // the declaration would have meant the same thing if no prior
18589 // declaration were found, that is, if it was found in the same
18590 // scope where we would have injected a declaration.
18591 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18592 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18593 return PrevTagDecl;
18594 // This is in the injected scope, create a new declaration in
18595 // that scope.
18596 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18597 } else {
18598 return PrevTagDecl;
18599 }
18600 }
18601
18602 // Diagnose attempts to redefine a tag.
18603 if (TUK == TagUseKind::Definition) {
18604 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18605 // If the type is currently being defined, complain
18606 // about a nested redefinition.
18607 if (Def->isBeingDefined()) {
18608 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18609 Diag(Loc: PrevTagDecl->getLocation(),
18610 DiagID: diag::note_previous_definition);
18611 Name = nullptr;
18612 Previous.clear();
18613 Invalid = true;
18614 } else {
18615 // If we're defining a specialization and the previous
18616 // definition is from an implicit instantiation, don't emit an
18617 // error here; we'll catch this in the general case below.
18618 bool IsExplicitSpecializationAfterInstantiation = false;
18619 if (isMemberSpecialization) {
18620 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18621 IsExplicitSpecializationAfterInstantiation =
18622 RD->getTemplateSpecializationKind() !=
18623 TSK_ExplicitSpecialization;
18624 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18625 IsExplicitSpecializationAfterInstantiation =
18626 ED->getTemplateSpecializationKind() !=
18627 TSK_ExplicitSpecialization;
18628 }
18629
18630 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18631 // do not keep more that one definition around (merge them).
18632 // However, ensure the decl passes the structural compatibility
18633 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18634 NamedDecl *Hidden = nullptr;
18635 bool HiddenDefVisible = false;
18636 if (SkipBody &&
18637 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18638 getLangOpts().C23)) {
18639 // There is a definition of this tag, but it is not visible.
18640 // We explicitly make use of C++'s one definition rule here,
18641 // and assume that this definition is identical to the hidden
18642 // one we already have. Make the existing definition visible
18643 // and use it in place of this one.
18644 if (!getLangOpts().CPlusPlus) {
18645 // Postpone making the old definition visible until after we
18646 // complete parsing the new one and do the structural
18647 // comparison.
18648 SkipBody->CheckSameAsPrevious = true;
18649 SkipBody->New = createTagFromNewDecl();
18650 SkipBody->Previous = Def;
18651
18652 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18653 return Def;
18654 }
18655
18656 SkipBody->ShouldSkip = true;
18657 SkipBody->Previous = Def;
18658 if (!HiddenDefVisible && Hidden)
18659 makeMergedDefinitionVisible(ND: Hidden);
18660 // Carry on and handle it like a normal definition. We'll
18661 // skip starting the definition later.
18662
18663 } else if (!IsExplicitSpecializationAfterInstantiation) {
18664 // A redeclaration in function prototype scope in C isn't
18665 // visible elsewhere, so merely issue a warning.
18666 if (!getLangOpts().CPlusPlus &&
18667 S->containedInPrototypeScope())
18668 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18669 << Name;
18670 else
18671 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18672 notePreviousDefinition(Old: Def,
18673 New: NameLoc.isValid() ? NameLoc : KWLoc);
18674 // If this is a redefinition, recover by making this
18675 // struct be anonymous, which will make any later
18676 // references get the previous definition.
18677 Name = nullptr;
18678 Previous.clear();
18679 Invalid = true;
18680 }
18681 }
18682 }
18683
18684 // Okay, this is definition of a previously declared or referenced
18685 // tag. We're going to create a new Decl for it.
18686 }
18687
18688 // Okay, we're going to make a redeclaration. If this is some kind
18689 // of reference, make sure we build the redeclaration in the same DC
18690 // as the original, and ignore the current access specifier.
18691 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18692 SearchDC = PrevTagDecl->getDeclContext();
18693 AS = AS_none;
18694 }
18695 }
18696 // If we get here we have (another) forward declaration or we
18697 // have a definition. Just create a new decl.
18698
18699 } else {
18700 // If we get here, this is a definition of a new tag type in a nested
18701 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18702 // new decl/type. We set PrevDecl to NULL so that the entities
18703 // have distinct types.
18704 Previous.clear();
18705 }
18706 // If we get here, we're going to create a new Decl. If PrevDecl
18707 // is non-NULL, it's a definition of the tag declared by
18708 // PrevDecl. If it's NULL, we have a new definition.
18709
18710 // Otherwise, PrevDecl is not a tag, but was found with tag
18711 // lookup. This is only actually possible in C++, where a few
18712 // things like templates still live in the tag namespace.
18713 } else {
18714 // Use a better diagnostic if an elaborated-type-specifier
18715 // found the wrong kind of type on the first
18716 // (non-redeclaration) lookup.
18717 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18718 !Previous.isForRedeclaration()) {
18719 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18720 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18721 << PrevDecl << NTK << Kind;
18722 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18723 Invalid = true;
18724
18725 // Otherwise, only diagnose if the declaration is in scope.
18726 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18727 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18728 // do nothing
18729
18730 // Diagnose implicit declarations introduced by elaborated types.
18731 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18732 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18733 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18734 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18735 Invalid = true;
18736
18737 // Otherwise it's a declaration. Call out a particularly common
18738 // case here.
18739 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18740 unsigned Kind = 0;
18741 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18742 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18743 << Name << Kind << TND->getUnderlyingType();
18744 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18745 Invalid = true;
18746
18747 // Otherwise, diagnose.
18748 } else {
18749 // The tag name clashes with something else in the target scope,
18750 // issue an error and recover by making this tag be anonymous.
18751 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18752 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18753 Name = nullptr;
18754 Invalid = true;
18755 }
18756
18757 // The existing declaration isn't relevant to us; we're in a
18758 // new scope, so clear out the previous declaration.
18759 Previous.clear();
18760 }
18761 }
18762
18763CreateNewDecl:
18764
18765 TagDecl *PrevDecl = nullptr;
18766 if (Previous.isSingleResult())
18767 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18768
18769 // If there is an identifier, use the location of the identifier as the
18770 // location of the decl, otherwise use the location of the struct/union
18771 // keyword.
18772 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18773
18774 // Otherwise, create a new declaration. If there is a previous
18775 // declaration of the same entity, the two will be linked via
18776 // PrevDecl.
18777 TagDecl *New;
18778
18779 if (Kind == TagTypeKind::Enum) {
18780 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18781 // enum X { A, B, C } D; D should chain to X.
18782 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18783 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18784 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18785
18786 EnumDecl *ED = cast<EnumDecl>(Val: New);
18787 ED->setEnumKeyRange(SourceRange(
18788 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18789
18790 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18791 StdAlignValT = cast<EnumDecl>(Val: New);
18792
18793 // If this is an undefined enum, warn.
18794 if (TUK != TagUseKind::Definition && !Invalid) {
18795 TagDecl *Def;
18796 if (IsFixed && ED->isFixed()) {
18797 // C++0x: 7.2p2: opaque-enum-declaration.
18798 // Conflicts are diagnosed above. Do nothing.
18799 } else if (PrevDecl &&
18800 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18801 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18802 << New;
18803 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18804 } else {
18805 unsigned DiagID = diag::ext_forward_ref_enum;
18806 if (getLangOpts().MSVCCompat)
18807 DiagID = diag::ext_ms_forward_ref_enum;
18808 else if (getLangOpts().CPlusPlus)
18809 DiagID = diag::err_forward_ref_enum;
18810 Diag(Loc, DiagID);
18811 }
18812 }
18813
18814 if (EnumUnderlying) {
18815 EnumDecl *ED = cast<EnumDecl>(Val: New);
18816 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18817 ED->setIntegerTypeSourceInfo(TI);
18818 else
18819 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18820 QualType EnumTy = ED->getIntegerType();
18821 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18822 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18823 : EnumTy);
18824 assert(ED->isComplete() && "enum with type should be complete");
18825 }
18826 } else {
18827 // struct/union/class
18828
18829 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18830 // struct X { int A; } D; D should chain to X.
18831 if (getLangOpts().CPlusPlus) {
18832 // FIXME: Look for a way to use RecordDecl for simple structs.
18833 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18834 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18835
18836 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18837 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18838 } else
18839 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18840 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18841 }
18842
18843 // Only C23 and later allow defining new types in 'offsetof()'.
18844 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18845 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18846 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18847 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18848
18849 // C++11 [dcl.type]p3:
18850 // A type-specifier-seq shall not define a class or enumeration [...].
18851 if (!Invalid && getLangOpts().CPlusPlus &&
18852 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18853 TUK == TagUseKind::Definition) {
18854 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18855 << Context.getCanonicalTagType(TD: New);
18856 Invalid = true;
18857 }
18858
18859 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18860 DC->getDeclKind() == Decl::Enum) {
18861 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18862 << Context.getCanonicalTagType(TD: New);
18863 Invalid = true;
18864 }
18865
18866 // Maybe add qualifier info.
18867 if (SS.isNotEmpty()) {
18868 if (SS.isSet()) {
18869 // If this is either a declaration or a definition, check the
18870 // nested-name-specifier against the current context.
18871 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18872 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18873 /*TemplateId=*/nullptr,
18874 IsMemberSpecialization: isMemberSpecialization))
18875 Invalid = true;
18876
18877 New->setQualifierInfo(SS.getWithLocInContext(Context));
18878 if (TemplateParameterLists.size() > 0) {
18879 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18880 }
18881 }
18882 else
18883 Invalid = true;
18884 }
18885
18886 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18887 // Add alignment attributes if necessary; these attributes are checked when
18888 // the ASTContext lays out the structure.
18889 //
18890 // It is important for implementing the correct semantics that this
18891 // happen here (in ActOnTag). The #pragma pack stack is
18892 // maintained as a result of parser callbacks which can occur at
18893 // many points during the parsing of a struct declaration (because
18894 // the #pragma tokens are effectively skipped over during the
18895 // parsing of the struct).
18896 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18897 if (LangOpts.HLSL)
18898 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18899 AddAlignmentAttributesForRecord(RD);
18900 AddMsStructLayoutForRecord(RD);
18901 }
18902 }
18903
18904 if (ModulePrivateLoc.isValid()) {
18905 if (isMemberSpecialization)
18906 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18907 << 2
18908 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18909 // __module_private__ does not apply to local classes. However, we only
18910 // diagnose this as an error when the declaration specifiers are
18911 // freestanding. Here, we just ignore the __module_private__.
18912 else if (!SearchDC->isFunctionOrMethod())
18913 New->setModulePrivate();
18914 }
18915
18916 // If this is a specialization of a member class (of a class template),
18917 // check the specialization.
18918 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18919 Invalid = true;
18920
18921 // If we're declaring or defining a tag in function prototype scope in C,
18922 // note that this type can only be used within the function and add it to
18923 // the list of decls to inject into the function definition scope. However,
18924 // in C23 and later, while the type is only visible within the function, the
18925 // function can be called with a compatible type defined in the same TU, so
18926 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18927 if ((Name || Kind == TagTypeKind::Enum) &&
18928 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18929 if (getLangOpts().CPlusPlus) {
18930 // C++ [dcl.fct]p6:
18931 // Types shall not be defined in return or parameter types.
18932 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18933 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18934 << Name;
18935 Invalid = true;
18936 }
18937 if (TUK == TagUseKind::Declaration)
18938 Invalid = true;
18939 } else if (!PrevDecl) {
18940 // In C23 mode, if the declaration is complete, we do not want to
18941 // diagnose.
18942 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18943 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
18944 << Context.getCanonicalTagType(TD: New);
18945 }
18946 }
18947
18948 if (Invalid)
18949 New->setInvalidDecl();
18950
18951 // Set the lexical context. If the tag has a C++ scope specifier, the
18952 // lexical context will be different from the semantic context.
18953 New->setLexicalDeclContext(CurContext);
18954
18955 // Mark this as a friend decl if applicable.
18956 // In Microsoft mode, a friend declaration also acts as a forward
18957 // declaration so we always pass true to setObjectOfFriendDecl to make
18958 // the tag name visible.
18959 if (TUK == TagUseKind::Friend)
18960 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18961
18962 // Set the access specifier.
18963 if (!Invalid && SearchDC->isRecord())
18964 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18965
18966 if (PrevDecl)
18967 CheckRedeclarationInModule(New, Old: PrevDecl);
18968
18969 if (TUK == TagUseKind::Definition) {
18970 if (!SkipBody || !SkipBody->ShouldSkip) {
18971 New->startDefinition();
18972 } else {
18973 New->setCompleteDefinition();
18974 New->demoteThisDefinitionToDeclaration();
18975 }
18976 }
18977
18978 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18979 AddPragmaAttributes(S, D: New);
18980
18981 // If this has an identifier, add it to the scope stack.
18982 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18983 // We might be replacing an existing declaration in the lookup tables;
18984 // if so, borrow its access specifier.
18985 if (PrevDecl)
18986 New->setAccess(PrevDecl->getAccess());
18987
18988 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18989 DC->makeDeclVisibleInContext(D: New);
18990 if (Name) // can be null along some error paths
18991 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18992 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18993 } else if (Name) {
18994 S = getNonFieldDeclScope(S);
18995 PushOnScopeChains(D: New, S, AddToContext: true);
18996 } else {
18997 CurContext->addDecl(D: New);
18998 }
18999
19000 // If this is the C FILE type, notify the AST context.
19001 if (IdentifierInfo *II = New->getIdentifier())
19002 if (!New->isInvalidDecl() &&
19003 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19004 II->isStr(Str: "FILE"))
19005 Context.setFILEDecl(New);
19006
19007 if (PrevDecl)
19008 mergeDeclAttributes(New, Old: PrevDecl);
19009
19010 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19011 inferGslOwnerPointerAttribute(Record: CXXRD);
19012 inferNullableClassAttribute(CRD: CXXRD);
19013 }
19014
19015 // If there's a #pragma GCC visibility in scope, set the visibility of this
19016 // record.
19017 AddPushedVisibilityAttribute(RD: New);
19018
19019 // If this is not a definition, process API notes for it now.
19020 if (TUK != TagUseKind::Definition)
19021 ProcessAPINotes(D: New);
19022
19023 if (isMemberSpecialization && !New->isInvalidDecl())
19024 CompleteMemberSpecialization(Member: New, Previous);
19025
19026 OwnedDecl = true;
19027 // In C++, don't return an invalid declaration. We can't recover well from
19028 // the cases where we make the type anonymous.
19029 if (Invalid && getLangOpts().CPlusPlus) {
19030 if (New->isBeingDefined())
19031 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19032 RD->completeDefinition();
19033 return true;
19034 } else if (SkipBody && SkipBody->ShouldSkip) {
19035 return SkipBody->Previous;
19036 } else {
19037 return New;
19038 }
19039}
19040
19041void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19042 AdjustDeclIfTemplate(Decl&: TagD);
19043 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19044
19045 // Enter the tag context.
19046 PushDeclContext(S, DC: Tag);
19047
19048 ActOnDocumentableDecl(D: TagD);
19049
19050 // If there's a #pragma GCC visibility in scope, set the visibility of this
19051 // record.
19052 AddPushedVisibilityAttribute(RD: Tag);
19053}
19054
19055bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19056 SkipBodyInfo &SkipBody) {
19057 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19058 return false;
19059
19060 // Make the previous decl visible.
19061 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19062 CleanupMergedEnum(S, New: SkipBody.New);
19063 return true;
19064}
19065
19066void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19067 SourceLocation FinalLoc,
19068 bool IsFinalSpelledSealed,
19069 bool IsAbstract,
19070 SourceLocation LBraceLoc) {
19071 AdjustDeclIfTemplate(Decl&: TagD);
19072 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19073
19074 FieldCollector->StartClass();
19075
19076 if (!Record->getIdentifier())
19077 return;
19078
19079 if (IsAbstract)
19080 Record->markAbstract();
19081
19082 if (FinalLoc.isValid()) {
19083 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19084 S: IsFinalSpelledSealed
19085 ? FinalAttr::Keyword_sealed
19086 : FinalAttr::Keyword_final));
19087 }
19088
19089 // C++ [class]p2:
19090 // [...] The class-name is also inserted into the scope of the
19091 // class itself; this is known as the injected-class-name. For
19092 // purposes of access checking, the injected-class-name is treated
19093 // as if it were a public member name.
19094 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19095 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19096 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19097 InjectedClassName->setImplicit();
19098 InjectedClassName->setAccess(AS_public);
19099 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19100 InjectedClassName->setDescribedClassTemplate(Template);
19101
19102 PushOnScopeChains(D: InjectedClassName, S);
19103 assert(InjectedClassName->isInjectedClassName() &&
19104 "Broken injected-class-name");
19105}
19106
19107void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19108 SourceRange BraceRange) {
19109 AdjustDeclIfTemplate(Decl&: TagD);
19110 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19111 Tag->setBraceRange(BraceRange);
19112
19113 // Make sure we "complete" the definition even it is invalid.
19114 if (Tag->isBeingDefined()) {
19115 assert(Tag->isInvalidDecl() && "We should already have completed it");
19116 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19117 RD->completeDefinition();
19118 }
19119
19120 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19121 FieldCollector->FinishClass();
19122 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19123 auto *Def = RD->getDefinition();
19124 assert(Def && "The record is expected to have a completed definition");
19125 unsigned NumInitMethods = 0;
19126 for (auto *Method : Def->methods()) {
19127 if (!Method->getIdentifier())
19128 continue;
19129 if (Method->getName() == "__init")
19130 NumInitMethods++;
19131 }
19132 if (NumInitMethods > 1 || !Def->hasInitMethod())
19133 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19134 }
19135
19136 // If we're defining a dynamic class in a module interface unit, we always
19137 // need to produce the vtable for it, even if the vtable is not used in the
19138 // current TU.
19139 //
19140 // The case where the current class is not dynamic is handled in
19141 // MarkVTableUsed.
19142 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19143 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19144 }
19145
19146 // Exit this scope of this tag's definition.
19147 PopDeclContext();
19148
19149 if (getCurLexicalContext()->isObjCContainer() &&
19150 Tag->getDeclContext()->isFileContext())
19151 Tag->setTopLevelDeclInObjCContainer();
19152
19153 // Notify the consumer that we've defined a tag.
19154 if (!Tag->isInvalidDecl())
19155 Consumer.HandleTagDeclDefinition(D: Tag);
19156
19157 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19158 // from XLs and instead matches the XL #pragma pack(1) behavior.
19159 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19160 AlignPackStack.hasValue()) {
19161 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19162 // Only diagnose #pragma align(packed).
19163 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19164 return;
19165 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19166 if (!RD)
19167 return;
19168 // Only warn if there is at least 1 bitfield member.
19169 if (llvm::any_of(Range: RD->fields(),
19170 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19171 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19172 }
19173}
19174
19175void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19176 AdjustDeclIfTemplate(Decl&: TagD);
19177 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19178 Tag->setInvalidDecl();
19179
19180 // Make sure we "complete" the definition even it is invalid.
19181 if (Tag->isBeingDefined()) {
19182 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19183 RD->completeDefinition();
19184 }
19185
19186 // We're undoing ActOnTagStartDefinition here, not
19187 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19188 // the FieldCollector.
19189
19190 PopDeclContext();
19191}
19192
19193// Note that FieldName may be null for anonymous bitfields.
19194ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19195 const IdentifierInfo *FieldName,
19196 QualType FieldTy, bool IsMsStruct,
19197 Expr *BitWidth) {
19198 assert(BitWidth);
19199 if (BitWidth->containsErrors())
19200 return ExprError();
19201
19202 // C99 6.7.2.1p4 - verify the field type.
19203 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19204 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19205 // Handle incomplete and sizeless types with a specific error.
19206 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19207 DiagID: diag::err_field_incomplete_or_sizeless))
19208 return ExprError();
19209 if (FieldName)
19210 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19211 << FieldName << FieldTy << BitWidth->getSourceRange();
19212 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19213 << FieldTy << BitWidth->getSourceRange();
19214 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19215 return ExprError();
19216
19217 // If the bit-width is type- or value-dependent, don't try to check
19218 // it now.
19219 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19220 return BitWidth;
19221
19222 llvm::APSInt Value;
19223 ExprResult ICE =
19224 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19225 if (ICE.isInvalid())
19226 return ICE;
19227 BitWidth = ICE.get();
19228
19229 // Zero-width bitfield is ok for anonymous field.
19230 if (Value == 0 && FieldName)
19231 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19232 << FieldName << BitWidth->getSourceRange();
19233
19234 if (Value.isSigned() && Value.isNegative()) {
19235 if (FieldName)
19236 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19237 << FieldName << toString(I: Value, Radix: 10);
19238 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19239 << toString(I: Value, Radix: 10);
19240 }
19241
19242 // The size of the bit-field must not exceed our maximum permitted object
19243 // size.
19244 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19245 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19246 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19247 }
19248
19249 if (!FieldTy->isDependentType()) {
19250 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19251 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19252 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19253
19254 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19255 // ABI.
19256 bool CStdConstraintViolation =
19257 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19258 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19259 if (CStdConstraintViolation || MSBitfieldViolation) {
19260 unsigned DiagWidth =
19261 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19262 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19263 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19264 << !CStdConstraintViolation << DiagWidth;
19265 }
19266
19267 // Warn on types where the user might conceivably expect to get all
19268 // specified bits as value bits: that's all integral types other than
19269 // 'bool'.
19270 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19271 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19272 << FieldName << Value << (unsigned)TypeWidth;
19273 }
19274 }
19275
19276 if (isa<ConstantExpr>(Val: BitWidth))
19277 return BitWidth;
19278 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19279}
19280
19281Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19282 Declarator &D, Expr *BitfieldWidth) {
19283 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19284 D, BitfieldWidth,
19285 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19286 return Res;
19287}
19288
19289FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19290 SourceLocation DeclStart,
19291 Declarator &D, Expr *BitWidth,
19292 InClassInitStyle InitStyle,
19293 AccessSpecifier AS) {
19294 if (D.isDecompositionDeclarator()) {
19295 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19296 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19297 << Decomp.getSourceRange();
19298 return nullptr;
19299 }
19300
19301 const IdentifierInfo *II = D.getIdentifier();
19302 SourceLocation Loc = DeclStart;
19303 if (II) Loc = D.getIdentifierLoc();
19304
19305 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19306 QualType T = TInfo->getType();
19307 if (getLangOpts().CPlusPlus) {
19308 CheckExtraCXXDefaultArguments(D);
19309
19310 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19311 UPPC: UPPC_DataMemberType)) {
19312 D.setInvalidType();
19313 T = Context.IntTy;
19314 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19315 }
19316 }
19317
19318 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19319
19320 if (D.getDeclSpec().isInlineSpecified())
19321 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19322 << getLangOpts().CPlusPlus17;
19323 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19324 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19325 DiagID: diag::err_invalid_thread)
19326 << DeclSpec::getSpecifierName(S: TSCS);
19327
19328 // Check to see if this name was declared as a member previously
19329 NamedDecl *PrevDecl = nullptr;
19330 LookupResult Previous(*this, II, Loc, LookupMemberName,
19331 RedeclarationKind::ForVisibleRedeclaration);
19332 LookupName(R&: Previous, S);
19333 switch (Previous.getResultKind()) {
19334 case LookupResultKind::Found:
19335 case LookupResultKind::FoundUnresolvedValue:
19336 PrevDecl = Previous.getAsSingle<NamedDecl>();
19337 break;
19338
19339 case LookupResultKind::FoundOverloaded:
19340 PrevDecl = Previous.getRepresentativeDecl();
19341 break;
19342
19343 case LookupResultKind::NotFound:
19344 case LookupResultKind::NotFoundInCurrentInstantiation:
19345 case LookupResultKind::Ambiguous:
19346 break;
19347 }
19348 Previous.suppressDiagnostics();
19349
19350 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19351 // Maybe we will complain about the shadowed template parameter.
19352 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19353 // Just pretend that we didn't see the previous declaration.
19354 PrevDecl = nullptr;
19355 }
19356
19357 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19358 PrevDecl = nullptr;
19359
19360 bool Mutable
19361 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19362 SourceLocation TSSL = D.getBeginLoc();
19363 FieldDecl *NewFD
19364 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19365 TSSL, AS, PrevDecl, D: &D);
19366
19367 if (NewFD->isInvalidDecl())
19368 Record->setInvalidDecl();
19369
19370 if (D.getDeclSpec().isModulePrivateSpecified())
19371 NewFD->setModulePrivate();
19372
19373 if (NewFD->isInvalidDecl() && PrevDecl) {
19374 // Don't introduce NewFD into scope; there's already something
19375 // with the same name in the same scope.
19376 } else if (II) {
19377 PushOnScopeChains(D: NewFD, S);
19378 } else
19379 Record->addDecl(D: NewFD);
19380
19381 return NewFD;
19382}
19383
19384FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19385 TypeSourceInfo *TInfo,
19386 RecordDecl *Record, SourceLocation Loc,
19387 bool Mutable, Expr *BitWidth,
19388 InClassInitStyle InitStyle,
19389 SourceLocation TSSL,
19390 AccessSpecifier AS, NamedDecl *PrevDecl,
19391 Declarator *D) {
19392 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19393 bool InvalidDecl = false;
19394 if (D) InvalidDecl = D->isInvalidType();
19395
19396 // If we receive a broken type, recover by assuming 'int' and
19397 // marking this declaration as invalid.
19398 if (T.isNull() || T->containsErrors()) {
19399 InvalidDecl = true;
19400 T = Context.IntTy;
19401 }
19402
19403 QualType EltTy = Context.getBaseElementType(QT: T);
19404 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19405 bool isIncomplete =
19406 LangOpts.HLSL // HLSL allows sizeless builtin types
19407 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19408 : RequireCompleteSizedType(Loc, T: EltTy,
19409 DiagID: diag::err_field_incomplete_or_sizeless);
19410 if (isIncomplete) {
19411 // Fields of incomplete type force their record to be invalid.
19412 Record->setInvalidDecl();
19413 InvalidDecl = true;
19414 } else {
19415 NamedDecl *Def;
19416 EltTy->isIncompleteType(Def: &Def);
19417 if (Def && Def->isInvalidDecl()) {
19418 Record->setInvalidDecl();
19419 InvalidDecl = true;
19420 }
19421 }
19422 }
19423
19424 // TR 18037 does not allow fields to be declared with address space
19425 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19426 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19427 Diag(Loc, DiagID: diag::err_field_with_address_space);
19428 Record->setInvalidDecl();
19429 InvalidDecl = true;
19430 }
19431
19432 if (LangOpts.OpenCL) {
19433 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19434 // used as structure or union field: image, sampler, event or block types.
19435 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19436 T->isBlockPointerType()) {
19437 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19438 Record->setInvalidDecl();
19439 InvalidDecl = true;
19440 }
19441 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19442 // is enabled.
19443 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19444 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19445 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19446 InvalidDecl = true;
19447 }
19448 }
19449
19450 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19451 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19452 T.hasQualifiers()) {
19453 InvalidDecl = true;
19454 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19455 }
19456
19457 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19458 // than a variably modified type.
19459 if (!InvalidDecl && T->isVariablyModifiedType()) {
19460 if (!tryToFixVariablyModifiedVarType(
19461 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19462 InvalidDecl = true;
19463 }
19464
19465 // Fields can not have abstract class types
19466 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19467 DiagID: diag::err_abstract_type_in_decl,
19468 Args: AbstractFieldType))
19469 InvalidDecl = true;
19470
19471 if (InvalidDecl)
19472 BitWidth = nullptr;
19473 // If this is declared as a bit-field, check the bit-field.
19474 if (BitWidth) {
19475 BitWidth =
19476 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19477 if (!BitWidth) {
19478 InvalidDecl = true;
19479 BitWidth = nullptr;
19480 }
19481 }
19482
19483 // Check that 'mutable' is consistent with the type of the declaration.
19484 if (!InvalidDecl && Mutable) {
19485 unsigned DiagID = 0;
19486 if (T->isReferenceType())
19487 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19488 : diag::err_mutable_reference;
19489 else if (T.isConstQualified())
19490 DiagID = diag::err_mutable_const;
19491
19492 if (DiagID) {
19493 SourceLocation ErrLoc = Loc;
19494 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19495 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19496 Diag(Loc: ErrLoc, DiagID);
19497 if (DiagID != diag::ext_mutable_reference) {
19498 Mutable = false;
19499 InvalidDecl = true;
19500 }
19501 }
19502 }
19503
19504 // C++11 [class.union]p8 (DR1460):
19505 // At most one variant member of a union may have a
19506 // brace-or-equal-initializer.
19507 if (InitStyle != ICIS_NoInit)
19508 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19509
19510 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19511 BW: BitWidth, Mutable, InitStyle);
19512 if (InvalidDecl)
19513 NewFD->setInvalidDecl();
19514
19515 if (!InvalidDecl)
19516 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19517
19518 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19519 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19520 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19521 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19522 NewFD->setInvalidDecl();
19523 }
19524
19525 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19526 if (Record->isUnion()) {
19527 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19528 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19529
19530 // C++ [class.union]p1: An object of a class with a non-trivial
19531 // constructor, a non-trivial copy constructor, a non-trivial
19532 // destructor, or a non-trivial copy assignment operator
19533 // cannot be a member of a union, nor can an array of such
19534 // objects.
19535 if (CheckNontrivialField(FD: NewFD))
19536 NewFD->setInvalidDecl();
19537 }
19538
19539 // C++ [class.union]p1: If a union contains a member of reference type,
19540 // the program is ill-formed, except when compiling with MSVC extensions
19541 // enabled.
19542 if (EltTy->isReferenceType()) {
19543 const bool HaveMSExt =
19544 getLangOpts().MicrosoftExt &&
19545 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19546
19547 Diag(Loc: NewFD->getLocation(),
19548 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19549 : diag::err_union_member_of_reference_type)
19550 << NewFD->getDeclName() << EltTy;
19551 if (!HaveMSExt)
19552 NewFD->setInvalidDecl();
19553 }
19554 }
19555 }
19556
19557 // FIXME: We need to pass in the attributes given an AST
19558 // representation, not a parser representation.
19559 if (D) {
19560 // FIXME: The current scope is almost... but not entirely... correct here.
19561 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19562
19563 if (NewFD->hasAttrs())
19564 CheckAlignasUnderalignment(D: NewFD);
19565 }
19566
19567 // In auto-retain/release, infer strong retension for fields of
19568 // retainable type.
19569 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19570 NewFD->setInvalidDecl();
19571
19572 if (T.isObjCGCWeak())
19573 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19574
19575 // PPC MMA non-pointer types are not allowed as field types.
19576 if (Context.getTargetInfo().getTriple().isPPC64() &&
19577 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19578 NewFD->setInvalidDecl();
19579
19580 NewFD->setAccess(AS);
19581 return NewFD;
19582}
19583
19584bool Sema::CheckNontrivialField(FieldDecl *FD) {
19585 assert(FD);
19586 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19587
19588 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19589 return false;
19590
19591 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19592 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19593 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19594 // We check for copy constructors before constructors
19595 // because otherwise we'll never get complaints about
19596 // copy constructors.
19597
19598 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19599 // We're required to check for any non-trivial constructors. Since the
19600 // implicit default constructor is suppressed if there are any
19601 // user-declared constructors, we just need to check that there is a
19602 // trivial default constructor and a trivial copy constructor. (We don't
19603 // worry about move constructors here, since this is a C++98 check.)
19604 if (RDecl->hasNonTrivialCopyConstructor())
19605 member = CXXSpecialMemberKind::CopyConstructor;
19606 else if (!RDecl->hasTrivialDefaultConstructor())
19607 member = CXXSpecialMemberKind::DefaultConstructor;
19608 else if (RDecl->hasNonTrivialCopyAssignment())
19609 member = CXXSpecialMemberKind::CopyAssignment;
19610 else if (RDecl->hasNonTrivialDestructor())
19611 member = CXXSpecialMemberKind::Destructor;
19612
19613 if (member != CXXSpecialMemberKind::Invalid) {
19614 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19615 RDecl->hasObjectMember()) {
19616 // Objective-C++ ARC: it is an error to have a non-trivial field of
19617 // a union. However, system headers in Objective-C programs
19618 // occasionally have Objective-C lifetime objects within unions,
19619 // and rather than cause the program to fail, we make those
19620 // members unavailable.
19621 SourceLocation Loc = FD->getLocation();
19622 if (getSourceManager().isInSystemHeader(Loc)) {
19623 if (!FD->hasAttr<UnavailableAttr>())
19624 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19625 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19626 return false;
19627 }
19628 }
19629
19630 Diag(Loc: FD->getLocation(),
19631 DiagID: getLangOpts().CPlusPlus11
19632 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19633 : diag::err_illegal_union_or_anon_struct_member)
19634 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19635 DiagnoseNontrivial(Record: RDecl, CSM: member);
19636 return !getLangOpts().CPlusPlus11;
19637 }
19638 }
19639
19640 return false;
19641}
19642
19643void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19644 SmallVectorImpl<Decl *> &AllIvarDecls) {
19645 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19646 return;
19647
19648 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19649 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19650
19651 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19652 return;
19653 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19654 if (!ID) {
19655 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19656 if (!CD->IsClassExtension())
19657 return;
19658 }
19659 // No need to add this to end of @implementation.
19660 else
19661 return;
19662 }
19663 // All conditions are met. Add a new bitfield to the tail end of ivars.
19664 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19665 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19666 Expr *BitWidth =
19667 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19668
19669 Ivar = ObjCIvarDecl::Create(
19670 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19671 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19672 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19673 AllIvarDecls.push_back(Elt: Ivar);
19674}
19675
19676/// [class.dtor]p4:
19677/// At the end of the definition of a class, overload resolution is
19678/// performed among the prospective destructors declared in that class with
19679/// an empty argument list to select the destructor for the class, also
19680/// known as the selected destructor.
19681///
19682/// We do the overload resolution here, then mark the selected constructor in the AST.
19683/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19684static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19685 if (!Record->hasUserDeclaredDestructor()) {
19686 return;
19687 }
19688
19689 SourceLocation Loc = Record->getLocation();
19690 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19691
19692 for (auto *Decl : Record->decls()) {
19693 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19694 if (DD->isInvalidDecl())
19695 continue;
19696 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19697 CandidateSet&: OCS);
19698 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19699 }
19700 }
19701
19702 if (OCS.empty()) {
19703 return;
19704 }
19705 OverloadCandidateSet::iterator Best;
19706 unsigned Msg = 0;
19707 OverloadCandidateDisplayKind DisplayKind;
19708
19709 switch (OCS.BestViableFunction(S, Loc, Best)) {
19710 case OR_Success:
19711 case OR_Deleted:
19712 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19713 break;
19714
19715 case OR_Ambiguous:
19716 Msg = diag::err_ambiguous_destructor;
19717 DisplayKind = OCD_AmbiguousCandidates;
19718 break;
19719
19720 case OR_No_Viable_Function:
19721 Msg = diag::err_no_viable_destructor;
19722 DisplayKind = OCD_AllCandidates;
19723 break;
19724 }
19725
19726 if (Msg) {
19727 // OpenCL have got their own thing going with destructors. It's slightly broken,
19728 // but we allow it.
19729 if (!S.LangOpts.OpenCL) {
19730 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19731 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19732 Record->setInvalidDecl();
19733 }
19734 // It's a bit hacky: At this point we've raised an error but we want the
19735 // rest of the compiler to continue somehow working. However almost
19736 // everything we'll try to do with the class will depend on there being a
19737 // destructor. So let's pretend the first one is selected and hope for the
19738 // best.
19739 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19740 }
19741}
19742
19743/// [class.mem.special]p5
19744/// Two special member functions are of the same kind if:
19745/// - they are both default constructors,
19746/// - they are both copy or move constructors with the same first parameter
19747/// type, or
19748/// - they are both copy or move assignment operators with the same first
19749/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19750static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19751 CXXMethodDecl *M1,
19752 CXXMethodDecl *M2,
19753 CXXSpecialMemberKind CSM) {
19754 // We don't want to compare templates to non-templates: See
19755 // https://github.com/llvm/llvm-project/issues/59206
19756 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19757 return bool(M1->getDescribedFunctionTemplate()) ==
19758 bool(M2->getDescribedFunctionTemplate());
19759 // FIXME: better resolve CWG
19760 // https://cplusplus.github.io/CWG/issues/2787.html
19761 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19762 T2: M2->getNonObjectParameter(I: 0)->getType()))
19763 return false;
19764 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19765 T2: M2->getFunctionObjectParameterReferenceType()))
19766 return false;
19767
19768 return true;
19769}
19770
19771/// [class.mem.special]p6:
19772/// An eligible special member function is a special member function for which:
19773/// - the function is not deleted,
19774/// - the associated constraints, if any, are satisfied, and
19775/// - no special member function of the same kind whose associated constraints
19776/// [CWG2595], if any, are satisfied is more constrained.
19777static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19778 ArrayRef<CXXMethodDecl *> Methods,
19779 CXXSpecialMemberKind CSM) {
19780 SmallVector<bool, 4> SatisfactionStatus;
19781
19782 for (CXXMethodDecl *Method : Methods) {
19783 if (!Method->getTrailingRequiresClause())
19784 SatisfactionStatus.push_back(Elt: true);
19785 else {
19786 ConstraintSatisfaction Satisfaction;
19787 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19788 SatisfactionStatus.push_back(Elt: false);
19789 else
19790 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19791 }
19792 }
19793
19794 for (size_t i = 0; i < Methods.size(); i++) {
19795 if (!SatisfactionStatus[i])
19796 continue;
19797 CXXMethodDecl *Method = Methods[i];
19798 CXXMethodDecl *OrigMethod = Method;
19799 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19800 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19801
19802 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19803 bool AnotherMethodIsMoreConstrained = false;
19804 for (size_t j = 0; j < Methods.size(); j++) {
19805 if (i == j || !SatisfactionStatus[j])
19806 continue;
19807 CXXMethodDecl *OtherMethod = Methods[j];
19808 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19809 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19810
19811 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19812 CSM))
19813 continue;
19814
19815 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19816 if (!Other)
19817 continue;
19818 if (!Orig) {
19819 AnotherMethodIsMoreConstrained = true;
19820 break;
19821 }
19822 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19823 Result&: AnotherMethodIsMoreConstrained)) {
19824 // There was an error with the constraints comparison. Exit the loop
19825 // and don't consider this function eligible.
19826 AnotherMethodIsMoreConstrained = true;
19827 }
19828 if (AnotherMethodIsMoreConstrained)
19829 break;
19830 }
19831 // FIXME: Do not consider deleted methods as eligible after implementing
19832 // DR1734 and DR1496.
19833 if (!AnotherMethodIsMoreConstrained) {
19834 Method->setIneligibleOrNotSelected(false);
19835 Record->addedEligibleSpecialMemberFunction(MD: Method,
19836 SMKind: 1 << llvm::to_underlying(E: CSM));
19837 }
19838 }
19839}
19840
19841static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19842 CXXRecordDecl *Record) {
19843 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19844 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19845 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19846 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19847 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19848
19849 for (auto *Decl : Record->decls()) {
19850 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19851 if (!MD) {
19852 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19853 if (FTD)
19854 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19855 }
19856 if (!MD)
19857 continue;
19858 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19859 if (CD->isInvalidDecl())
19860 continue;
19861 if (CD->isDefaultConstructor())
19862 DefaultConstructors.push_back(Elt: MD);
19863 else if (CD->isCopyConstructor())
19864 CopyConstructors.push_back(Elt: MD);
19865 else if (CD->isMoveConstructor())
19866 MoveConstructors.push_back(Elt: MD);
19867 } else if (MD->isCopyAssignmentOperator()) {
19868 CopyAssignmentOperators.push_back(Elt: MD);
19869 } else if (MD->isMoveAssignmentOperator()) {
19870 MoveAssignmentOperators.push_back(Elt: MD);
19871 }
19872 }
19873
19874 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19875 CSM: CXXSpecialMemberKind::DefaultConstructor);
19876 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19877 CSM: CXXSpecialMemberKind::CopyConstructor);
19878 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19879 CSM: CXXSpecialMemberKind::MoveConstructor);
19880 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19881 CSM: CXXSpecialMemberKind::CopyAssignment);
19882 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19883 CSM: CXXSpecialMemberKind::MoveAssignment);
19884}
19885
19886bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19887 // Check to see if a FieldDecl is a pointer to a function.
19888 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19889 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19890 if (!FD) {
19891 // Check whether this is a forward declaration that was inserted by
19892 // Clang. This happens when a non-forward declared / defined type is
19893 // used, e.g.:
19894 //
19895 // struct foo {
19896 // struct bar *(*f)();
19897 // struct bar *(*g)();
19898 // };
19899 //
19900 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19901 // incomplete definition.
19902 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19903 return !TD->isCompleteDefinition();
19904 return false;
19905 }
19906 QualType FieldType = FD->getType().getDesugaredType(Context);
19907 if (isa<PointerType>(Val: FieldType)) {
19908 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19909 return PointeeType.getDesugaredType(Context)->isFunctionType();
19910 }
19911 // If a member is a struct entirely of function pointers, that counts too.
19912 if (const auto *Record = FieldType->getAsRecordDecl();
19913 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19914 return true;
19915 return false;
19916 };
19917
19918 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19919}
19920
19921void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19922 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19923 SourceLocation RBrac,
19924 const ParsedAttributesView &Attrs) {
19925 assert(EnclosingDecl && "missing record or interface decl");
19926
19927 // If this is an Objective-C @implementation or category and we have
19928 // new fields here we should reset the layout of the interface since
19929 // it will now change.
19930 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19931 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19932 switch (DC->getKind()) {
19933 default: break;
19934 case Decl::ObjCCategory:
19935 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19936 break;
19937 case Decl::ObjCImplementation:
19938 Context.
19939 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19940 break;
19941 }
19942 }
19943
19944 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19945 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19946
19947 // Start counting up the number of named members; make sure to include
19948 // members of anonymous structs and unions in the total.
19949 unsigned NumNamedMembers = 0;
19950 if (Record) {
19951 for (const auto *I : Record->decls()) {
19952 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19953 if (IFD->getDeclName())
19954 ++NumNamedMembers;
19955 }
19956 }
19957
19958 // Verify that all the fields are okay.
19959 SmallVector<FieldDecl*, 32> RecFields;
19960 const FieldDecl *PreviousField = nullptr;
19961 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19962 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19963 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19964
19965 // Get the type for the field.
19966 const Type *FDTy = FD->getType().getTypePtr();
19967
19968 if (!FD->isAnonymousStructOrUnion()) {
19969 // Remember all fields written by the user.
19970 RecFields.push_back(Elt: FD);
19971 }
19972
19973 // If the field is already invalid for some reason, don't emit more
19974 // diagnostics about it.
19975 if (FD->isInvalidDecl()) {
19976 EnclosingDecl->setInvalidDecl();
19977 continue;
19978 }
19979
19980 // C99 6.7.2.1p2:
19981 // A structure or union shall not contain a member with
19982 // incomplete or function type (hence, a structure shall not
19983 // contain an instance of itself, but may contain a pointer to
19984 // an instance of itself), except that the last member of a
19985 // structure with more than one named member may have incomplete
19986 // array type; such a structure (and any union containing,
19987 // possibly recursively, a member that is such a structure)
19988 // shall not be a member of a structure or an element of an
19989 // array.
19990 bool IsLastField = (i + 1 == Fields.end());
19991 if (FDTy->isFunctionType()) {
19992 // Field declared as a function.
19993 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19994 << FD->getDeclName();
19995 FD->setInvalidDecl();
19996 EnclosingDecl->setInvalidDecl();
19997 continue;
19998 } else if (FDTy->isIncompleteArrayType() &&
19999 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20000 if (Record) {
20001 // Flexible array member.
20002 // Microsoft and g++ is more permissive regarding flexible array.
20003 // It will accept flexible array in union and also
20004 // as the sole element of a struct/class.
20005 unsigned DiagID = 0;
20006 if (!Record->isUnion() && !IsLastField) {
20007 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20008 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20009 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20010 FD->setInvalidDecl();
20011 EnclosingDecl->setInvalidDecl();
20012 continue;
20013 } else if (Record->isUnion())
20014 DiagID = getLangOpts().MicrosoftExt
20015 ? diag::ext_flexible_array_union_ms
20016 : diag::ext_flexible_array_union_gnu;
20017 else if (NumNamedMembers < 1)
20018 DiagID = getLangOpts().MicrosoftExt
20019 ? diag::ext_flexible_array_empty_aggregate_ms
20020 : diag::ext_flexible_array_empty_aggregate_gnu;
20021
20022 if (DiagID)
20023 Diag(Loc: FD->getLocation(), DiagID)
20024 << FD->getDeclName() << Record->getTagKind();
20025 // While the layout of types that contain virtual bases is not specified
20026 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20027 // virtual bases after the derived members. This would make a flexible
20028 // array member declared at the end of an object not adjacent to the end
20029 // of the type.
20030 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20031 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20032 << FD->getDeclName() << Record->getTagKind();
20033 if (!getLangOpts().C99)
20034 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20035 << FD->getDeclName() << Record->getTagKind();
20036
20037 // If the element type has a non-trivial destructor, we would not
20038 // implicitly destroy the elements, so disallow it for now.
20039 //
20040 // FIXME: GCC allows this. We should probably either implicitly delete
20041 // the destructor of the containing class, or just allow this.
20042 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20043 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20044 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20045 << FD->getDeclName() << FD->getType();
20046 FD->setInvalidDecl();
20047 EnclosingDecl->setInvalidDecl();
20048 continue;
20049 }
20050 // Okay, we have a legal flexible array member at the end of the struct.
20051 Record->setHasFlexibleArrayMember(true);
20052 } else {
20053 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20054 // unless they are followed by another ivar. That check is done
20055 // elsewhere, after synthesized ivars are known.
20056 }
20057 } else if (!FDTy->isDependentType() &&
20058 (LangOpts.HLSL // HLSL allows sizeless builtin types
20059 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20060 DiagID: diag::err_incomplete_type)
20061 : RequireCompleteSizedType(
20062 Loc: FD->getLocation(), T: FD->getType(),
20063 DiagID: diag::err_field_incomplete_or_sizeless))) {
20064 // Incomplete type
20065 FD->setInvalidDecl();
20066 EnclosingDecl->setInvalidDecl();
20067 continue;
20068 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20069 if (Record && RD->hasFlexibleArrayMember()) {
20070 // A type which contains a flexible array member is considered to be a
20071 // flexible array member.
20072 Record->setHasFlexibleArrayMember(true);
20073 if (!Record->isUnion()) {
20074 // If this is a struct/class and this is not the last element, reject
20075 // it. Note that GCC supports variable sized arrays in the middle of
20076 // structures.
20077 if (!IsLastField)
20078 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20079 << FD->getDeclName() << FD->getType();
20080 else {
20081 // We support flexible arrays at the end of structs in
20082 // other structs as an extension.
20083 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20084 << FD->getDeclName();
20085 }
20086 }
20087 }
20088 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20089 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20090 DiagID: diag::err_abstract_type_in_decl,
20091 Args: AbstractIvarType)) {
20092 // Ivars can not have abstract class types
20093 FD->setInvalidDecl();
20094 }
20095 if (Record && RD->hasObjectMember())
20096 Record->setHasObjectMember(true);
20097 if (Record && RD->hasVolatileMember())
20098 Record->setHasVolatileMember(true);
20099 } else if (FDTy->isObjCObjectType()) {
20100 /// A field cannot be an Objective-c object
20101 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20102 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20103 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20104 FD->setType(T);
20105 } else if (Record && Record->isUnion() &&
20106 FD->getType().hasNonTrivialObjCLifetime() &&
20107 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20108 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20109 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20110 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20111 // For backward compatibility, fields of C unions declared in system
20112 // headers that have non-trivial ObjC ownership qualifications are marked
20113 // as unavailable unless the qualifier is explicit and __strong. This can
20114 // break ABI compatibility between programs compiled with ARC and MRR, but
20115 // is a better option than rejecting programs using those unions under
20116 // ARC.
20117 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20118 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20119 Range: FD->getLocation()));
20120 } else if (getLangOpts().ObjC &&
20121 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20122 !Record->hasObjectMember()) {
20123 if (FD->getType()->isObjCObjectPointerType() ||
20124 FD->getType().isObjCGCStrong())
20125 Record->setHasObjectMember(true);
20126 else if (Context.getAsArrayType(T: FD->getType())) {
20127 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20128 if (const auto *RD = BaseType->getAsRecordDecl();
20129 RD && RD->hasObjectMember())
20130 Record->setHasObjectMember(true);
20131 else if (BaseType->isObjCObjectPointerType() ||
20132 BaseType.isObjCGCStrong())
20133 Record->setHasObjectMember(true);
20134 }
20135 }
20136
20137 if (Record && !getLangOpts().CPlusPlus &&
20138 !shouldIgnoreForRecordTriviality(FD)) {
20139 QualType FT = FD->getType();
20140 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20141 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20142 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20143 Record->isUnion())
20144 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20145 }
20146 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20147 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20148 Record->setNonTrivialToPrimitiveCopy(true);
20149 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20150 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20151 }
20152 if (FD->hasAttr<ExplicitInitAttr>())
20153 Record->setHasUninitializedExplicitInitFields(true);
20154 if (FT.isDestructedType()) {
20155 Record->setNonTrivialToPrimitiveDestroy(true);
20156 Record->setParamDestroyedInCallee(true);
20157 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20158 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20159 }
20160
20161 if (const auto *RD = FT->getAsRecordDecl()) {
20162 if (RD->getArgPassingRestrictions() ==
20163 RecordArgPassingKind::CanNeverPassInRegs)
20164 Record->setArgPassingRestrictions(
20165 RecordArgPassingKind::CanNeverPassInRegs);
20166 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20167 Record->setArgPassingRestrictions(
20168 RecordArgPassingKind::CanNeverPassInRegs);
20169 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20170 Q && Q.isAddressDiscriminated()) {
20171 Record->setArgPassingRestrictions(
20172 RecordArgPassingKind::CanNeverPassInRegs);
20173 Record->setNonTrivialToPrimitiveCopy(true);
20174 }
20175 }
20176
20177 if (Record && FD->getType().isVolatileQualified())
20178 Record->setHasVolatileMember(true);
20179 bool ReportMSBitfieldStoragePacking =
20180 Record && PreviousField &&
20181 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20182 Loc: Record->getLocation());
20183 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20184 return FD->isBitField() && !FD->getType()->isDependentType();
20185 };
20186
20187 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20188 IsNonDependentBitField(PreviousField)) {
20189 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20190 CharUnits PreviousFieldStorageSize =
20191 Context.getTypeSizeInChars(T: PreviousField->getType());
20192 if (FDStorageSize != PreviousFieldStorageSize) {
20193 Diag(Loc: FD->getLocation(),
20194 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20195 << FD << FD->getType() << FDStorageSize.getQuantity()
20196 << PreviousFieldStorageSize.getQuantity();
20197 Diag(Loc: PreviousField->getLocation(),
20198 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20199 << PreviousField << PreviousField->getType();
20200 }
20201 }
20202 // Keep track of the number of named members.
20203 if (FD->getIdentifier())
20204 ++NumNamedMembers;
20205 }
20206
20207 // Okay, we successfully defined 'Record'.
20208 if (Record) {
20209 bool Completed = false;
20210 if (S) {
20211 Scope *Parent = S->getParent();
20212 if (Parent && Parent->isTypeAliasScope() &&
20213 Parent->isTemplateParamScope())
20214 Record->setInvalidDecl();
20215 }
20216
20217 if (CXXRecord) {
20218 if (!CXXRecord->isInvalidDecl()) {
20219 // Set access bits correctly on the directly-declared conversions.
20220 for (CXXRecordDecl::conversion_iterator
20221 I = CXXRecord->conversion_begin(),
20222 E = CXXRecord->conversion_end(); I != E; ++I)
20223 I.setAccess((*I)->getAccess());
20224 }
20225
20226 // Add any implicitly-declared members to this class.
20227 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20228
20229 if (!CXXRecord->isDependentType()) {
20230 if (!CXXRecord->isInvalidDecl()) {
20231 // If we have virtual base classes, we may end up finding multiple
20232 // final overriders for a given virtual function. Check for this
20233 // problem now.
20234 if (CXXRecord->getNumVBases()) {
20235 CXXFinalOverriderMap FinalOverriders;
20236 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20237
20238 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20239 MEnd = FinalOverriders.end();
20240 M != MEnd; ++M) {
20241 for (OverridingMethods::iterator SO = M->second.begin(),
20242 SOEnd = M->second.end();
20243 SO != SOEnd; ++SO) {
20244 assert(SO->second.size() > 0 &&
20245 "Virtual function without overriding functions?");
20246 if (SO->second.size() == 1)
20247 continue;
20248
20249 // C++ [class.virtual]p2:
20250 // In a derived class, if a virtual member function of a base
20251 // class subobject has more than one final overrider the
20252 // program is ill-formed.
20253 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20254 << (const NamedDecl *)M->first << Record;
20255 Diag(Loc: M->first->getLocation(),
20256 DiagID: diag::note_overridden_virtual_function);
20257 for (OverridingMethods::overriding_iterator
20258 OM = SO->second.begin(),
20259 OMEnd = SO->second.end();
20260 OM != OMEnd; ++OM)
20261 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20262 << (const NamedDecl *)M->first << OM->Method->getParent();
20263
20264 Record->setInvalidDecl();
20265 }
20266 }
20267 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20268 Completed = true;
20269 }
20270 }
20271 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20272 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20273 }
20274 }
20275
20276 if (!Completed)
20277 Record->completeDefinition();
20278
20279 // Handle attributes before checking the layout.
20280 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20281
20282 // Maybe randomize the record's decls. We automatically randomize a record
20283 // of function pointers, unless it has the "no_randomize_layout" attribute.
20284 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20285 !Record->isRandomized() && !Record->isUnion() &&
20286 (Record->hasAttr<RandomizeLayoutAttr>() ||
20287 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20288 EntirelyFunctionPointers(Record)))) {
20289 SmallVector<Decl *, 32> NewDeclOrdering;
20290 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20291 FinalOrdering&: NewDeclOrdering))
20292 Record->reorderDecls(Decls: NewDeclOrdering);
20293 }
20294
20295 // We may have deferred checking for a deleted destructor. Check now.
20296 if (CXXRecord) {
20297 auto *Dtor = CXXRecord->getDestructor();
20298 if (Dtor && Dtor->isImplicit() &&
20299 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20300 CXXRecord->setImplicitDestructorIsDeleted();
20301 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20302 }
20303 }
20304
20305 if (Record->hasAttrs()) {
20306 CheckAlignasUnderalignment(D: Record);
20307
20308 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20309 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20310 Range: IA->getRange(), BestCase: IA->getBestCase(),
20311 SemanticSpelling: IA->getInheritanceModel());
20312 }
20313
20314 // Check if the structure/union declaration is a type that can have zero
20315 // size in C. For C this is a language extension, for C++ it may cause
20316 // compatibility problems.
20317 bool CheckForZeroSize;
20318 if (!getLangOpts().CPlusPlus) {
20319 CheckForZeroSize = true;
20320 } else {
20321 // For C++ filter out types that cannot be referenced in C code.
20322 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20323 CheckForZeroSize =
20324 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20325 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20326 CXXRecord->isCLike();
20327 }
20328 if (CheckForZeroSize) {
20329 bool ZeroSize = true;
20330 bool IsEmpty = true;
20331 unsigned NonBitFields = 0;
20332 for (RecordDecl::field_iterator I = Record->field_begin(),
20333 E = Record->field_end();
20334 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20335 IsEmpty = false;
20336 if (I->isUnnamedBitField()) {
20337 if (!I->isZeroLengthBitField())
20338 ZeroSize = false;
20339 } else {
20340 ++NonBitFields;
20341 QualType FieldType = I->getType();
20342 if (FieldType->isIncompleteType() ||
20343 !Context.getTypeSizeInChars(T: FieldType).isZero())
20344 ZeroSize = false;
20345 }
20346 }
20347
20348 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20349 // allowed in C++, but warn if its declaration is inside
20350 // extern "C" block.
20351 if (ZeroSize) {
20352 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20353 diag::warn_zero_size_struct_union_in_extern_c :
20354 diag::warn_zero_size_struct_union_compat)
20355 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20356 }
20357
20358 // Structs without named members are extension in C (C99 6.7.2.1p7),
20359 // but are accepted by GCC. In C2y, this became implementation-defined
20360 // (C2y 6.7.3.2p10).
20361 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20362 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20363 : diag::ext_no_named_members_in_struct_union)
20364 << Record->isUnion();
20365 }
20366 }
20367 } else {
20368 ObjCIvarDecl **ClsFields =
20369 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20370 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20371 ID->setEndOfDefinitionLoc(RBrac);
20372 // Add ivar's to class's DeclContext.
20373 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20374 ClsFields[i]->setLexicalDeclContext(ID);
20375 ID->addDecl(D: ClsFields[i]);
20376 }
20377 // Must enforce the rule that ivars in the base classes may not be
20378 // duplicates.
20379 if (ID->getSuperClass())
20380 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20381 } else if (ObjCImplementationDecl *IMPDecl =
20382 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20383 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20384 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20385 // Ivar declared in @implementation never belongs to the implementation.
20386 // Only it is in implementation's lexical context.
20387 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20388 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20389 Loc: RBrac);
20390 IMPDecl->setIvarLBraceLoc(LBrac);
20391 IMPDecl->setIvarRBraceLoc(RBrac);
20392 } else if (ObjCCategoryDecl *CDecl =
20393 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20394 // case of ivars in class extension; all other cases have been
20395 // reported as errors elsewhere.
20396 // FIXME. Class extension does not have a LocEnd field.
20397 // CDecl->setLocEnd(RBrac);
20398 // Add ivar's to class extension's DeclContext.
20399 // Diagnose redeclaration of private ivars.
20400 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20401 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20402 if (IDecl) {
20403 if (const ObjCIvarDecl *ClsIvar =
20404 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20405 Diag(Loc: ClsFields[i]->getLocation(),
20406 DiagID: diag::err_duplicate_ivar_declaration);
20407 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20408 continue;
20409 }
20410 for (const auto *Ext : IDecl->known_extensions()) {
20411 if (const ObjCIvarDecl *ClsExtIvar
20412 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20413 Diag(Loc: ClsFields[i]->getLocation(),
20414 DiagID: diag::err_duplicate_ivar_declaration);
20415 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20416 continue;
20417 }
20418 }
20419 }
20420 ClsFields[i]->setLexicalDeclContext(CDecl);
20421 CDecl->addDecl(D: ClsFields[i]);
20422 }
20423 CDecl->setIvarLBraceLoc(LBrac);
20424 CDecl->setIvarRBraceLoc(RBrac);
20425 }
20426 }
20427 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20428 ProcessAPINotes(D: Record);
20429}
20430
20431// Given an integral type, return the next larger integral type
20432// (or a NULL type of no such type exists).
20433static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20434 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20435 // enum checking below.
20436 assert((T->isIntegralType(Context) ||
20437 T->isEnumeralType()) && "Integral type required!");
20438 const unsigned NumTypes = 4;
20439 QualType SignedIntegralTypes[NumTypes] = {
20440 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20441 };
20442 QualType UnsignedIntegralTypes[NumTypes] = {
20443 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20444 Context.UnsignedLongLongTy
20445 };
20446
20447 unsigned BitWidth = Context.getTypeSize(T);
20448 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20449 : UnsignedIntegralTypes;
20450 for (unsigned I = 0; I != NumTypes; ++I)
20451 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20452 return Types[I];
20453
20454 return QualType();
20455}
20456
20457EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20458 EnumConstantDecl *LastEnumConst,
20459 SourceLocation IdLoc,
20460 IdentifierInfo *Id,
20461 Expr *Val) {
20462 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20463 llvm::APSInt EnumVal(IntWidth);
20464 QualType EltTy;
20465
20466 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20467 Val = nullptr;
20468
20469 if (Val)
20470 Val = DefaultLvalueConversion(E: Val).get();
20471
20472 if (Val) {
20473 if (Enum->isDependentType() || Val->isTypeDependent() ||
20474 Val->containsErrors())
20475 EltTy = Context.DependentTy;
20476 else {
20477 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20478 // underlying type, but do allow it in all other contexts.
20479 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20480 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20481 // constant-expression in the enumerator-definition shall be a converted
20482 // constant expression of the underlying type.
20483 EltTy = Enum->getIntegerType();
20484 ExprResult Converted = CheckConvertedConstantExpression(
20485 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20486 if (Converted.isInvalid())
20487 Val = nullptr;
20488 else
20489 Val = Converted.get();
20490 } else if (!Val->isValueDependent() &&
20491 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20492 CanFold: AllowFoldKind::Allow)
20493 .get())) {
20494 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20495 } else {
20496 if (Enum->isComplete()) {
20497 EltTy = Enum->getIntegerType();
20498
20499 // In Obj-C and Microsoft mode, require the enumeration value to be
20500 // representable in the underlying type of the enumeration. In C++11,
20501 // we perform a non-narrowing conversion as part of converted constant
20502 // expression checking.
20503 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20504 if (Context.getTargetInfo()
20505 .getTriple()
20506 .isWindowsMSVCEnvironment()) {
20507 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20508 } else {
20509 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20510 }
20511 }
20512
20513 // Cast to the underlying type.
20514 Val = ImpCastExprToType(E: Val, Type: EltTy,
20515 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20516 : CK_IntegralCast)
20517 .get();
20518 } else if (getLangOpts().CPlusPlus) {
20519 // C++11 [dcl.enum]p5:
20520 // If the underlying type is not fixed, the type of each enumerator
20521 // is the type of its initializing value:
20522 // - If an initializer is specified for an enumerator, the
20523 // initializing value has the same type as the expression.
20524 EltTy = Val->getType();
20525 } else {
20526 // C99 6.7.2.2p2:
20527 // The expression that defines the value of an enumeration constant
20528 // shall be an integer constant expression that has a value
20529 // representable as an int.
20530
20531 // Complain if the value is not representable in an int.
20532 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20533 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20534 ? diag::warn_c17_compat_enum_value_not_int
20535 : diag::ext_c23_enum_value_not_int)
20536 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20537 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20538 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20539 // Force the type of the expression to 'int'.
20540 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20541 }
20542 EltTy = Val->getType();
20543 }
20544 }
20545 }
20546 }
20547
20548 if (!Val) {
20549 if (Enum->isDependentType())
20550 EltTy = Context.DependentTy;
20551 else if (!LastEnumConst) {
20552 // C++0x [dcl.enum]p5:
20553 // If the underlying type is not fixed, the type of each enumerator
20554 // is the type of its initializing value:
20555 // - If no initializer is specified for the first enumerator, the
20556 // initializing value has an unspecified integral type.
20557 //
20558 // GCC uses 'int' for its unspecified integral type, as does
20559 // C99 6.7.2.2p3.
20560 if (Enum->isFixed()) {
20561 EltTy = Enum->getIntegerType();
20562 }
20563 else {
20564 EltTy = Context.IntTy;
20565 }
20566 } else {
20567 // Assign the last value + 1.
20568 EnumVal = LastEnumConst->getInitVal();
20569 ++EnumVal;
20570 EltTy = LastEnumConst->getType();
20571
20572 // Check for overflow on increment.
20573 if (EnumVal < LastEnumConst->getInitVal()) {
20574 // C++0x [dcl.enum]p5:
20575 // If the underlying type is not fixed, the type of each enumerator
20576 // is the type of its initializing value:
20577 //
20578 // - Otherwise the type of the initializing value is the same as
20579 // the type of the initializing value of the preceding enumerator
20580 // unless the incremented value is not representable in that type,
20581 // in which case the type is an unspecified integral type
20582 // sufficient to contain the incremented value. If no such type
20583 // exists, the program is ill-formed.
20584 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20585 if (T.isNull() || Enum->isFixed()) {
20586 // There is no integral type larger enough to represent this
20587 // value. Complain, then allow the value to wrap around.
20588 EnumVal = LastEnumConst->getInitVal();
20589 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20590 ++EnumVal;
20591 if (Enum->isFixed())
20592 // When the underlying type is fixed, this is ill-formed.
20593 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20594 << toString(I: EnumVal, Radix: 10)
20595 << EltTy;
20596 else
20597 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20598 << toString(I: EnumVal, Radix: 10);
20599 } else {
20600 EltTy = T;
20601 }
20602
20603 // Retrieve the last enumerator's value, extent that type to the
20604 // type that is supposed to be large enough to represent the incremented
20605 // value, then increment.
20606 EnumVal = LastEnumConst->getInitVal();
20607 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20608 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20609 ++EnumVal;
20610
20611 // If we're not in C++, diagnose the overflow of enumerator values,
20612 // which in C99 means that the enumerator value is not representable in
20613 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20614 // are representable in some larger integral type and we allow it in
20615 // older language modes as an extension.
20616 // Exclude fixed enumerators since they are diagnosed with an error for
20617 // this case.
20618 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20619 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20620 ? diag::warn_c17_compat_enum_value_not_int
20621 : diag::ext_c23_enum_value_not_int)
20622 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20623 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20624 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20625 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20626 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20627 : diag::ext_c23_enum_value_not_int)
20628 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20629 }
20630 }
20631 }
20632
20633 if (!EltTy->isDependentType()) {
20634 // Make the enumerator value match the signedness and size of the
20635 // enumerator's type.
20636 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20637 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20638 }
20639
20640 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20641 E: Val, V: EnumVal);
20642}
20643
20644SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20645 SourceLocation IILoc) {
20646 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20647 !getLangOpts().CPlusPlus)
20648 return SkipBodyInfo();
20649
20650 // We have an anonymous enum definition. Look up the first enumerator to
20651 // determine if we should merge the definition with an existing one and
20652 // skip the body.
20653 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20654 Redecl: forRedeclarationInCurContext());
20655 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20656 if (!PrevECD)
20657 return SkipBodyInfo();
20658
20659 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20660 NamedDecl *Hidden;
20661 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20662 SkipBodyInfo Skip;
20663 Skip.Previous = Hidden;
20664 return Skip;
20665 }
20666
20667 return SkipBodyInfo();
20668}
20669
20670Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20671 SourceLocation IdLoc, IdentifierInfo *Id,
20672 const ParsedAttributesView &Attrs,
20673 SourceLocation EqualLoc, Expr *Val,
20674 SkipBodyInfo *SkipBody) {
20675 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20676 EnumConstantDecl *LastEnumConst =
20677 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20678
20679 // The scope passed in may not be a decl scope. Zip up the scope tree until
20680 // we find one that is.
20681 S = getNonFieldDeclScope(S);
20682
20683 // Verify that there isn't already something declared with this name in this
20684 // scope.
20685 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20686 RedeclarationKind::ForVisibleRedeclaration);
20687 LookupName(R, S);
20688 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20689
20690 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20691 // Maybe we will complain about the shadowed template parameter.
20692 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20693 // Just pretend that we didn't see the previous declaration.
20694 PrevDecl = nullptr;
20695 }
20696
20697 // C++ [class.mem]p15:
20698 // If T is the name of a class, then each of the following shall have a name
20699 // different from T:
20700 // - every enumerator of every member of class T that is an unscoped
20701 // enumerated type
20702 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20703 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20704 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20705 return nullptr;
20706
20707 EnumConstantDecl *New =
20708 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20709 if (!New)
20710 return nullptr;
20711
20712 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20713 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20714 // Check for other kinds of shadowing not already handled.
20715 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20716 }
20717
20718 // When in C++, we may get a TagDecl with the same name; in this case the
20719 // enum constant will 'hide' the tag.
20720 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20721 "Received TagDecl when not in C++!");
20722 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20723 if (isa<EnumConstantDecl>(Val: PrevDecl))
20724 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20725 else
20726 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20727 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20728 return nullptr;
20729 }
20730 }
20731
20732 // Process attributes.
20733 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20734 AddPragmaAttributes(S, D: New);
20735 ProcessAPINotes(D: New);
20736
20737 // Register this decl in the current scope stack.
20738 New->setAccess(TheEnumDecl->getAccess());
20739 PushOnScopeChains(D: New, S);
20740
20741 ActOnDocumentableDecl(D: New);
20742
20743 return New;
20744}
20745
20746// Returns true when the enum initial expression does not trigger the
20747// duplicate enum warning. A few common cases are exempted as follows:
20748// Element2 = Element1
20749// Element2 = Element1 + 1
20750// Element2 = Element1 - 1
20751// Where Element2 and Element1 are from the same enum.
20752static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20753 Expr *InitExpr = ECD->getInitExpr();
20754 if (!InitExpr)
20755 return true;
20756 InitExpr = InitExpr->IgnoreImpCasts();
20757
20758 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20759 if (!BO->isAdditiveOp())
20760 return true;
20761 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20762 if (!IL)
20763 return true;
20764 if (IL->getValue() != 1)
20765 return true;
20766
20767 InitExpr = BO->getLHS();
20768 }
20769
20770 // This checks if the elements are from the same enum.
20771 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20772 if (!DRE)
20773 return true;
20774
20775 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20776 if (!EnumConstant)
20777 return true;
20778
20779 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20780 Enum)
20781 return true;
20782
20783 return false;
20784}
20785
20786// Emits a warning when an element is implicitly set a value that
20787// a previous element has already been set to.
20788static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20789 EnumDecl *Enum, QualType EnumType) {
20790 // Avoid anonymous enums
20791 if (!Enum->getIdentifier())
20792 return;
20793
20794 // Only check for small enums.
20795 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20796 return;
20797
20798 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20799 return;
20800
20801 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20802 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20803
20804 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20805
20806 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20807 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20808
20809 // Use int64_t as a key to avoid needing special handling for map keys.
20810 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20811 llvm::APSInt Val = D->getInitVal();
20812 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20813 };
20814
20815 DuplicatesVector DupVector;
20816 ValueToVectorMap EnumMap;
20817
20818 // Populate the EnumMap with all values represented by enum constants without
20819 // an initializer.
20820 for (auto *Element : Elements) {
20821 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20822
20823 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20824 // this constant. Skip this enum since it may be ill-formed.
20825 if (!ECD) {
20826 return;
20827 }
20828
20829 // Constants with initializers are handled in the next loop.
20830 if (ECD->getInitExpr())
20831 continue;
20832
20833 // Duplicate values are handled in the next loop.
20834 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20835 }
20836
20837 if (EnumMap.size() == 0)
20838 return;
20839
20840 // Create vectors for any values that has duplicates.
20841 for (auto *Element : Elements) {
20842 // The last loop returned if any constant was null.
20843 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20844 if (!ValidDuplicateEnum(ECD, Enum))
20845 continue;
20846
20847 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20848 if (Iter == EnumMap.end())
20849 continue;
20850
20851 DeclOrVector& Entry = Iter->second;
20852 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20853 // Ensure constants are different.
20854 if (D == ECD)
20855 continue;
20856
20857 // Create new vector and push values onto it.
20858 auto Vec = std::make_unique<ECDVector>();
20859 Vec->push_back(Elt: D);
20860 Vec->push_back(Elt: ECD);
20861
20862 // Update entry to point to the duplicates vector.
20863 Entry = Vec.get();
20864
20865 // Store the vector somewhere we can consult later for quick emission of
20866 // diagnostics.
20867 DupVector.emplace_back(Args: std::move(Vec));
20868 continue;
20869 }
20870
20871 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20872 // Make sure constants are not added more than once.
20873 if (*Vec->begin() == ECD)
20874 continue;
20875
20876 Vec->push_back(Elt: ECD);
20877 }
20878
20879 // Emit diagnostics.
20880 for (const auto &Vec : DupVector) {
20881 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20882
20883 // Emit warning for one enum constant.
20884 auto *FirstECD = Vec->front();
20885 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20886 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20887 << FirstECD->getSourceRange();
20888
20889 // Emit one note for each of the remaining enum constants with
20890 // the same value.
20891 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20892 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20893 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20894 << ECD->getSourceRange();
20895 }
20896}
20897
20898bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20899 bool AllowMask) const {
20900 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20901 assert(ED->isCompleteDefinition() && "expected enum definition");
20902
20903 auto R = FlagBitsCache.try_emplace(Key: ED);
20904 llvm::APInt &FlagBits = R.first->second;
20905
20906 if (R.second) {
20907 for (auto *E : ED->enumerators()) {
20908 const auto &EVal = E->getInitVal();
20909 // Only single-bit enumerators introduce new flag values.
20910 if (EVal.isPowerOf2())
20911 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20912 }
20913 }
20914
20915 // A value is in a flag enum if either its bits are a subset of the enum's
20916 // flag bits (the first condition) or we are allowing masks and the same is
20917 // true of its complement (the second condition). When masks are allowed, we
20918 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20919 //
20920 // While it's true that any value could be used as a mask, the assumption is
20921 // that a mask will have all of the insignificant bits set. Anything else is
20922 // likely a logic error.
20923 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20924 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20925}
20926
20927// Emits a warning when a suspicious comparison operator is used along side
20928// binary operators in enum initializers.
20929static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20930 const EnumDecl *Enum) {
20931 bool HasBitwiseOp = false;
20932 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20933
20934 // Iterate over all the enum values, gather suspisious comparison ops and
20935 // whether any enum initialisers contain a binary operator.
20936 for (const auto *ECD : Enum->enumerators()) {
20937 const Expr *InitExpr = ECD->getInitExpr();
20938 if (!InitExpr)
20939 continue;
20940
20941 const Expr *E = InitExpr->IgnoreParenImpCasts();
20942
20943 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
20944 BinaryOperatorKind Op = BinOp->getOpcode();
20945
20946 // Check for bitwise ops (<<, >>, &, |)
20947 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20948 HasBitwiseOp = true;
20949 } else if (Op == BO_LT || Op == BO_GT) {
20950 // Check for the typo pattern (Comparison < or >)
20951 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20952 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
20953 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20954 if (IntLiteral->getValue() == 1)
20955 SuspiciousCompares.push_back(Elt: BinOp);
20956 }
20957 }
20958 }
20959 }
20960
20961 // If we found a bitwise op and some sus compares, iterate over the compares
20962 // and warn.
20963 if (HasBitwiseOp) {
20964 for (const auto *BinOp : SuspiciousCompares) {
20965 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20966 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
20967 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
20968 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20969
20970 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
20971 << BinOp->getOpcodeStr() << SuggestedOp;
20972
20973 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
20974 << SuggestedOp
20975 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
20976 }
20977 }
20978}
20979
20980void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20981 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20982 const ParsedAttributesView &Attrs) {
20983 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20984 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
20985
20986 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20987 ProcessAPINotes(D: Enum);
20988
20989 if (Enum->isDependentType()) {
20990 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20991 EnumConstantDecl *ECD =
20992 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20993 if (!ECD) continue;
20994
20995 ECD->setType(EnumType);
20996 }
20997
20998 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20999 return;
21000 }
21001
21002 // Verify that all the values are okay, compute the size of the values, and
21003 // reverse the list.
21004 unsigned NumNegativeBits = 0;
21005 unsigned NumPositiveBits = 0;
21006 bool MembersRepresentableByInt =
21007 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21008
21009 // Figure out the type that should be used for this enum.
21010 QualType BestType;
21011 unsigned BestWidth;
21012
21013 // C++0x N3000 [conv.prom]p3:
21014 // An rvalue of an unscoped enumeration type whose underlying
21015 // type is not fixed can be converted to an rvalue of the first
21016 // of the following types that can represent all the values of
21017 // the enumeration: int, unsigned int, long int, unsigned long
21018 // int, long long int, or unsigned long long int.
21019 // C99 6.4.4.3p2:
21020 // An identifier declared as an enumeration constant has type int.
21021 // The C99 rule is modified by C23.
21022 QualType BestPromotionType;
21023
21024 bool Packed = Enum->hasAttr<PackedAttr>();
21025 // -fshort-enums is the equivalent to specifying the packed attribute on all
21026 // enum definitions.
21027 if (LangOpts.ShortEnums)
21028 Packed = true;
21029
21030 // If the enum already has a type because it is fixed or dictated by the
21031 // target, promote that type instead of analyzing the enumerators.
21032 if (Enum->isComplete()) {
21033 BestType = Enum->getIntegerType();
21034 if (Context.isPromotableIntegerType(T: BestType))
21035 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21036 else
21037 BestPromotionType = BestType;
21038
21039 BestWidth = Context.getIntWidth(T: BestType);
21040 } else {
21041 bool EnumTooLarge = Context.computeBestEnumTypes(
21042 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21043 BestWidth = Context.getIntWidth(T: BestType);
21044 if (EnumTooLarge)
21045 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21046 }
21047
21048 // Loop over all of the enumerator constants, changing their types to match
21049 // the type of the enum if needed.
21050 for (auto *D : Elements) {
21051 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21052 if (!ECD) continue; // Already issued a diagnostic.
21053
21054 // C99 says the enumerators have int type, but we allow, as an
21055 // extension, the enumerators to be larger than int size. If each
21056 // enumerator value fits in an int, type it as an int, otherwise type it the
21057 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21058 // that X has type 'int', not 'unsigned'.
21059
21060 // Determine whether the value fits into an int.
21061 llvm::APSInt InitVal = ECD->getInitVal();
21062
21063 // If it fits into an integer type, force it. Otherwise force it to match
21064 // the enum decl type.
21065 QualType NewTy;
21066 unsigned NewWidth;
21067 bool NewSign;
21068 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21069 MembersRepresentableByInt) {
21070 // C23 6.7.3.3.3p15:
21071 // The enumeration member type for an enumerated type without fixed
21072 // underlying type upon completion is:
21073 // - int if all the values of the enumeration are representable as an
21074 // int; or,
21075 // - the enumerated type
21076 NewTy = Context.IntTy;
21077 NewWidth = Context.getTargetInfo().getIntWidth();
21078 NewSign = true;
21079 } else if (ECD->getType() == BestType) {
21080 // Already the right type!
21081 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21082 // C++ [dcl.enum]p4: Following the closing brace of an
21083 // enum-specifier, each enumerator has the type of its
21084 // enumeration.
21085 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21086 // with fixed underlying type is the enumerated type.
21087 ECD->setType(EnumType);
21088 continue;
21089 } else {
21090 NewTy = BestType;
21091 NewWidth = BestWidth;
21092 NewSign = BestType->isSignedIntegerOrEnumerationType();
21093 }
21094
21095 // Adjust the APSInt value.
21096 InitVal = InitVal.extOrTrunc(width: NewWidth);
21097 InitVal.setIsSigned(NewSign);
21098 ECD->setInitVal(C: Context, V: InitVal);
21099
21100 // Adjust the Expr initializer and type.
21101 if (ECD->getInitExpr() &&
21102 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21103 ECD->setInitExpr(ImplicitCastExpr::Create(
21104 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21105 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21106 if (getLangOpts().CPlusPlus ||
21107 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21108 // C++ [dcl.enum]p4: Following the closing brace of an
21109 // enum-specifier, each enumerator has the type of its
21110 // enumeration.
21111 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21112 // with fixed underlying type is the enumerated type.
21113 ECD->setType(EnumType);
21114 else
21115 ECD->setType(NewTy);
21116 }
21117
21118 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21119 NumPositiveBits, NumNegativeBits);
21120
21121 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21122 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21123
21124 if (Enum->isClosedFlag()) {
21125 for (Decl *D : Elements) {
21126 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21127 if (!ECD) continue; // Already issued a diagnostic.
21128
21129 llvm::APSInt InitVal = ECD->getInitVal();
21130 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21131 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21132 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21133 << ECD << Enum;
21134 }
21135 }
21136
21137 // Now that the enum type is defined, ensure it's not been underaligned.
21138 if (Enum->hasAttrs())
21139 CheckAlignasUnderalignment(D: Enum);
21140}
21141
21142Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21143 SourceLocation EndLoc) {
21144
21145 FileScopeAsmDecl *New =
21146 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21147 CurContext->addDecl(D: New);
21148 return New;
21149}
21150
21151TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21152 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21153 CurContext->addDecl(D: New);
21154 PushDeclContext(S, DC: New);
21155 PushFunctionScope();
21156 PushCompoundScope(IsStmtExpr: false);
21157 return New;
21158}
21159
21160void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21161 if (Statement)
21162 D->setStmt(Statement);
21163 PopCompoundScope();
21164 PopFunctionScopeInfo();
21165 PopDeclContext();
21166}
21167
21168void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21169 IdentifierInfo* AliasName,
21170 SourceLocation PragmaLoc,
21171 SourceLocation NameLoc,
21172 SourceLocation AliasNameLoc) {
21173 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21174 NameKind: LookupOrdinaryName);
21175 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21176 AttributeCommonInfo::Form::Pragma());
21177 AsmLabelAttr *Attr =
21178 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21179
21180 // If a declaration that:
21181 // 1) declares a function or a variable
21182 // 2) has external linkage
21183 // already exists, add a label attribute to it.
21184 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21185 if (isDeclExternC(D: PrevDecl))
21186 PrevDecl->addAttr(A: Attr);
21187 else
21188 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21189 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21190 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21191 } else
21192 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21193}
21194
21195void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21196 SourceLocation PragmaLoc,
21197 SourceLocation NameLoc) {
21198 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21199
21200 if (PrevDecl) {
21201 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21202 } else {
21203 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21204 }
21205}
21206
21207void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21208 IdentifierInfo* AliasName,
21209 SourceLocation PragmaLoc,
21210 SourceLocation NameLoc,
21211 SourceLocation AliasNameLoc) {
21212 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21213 NameKind: LookupOrdinaryName);
21214 WeakInfo W = WeakInfo(Name, NameLoc);
21215
21216 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21217 if (!PrevDecl->hasAttr<AliasAttr>())
21218 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21219 DeclApplyPragmaWeak(S: TUScope, ND, W);
21220 } else {
21221 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21222 }
21223}
21224
21225Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21226 bool Final) {
21227 assert(FD && "Expected non-null FunctionDecl");
21228
21229 // Templates are emitted when they're instantiated.
21230 if (FD->isDependentContext())
21231 return FunctionEmissionStatus::TemplateDiscarded;
21232
21233 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21234 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21235 FD->hasAttr<SYCLExternalAttr>()))
21236 return FunctionEmissionStatus::Emitted;
21237
21238 // Check whether this function is an externally visible definition.
21239 auto IsEmittedForExternalSymbol = [this, FD]() {
21240 // We have to check the GVA linkage of the function's *definition* -- if we
21241 // only have a declaration, we don't know whether or not the function will
21242 // be emitted, because (say) the definition could include "inline".
21243 const FunctionDecl *Def = FD->getDefinition();
21244
21245 // We can't compute linkage when we skip function bodies.
21246 return Def && !Def->hasSkippedBody() &&
21247 !isDiscardableGVALinkage(
21248 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21249 };
21250
21251 if (LangOpts.OpenMPIsTargetDevice) {
21252 // In OpenMP device mode we will not emit host only functions, or functions
21253 // we don't need due to their linkage.
21254 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21255 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21256 // DevTy may be changed later by
21257 // #pragma omp declare target to(*) device_type(*).
21258 // Therefore DevTy having no value does not imply host. The emission status
21259 // will be checked again at the end of compilation unit with Final = true.
21260 if (DevTy)
21261 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21262 return FunctionEmissionStatus::OMPDiscarded;
21263 // If we have an explicit value for the device type, or we are in a target
21264 // declare context, we need to emit all extern and used symbols.
21265 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21266 if (IsEmittedForExternalSymbol())
21267 return FunctionEmissionStatus::Emitted;
21268 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21269 // we'll omit it.
21270 if (Final)
21271 return FunctionEmissionStatus::OMPDiscarded;
21272 } else if (LangOpts.OpenMP > 45) {
21273 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21274 // function. In 5.0, no_host was introduced which might cause a function to
21275 // be omitted.
21276 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21277 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21278 if (DevTy)
21279 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21280 return FunctionEmissionStatus::OMPDiscarded;
21281 }
21282
21283 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21284 return FunctionEmissionStatus::Emitted;
21285
21286 if (LangOpts.CUDA) {
21287 // When compiling for device, host functions are never emitted. Similarly,
21288 // when compiling for host, device and global functions are never emitted.
21289 // (Technically, we do emit a host-side stub for global functions, but this
21290 // doesn't count for our purposes here.)
21291 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21292 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21293 return FunctionEmissionStatus::CUDADiscarded;
21294 if (!LangOpts.CUDAIsDevice &&
21295 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21296 return FunctionEmissionStatus::CUDADiscarded;
21297
21298 if (IsEmittedForExternalSymbol())
21299 return FunctionEmissionStatus::Emitted;
21300 }
21301
21302 // Otherwise, the function is known-emitted if it's in our set of
21303 // known-emitted functions.
21304 return FunctionEmissionStatus::Unknown;
21305}
21306
21307bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21308 // Host-side references to a __global__ function refer to the stub, so the
21309 // function itself is never emitted and therefore should not be marked.
21310 // If we have host fn calls kernel fn calls host+device, the HD function
21311 // does not get instantiated on the host. We model this by omitting at the
21312 // call to the kernel from the callgraph. This ensures that, when compiling
21313 // for host, only HD functions actually called from the host get marked as
21314 // known-emitted.
21315 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21316 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21317}
21318
21319bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21320 bool &Visible) {
21321 Visible = hasVisibleDefinition(D, Suggested);
21322 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21323 // for declaratins which is attached to named modules.
21324 // We only did this if the current module is named module as we have better
21325 // diagnostics for declarations in global module and named modules.
21326 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21327 D->isInNamedModule())
21328 return false;
21329 // The redefinition of D in the **current** TU is allowed if D is invisible or
21330 // D is defined in the global module of other module units.
21331 return D->isInAnotherModuleUnit() || !Visible;
21332}
21333