1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NonTrivialTypeVisitor.h"
29#include "clang/AST/Randstruct.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticComment.h"
34#include "clang/Basic/HLSLRuntime.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/CXXFieldCollector.h"
43#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/DelayedDiagnostic.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/ParsedTemplate.h"
48#include "clang/Sema/Scope.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaAMDGPU.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaInternal.h"
55#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaOpenACC.h"
57#include "clang/Sema/SemaOpenMP.h"
58#include "clang/Sema/SemaPPC.h"
59#include "clang/Sema/SemaRISCV.h"
60#include "clang/Sema/SemaSYCL.h"
61#include "clang/Sema/SemaSwift.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
81Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
84 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
85 }
86
87 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(D: ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
127 isa<ClassTemplateSpecializationDecl>(Val: RD);
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
149void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
156 Diag(Loc: NameLoc,
157 DiagID: DCK == DiagCtorKind::Typename
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
165 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Val: Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(T: Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
215 if (!isa<TypeDecl>(Val: ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(Val: DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
274}
275
276ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(T: ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(SS: *SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
318 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
319 NNS: SS->getScopeRep(), Name: &II);
320 if (!getLangOpts().CPlusPlus20)
321 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
328 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
331 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
332 QualType T = CheckTypenameType(
333 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
334 : ElaboratedTypeKeyword::None,
335 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
336 return ParsedType::make(P: T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(R&: Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(R&: Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(R&: Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
387 case LookupResultKind::NotFound:
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
393 Mode: CorrectTypoKind::ErrorRecovery);
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
395 TemplateTy Template;
396 bool MemberOfUnknownSpecialization;
397 UnqualifiedId TemplateName;
398 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
399 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
430 case LookupResultKind::NotFoundInCurrentInstantiation:
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
433 NNS: SS->getScopeRep(), Name: &II);
434 TypeLocBuilder TLB;
435 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
436 TL.setElaboratedKeywordLoc(SourceLocation());
437 TL.setQualifierLoc(SS->getWithLocInContext(Context));
438 TL.setNameLoc(NameLoc);
439 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
440 }
441 [[fallthrough]];
442 case LookupResultKind::FoundOverloaded:
443 case LookupResultKind::FoundUnresolvedValue:
444 Result.suppressDiagnostics();
445 return nullptr;
446
447 case LookupResultKind::Ambiguous:
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
462 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
463 Val: RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
491 case LookupResultKind::Found:
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
503 : DiagCtorKind::None,
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
507 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
508 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
509 D: FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(P: T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 QualifierLoc: SS ? SS->getWithLocInContext(Context)
514 : NestedNameSpecifierLoc(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
517 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
518 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(P: T);
522 auto TL = TLB.push<TagTypeLoc>(T);
523 TL.setElaboratedKeywordLoc(SourceLocation());
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
525 : NestedNameSpecifierLoc());
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
528 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
529 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
530 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(P: T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
535 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
538 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
539 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
540 D: UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(P: T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
545 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(Decl: TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(P: T);
551 if (isa<ObjCTypeParamType>(Val: T))
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
556 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(P: ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
570 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(P: T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
580 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
583 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(P: Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
594 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
595 Template);
596 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
597 TL.setElaboratedKeywordLoc(SourceLocation());
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
600 : NestedNameSpecifierLoc());
601 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
611static NestedNameSpecifier
612synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
620 if (isa<TranslationUnitDecl>(Val: DC))
621 return NestedNameSpecifier::getGlobal();
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
631findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
641ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
655 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
656 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
658 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
684 DepTL.setElaboratedKeywordLoc(SourceLocation());
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
687}
688
689DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, AllowBuiltinCreation: false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
697 case TagTypeKind::Struct:
698 return DeclSpec::TST_struct;
699 case TagTypeKind::Interface:
700 return DeclSpec::TST_interface;
701 case TagTypeKind::Union:
702 return DeclSpec::TST_union;
703 case TagTypeKind::Class:
704 return DeclSpec::TST_class;
705 case TagTypeKind::Enum:
706 return DeclSpec::TST_enum;
707 }
708 }
709
710 return DeclSpec::TST_unspecified;
711}
712
713bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
718 case NestedNameSpecifier::Kind::MicrosoftSuper:
719 return true;
720 case NestedNameSpecifier::Kind::Type: {
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
732void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
750 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
751 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Correction: Corrected,
757 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Correction: Corrected,
765 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, ErrorRecovery: CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
769 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Correction: Corrected,
773 TypoDiag: PDiag(DiagID: IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 ErrorRecovery: CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
788 R: SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
792 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(Id: II, IdLoc: IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
822 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
828 } else if (isDependentScopeSpecifier(SS: *SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
835
836 Diag(Loc: SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(Ty: SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(K: tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
853 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
857 return true;
858 }
859
860 return false;
861}
862
863static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
872 case TagTypeKind::Class:
873 FixItTagName = "class ";
874 break;
875
876 case TagTypeKind::Enum:
877 FixItTagName = "enum ";
878 break;
879
880 case TagTypeKind::Struct:
881 FixItTagName = "struct ";
882 break;
883
884 case TagTypeKind::Interface:
885 FixItTagName = "__interface ";
886 break;
887
888 case TagTypeKind::Union:
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
904 Result.clear(Kind: Sema::LookupTagName);
905 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
912Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
916 CorrectionCandidateCallback *CCC) {
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(II: *Name, S, SS: &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
928 return NameClassification::Unknown();
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
936 return NameClassification::Error();
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
952 if (Ivar.isInvalid())
953 return NameClassification::Error();
954 if (Ivar.isUsable())
955 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
959 LookupBuiltin(R&: Result);
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
967 case LookupResultKind::NotFound:
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
973 if (getLangOpts().CPlusPlus)
974 return NameClassification::UndeclaredNonType();
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
992 return NameClassification::NonType(D);
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1001 TemplateName Template =
1002 Context.getAssumedTemplateName(Name: NameInfo.getName());
1003 return NameClassification::UndeclaredTemplate(Name: Template);
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1020 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1045 << Name << computeDeclContext(SS, EnteringContext: false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(D: FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1070 if (R.isInvalid())
1071 return NameClassification::Error();
1072 if (R.isUsable())
1073 return NameClassification::NonType(D: Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1082 return NameClassification::Unknown();
1083
1084 case LookupResultKind::NotFoundInCurrentInstantiation: {
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1099 return NameClassification::DependentNonType();
1100 }
1101
1102 case LookupResultKind::Found:
1103 case LookupResultKind::FoundOverloaded:
1104 case LookupResultKind::FoundUnresolvedValue:
1105 break;
1106
1107 case LookupResultKind::Ambiguous:
1108 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1109 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1122 FilterAcceptableTemplateNames(R&: Result);
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1130 return NameClassification::Error();
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1134 (IsFilteredTemplateName ||
1135 hasAnyAcceptableTemplateNames(
1136 R&: Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1139 getLangOpts().CPlusPlus20))) {
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1151 FilterAcceptableTemplateNames(R&: Result);
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1155 TemplateName Template;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1159 End: Result.end());
1160 } else if (!Result.empty()) {
1161 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1162 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 Qualifier: SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1188 return NameClassification::FunctionTemplate(Name: Template);
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1192 : NameClassification::TypeTemplate(Name: Template);
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1199 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1200 D: USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1205 Decl: Type);
1206 if (isa<TagType>(Val: T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1208 TTL.setElaboratedKeywordLoc(SourceLocation());
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(Val: T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(Val: T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1223 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1228 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1229 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1243
1244 if (NextToken.is(K: tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1248 return NameClassification::Unknown();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Decl: Class);
1252 return ParsedType::make(P: T);
1253 }
1254
1255 if (isa<ConceptDecl>(Val: FirstDecl)) {
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1258 return NameClassification::Concept(Name: TemplateName(USD));
1259 return NameClassification::Concept(
1260 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1265 return NameClassification::Error();
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1269 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1270 !isa<VarTemplateDecl>(Val: FirstDecl))
1271 return NameClassification::TypeTemplate(
1272 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1277 if ((NextToken.is(K: tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1293 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1297 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1298 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1299 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1303ExprResult
1304Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1310}
1311
1312ExprResult
1313Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1323ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1324 NamedDecl *Found,
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(D: Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1340ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(Other: ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1350 LookupOrdinaryName);
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(D: *I, AS: I.getAccess());
1354 Result.resolveKind();
1355 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1356 TemplateArgs: nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1364Sema::TemplateNameKindForDiagnostics
1365Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1366 auto *TD = Name.getAsTemplateDecl();
1367 if (!TD)
1368 return TemplateNameKindForDiagnostics::DependentTemplate;
1369 if (isa<ClassTemplateDecl>(Val: TD))
1370 return TemplateNameKindForDiagnostics::ClassTemplate;
1371 if (isa<FunctionTemplateDecl>(Val: TD))
1372 return TemplateNameKindForDiagnostics::FunctionTemplate;
1373 if (isa<VarTemplateDecl>(Val: TD))
1374 return TemplateNameKindForDiagnostics::VarTemplate;
1375 if (isa<TypeAliasTemplateDecl>(Val: TD))
1376 return TemplateNameKindForDiagnostics::AliasTemplate;
1377 if (isa<TemplateTemplateParmDecl>(Val: TD))
1378 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1379 if (isa<ConceptDecl>(Val: TD))
1380 return TemplateNameKindForDiagnostics::Concept;
1381 return TemplateNameKindForDiagnostics::DependentTemplate;
1382}
1383
1384void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1392void Sema::PopDeclContext() {
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1399Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1413void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1414 CurContext = static_cast<decltype(CurContext)>(Context);
1415}
1416
1417void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1448 EnterTemplatedContext(S: S->getParent(), DC);
1449 }
1450}
1451
1452void Sema::ExitDeclaratorContext(Scope *S) {
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1465void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1508void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1509 // We assume that the caller has already called
1510 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1511 FunctionDecl *FD = D->getAsFunction();
1512 if (!FD)
1513 return;
1514
1515 // Same implementation as PushDeclContext, but enters the context
1516 // from the lexical parent, rather than the top-level class.
1517 assert(CurContext == FD->getLexicalParent() &&
1518 "The next DeclContext should be lexically contained in the current one.");
1519 CurContext = FD;
1520 S->setEntity(CurContext);
1521
1522 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1523 ParmVarDecl *Param = FD->getParamDecl(i: P);
1524 // If the parameter has an identifier, then add it to the scope
1525 if (Param->getIdentifier()) {
1526 S->AddDecl(D: Param);
1527 IdResolver.AddDecl(D: Param);
1528 }
1529 }
1530}
1531
1532void Sema::ActOnExitFunctionContext() {
1533 // Same implementation as PopDeclContext, but returns to the lexical parent,
1534 // rather than the top-level class.
1535 assert(CurContext && "DeclContext imbalance!");
1536 CurContext = CurContext->getLexicalParent();
1537 assert(CurContext && "Popped translation unit!");
1538}
1539
1540/// Determine whether overloading is allowed for a new function
1541/// declaration considering prior declarations of the same name.
1542///
1543/// This routine determines whether overloading is possible, not
1544/// whether a new declaration actually overloads a previous one.
1545/// It will return true in C++ (where overloads are always permitted)
1546/// or, as a C extension, when either the new declaration or a
1547/// previous one is declared with the 'overloadable' attribute.
1548static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1549 ASTContext &Context,
1550 const FunctionDecl *New) {
1551 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1552 return true;
1553
1554 // Multiversion function declarations are not overloads in the
1555 // usual sense of that term, but lookup will report that an
1556 // overload set was found if more than one multiversion function
1557 // declaration is present for the same name. It is therefore
1558 // inadequate to assume that some prior declaration(s) had
1559 // the overloadable attribute; checking is required. Since one
1560 // declaration is permitted to omit the attribute, it is necessary
1561 // to check at least two; hence the 'any_of' check below. Note that
1562 // the overloadable attribute is implicitly added to declarations
1563 // that were required to have it but did not.
1564 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1565 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1566 return ND->hasAttr<OverloadableAttr>();
1567 });
1568 } else if (Previous.getResultKind() == LookupResultKind::Found)
1569 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1570
1571 return false;
1572}
1573
1574void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1575 // Move up the scope chain until we find the nearest enclosing
1576 // non-transparent context. The declaration will be introduced into this
1577 // scope.
1578 while (S->getEntity() && S->getEntity()->isTransparentContext())
1579 S = S->getParent();
1580
1581 // Add scoped declarations into their context, so that they can be
1582 // found later. Declarations without a context won't be inserted
1583 // into any context.
1584 if (AddToContext)
1585 CurContext->addDecl(D);
1586
1587 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1588 // are function-local declarations.
1589 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1590 if (!S->getFnParent())
1591 return;
1592
1593 // Even inside a function, an out-of-line definition of a type that is
1594 // nested inside a local class must not be pushed into the enclosing
1595 // function scope. For example:
1596 //
1597 // class A { public: class B; };
1598 // class A::B {}; // out-of-line definition inside the function
1599 // B b; // must fail - only A::B is valid
1600 // Wrapper{B{}} // must also fail
1601 //
1602 // Per C++ scoping rules only the qualified form A::B is accessible.
1603 // Without this guard, PushOnScopeChains would add B to the function's
1604 // local scope, making it findable via unqualified lookup, which is
1605 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1606 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1607 // of a local class being defined out-of-line.
1608 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1609 return;
1610 }
1611
1612 // Template instantiations should also not be pushed into scope.
1613 if (isa<FunctionDecl>(Val: D) &&
1614 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1615 return;
1616
1617 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1618 S->AddDecl(D);
1619 return;
1620 }
1621 // If this replaces anything in the current scope,
1622 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1623 IEnd = IdResolver.end();
1624 for (; I != IEnd; ++I) {
1625 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1626 S->RemoveDecl(D: *I);
1627 IdResolver.RemoveDecl(D: *I);
1628
1629 // Should only need to replace one decl.
1630 break;
1631 }
1632 }
1633
1634 S->AddDecl(D);
1635
1636 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1637 // Implicitly-generated labels may end up getting generated in an order that
1638 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1639 // the label at the appropriate place in the identifier chain.
1640 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1641 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1642 if (IDC == CurContext) {
1643 if (!S->isDeclScope(D: *I))
1644 continue;
1645 } else if (IDC->Encloses(DC: CurContext))
1646 break;
1647 }
1648
1649 IdResolver.InsertDeclAfter(Pos: I, D);
1650 } else {
1651 IdResolver.AddDecl(D);
1652 }
1653 warnOnReservedIdentifier(D);
1654}
1655
1656bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1657 bool AllowInlineNamespace) const {
1658 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1659}
1660
1661Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1662 DeclContext *TargetDC = DC->getPrimaryContext();
1663 do {
1664 if (DeclContext *ScopeDC = S->getEntity())
1665 if (ScopeDC->getPrimaryContext() == TargetDC)
1666 return S;
1667 } while ((S = S->getParent()));
1668
1669 return nullptr;
1670}
1671
1672static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1673 DeclContext*,
1674 ASTContext&);
1675
1676void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1677 bool ConsiderLinkage,
1678 bool AllowInlineNamespace) {
1679 LookupResult::Filter F = R.makeFilter();
1680 while (F.hasNext()) {
1681 NamedDecl *D = F.next();
1682
1683 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1684 continue;
1685
1686 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1687 continue;
1688
1689 F.erase();
1690 }
1691
1692 F.done();
1693}
1694
1695static bool isImplicitInstantiation(NamedDecl *D) {
1696 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1697 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1698 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1699 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1700 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1701 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1702
1703 return false;
1704}
1705
1706bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1707 // [module.interface]p7:
1708 // A declaration is attached to a module as follows:
1709 // - If the declaration is a non-dependent friend declaration that nominates a
1710 // function with a declarator-id that is a qualified-id or template-id or that
1711 // nominates a class other than with an elaborated-type-specifier with neither
1712 // a nested-name-specifier nor a simple-template-id, it is attached to the
1713 // module to which the friend is attached ([basic.link]).
1714 if (New->getFriendObjectKind() &&
1715 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1716 New->setLocalOwningModule(Old->getOwningModule());
1717 makeMergedDefinitionVisible(ND: New);
1718 return false;
1719 }
1720
1721 // Although we have questions for the module ownership of implicit
1722 // instantiations, it should be sure that we shouldn't diagnose the
1723 // redeclaration of incorrect module ownership for different implicit
1724 // instantiations in different modules. We will diagnose the redeclaration of
1725 // incorrect module ownership for the template itself.
1726 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1727 return false;
1728
1729 Module *NewM = New->getOwningModule();
1730 Module *OldM = Old->getOwningModule();
1731
1732 if (NewM && NewM->isPrivateModule())
1733 NewM = NewM->Parent;
1734 if (OldM && OldM->isPrivateModule())
1735 OldM = OldM->Parent;
1736
1737 if (NewM == OldM)
1738 return false;
1739
1740 if (NewM && OldM) {
1741 // A module implementation unit has visibility of the decls in its
1742 // implicitly imported interface.
1743 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1744 return false;
1745
1746 // Partitions are part of the module, but a partition could import another
1747 // module, so verify that the PMIs agree.
1748 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1749 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1750 return false;
1751 }
1752
1753 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1754 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1755 if (NewIsModuleInterface || OldIsModuleInterface) {
1756 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1757 // if a declaration of D [...] appears in the purview of a module, all
1758 // other such declarations shall appear in the purview of the same module
1759 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1760 << New
1761 << NewIsModuleInterface
1762 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1763 << OldIsModuleInterface
1764 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1765 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1766 New->setInvalidDecl();
1767 return true;
1768 }
1769
1770 return false;
1771}
1772
1773bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1774 // [module.interface]p1:
1775 // An export-declaration shall inhabit a namespace scope.
1776 //
1777 // So it is meaningless to talk about redeclaration which is not at namespace
1778 // scope.
1779 if (!New->getLexicalDeclContext()
1780 ->getNonTransparentContext()
1781 ->isFileContext() ||
1782 !Old->getLexicalDeclContext()
1783 ->getNonTransparentContext()
1784 ->isFileContext())
1785 return false;
1786
1787 bool IsNewExported = New->isInExportDeclContext();
1788 bool IsOldExported = Old->isInExportDeclContext();
1789
1790 // It should be irrevelant if both of them are not exported.
1791 if (!IsNewExported && !IsOldExported)
1792 return false;
1793
1794 if (IsOldExported)
1795 return false;
1796
1797 // If the Old declaration are not attached to named modules
1798 // and the New declaration are attached to global module.
1799 // It should be fine to allow the export since it doesn't change
1800 // the linkage of declarations. See
1801 // https://github.com/llvm/llvm-project/issues/98583 for details.
1802 if (!Old->isInNamedModule() && New->getOwningModule() &&
1803 New->getOwningModule()->isImplicitGlobalModule())
1804 return false;
1805
1806 assert(IsNewExported);
1807
1808 auto Lk = Old->getFormalLinkage();
1809 int S = 0;
1810 if (Lk == Linkage::Internal)
1811 S = 1;
1812 else if (Lk == Linkage::Module)
1813 S = 2;
1814 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1815 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1816 return true;
1817}
1818
1819bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1820 if (CheckRedeclarationModuleOwnership(New, Old))
1821 return true;
1822
1823 if (CheckRedeclarationExported(New, Old))
1824 return true;
1825
1826 return false;
1827}
1828
1829bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1830 const NamedDecl *Old) const {
1831 assert(getASTContext().isSameEntity(New, Old) &&
1832 "New and Old are not the same definition, we should diagnostic it "
1833 "immediately instead of checking it.");
1834 assert(const_cast<Sema *>(this)->isReachable(New) &&
1835 const_cast<Sema *>(this)->isReachable(Old) &&
1836 "We shouldn't see unreachable definitions here.");
1837
1838 Module *NewM = New->getOwningModule();
1839 Module *OldM = Old->getOwningModule();
1840
1841 // We only checks for named modules here. The header like modules is skipped.
1842 // FIXME: This is not right if we import the header like modules in the module
1843 // purview.
1844 //
1845 // For example, assuming "header.h" provides definition for `D`.
1846 // ```C++
1847 // //--- M.cppm
1848 // export module M;
1849 // import "header.h"; // or #include "header.h" but import it by clang modules
1850 // actually.
1851 //
1852 // //--- Use.cpp
1853 // import M;
1854 // import "header.h"; // or uses clang modules.
1855 // ```
1856 //
1857 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1858 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1859 // reject it. But the current implementation couldn't detect the case since we
1860 // don't record the information about the importee modules.
1861 //
1862 // But this might not be painful in practice. Since the design of C++20 Named
1863 // Modules suggests us to use headers in global module fragment instead of
1864 // module purview.
1865 if (NewM && NewM->isHeaderLikeModule())
1866 NewM = nullptr;
1867 if (OldM && OldM->isHeaderLikeModule())
1868 OldM = nullptr;
1869
1870 if (!NewM && !OldM)
1871 return true;
1872
1873 // [basic.def.odr]p14.3
1874 // Each such definition shall not be attached to a named module
1875 // ([module.unit]).
1876 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1877 return true;
1878
1879 // Then New and Old lives in the same TU if their share one same module unit.
1880 if (NewM)
1881 NewM = NewM->getTopLevelModule();
1882 if (OldM)
1883 OldM = OldM->getTopLevelModule();
1884 return OldM == NewM;
1885}
1886
1887static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1888 if (D->getDeclContext()->isFileContext())
1889 return false;
1890
1891 return isa<UsingShadowDecl>(Val: D) ||
1892 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1893 isa<UnresolvedUsingValueDecl>(Val: D);
1894}
1895
1896/// Removes using shadow declarations not at class scope from the lookup
1897/// results.
1898static void RemoveUsingDecls(LookupResult &R) {
1899 LookupResult::Filter F = R.makeFilter();
1900 while (F.hasNext())
1901 if (isUsingDeclNotAtClassScope(D: F.next()))
1902 F.erase();
1903
1904 F.done();
1905}
1906
1907/// Check for this common pattern:
1908/// @code
1909/// class S {
1910/// S(const S&); // DO NOT IMPLEMENT
1911/// void operator=(const S&); // DO NOT IMPLEMENT
1912/// };
1913/// @endcode
1914static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1915 // FIXME: Should check for private access too but access is set after we get
1916 // the decl here.
1917 if (D->doesThisDeclarationHaveABody())
1918 return false;
1919
1920 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1921 return CD->isCopyConstructor();
1922 return D->isCopyAssignmentOperator();
1923}
1924
1925bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1926 const DeclContext *DC = D->getDeclContext();
1927 while (!DC->isTranslationUnit()) {
1928 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1929 if (!RD->hasNameForLinkage())
1930 return true;
1931 }
1932 DC = DC->getParent();
1933 }
1934
1935 return !D->isExternallyVisible();
1936}
1937
1938bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1939 assert(D);
1940
1941 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1942 return false;
1943
1944 // Ignore all entities declared within templates, and out-of-line definitions
1945 // of members of class templates.
1946 if (D->getDeclContext()->isDependentContext() ||
1947 D->getLexicalDeclContext()->isDependentContext())
1948 return false;
1949
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1951 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1952 return false;
1953 // A non-out-of-line declaration of a member specialization was implicitly
1954 // instantiated; it's the out-of-line declaration that we're interested in.
1955 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1956 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1957 return false;
1958
1959 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1960 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1961 return false;
1962 } else {
1963 // 'static inline' functions are defined in headers; don't warn.
1964 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1965 return false;
1966 }
1967
1968 if (FD->doesThisDeclarationHaveABody() &&
1969 Context.DeclMustBeEmitted(D: FD))
1970 return false;
1971 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1972 // Constants and utility variables are defined in headers with internal
1973 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1974 // like "inline".)
1975 if (!isMainFileLoc(Loc: VD->getLocation()))
1976 return false;
1977
1978 if (Context.DeclMustBeEmitted(D: VD))
1979 return false;
1980
1981 if (VD->isStaticDataMember() &&
1982 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1983 return false;
1984 if (VD->isStaticDataMember() &&
1985 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1986 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1987 return false;
1988
1989 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
1990 return false;
1991 } else {
1992 return false;
1993 }
1994
1995 // Only warn for unused decls internal to the translation unit.
1996 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1997 // for inline functions defined in the main source file, for instance.
1998 return mightHaveNonExternalLinkage(D);
1999}
2000
2001void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2002 if (!D)
2003 return;
2004
2005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2006 const FunctionDecl *First = FD->getFirstDecl();
2007 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2008 return; // First should already be in the vector.
2009 }
2010
2011 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2012 const VarDecl *First = VD->getFirstDecl();
2013 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2014 return; // First should already be in the vector.
2015 }
2016
2017 if (ShouldWarnIfUnusedFileScopedDecl(D))
2018 UnusedFileScopedDecls.push_back(LocalValue: D);
2019}
2020
2021static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2022 const NamedDecl *D) {
2023 if (D->isInvalidDecl())
2024 return false;
2025
2026 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2027 // For a decomposition declaration, warn if none of the bindings are
2028 // referenced, instead of if the variable itself is referenced (which
2029 // it is, by the bindings' expressions).
2030 bool IsAllIgnored = true;
2031 for (const auto *BD : DD->bindings()) {
2032 if (BD->isReferenced())
2033 return false;
2034 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2035 BD->hasAttr<UnusedAttr>());
2036 }
2037 if (IsAllIgnored)
2038 return false;
2039 } else if (!D->getDeclName()) {
2040 return false;
2041 } else if (D->isReferenced() || D->isUsed()) {
2042 return false;
2043 }
2044
2045 if (D->isPlaceholderVar(LangOpts))
2046 return false;
2047
2048 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2049 D->hasAttr<CleanupAttr>())
2050 return false;
2051
2052 if (isa<LabelDecl>(Val: D))
2053 return true;
2054
2055 // Except for labels, we only care about unused decls that are local to
2056 // functions.
2057 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2058 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2059 // For dependent types, the diagnostic is deferred.
2060 WithinFunction =
2061 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2062 if (!WithinFunction)
2063 return false;
2064
2065 if (isa<TypedefNameDecl>(Val: D))
2066 return true;
2067
2068 // White-list anything that isn't a local variable.
2069 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2070 return false;
2071
2072 // Types of valid local variables should be complete, so this should succeed.
2073 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2074
2075 const Expr *Init = VD->getInit();
2076 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2077 Init = Cleanups->getSubExpr();
2078
2079 const auto *Ty = VD->getType().getTypePtr();
2080
2081 // Only look at the outermost level of typedef.
2082 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2083 // Allow anything marked with __attribute__((unused)).
2084 if (TT->getDecl()->hasAttr<UnusedAttr>())
2085 return false;
2086 }
2087
2088 // Warn for reference variables whose initializtion performs lifetime
2089 // extension.
2090 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2091 MTE && MTE->getExtendingDecl()) {
2092 Ty = VD->getType().getNonReferenceType().getTypePtr();
2093 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2094 }
2095
2096 // If we failed to complete the type for some reason, or if the type is
2097 // dependent, don't diagnose the variable.
2098 if (Ty->isIncompleteType() || Ty->isDependentType())
2099 return false;
2100
2101 // Look at the element type to ensure that the warning behaviour is
2102 // consistent for both scalars and arrays.
2103 Ty = Ty->getBaseElementTypeUnsafe();
2104
2105 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2106 if (Tag->hasAttr<UnusedAttr>())
2107 return false;
2108
2109 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2110 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2111 return false;
2112
2113 if (Init) {
2114 const auto *Construct =
2115 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2116 if (Construct && !Construct->isElidable()) {
2117 const CXXConstructorDecl *CD = Construct->getConstructor();
2118 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2119 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2120 return false;
2121 }
2122
2123 // Suppress the warning if we don't know how this is constructed, and
2124 // it could possibly be non-trivial constructor.
2125 if (Init->isTypeDependent()) {
2126 for (const CXXConstructorDecl *Ctor : RD->ctors())
2127 if (!Ctor->isTrivial())
2128 return false;
2129 }
2130
2131 // Suppress the warning if the constructor is unresolved because
2132 // its arguments are dependent.
2133 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2134 return false;
2135 }
2136 }
2137 }
2138
2139 // TODO: __attribute__((unused)) templates?
2140 }
2141
2142 return true;
2143}
2144
2145static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2146 FixItHint &Hint) {
2147 if (isa<LabelDecl>(Val: D)) {
2148 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2149 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2150 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2151 if (AfterColon.isInvalid())
2152 return;
2153 Hint = FixItHint::CreateRemoval(
2154 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2155 }
2156}
2157
2158void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2159 DiagnoseUnusedNestedTypedefs(
2160 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2161}
2162
2163void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2164 DiagReceiverTy DiagReceiver) {
2165 if (D->isDependentType())
2166 return;
2167
2168 for (auto *TmpD : D->decls()) {
2169 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2170 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2171 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2172 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2173 }
2174}
2175
2176void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2177 DiagnoseUnusedDecl(
2178 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2179}
2180
2181void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2182 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2183 return;
2184
2185 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2186 // typedefs can be referenced later on, so the diagnostics are emitted
2187 // at end-of-translation-unit.
2188 UnusedLocalTypedefNameCandidates.insert(Ptr: TD);
2189 return;
2190 }
2191
2192 FixItHint Hint;
2193 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2194
2195 unsigned DiagID;
2196 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2197 DiagID = diag::warn_unused_exception_param;
2198 else if (isa<LabelDecl>(Val: D))
2199 DiagID = diag::warn_unused_label;
2200 else
2201 DiagID = diag::warn_unused_variable;
2202
2203 SourceLocation DiagLoc = D->getLocation();
2204 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2205}
2206
2207void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2208 DiagReceiverTy DiagReceiver) {
2209 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2210 // it's not really unused.
2211 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2212 return;
2213
2214 // In C++, `_` variables behave as if they were maybe_unused
2215 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2216 return;
2217
2218 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2219
2220 if (Ty->isReferenceType() || Ty->isDependentType())
2221 return;
2222
2223 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2224 if (Tag->hasAttr<UnusedAttr>())
2225 return;
2226 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2227 // mimic gcc's behavior.
2228 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2229 RD && !RD->hasAttr<WarnUnusedAttr>())
2230 return;
2231 }
2232
2233 // Don't warn on volatile file-scope variables. They are visible beyond their
2234 // declaring function and writes to them could be observable side effects.
2235 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2236 return;
2237
2238 // Don't warn about __block Objective-C pointer variables, as they might
2239 // be assigned in the block but not used elsewhere for the purpose of lifetime
2240 // extension.
2241 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2242 return;
2243
2244 // Don't warn about Objective-C pointer variables with precise lifetime
2245 // semantics; they can be used to ensure ARC releases the object at a known
2246 // time, which may mean assignment but no other references.
2247 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2248 return;
2249
2250 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2251 if (iter == RefsMinusAssignments.end())
2252 return;
2253
2254 assert(iter->getSecond() >= 0 &&
2255 "Found a negative number of references to a VarDecl");
2256 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2257 // Assume the given VarDecl is "used" if its ref count stored in
2258 // `RefMinusAssignments` is positive, with one exception.
2259 //
2260 // For a C++ variable whose decl (with initializer) entirely consist the
2261 // condition expression of a if/while/for construct,
2262 // Clang creates a DeclRefExpr for the condition expression rather than a
2263 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2264 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2265 // used in the body of the if/while/for construct.
2266 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2267 if (!UnusedCXXCondDecl)
2268 return;
2269 }
2270
2271 unsigned DiagID;
2272 if (isa<ParmVarDecl>(Val: VD))
2273 DiagID = diag::warn_unused_but_set_parameter;
2274 else if (VD->isFileVarDecl())
2275 DiagID = diag::warn_unused_but_set_global;
2276 else
2277 DiagID = diag::warn_unused_but_set_variable;
2278 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2279}
2280
2281static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2282 Sema::DiagReceiverTy DiagReceiver) {
2283 // Verify that we have no forward references left. If so, there was a goto
2284 // or address of a label taken, but no definition of it. Label fwd
2285 // definitions are indicated with a null substmt which is also not a resolved
2286 // MS inline assembly label name.
2287 bool Diagnose = false;
2288 if (L->isMSAsmLabel())
2289 Diagnose = !L->isResolvedMSAsmLabel();
2290 else
2291 Diagnose = L->getStmt() == nullptr;
2292 if (Diagnose)
2293 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2294 << L);
2295}
2296
2297void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2298 S->applyNRVO();
2299
2300 if (S->decl_empty()) return;
2301 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2302 "Scope shouldn't contain decls!");
2303
2304 /// We visit the decls in non-deterministic order, but we want diagnostics
2305 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2306 /// and sort the diagnostics before emitting them, after we visited all decls.
2307 struct LocAndDiag {
2308 SourceLocation Loc;
2309 std::optional<SourceLocation> PreviousDeclLoc;
2310 PartialDiagnostic PD;
2311 };
2312 SmallVector<LocAndDiag, 16> DeclDiags;
2313 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2314 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2315 };
2316 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2317 SourceLocation PreviousDeclLoc,
2318 PartialDiagnostic PD) {
2319 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2320 };
2321
2322 for (auto *TmpD : S->decls()) {
2323 assert(TmpD && "This decl didn't get pushed??");
2324
2325 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2326 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2327
2328 // Diagnose unused variables in this scope.
2329 if (!S->hasUnrecoverableErrorOccurred()) {
2330 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2331 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2332 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2333 // Wait until end of TU to diagnose internal linkage file vars.
2334 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2335 VD && !VD->isInternalLinkageFileVar()) {
2336 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2337 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2338 }
2339 }
2340
2341 if (!D->getDeclName()) continue;
2342
2343 // If this was a forward reference to a label, verify it was defined.
2344 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2345 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2346
2347 // Partial translation units that are created in incremental processing must
2348 // not clean up the IdResolver because PTUs should take into account the
2349 // declarations that came from previous PTUs.
2350 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2351 getLangOpts().CPlusPlus)
2352 IdResolver.RemoveDecl(D);
2353
2354 // Warn on it if we are shadowing a declaration.
2355 auto ShadowI = ShadowingDecls.find(Val: D);
2356 if (ShadowI != ShadowingDecls.end()) {
2357 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2358 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2359 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2360 << D << FD << FD->getParent());
2361 }
2362 ShadowingDecls.erase(I: ShadowI);
2363 }
2364 }
2365
2366 llvm::sort(C&: DeclDiags,
2367 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2368 // The particular order for diagnostics is not important, as long
2369 // as the order is deterministic. Using the raw location is going
2370 // to generally be in source order unless there are macro
2371 // expansions involved.
2372 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2373 });
2374 for (const LocAndDiag &D : DeclDiags) {
2375 Diag(Loc: D.Loc, PD: D.PD);
2376 if (D.PreviousDeclLoc)
2377 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2378 }
2379}
2380
2381Scope *Sema::getNonFieldDeclScope(Scope *S) {
2382 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2383 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2384 (S->isClassScope() && !getLangOpts().CPlusPlus))
2385 S = S->getParent();
2386 return S;
2387}
2388
2389static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2390 ASTContext::GetBuiltinTypeError Error) {
2391 switch (Error) {
2392 case ASTContext::GE_None:
2393 return "";
2394 case ASTContext::GE_Missing_type:
2395 return BuiltinInfo.getHeaderName(ID);
2396 case ASTContext::GE_Missing_stdio:
2397 return "stdio.h";
2398 case ASTContext::GE_Missing_setjmp:
2399 return "setjmp.h";
2400 case ASTContext::GE_Missing_ucontext:
2401 return "ucontext.h";
2402 }
2403 llvm_unreachable("unhandled error kind");
2404}
2405
2406FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2407 unsigned ID, SourceLocation Loc) {
2408 DeclContext *Parent = Context.getTranslationUnitDecl();
2409
2410 if (getLangOpts().CPlusPlus) {
2411 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2412 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2413 CLinkageDecl->setImplicit();
2414 Parent->addDecl(D: CLinkageDecl);
2415 Parent = CLinkageDecl;
2416 }
2417
2418 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2419 if (Context.BuiltinInfo.isImmediate(ID)) {
2420 assert(getLangOpts().CPlusPlus20 &&
2421 "consteval builtins should only be available in C++20 mode");
2422 ConstexprKind = ConstexprSpecKind::Consteval;
2423 }
2424
2425 FunctionDecl *New = FunctionDecl::Create(
2426 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2427 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2428 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2429 New->setImplicit();
2430 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2431
2432 // Create Decl objects for each parameter, adding them to the
2433 // FunctionDecl.
2434 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2435 SmallVector<ParmVarDecl *, 16> Params;
2436 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2437 ParmVarDecl *parm = ParmVarDecl::Create(
2438 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2439 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2440 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2441 Params.push_back(Elt: parm);
2442 }
2443 New->setParams(Params);
2444 }
2445
2446 AddKnownFunctionAttributes(FD: New);
2447 return New;
2448}
2449
2450NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2451 Scope *S, bool ForRedeclaration,
2452 SourceLocation Loc) {
2453 LookupNecessaryTypesForBuiltin(S, ID);
2454
2455 ASTContext::GetBuiltinTypeError Error;
2456 QualType R = Context.GetBuiltinType(ID, Error);
2457 if (Error) {
2458 if (!ForRedeclaration)
2459 return nullptr;
2460
2461 // If we have a builtin without an associated type we should not emit a
2462 // warning when we were not able to find a type for it.
2463 if (Error == ASTContext::GE_Missing_type ||
2464 Context.BuiltinInfo.allowTypeMismatch(ID))
2465 return nullptr;
2466
2467 // If we could not find a type for setjmp it is because the jmp_buf type was
2468 // not defined prior to the setjmp declaration.
2469 if (Error == ASTContext::GE_Missing_setjmp) {
2470 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2471 << Context.BuiltinInfo.getName(ID);
2472 return nullptr;
2473 }
2474
2475 // Generally, we emit a warning that the declaration requires the
2476 // appropriate header.
2477 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2478 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2479 << Context.BuiltinInfo.getName(ID);
2480 return nullptr;
2481 }
2482
2483 if (!ForRedeclaration &&
2484 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2485 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2486 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2487 : diag::ext_implicit_lib_function_decl)
2488 << Context.BuiltinInfo.getName(ID) << R;
2489 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2490 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2491 << Header << Context.BuiltinInfo.getName(ID);
2492 }
2493
2494 if (R.isNull())
2495 return nullptr;
2496
2497 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2498 RegisterLocallyScopedExternCDecl(ND: New, S);
2499
2500 // TUScope is the translation-unit scope to insert this function into.
2501 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2502 // relate Scopes to DeclContexts, and probably eliminate CurContext
2503 // entirely, but we're not there yet.
2504 DeclContext *SavedContext = CurContext;
2505 CurContext = New->getDeclContext();
2506 PushOnScopeChains(D: New, S: TUScope);
2507 CurContext = SavedContext;
2508 return New;
2509}
2510
2511/// Typedef declarations don't have linkage, but they still denote the same
2512/// entity if their types are the same.
2513/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2514/// isSameEntity.
2515static void
2516filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2517 LookupResult &Previous) {
2518 // This is only interesting when modules are enabled.
2519 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2520 return;
2521
2522 // Empty sets are uninteresting.
2523 if (Previous.empty())
2524 return;
2525
2526 LookupResult::Filter Filter = Previous.makeFilter();
2527 while (Filter.hasNext()) {
2528 NamedDecl *Old = Filter.next();
2529
2530 // Non-hidden declarations are never ignored.
2531 if (S.isVisible(D: Old))
2532 continue;
2533
2534 // Declarations of the same entity are not ignored, even if they have
2535 // different linkages.
2536 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2537 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2538 T2: Decl->getUnderlyingType()))
2539 continue;
2540
2541 // If both declarations give a tag declaration a typedef name for linkage
2542 // purposes, then they declare the same entity.
2543 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2544 Decl->getAnonDeclWithTypedefName())
2545 continue;
2546 }
2547
2548 Filter.erase();
2549 }
2550
2551 Filter.done();
2552}
2553
2554bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2555 QualType OldType;
2556 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2557 OldType = OldTypedef->getUnderlyingType();
2558 else
2559 OldType = Context.getTypeDeclType(Decl: Old);
2560 QualType NewType = New->getUnderlyingType();
2561
2562 if (NewType->isVariablyModifiedType()) {
2563 // Must not redefine a typedef with a variably-modified type.
2564 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2565 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2566 << Kind << NewType;
2567 if (Old->getLocation().isValid())
2568 notePreviousDefinition(Old, New: New->getLocation());
2569 New->setInvalidDecl();
2570 return true;
2571 }
2572
2573 if (OldType != NewType &&
2574 !OldType->isDependentType() &&
2575 !NewType->isDependentType() &&
2576 !Context.hasSameType(T1: OldType, T2: NewType)) {
2577 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2578 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2579 << Kind << NewType << OldType;
2580 if (Old->getLocation().isValid())
2581 notePreviousDefinition(Old, New: New->getLocation());
2582 New->setInvalidDecl();
2583 return true;
2584 }
2585 return false;
2586}
2587
2588void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2589 LookupResult &OldDecls) {
2590 // If the new decl is known invalid already, don't bother doing any
2591 // merging checks.
2592 if (New->isInvalidDecl()) return;
2593
2594 // Allow multiple definitions for ObjC built-in typedefs.
2595 // FIXME: Verify the underlying types are equivalent!
2596 if (getLangOpts().ObjC) {
2597 const IdentifierInfo *TypeID = New->getIdentifier();
2598 switch (TypeID->getLength()) {
2599 default: break;
2600 case 2:
2601 {
2602 if (!TypeID->isStr(Str: "id"))
2603 break;
2604 QualType T = New->getUnderlyingType();
2605 if (!T->isPointerType())
2606 break;
2607 if (!T->isVoidPointerType()) {
2608 QualType PT = T->castAs<PointerType>()->getPointeeType();
2609 if (!PT->isStructureType())
2610 break;
2611 }
2612 Context.setObjCIdRedefinitionType(T);
2613 // Install the built-in type for 'id', ignoring the current definition.
2614 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2615 modedTy: Context.getObjCIdType());
2616 return;
2617 }
2618 case 5:
2619 if (!TypeID->isStr(Str: "Class"))
2620 break;
2621 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2622 // Install the built-in type for 'Class', ignoring the current definition.
2623 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2624 modedTy: Context.getObjCClassType());
2625 return;
2626 case 3:
2627 if (!TypeID->isStr(Str: "SEL"))
2628 break;
2629 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2630 // Install the built-in type for 'SEL', ignoring the current definition.
2631 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2632 modedTy: Context.getObjCSelType());
2633 return;
2634 }
2635 // Fall through - the typedef name was not a builtin type.
2636 }
2637
2638 // Verify the old decl was also a type.
2639 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2640 if (!Old) {
2641 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2642 << New->getDeclName();
2643
2644 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2645 if (OldD->getLocation().isValid())
2646 notePreviousDefinition(Old: OldD, New: New->getLocation());
2647
2648 return New->setInvalidDecl();
2649 }
2650
2651 // If the old declaration is invalid, just give up here.
2652 if (Old->isInvalidDecl())
2653 return New->setInvalidDecl();
2654
2655 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2656 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2657 auto *NewTag = New->getAnonDeclWithTypedefName();
2658 NamedDecl *Hidden = nullptr;
2659 if (OldTag && NewTag &&
2660 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2661 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2662 // There is a definition of this tag, but it is not visible. Use it
2663 // instead of our tag.
2664 if (OldTD->isModed())
2665 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2666 modedTy: OldTD->getUnderlyingType());
2667 else
2668 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2669
2670 // Make the old tag definition visible.
2671 makeMergedDefinitionVisible(ND: Hidden);
2672
2673 CleanupMergedEnum(S, New: NewTag);
2674 }
2675 }
2676
2677 // If the typedef types are not identical, reject them in all languages and
2678 // with any extensions enabled.
2679 if (isIncompatibleTypedef(Old, New))
2680 return;
2681
2682 // The types match. Link up the redeclaration chain and merge attributes if
2683 // the old declaration was a typedef.
2684 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2685 New->setPreviousDecl(Typedef);
2686 mergeDeclAttributes(New, Old);
2687 }
2688
2689 if (getLangOpts().MicrosoftExt)
2690 return;
2691
2692 if (getLangOpts().CPlusPlus) {
2693 // C++ [dcl.typedef]p2:
2694 // In a given non-class scope, a typedef specifier can be used to
2695 // redefine the name of any type declared in that scope to refer
2696 // to the type to which it already refers.
2697 if (!isa<CXXRecordDecl>(Val: CurContext))
2698 return;
2699
2700 // C++0x [dcl.typedef]p4:
2701 // In a given class scope, a typedef specifier can be used to redefine
2702 // any class-name declared in that scope that is not also a typedef-name
2703 // to refer to the type to which it already refers.
2704 //
2705 // This wording came in via DR424, which was a correction to the
2706 // wording in DR56, which accidentally banned code like:
2707 //
2708 // struct S {
2709 // typedef struct A { } A;
2710 // };
2711 //
2712 // in the C++03 standard. We implement the C++0x semantics, which
2713 // allow the above but disallow
2714 //
2715 // struct S {
2716 // typedef int I;
2717 // typedef int I;
2718 // };
2719 //
2720 // since that was the intent of DR56.
2721 if (!isa<TypedefNameDecl>(Val: Old))
2722 return;
2723
2724 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2725 << New->getDeclName();
2726 notePreviousDefinition(Old, New: New->getLocation());
2727 return New->setInvalidDecl();
2728 }
2729
2730 // Modules always permit redefinition of typedefs, as does C11.
2731 if (getLangOpts().Modules || getLangOpts().C11)
2732 return;
2733
2734 // If we have a redefinition of a typedef in C, emit a warning. This warning
2735 // is normally mapped to an error, but can be controlled with
2736 // -Wtypedef-redefinition. If either the original or the redefinition is
2737 // in a system header, don't emit this for compatibility with GCC.
2738 if (getDiagnostics().getSuppressSystemWarnings() &&
2739 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2740 (Old->isImplicit() ||
2741 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2742 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2743 return;
2744
2745 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2746 << New->getDeclName();
2747 notePreviousDefinition(Old, New: New->getLocation());
2748}
2749
2750void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2751 // If this was an unscoped enumeration, yank all of its enumerators
2752 // out of the scope.
2753 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2754 Scope *EnumScope = getNonFieldDeclScope(S);
2755 for (auto *ECD : ED->enumerators()) {
2756 assert(EnumScope->isDeclScope(ECD));
2757 EnumScope->RemoveDecl(D: ECD);
2758 IdResolver.RemoveDecl(D: ECD);
2759 }
2760 }
2761}
2762
2763/// DeclhasAttr - returns true if decl Declaration already has the target
2764/// attribute.
2765static bool DeclHasAttr(const Decl *D, const Attr *A) {
2766 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2767 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2768 for (const auto *i : D->attrs())
2769 if (i->getKind() == A->getKind()) {
2770 if (Ann) {
2771 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2772 return true;
2773 continue;
2774 }
2775 // FIXME: Don't hardcode this check
2776 if (OA && isa<OwnershipAttr>(Val: i))
2777 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2778 return true;
2779 }
2780
2781 return false;
2782}
2783
2784static bool isAttributeTargetADefinition(Decl *D) {
2785 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2786 return VD->isThisDeclarationADefinition();
2787 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2788 return TD->isCompleteDefinition() || TD->isBeingDefined();
2789 return true;
2790}
2791
2792/// Merge alignment attributes from \p Old to \p New, taking into account the
2793/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2794///
2795/// \return \c true if any attributes were added to \p New.
2796static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2797 // Look for alignas attributes on Old, and pick out whichever attribute
2798 // specifies the strictest alignment requirement.
2799 AlignedAttr *OldAlignasAttr = nullptr;
2800 AlignedAttr *OldStrictestAlignAttr = nullptr;
2801 unsigned OldAlign = 0;
2802 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2803 // FIXME: We have no way of representing inherited dependent alignments
2804 // in a case like:
2805 // template<int A, int B> struct alignas(A) X;
2806 // template<int A, int B> struct alignas(B) X {};
2807 // For now, we just ignore any alignas attributes which are not on the
2808 // definition in such a case.
2809 if (I->isAlignmentDependent())
2810 return false;
2811
2812 if (I->isAlignas())
2813 OldAlignasAttr = I;
2814
2815 unsigned Align = I->getAlignment(Ctx&: S.Context);
2816 if (Align > OldAlign) {
2817 OldAlign = Align;
2818 OldStrictestAlignAttr = I;
2819 }
2820 }
2821
2822 // Look for alignas attributes on New.
2823 AlignedAttr *NewAlignasAttr = nullptr;
2824 unsigned NewAlign = 0;
2825 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2826 if (I->isAlignmentDependent())
2827 return false;
2828
2829 if (I->isAlignas())
2830 NewAlignasAttr = I;
2831
2832 unsigned Align = I->getAlignment(Ctx&: S.Context);
2833 if (Align > NewAlign)
2834 NewAlign = Align;
2835 }
2836
2837 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2838 // Both declarations have 'alignas' attributes. We require them to match.
2839 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2840 // fall short. (If two declarations both have alignas, they must both match
2841 // every definition, and so must match each other if there is a definition.)
2842
2843 // If either declaration only contains 'alignas(0)' specifiers, then it
2844 // specifies the natural alignment for the type.
2845 if (OldAlign == 0 || NewAlign == 0) {
2846 QualType Ty;
2847 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2848 Ty = VD->getType();
2849 else
2850 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2851
2852 if (OldAlign == 0)
2853 OldAlign = S.Context.getTypeAlign(T: Ty);
2854 if (NewAlign == 0)
2855 NewAlign = S.Context.getTypeAlign(T: Ty);
2856 }
2857
2858 if (OldAlign != NewAlign) {
2859 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2860 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2861 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2862 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2863 }
2864 }
2865
2866 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2867 // C++11 [dcl.align]p6:
2868 // if any declaration of an entity has an alignment-specifier,
2869 // every defining declaration of that entity shall specify an
2870 // equivalent alignment.
2871 // C11 6.7.5/7:
2872 // If the definition of an object does not have an alignment
2873 // specifier, any other declaration of that object shall also
2874 // have no alignment specifier.
2875 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2876 << OldAlignasAttr;
2877 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2878 << OldAlignasAttr;
2879 }
2880
2881 bool AnyAdded = false;
2882
2883 // Ensure we have an attribute representing the strictest alignment.
2884 if (OldAlign > NewAlign) {
2885 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2886 Clone->setInherited(true);
2887 New->addAttr(A: Clone);
2888 AnyAdded = true;
2889 }
2890
2891 // Ensure we have an alignas attribute if the old declaration had one.
2892 if (OldAlignasAttr && !NewAlignasAttr &&
2893 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2894 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2895 Clone->setInherited(true);
2896 New->addAttr(A: Clone);
2897 AnyAdded = true;
2898 }
2899
2900 return AnyAdded;
2901}
2902
2903#define WANT_DECL_MERGE_LOGIC
2904#include "clang/Sema/AttrParsedAttrImpl.inc"
2905#undef WANT_DECL_MERGE_LOGIC
2906
2907static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2908 const InheritableAttr *Attr,
2909 AvailabilityMergeKind AMK) {
2910 // Diagnose any mutual exclusions between the attribute that we want to add
2911 // and attributes that already exist on the declaration.
2912 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2913 return false;
2914
2915 // This function copies an attribute Attr from a previous declaration to the
2916 // new declaration D if the new declaration doesn't itself have that attribute
2917 // yet or if that attribute allows duplicates.
2918 // If you're adding a new attribute that requires logic different from
2919 // "use explicit attribute on decl if present, else use attribute from
2920 // previous decl", for example if the attribute needs to be consistent
2921 // between redeclarations, you need to call a custom merge function here.
2922 InheritableAttr *NewAttr = nullptr;
2923 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2924 const IdentifierInfo *InferredPlatformII = nullptr;
2925 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2926 InferredPlatformII = Inf->getPlatform();
2927 NewAttr = S.mergeAndInferAvailabilityAttr(
2928 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2929 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2930 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2931 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2932 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2933 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2934 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2935 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2936 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2937 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2938 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2939 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2940 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2941 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2942 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2943 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2944 FirstArg: FA->getFirstArg());
2945 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2946 NewAttr = S.mergeFormatMatchesAttr(
2947 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2948 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2949 NewAttr = S.mergeModularFormatAttr(
2950 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2951 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2952 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2953 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2954 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2955 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2956 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2957 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2958 Model: IA->getInheritanceModel());
2959 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2960 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2961 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2962 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2963 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2964 isa<CUDAGlobalAttr>(Val: Attr))) {
2965 // CUDA target attributes are part of function signature for
2966 // overloading purposes and must not be merged.
2967 return false;
2968 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2969 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2970 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2971 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2972 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2973 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2974 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2975 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2976 else if (isa<AlignedAttr>(Val: Attr))
2977 // AlignedAttrs are handled separately, because we need to handle all
2978 // such attributes on a declaration at the same time.
2979 NewAttr = nullptr;
2980 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2981 (AMK == AvailabilityMergeKind::Override ||
2982 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2983 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2984 NewAttr = nullptr;
2985 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2986 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2987 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2988 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2989 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2990 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2991 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2992 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2993 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2994 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2995 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2996 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2997 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2998 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2999 Z: NT->getZ());
3000 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3001 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3002 Preferred: WS->getPreferred(),
3003 SpelledArgsCount: WS->getSpelledArgsCount());
3004 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3005 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3006 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3007 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3008 else if (isa<SuppressAttr>(Val: Attr))
3009 // Do nothing. Each redeclaration should be suppressed separately.
3010 NewAttr = nullptr;
3011 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3012 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3013 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3014 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3015 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3016 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3017
3018 if (NewAttr) {
3019 NewAttr->setInherited(true);
3020 D->addAttr(A: NewAttr);
3021 if (isa<MSInheritanceAttr>(Val: NewAttr))
3022 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3023 return true;
3024 }
3025
3026 return false;
3027}
3028
3029static const NamedDecl *getDefinition(const Decl *D) {
3030 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3031 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3032 return Def;
3033 return nullptr;
3034 }
3035 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3036 const VarDecl *Def = VD->getDefinition();
3037 if (Def)
3038 return Def;
3039 return VD->getActingDefinition();
3040 }
3041 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3042 const FunctionDecl *Def = nullptr;
3043 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3044 return Def;
3045 }
3046 return nullptr;
3047}
3048
3049static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3050 for (const auto *Attribute : D->attrs())
3051 if (Attribute->getKind() == Kind)
3052 return true;
3053 return false;
3054}
3055
3056/// checkNewAttributesAfterDef - If we already have a definition, check that
3057/// there are no new attributes in this declaration.
3058static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3059 if (!New->hasAttrs())
3060 return;
3061
3062 const NamedDecl *Def = getDefinition(D: Old);
3063 if (!Def || Def == New)
3064 return;
3065
3066 AttrVec &NewAttributes = New->getAttrs();
3067 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3068 Attr *NewAttribute = NewAttributes[I];
3069
3070 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3072 SkipBodyInfo SkipBody;
3073 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3074
3075 // If we're skipping this definition, drop the "alias" attribute.
3076 if (SkipBody.ShouldSkip) {
3077 NewAttributes.erase(CI: NewAttributes.begin() + I);
3078 --E;
3079 continue;
3080 }
3081 } else {
3082 VarDecl *VD = cast<VarDecl>(Val: New);
3083 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3084 VarDecl::TentativeDefinition
3085 ? diag::err_alias_after_tentative
3086 : diag::err_redefinition;
3087 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3088 if (Diag == diag::err_redefinition)
3089 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3090 else
3091 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3092 VD->setInvalidDecl();
3093 }
3094 ++I;
3095 continue;
3096 }
3097
3098 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3099 // Tentative definitions are only interesting for the alias check above.
3100 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3101 ++I;
3102 continue;
3103 }
3104 }
3105
3106 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3107 ++I;
3108 continue; // regular attr merging will take care of validating this.
3109 }
3110
3111 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3112 // C's _Noreturn is allowed to be added to a function after it is defined.
3113 ++I;
3114 continue;
3115 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3116 // msvc will allow a subsequent definition to add an uuid to a class
3117 ++I;
3118 continue;
3119 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3120 Val: NewAttribute) &&
3121 NewAttribute->isStandardAttributeSyntax()) {
3122 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3123 // deprecated attribute can later be re-declared with the attribute and
3124 // vice-versa.
3125 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3126 // maybe_unused attribute can later be redeclared with the attribute and
3127 // vice versa.
3128 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3129 // nodiscard attribute can later be redeclared with the attribute and
3130 // vice-versa.
3131 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3132 ++I;
3133 continue;
3134 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3135 if (AA->isAlignas()) {
3136 // C++11 [dcl.align]p6:
3137 // if any declaration of an entity has an alignment-specifier,
3138 // every defining declaration of that entity shall specify an
3139 // equivalent alignment.
3140 // C11 6.7.5/7:
3141 // If the definition of an object does not have an alignment
3142 // specifier, any other declaration of that object shall also
3143 // have no alignment specifier.
3144 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3145 << AA;
3146 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3147 << AA;
3148 NewAttributes.erase(CI: NewAttributes.begin() + I);
3149 --E;
3150 continue;
3151 }
3152 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3153 // If there is a C definition followed by a redeclaration with this
3154 // attribute then there are two different definitions. In C++, prefer the
3155 // standard diagnostics.
3156 if (!S.getLangOpts().CPlusPlus) {
3157 S.Diag(Loc: NewAttribute->getLocation(),
3158 DiagID: diag::err_loader_uninitialized_redeclaration);
3159 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3160 NewAttributes.erase(CI: NewAttributes.begin() + I);
3161 --E;
3162 continue;
3163 }
3164 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3165 cast<VarDecl>(Val: New)->isInline() &&
3166 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3167 // Don't warn about applying selectany to implicitly inline variables.
3168 // Older compilers and language modes would require the use of selectany
3169 // to make such variables inline, and it would have no effect if we
3170 // honored it.
3171 ++I;
3172 continue;
3173 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3174 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3175 // declarations after definitions.
3176 ++I;
3177 continue;
3178 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3179 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3180 // error since the definition will have already been created without
3181 // the semantic effects of the attribute having been applied.
3182 S.Diag(Loc: NewAttribute->getLocation(),
3183 DiagID: diag::err_sycl_entry_point_after_definition)
3184 << NewAttribute;
3185 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3186 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3187 ++I;
3188 continue;
3189 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3190 // SYCLExternalAttr may be added after a definition.
3191 ++I;
3192 continue;
3193 }
3194
3195 S.Diag(Loc: NewAttribute->getLocation(),
3196 DiagID: diag::warn_attribute_precede_definition);
3197 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3198 NewAttributes.erase(CI: NewAttributes.begin() + I);
3199 --E;
3200 }
3201}
3202
3203static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3204 const ConstInitAttr *CIAttr,
3205 bool AttrBeforeInit) {
3206 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3207
3208 // Figure out a good way to write this specifier on the old declaration.
3209 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3210 // enough of the attribute list spelling information to extract that without
3211 // heroics.
3212 std::string SuitableSpelling;
3213 if (S.getLangOpts().CPlusPlus20)
3214 SuitableSpelling = std::string(
3215 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3216 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3217 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3218 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3219 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3220 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3221 tok::r_square, tok::r_square}));
3222 if (SuitableSpelling.empty())
3223 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3224 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3225 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3226 tok::r_paren, tok::r_paren}));
3227 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3228 SuitableSpelling = "constinit";
3229 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3230 SuitableSpelling = "[[clang::require_constant_initialization]]";
3231 if (SuitableSpelling.empty())
3232 SuitableSpelling = "__attribute__((require_constant_initialization))";
3233 SuitableSpelling += " ";
3234
3235 if (AttrBeforeInit) {
3236 // extern constinit int a;
3237 // int a = 0; // error (missing 'constinit'), accepted as extension
3238 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3239 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3240 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3241 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3242 } else {
3243 // int a = 0;
3244 // constinit extern int a; // error (missing 'constinit')
3245 S.Diag(Loc: CIAttr->getLocation(),
3246 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3247 : diag::warn_require_const_init_added_too_late)
3248 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3249 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3250 << CIAttr->isConstinit()
3251 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3252 }
3253}
3254
3255void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3256 AvailabilityMergeKind AMK) {
3257 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3258 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3259 NewAttr->setInherited(true);
3260 New->addAttr(A: NewAttr);
3261 }
3262 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3263 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3264 NewAttr->setInherited(true);
3265 New->addAttr(A: NewAttr);
3266 }
3267
3268 if (!Old->hasAttrs() && !New->hasAttrs())
3269 return;
3270
3271 // [dcl.constinit]p1:
3272 // If the [constinit] specifier is applied to any declaration of a
3273 // variable, it shall be applied to the initializing declaration.
3274 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3275 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3276 if (bool(OldConstInit) != bool(NewConstInit)) {
3277 const auto *OldVD = cast<VarDecl>(Val: Old);
3278 auto *NewVD = cast<VarDecl>(Val: New);
3279
3280 // Find the initializing declaration. Note that we might not have linked
3281 // the new declaration into the redeclaration chain yet.
3282 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3283 if (!InitDecl &&
3284 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3285 InitDecl = NewVD;
3286
3287 if (InitDecl == NewVD) {
3288 // This is the initializing declaration. If it would inherit 'constinit',
3289 // that's ill-formed. (Note that we do not apply this to the attribute
3290 // form).
3291 if (OldConstInit && OldConstInit->isConstinit())
3292 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3293 /*AttrBeforeInit=*/true);
3294 } else if (NewConstInit) {
3295 // This is the first time we've been told that this declaration should
3296 // have a constant initializer. If we already saw the initializing
3297 // declaration, this is too late.
3298 if (InitDecl && InitDecl != NewVD) {
3299 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3300 /*AttrBeforeInit=*/false);
3301 NewVD->dropAttr<ConstInitAttr>();
3302 }
3303 }
3304 }
3305
3306 // Attributes declared post-definition are currently ignored.
3307 checkNewAttributesAfterDef(S&: *this, New, Old);
3308
3309 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3310 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3311 if (!OldA->isEquivalent(Other: NewA)) {
3312 // This redeclaration changes __asm__ label.
3313 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3314 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3315 }
3316 } else if (Old->isUsed()) {
3317 // This redeclaration adds an __asm__ label to a declaration that has
3318 // already been ODR-used.
3319 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3320 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3321 }
3322 }
3323
3324 // Re-declaration cannot add abi_tag's.
3325 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3326 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3327 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3328 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3329 Diag(Loc: NewAbiTagAttr->getLocation(),
3330 DiagID: diag::err_new_abi_tag_on_redeclaration)
3331 << NewTag;
3332 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3333 }
3334 }
3335 } else {
3336 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3337 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3338 }
3339 }
3340
3341 // This redeclaration adds a section attribute.
3342 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3343 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3344 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3345 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3346 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3347 }
3348 }
3349 }
3350
3351 // Redeclaration adds code-seg attribute.
3352 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3353 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3354 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3355 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3356 << 0 /*codeseg*/;
3357 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3358 }
3359
3360 if (!Old->hasAttrs())
3361 return;
3362
3363 bool foundAny = New->hasAttrs();
3364
3365 // Ensure that any moving of objects within the allocated map is done before
3366 // we process them.
3367 if (!foundAny) New->setAttrs(AttrVec());
3368
3369 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3370 // Ignore deprecated/unavailable/availability attributes if requested.
3371 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3372 if (isa<DeprecatedAttr>(Val: I) ||
3373 isa<UnavailableAttr>(Val: I) ||
3374 isa<AvailabilityAttr>(Val: I)) {
3375 switch (AMK) {
3376 case AvailabilityMergeKind::None:
3377 continue;
3378
3379 case AvailabilityMergeKind::Redeclaration:
3380 case AvailabilityMergeKind::Override:
3381 case AvailabilityMergeKind::ProtocolImplementation:
3382 case AvailabilityMergeKind::OptionalProtocolImplementation:
3383 LocalAMK = AMK;
3384 break;
3385 }
3386 }
3387
3388 // Already handled.
3389 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3390 continue;
3391
3392 if (isa<InferredNoReturnAttr>(Val: I)) {
3393 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3394 FD &&
3395 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3396 continue; // Don't propagate inferred noreturn attributes to explicit
3397 }
3398
3399 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3400 foundAny = true;
3401 }
3402
3403 if (mergeAlignedAttrs(S&: *this, New, Old))
3404 foundAny = true;
3405
3406 if (!foundAny) New->dropAttrs();
3407}
3408
3409void Sema::CheckAttributesOnDeducedType(Decl *D) {
3410 for (const Attr *A : D->attrs())
3411 checkAttrIsTypeDependent(D, A);
3412}
3413
3414// Returns the number of added attributes.
3415template <class T>
3416static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3417 Sema &S) {
3418 unsigned found = 0;
3419 for (const auto *I : From->specific_attrs<T>()) {
3420 if (!DeclHasAttr(To, I)) {
3421 T *newAttr = cast<T>(I->clone(S.Context));
3422 newAttr->setInherited(true);
3423 To->addAttr(A: newAttr);
3424 ++found;
3425 }
3426 }
3427 return found;
3428}
3429
3430template <class F>
3431static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3432 F &&propagator) {
3433 if (!From->hasAttrs()) {
3434 return;
3435 }
3436
3437 bool foundAny = To->hasAttrs();
3438
3439 // Ensure that any moving of objects within the allocated map is
3440 // done before we process them.
3441 if (!foundAny)
3442 To->setAttrs(AttrVec());
3443
3444 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3445
3446 if (!foundAny)
3447 To->dropAttrs();
3448}
3449
3450/// mergeParamDeclAttributes - Copy attributes from the old parameter
3451/// to the new one.
3452static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3453 const ParmVarDecl *oldDecl,
3454 Sema &S) {
3455 // C++11 [dcl.attr.depend]p2:
3456 // The first declaration of a function shall specify the
3457 // carries_dependency attribute for its declarator-id if any declaration
3458 // of the function specifies the carries_dependency attribute.
3459 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3460 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3461 S.Diag(Loc: CDA->getLocation(),
3462 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3463 // Find the first declaration of the parameter.
3464 // FIXME: Should we build redeclaration chains for function parameters?
3465 const FunctionDecl *FirstFD =
3466 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3467 const ParmVarDecl *FirstVD =
3468 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3469 S.Diag(Loc: FirstVD->getLocation(),
3470 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3471 }
3472
3473 propagateAttributes(
3474 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3475 unsigned found = 0;
3476 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3477 // Propagate the lifetimebound attribute from parameters to the
3478 // most recent declaration. Note that this doesn't include the implicit
3479 // 'this' parameter, as the attribute is applied to the function type in
3480 // that case.
3481 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3482 return found;
3483 });
3484}
3485
3486static bool EquivalentArrayTypes(QualType Old, QualType New,
3487 const ASTContext &Ctx) {
3488
3489 auto NoSizeInfo = [&Ctx](QualType Ty) {
3490 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3491 return true;
3492 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3493 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3494 return false;
3495 };
3496
3497 // `type[]` is equivalent to `type *` and `type[*]`.
3498 if (NoSizeInfo(Old) && NoSizeInfo(New))
3499 return true;
3500
3501 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3502 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3503 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3504 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3505 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3506 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3507 return false;
3508 return true;
3509 }
3510
3511 // Only compare size, ignore Size modifiers and CVR.
3512 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3513 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3514 Ctx.getAsConstantArrayType(T: New)->getSize();
3515 }
3516
3517 // Don't try to compare dependent sized array
3518 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3519 return true;
3520 }
3521
3522 return Old == New;
3523}
3524
3525static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3526 const ParmVarDecl *OldParam,
3527 Sema &S) {
3528 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3529 if (auto Newnullability = NewParam->getType()->getNullability()) {
3530 if (*Oldnullability != *Newnullability) {
3531 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3532 << DiagNullabilityKind(
3533 *Newnullability,
3534 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3535 != 0))
3536 << DiagNullabilityKind(
3537 *Oldnullability,
3538 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3539 != 0));
3540 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3541 }
3542 } else {
3543 QualType NewT = NewParam->getType();
3544 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3545 NewParam->setType(NewT);
3546 }
3547 }
3548 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3549 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3550 if (OldParamDT && NewParamDT &&
3551 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3552 QualType OldParamOT = OldParamDT->getOriginalType();
3553 QualType NewParamOT = NewParamDT->getOriginalType();
3554 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3555 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3556 << NewParam << NewParamOT;
3557 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3558 << OldParamOT;
3559 }
3560 }
3561}
3562
3563namespace {
3564
3565/// Used in MergeFunctionDecl to keep track of function parameters in
3566/// C.
3567struct GNUCompatibleParamWarning {
3568 ParmVarDecl *OldParm;
3569 ParmVarDecl *NewParm;
3570 QualType PromotedType;
3571};
3572
3573} // end anonymous namespace
3574
3575// Determine whether the previous declaration was a definition, implicit
3576// declaration, or a declaration.
3577template <typename T>
3578static std::pair<diag::kind, SourceLocation>
3579getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3580 diag::kind PrevDiag;
3581 SourceLocation OldLocation = Old->getLocation();
3582 if (Old->isThisDeclarationADefinition())
3583 PrevDiag = diag::note_previous_definition;
3584 else if (Old->isImplicit()) {
3585 PrevDiag = diag::note_previous_implicit_declaration;
3586 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3587 if (FD->getBuiltinID())
3588 PrevDiag = diag::note_previous_builtin_declaration;
3589 }
3590 if (OldLocation.isInvalid())
3591 OldLocation = New->getLocation();
3592 } else
3593 PrevDiag = diag::note_previous_declaration;
3594 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3595}
3596
3597/// canRedefineFunction - checks if a function can be redefined. Currently,
3598/// only extern inline functions can be redefined, and even then only in
3599/// GNU89 mode.
3600static bool canRedefineFunction(const FunctionDecl *FD,
3601 const LangOptions& LangOpts) {
3602 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3603 !LangOpts.CPlusPlus &&
3604 FD->isInlineSpecified() &&
3605 FD->getStorageClass() == SC_Extern);
3606}
3607
3608const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3609 const AttributedType *AT = T->getAs<AttributedType>();
3610 while (AT && !AT->isCallingConv())
3611 AT = AT->getModifiedType()->getAs<AttributedType>();
3612 return AT;
3613}
3614
3615template <typename T>
3616static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3617 const DeclContext *DC = Old->getDeclContext();
3618 if (DC->isRecord())
3619 return false;
3620
3621 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3622 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3623 return true;
3624 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3625 return true;
3626 return false;
3627}
3628
3629template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3630static bool isExternC(VarTemplateDecl *) { return false; }
3631static bool isExternC(FunctionTemplateDecl *) { return false; }
3632
3633/// Check whether a redeclaration of an entity introduced by a
3634/// using-declaration is valid, given that we know it's not an overload
3635/// (nor a hidden tag declaration).
3636template<typename ExpectedDecl>
3637static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3638 ExpectedDecl *New) {
3639 // C++11 [basic.scope.declarative]p4:
3640 // Given a set of declarations in a single declarative region, each of
3641 // which specifies the same unqualified name,
3642 // -- they shall all refer to the same entity, or all refer to functions
3643 // and function templates; or
3644 // -- exactly one declaration shall declare a class name or enumeration
3645 // name that is not a typedef name and the other declarations shall all
3646 // refer to the same variable or enumerator, or all refer to functions
3647 // and function templates; in this case the class name or enumeration
3648 // name is hidden (3.3.10).
3649
3650 // C++11 [namespace.udecl]p14:
3651 // If a function declaration in namespace scope or block scope has the
3652 // same name and the same parameter-type-list as a function introduced
3653 // by a using-declaration, and the declarations do not declare the same
3654 // function, the program is ill-formed.
3655
3656 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3657 if (Old &&
3658 !Old->getDeclContext()->getRedeclContext()->Equals(
3659 New->getDeclContext()->getRedeclContext()) &&
3660 !(isExternC(Old) && isExternC(New)))
3661 Old = nullptr;
3662
3663 if (!Old) {
3664 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3665 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3666 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3667 return true;
3668 }
3669 return false;
3670}
3671
3672static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3673 const FunctionDecl *B) {
3674 assert(A->getNumParams() == B->getNumParams());
3675
3676 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3677 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3678 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3679 if (AttrA == AttrB)
3680 return true;
3681 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3682 AttrA->isDynamic() == AttrB->isDynamic();
3683 };
3684
3685 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3686}
3687
3688/// If necessary, adjust the semantic declaration context for a qualified
3689/// declaration to name the correct inline namespace within the qualifier.
3690static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3691 DeclaratorDecl *OldD) {
3692 // The only case where we need to update the DeclContext is when
3693 // redeclaration lookup for a qualified name finds a declaration
3694 // in an inline namespace within the context named by the qualifier:
3695 //
3696 // inline namespace N { int f(); }
3697 // int ::f(); // Sema DC needs adjusting from :: to N::.
3698 //
3699 // For unqualified declarations, the semantic context *can* change
3700 // along the redeclaration chain (for local extern declarations,
3701 // extern "C" declarations, and friend declarations in particular).
3702 if (!NewD->getQualifier())
3703 return;
3704
3705 // NewD is probably already in the right context.
3706 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3707 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3708 if (NamedDC->Equals(DC: SemaDC))
3709 return;
3710
3711 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3712 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3713 "unexpected context for redeclaration");
3714
3715 auto *LexDC = NewD->getLexicalDeclContext();
3716 auto FixSemaDC = [=](NamedDecl *D) {
3717 if (!D)
3718 return;
3719 D->setDeclContext(SemaDC);
3720 D->setLexicalDeclContext(LexDC);
3721 };
3722
3723 FixSemaDC(NewD);
3724 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3725 FixSemaDC(FD->getDescribedFunctionTemplate());
3726 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3727 FixSemaDC(VD->getDescribedVarTemplate());
3728}
3729
3730bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3731 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3732 // Verify the old decl was also a function.
3733 FunctionDecl *Old = OldD->getAsFunction();
3734 if (!Old) {
3735 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3736 // We don't need to check the using friend pattern from other module unit
3737 // since we should have diagnosed such cases in its unit already.
3738 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3739 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3740 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3741 DiagID: diag::note_using_decl_target);
3742 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3743 << 0;
3744 return true;
3745 }
3746
3747 // Check whether the two declarations might declare the same function or
3748 // function template.
3749 if (FunctionTemplateDecl *NewTemplate =
3750 New->getDescribedFunctionTemplate()) {
3751 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3752 New: NewTemplate))
3753 return true;
3754 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3755 ->getAsFunction();
3756 } else {
3757 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3758 return true;
3759 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3760 }
3761 } else {
3762 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3763 << New->getDeclName();
3764 notePreviousDefinition(Old: OldD, New: New->getLocation());
3765 return true;
3766 }
3767 }
3768
3769 // If the old declaration was found in an inline namespace and the new
3770 // declaration was qualified, update the DeclContext to match.
3771 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3772
3773 // If the old declaration is invalid, just give up here.
3774 if (Old->isInvalidDecl())
3775 return true;
3776
3777 // Disallow redeclaration of some builtins.
3778 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3779 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3780 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3781 << Old << Old->getType();
3782 return true;
3783 }
3784
3785 diag::kind PrevDiag;
3786 SourceLocation OldLocation;
3787 std::tie(args&: PrevDiag, args&: OldLocation) =
3788 getNoteDiagForInvalidRedeclaration(Old, New);
3789
3790 // Don't complain about this if we're in GNU89 mode and the old function
3791 // is an extern inline function.
3792 // Don't complain about specializations. They are not supposed to have
3793 // storage classes.
3794 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3795 New->getStorageClass() == SC_Static &&
3796 Old->hasExternalFormalLinkage() &&
3797 !New->getTemplateSpecializationInfo() &&
3798 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3799 if (getLangOpts().MicrosoftExt) {
3800 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3801 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3802 } else {
3803 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3804 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3805 return true;
3806 }
3807 }
3808
3809 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3810 if (!Old->hasAttr<InternalLinkageAttr>()) {
3811 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3812 << ILA;
3813 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3814 New->dropAttr<InternalLinkageAttr>();
3815 }
3816
3817 if (auto *EA = New->getAttr<ErrorAttr>()) {
3818 if (!Old->hasAttr<ErrorAttr>()) {
3819 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3820 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3821 New->dropAttr<ErrorAttr>();
3822 }
3823 }
3824
3825 if (CheckRedeclarationInModule(New, Old))
3826 return true;
3827
3828 if (!getLangOpts().CPlusPlus) {
3829 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3830 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3831 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3832 << New << OldOvl;
3833
3834 // Try our best to find a decl that actually has the overloadable
3835 // attribute for the note. In most cases (e.g. programs with only one
3836 // broken declaration/definition), this won't matter.
3837 //
3838 // FIXME: We could do this if we juggled some extra state in
3839 // OverloadableAttr, rather than just removing it.
3840 const Decl *DiagOld = Old;
3841 if (OldOvl) {
3842 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3843 const auto *A = D->getAttr<OverloadableAttr>();
3844 return A && !A->isImplicit();
3845 });
3846 // If we've implicitly added *all* of the overloadable attrs to this
3847 // chain, emitting a "previous redecl" note is pointless.
3848 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3849 }
3850
3851 if (DiagOld)
3852 Diag(Loc: DiagOld->getLocation(),
3853 DiagID: diag::note_attribute_overloadable_prev_overload)
3854 << OldOvl;
3855
3856 if (OldOvl)
3857 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3858 else
3859 New->dropAttr<OverloadableAttr>();
3860 }
3861 }
3862
3863 // It is not permitted to redeclare an SME function with different SME
3864 // attributes.
3865 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3866 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3867 << New->getType() << Old->getType();
3868 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3869 return true;
3870 }
3871
3872 // If a function is first declared with a calling convention, but is later
3873 // declared or defined without one, all following decls assume the calling
3874 // convention of the first.
3875 //
3876 // It's OK if a function is first declared without a calling convention,
3877 // but is later declared or defined with the default calling convention.
3878 //
3879 // To test if either decl has an explicit calling convention, we look for
3880 // AttributedType sugar nodes on the type as written. If they are missing or
3881 // were canonicalized away, we assume the calling convention was implicit.
3882 //
3883 // Note also that we DO NOT return at this point, because we still have
3884 // other tests to run.
3885 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3886 QualType NewQType = Context.getCanonicalType(T: New->getType());
3887 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3888 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3889 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3890 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3891 bool RequiresAdjustment = false;
3892
3893 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3894 FunctionDecl *First = Old->getFirstDecl();
3895 const FunctionType *FT =
3896 First->getType().getCanonicalType()->castAs<FunctionType>();
3897 FunctionType::ExtInfo FI = FT->getExtInfo();
3898 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3899 if (!NewCCExplicit) {
3900 // Inherit the CC from the previous declaration if it was specified
3901 // there but not here.
3902 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3903 RequiresAdjustment = true;
3904 } else if (Old->getBuiltinID()) {
3905 // Builtin attribute isn't propagated to the new one yet at this point,
3906 // so we check if the old one is a builtin.
3907
3908 // Calling Conventions on a Builtin aren't really useful and setting a
3909 // default calling convention and cdecl'ing some builtin redeclarations is
3910 // common, so warn and ignore the calling convention on the redeclaration.
3911 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3912 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3913 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3914 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3915 RequiresAdjustment = true;
3916 } else {
3917 // Calling conventions aren't compatible, so complain.
3918 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3919 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3920 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3921 << !FirstCCExplicit
3922 << (!FirstCCExplicit ? "" :
3923 FunctionType::getNameForCallConv(CC: FI.getCC()));
3924
3925 // Put the note on the first decl, since it is the one that matters.
3926 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3927 return true;
3928 }
3929 }
3930
3931 // FIXME: diagnose the other way around?
3932 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3933 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3934 RequiresAdjustment = true;
3935 }
3936
3937 // If the declaration is marked with cfi_unchecked_callee but the definition
3938 // isn't, the definition is also cfi_unchecked_callee.
3939 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3940 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3941 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3942 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3943
3944 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3945 EPI2.CFIUncheckedCallee = true;
3946 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3947 Args: FPT2->getParamTypes(), EPI: EPI2);
3948 NewType = cast<FunctionType>(Val&: NewQType);
3949 New->setType(NewQType);
3950 }
3951 }
3952 }
3953
3954 // Merge regparm attribute.
3955 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3956 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3957 if (NewTypeInfo.getHasRegParm()) {
3958 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3959 << NewType->getRegParmType()
3960 << OldType->getRegParmType();
3961 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3962 return true;
3963 }
3964
3965 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3966 RequiresAdjustment = true;
3967 }
3968
3969 // Merge ns_returns_retained attribute.
3970 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3971 if (NewTypeInfo.getProducesResult()) {
3972 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3973 << "'ns_returns_retained'";
3974 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3975 return true;
3976 }
3977
3978 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3979 RequiresAdjustment = true;
3980 }
3981
3982 if (OldTypeInfo.getNoCallerSavedRegs() !=
3983 NewTypeInfo.getNoCallerSavedRegs()) {
3984 if (NewTypeInfo.getNoCallerSavedRegs()) {
3985 AnyX86NoCallerSavedRegistersAttr *Attr =
3986 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3987 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3988 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3989 return true;
3990 }
3991
3992 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3993 RequiresAdjustment = true;
3994 }
3995
3996 if (RequiresAdjustment) {
3997 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3998 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3999 New->setType(QualType(AdjustedType, 0));
4000 NewQType = Context.getCanonicalType(T: New->getType());
4001 }
4002
4003 // If this redeclaration makes the function inline, we may need to add it to
4004 // UndefinedButUsed.
4005 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4006 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4007 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4008 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4009 y: SourceLocation()));
4010
4011 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4012 // about it.
4013 if (New->hasAttr<GNUInlineAttr>() &&
4014 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4015 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4016 }
4017
4018 // If pass_object_size params don't match up perfectly, this isn't a valid
4019 // redeclaration.
4020 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4021 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4022 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4023 << New->getDeclName();
4024 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4025 return true;
4026 }
4027
4028 QualType OldQTypeForComparison = OldQType;
4029 if (Context.hasAnyFunctionEffects()) {
4030 const auto OldFX = Old->getFunctionEffects();
4031 const auto NewFX = New->getFunctionEffects();
4032 if (OldFX != NewFX) {
4033 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4034 for (const auto &Diff : Diffs) {
4035 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4036 Diag(Loc: New->getLocation(),
4037 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4038 << Diff.effectName();
4039 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4040 }
4041 }
4042 // Following a warning, we could skip merging effects from the previous
4043 // declaration, but that would trigger an additional "conflicting types"
4044 // error.
4045 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4046 FunctionEffectSet::Conflicts MergeErrs;
4047 FunctionEffectSet MergedFX =
4048 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4049 if (!MergeErrs.empty())
4050 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4051 OldLoc: Old->getLocation());
4052
4053 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4054 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4055 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4056 Args: NewFPT->getParamTypes(), EPI);
4057
4058 New->setType(ModQT);
4059 NewQType = New->getType();
4060
4061 // Revise OldQTForComparison to include the merged effects,
4062 // so as not to fail due to differences later.
4063 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4064 EPI = OldFPT->getExtProtoInfo();
4065 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4066 OldQTypeForComparison = Context.getFunctionType(
4067 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4068 }
4069 if (OldFX.empty()) {
4070 // A redeclaration may add the attribute to a previously seen function
4071 // body which needs to be verified.
4072 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4073 }
4074 }
4075 }
4076 }
4077
4078 if (getLangOpts().CPlusPlus) {
4079 OldQType = Context.getCanonicalType(T: Old->getType());
4080 NewQType = Context.getCanonicalType(T: New->getType());
4081
4082 // Go back to the type source info to compare the declared return types,
4083 // per C++1y [dcl.type.auto]p13:
4084 // Redeclarations or specializations of a function or function template
4085 // with a declared return type that uses a placeholder type shall also
4086 // use that placeholder, not a deduced type.
4087 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4088 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4089 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4090 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4091 OldT: OldDeclaredReturnType)) {
4092 QualType ResQT;
4093 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4094 OldDeclaredReturnType->isObjCObjectPointerType())
4095 // FIXME: This does the wrong thing for a deduced return type.
4096 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4097 if (ResQT.isNull()) {
4098 if (New->isCXXClassMember() && New->isOutOfLine())
4099 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4100 << New << New->getReturnTypeSourceRange();
4101 else if (Old->isExternC() && New->isExternC() &&
4102 !Old->hasAttr<OverloadableAttr>() &&
4103 !New->hasAttr<OverloadableAttr>())
4104 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4105 else
4106 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4107 << New->getReturnTypeSourceRange();
4108 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4109 << Old->getReturnTypeSourceRange();
4110 return true;
4111 }
4112 else
4113 NewQType = ResQT;
4114 }
4115
4116 QualType OldReturnType = OldType->getReturnType();
4117 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4118 if (OldReturnType != NewReturnType) {
4119 // If this function has a deduced return type and has already been
4120 // defined, copy the deduced value from the old declaration.
4121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4122 if (OldAT && OldAT->isDeduced()) {
4123 QualType DT = OldAT->getDeducedType();
4124 if (DT.isNull()) {
4125 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4126 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4127 } else {
4128 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4129 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4130 }
4131 }
4132 }
4133
4134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4136 if (OldMethod && NewMethod) {
4137 // Preserve triviality.
4138 NewMethod->setTrivial(OldMethod->isTrivial());
4139
4140 // MSVC allows explicit template specialization at class scope:
4141 // 2 CXXMethodDecls referring to the same function will be injected.
4142 // We don't want a redeclaration error.
4143 bool IsClassScopeExplicitSpecialization =
4144 OldMethod->isFunctionTemplateSpecialization() &&
4145 NewMethod->isFunctionTemplateSpecialization();
4146 bool isFriend = NewMethod->getFriendObjectKind();
4147
4148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4149 !IsClassScopeExplicitSpecialization) {
4150 // -- Member function declarations with the same name and the
4151 // same parameter types cannot be overloaded if any of them
4152 // is a static member function declaration.
4153 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4154 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4155 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4156 return true;
4157 }
4158
4159 // C++ [class.mem]p1:
4160 // [...] A member shall not be declared twice in the
4161 // member-specification, except that a nested class or member
4162 // class template can be declared and then later defined.
4163 if (!inTemplateInstantiation()) {
4164 unsigned NewDiag;
4165 if (isa<CXXConstructorDecl>(Val: OldMethod))
4166 NewDiag = diag::err_constructor_redeclared;
4167 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4168 NewDiag = diag::err_destructor_redeclared;
4169 else if (isa<CXXConversionDecl>(Val: NewMethod))
4170 NewDiag = diag::err_conv_function_redeclared;
4171 else
4172 NewDiag = diag::err_member_redeclared;
4173
4174 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4175 } else {
4176 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4177 << New << New->getType();
4178 }
4179 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4180 return true;
4181
4182 // Complain if this is an explicit declaration of a special
4183 // member that was initially declared implicitly.
4184 //
4185 // As an exception, it's okay to befriend such methods in order
4186 // to permit the implicit constructor/destructor/operator calls.
4187 } else if (OldMethod->isImplicit()) {
4188 if (isFriend) {
4189 NewMethod->setImplicit();
4190 } else {
4191 Diag(Loc: NewMethod->getLocation(),
4192 DiagID: diag::err_definition_of_implicitly_declared_member)
4193 << New << getSpecialMember(MD: OldMethod);
4194 return true;
4195 }
4196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4197 Diag(Loc: NewMethod->getLocation(),
4198 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4199 << getSpecialMember(MD: OldMethod);
4200 return true;
4201 }
4202 }
4203
4204 // C++1z [over.load]p2
4205 // Certain function declarations cannot be overloaded:
4206 // -- Function declarations that differ only in the return type,
4207 // the exception specification, or both cannot be overloaded.
4208
4209 // Check the exception specifications match. This may recompute the type of
4210 // both Old and New if it resolved exception specifications, so grab the
4211 // types again after this. Because this updates the type, we do this before
4212 // any of the other checks below, which may update the "de facto" NewQType
4213 // but do not necessarily update the type of New.
4214 if (CheckEquivalentExceptionSpec(Old, New))
4215 return true;
4216
4217 // C++11 [dcl.attr.noreturn]p1:
4218 // The first declaration of a function shall specify the noreturn
4219 // attribute if any declaration of that function specifies the noreturn
4220 // attribute.
4221 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4222 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4223 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4224 << NRA;
4225 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4226 }
4227
4228 // C++11 [dcl.attr.depend]p2:
4229 // The first declaration of a function shall specify the
4230 // carries_dependency attribute for its declarator-id if any declaration
4231 // of the function specifies the carries_dependency attribute.
4232 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4233 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4234 Diag(Loc: CDA->getLocation(),
4235 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4236 Diag(Loc: Old->getFirstDecl()->getLocation(),
4237 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4238 }
4239
4240 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4241 // When a function is declared with SYCL_EXTERNAL, that macro must be
4242 // used on the first declaration of that function in the translation unit.
4243 // Redeclarations of the function in the same translation unit may
4244 // optionally use SYCL_EXTERNAL, but this is not required.
4245 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4246 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4247 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4248 << SEA;
4249 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4250 }
4251
4252 // (C++98 8.3.5p3):
4253 // All declarations for a function shall agree exactly in both the
4254 // return type and the parameter-type-list.
4255 // We also want to respect all the extended bits except noreturn.
4256
4257 // noreturn should now match unless the old type info didn't have it.
4258 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4259 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4260 const FunctionType *OldTypeForComparison
4261 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4262 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4263 assert(OldQTypeForComparison.isCanonical());
4264 }
4265
4266 if (haveIncompatibleLanguageLinkages(Old, New)) {
4267 // As a special case, retain the language linkage from previous
4268 // declarations of a friend function as an extension.
4269 //
4270 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4271 // and is useful because there's otherwise no way to specify language
4272 // linkage within class scope.
4273 //
4274 // Check cautiously as the friend object kind isn't yet complete.
4275 if (New->getFriendObjectKind() != Decl::FOK_None) {
4276 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4277 Diag(Loc: OldLocation, DiagID: PrevDiag);
4278 } else {
4279 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4280 Diag(Loc: OldLocation, DiagID: PrevDiag);
4281 return true;
4282 }
4283 }
4284
4285 // HLSL check parameters for matching ABI specifications.
4286 if (getLangOpts().HLSL) {
4287 if (HLSL().CheckCompatibleParameterABI(New, Old))
4288 return true;
4289
4290 // If no errors are generated when checking parameter ABIs we can check if
4291 // the two declarations have the same type ignoring the ABIs and if so,
4292 // the declarations can be merged. This case for merging is only valid in
4293 // HLSL because there are no valid cases of merging mismatched parameter
4294 // ABIs except the HLSL implicit in and explicit in.
4295 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4296 U: NewQType))
4297 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4298 // Fall through for conflicting redeclarations and redefinitions.
4299 }
4300
4301 // If the function types are compatible, merge the declarations. Ignore the
4302 // exception specifier because it was already checked above in
4303 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4304 // about incompatible types under -fms-compatibility.
4305 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4306 U: NewQType))
4307 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4308
4309 // If the types are imprecise (due to dependent constructs in friends or
4310 // local extern declarations), it's OK if they differ. We'll check again
4311 // during instantiation.
4312 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4313 return false;
4314
4315 // Fall through for conflicting redeclarations and redefinitions.
4316 }
4317
4318 // C: Function types need to be compatible, not identical. This handles
4319 // duplicate function decls like "void f(int); void f(enum X);" properly.
4320 if (!getLangOpts().CPlusPlus) {
4321 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4322 // type is specified by a function definition that contains a (possibly
4323 // empty) identifier list, both shall agree in the number of parameters
4324 // and the type of each parameter shall be compatible with the type that
4325 // results from the application of default argument promotions to the
4326 // type of the corresponding identifier. ...
4327 // This cannot be handled by ASTContext::typesAreCompatible() because that
4328 // doesn't know whether the function type is for a definition or not when
4329 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4330 // we need to cover here is that the number of arguments agree as the
4331 // default argument promotion rules were already checked by
4332 // ASTContext::typesAreCompatible().
4333 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4334 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4335 if (Old->hasInheritedPrototype())
4336 Old = Old->getCanonicalDecl();
4337 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4338 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4339 return true;
4340 }
4341
4342 // If we are merging two functions where only one of them has a prototype,
4343 // we may have enough information to decide to issue a diagnostic that the
4344 // function without a prototype will change behavior in C23. This handles
4345 // cases like:
4346 // void i(); void i(int j);
4347 // void i(int j); void i();
4348 // void i(); void i(int j) {}
4349 // See ActOnFinishFunctionBody() for other cases of the behavior change
4350 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4351 // type without a prototype.
4352 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4353 !New->isImplicit() && !Old->isImplicit()) {
4354 const FunctionDecl *WithProto, *WithoutProto;
4355 if (New->hasWrittenPrototype()) {
4356 WithProto = New;
4357 WithoutProto = Old;
4358 } else {
4359 WithProto = Old;
4360 WithoutProto = New;
4361 }
4362
4363 if (WithProto->getNumParams() != 0) {
4364 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4365 // The one without the prototype will be changing behavior in C23, so
4366 // warn about that one so long as it's a user-visible declaration.
4367 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4368 if (WithoutProto == New)
4369 IsWithoutProtoADef = NewDeclIsDefn;
4370 else
4371 IsWithProtoADef = NewDeclIsDefn;
4372 Diag(Loc: WithoutProto->getLocation(),
4373 DiagID: diag::warn_non_prototype_changes_behavior)
4374 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4375 << (WithoutProto == Old) << IsWithProtoADef;
4376
4377 // The reason the one without the prototype will be changing behavior
4378 // is because of the one with the prototype, so note that so long as
4379 // it's a user-visible declaration. There is one exception to this:
4380 // when the new declaration is a definition without a prototype, the
4381 // old declaration with a prototype is not the cause of the issue,
4382 // and that does not need to be noted because the one with a
4383 // prototype will not change behavior in C23.
4384 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4385 !IsWithoutProtoADef)
4386 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4387 }
4388 }
4389 }
4390
4391 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4392 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4393 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4394 const FunctionProtoType *OldProto = nullptr;
4395 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4396 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4397 // The old declaration provided a function prototype, but the
4398 // new declaration does not. Merge in the prototype.
4399 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4400 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4401 Args: OldProto->getParamTypes(),
4402 EPI: OldProto->getExtProtoInfo());
4403 New->setType(NewQType);
4404 New->setHasInheritedPrototype();
4405
4406 // Synthesize parameters with the same types.
4407 SmallVector<ParmVarDecl *, 16> Params;
4408 for (const auto &ParamType : OldProto->param_types()) {
4409 ParmVarDecl *Param = ParmVarDecl::Create(
4410 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4411 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4412 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4413 Param->setImplicit();
4414 Params.push_back(Elt: Param);
4415 }
4416
4417 New->setParams(Params);
4418 }
4419
4420 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4421 }
4422 }
4423
4424 // Check if the function types are compatible when pointer size address
4425 // spaces are ignored.
4426 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4427 return false;
4428
4429 // GNU C permits a K&R definition to follow a prototype declaration
4430 // if the declared types of the parameters in the K&R definition
4431 // match the types in the prototype declaration, even when the
4432 // promoted types of the parameters from the K&R definition differ
4433 // from the types in the prototype. GCC then keeps the types from
4434 // the prototype.
4435 //
4436 // If a variadic prototype is followed by a non-variadic K&R definition,
4437 // the K&R definition becomes variadic. This is sort of an edge case, but
4438 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4439 // C99 6.9.1p8.
4440 if (!getLangOpts().CPlusPlus &&
4441 Old->hasPrototype() && !New->hasPrototype() &&
4442 New->getType()->getAs<FunctionProtoType>() &&
4443 Old->getNumParams() == New->getNumParams()) {
4444 SmallVector<QualType, 16> ArgTypes;
4445 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4446 const FunctionProtoType *OldProto
4447 = Old->getType()->getAs<FunctionProtoType>();
4448 const FunctionProtoType *NewProto
4449 = New->getType()->getAs<FunctionProtoType>();
4450
4451 // Determine whether this is the GNU C extension.
4452 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4453 NewProto->getReturnType());
4454 bool LooseCompatible = !MergedReturn.isNull();
4455 for (unsigned Idx = 0, End = Old->getNumParams();
4456 LooseCompatible && Idx != End; ++Idx) {
4457 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4458 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4459 if (Context.typesAreCompatible(T1: OldParm->getType(),
4460 T2: NewProto->getParamType(i: Idx))) {
4461 ArgTypes.push_back(Elt: NewParm->getType());
4462 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4463 T2: NewParm->getType(),
4464 /*CompareUnqualified=*/true)) {
4465 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4466 .PromotedType: NewProto->getParamType(i: Idx) };
4467 Warnings.push_back(Elt: Warn);
4468 ArgTypes.push_back(Elt: NewParm->getType());
4469 } else
4470 LooseCompatible = false;
4471 }
4472
4473 if (LooseCompatible) {
4474 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4475 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4476 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4477 << Warnings[Warn].PromotedType
4478 << Warnings[Warn].OldParm->getType();
4479 if (Warnings[Warn].OldParm->getLocation().isValid())
4480 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4481 DiagID: diag::note_previous_declaration);
4482 }
4483
4484 if (MergeTypeWithOld)
4485 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4486 EPI: OldProto->getExtProtoInfo()));
4487 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4488 }
4489
4490 // Fall through to diagnose conflicting types.
4491 }
4492
4493 // A function that has already been declared has been redeclared or
4494 // defined with a different type; show an appropriate diagnostic.
4495
4496 // If the previous declaration was an implicitly-generated builtin
4497 // declaration, then at the very least we should use a specialized note.
4498 unsigned BuiltinID;
4499 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4500 // If it's actually a library-defined builtin function like 'malloc'
4501 // or 'printf', just warn about the incompatible redeclaration.
4502 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4503 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4504 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4505 << Old << Old->getType();
4506 return false;
4507 }
4508
4509 PrevDiag = diag::note_previous_builtin_declaration;
4510 }
4511
4512 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4513 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4514 return true;
4515}
4516
4517bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4518 Scope *S, bool MergeTypeWithOld) {
4519 // Merge the attributes
4520 mergeDeclAttributes(New, Old);
4521
4522 // Merge "pure" flag.
4523 if (Old->isPureVirtual())
4524 New->setIsPureVirtual();
4525
4526 // Merge "used" flag.
4527 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4528 New->setIsUsed();
4529
4530 // Merge attributes from the parameters. These can mismatch with K&R
4531 // declarations.
4532 if (New->getNumParams() == Old->getNumParams())
4533 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4534 ParmVarDecl *NewParam = New->getParamDecl(i);
4535 ParmVarDecl *OldParam = Old->getParamDecl(i);
4536 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4537 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4538 }
4539
4540 if (getLangOpts().CPlusPlus)
4541 return MergeCXXFunctionDecl(New, Old, S);
4542
4543 // Merge the function types so the we get the composite types for the return
4544 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4545 // was visible.
4546 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4547 if (!Merged.isNull() && MergeTypeWithOld)
4548 New->setType(Merged);
4549
4550 return false;
4551}
4552
4553void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4554 ObjCMethodDecl *oldMethod) {
4555 // Merge the attributes, including deprecated/unavailable
4556 AvailabilityMergeKind MergeKind =
4557 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4558 ? (oldMethod->isOptional()
4559 ? AvailabilityMergeKind::OptionalProtocolImplementation
4560 : AvailabilityMergeKind::ProtocolImplementation)
4561 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4562 ? AvailabilityMergeKind::Redeclaration
4563 : AvailabilityMergeKind::Override;
4564
4565 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4566
4567 // Merge attributes from the parameters.
4568 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4569 oe = oldMethod->param_end();
4570 for (ObjCMethodDecl::param_iterator
4571 ni = newMethod->param_begin(), ne = newMethod->param_end();
4572 ni != ne && oi != oe; ++ni, ++oi)
4573 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4574
4575 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4576}
4577
4578static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4579 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4580
4581 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4582 ? diag::err_redefinition_different_type
4583 : diag::err_redeclaration_different_type)
4584 << New->getDeclName() << New->getType() << Old->getType();
4585
4586 diag::kind PrevDiag;
4587 SourceLocation OldLocation;
4588 std::tie(args&: PrevDiag, args&: OldLocation)
4589 = getNoteDiagForInvalidRedeclaration(Old, New);
4590 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4591 New->setInvalidDecl();
4592}
4593
4594void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4595 bool MergeTypeWithOld) {
4596 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4597 return;
4598
4599 QualType MergedT;
4600 if (getLangOpts().CPlusPlus) {
4601 if (New->getType()->isUndeducedType()) {
4602 // We don't know what the new type is until the initializer is attached.
4603 return;
4604 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4605 // These could still be something that needs exception specs checked.
4606 return MergeVarDeclExceptionSpecs(New, Old);
4607 }
4608 // C++ [basic.link]p10:
4609 // [...] the types specified by all declarations referring to a given
4610 // object or function shall be identical, except that declarations for an
4611 // array object can specify array types that differ by the presence or
4612 // absence of a major array bound (8.3.4).
4613 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4614 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4615 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4616
4617 // We are merging a variable declaration New into Old. If it has an array
4618 // bound, and that bound differs from Old's bound, we should diagnose the
4619 // mismatch.
4620 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4621 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4622 PrevVD = PrevVD->getPreviousDecl()) {
4623 QualType PrevVDTy = PrevVD->getType();
4624 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4625 continue;
4626
4627 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4628 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4629 }
4630 }
4631
4632 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4633 if (Context.hasSameType(T1: OldArray->getElementType(),
4634 T2: NewArray->getElementType()))
4635 MergedT = New->getType();
4636 }
4637 // FIXME: Check visibility. New is hidden but has a complete type. If New
4638 // has no array bound, it should not inherit one from Old, if Old is not
4639 // visible.
4640 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4641 if (Context.hasSameType(T1: OldArray->getElementType(),
4642 T2: NewArray->getElementType()))
4643 MergedT = Old->getType();
4644 }
4645 }
4646 else if (New->getType()->isObjCObjectPointerType() &&
4647 Old->getType()->isObjCObjectPointerType()) {
4648 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4649 Old->getType());
4650 }
4651 } else {
4652 // C 6.2.7p2:
4653 // All declarations that refer to the same object or function shall have
4654 // compatible type.
4655 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4656 }
4657 if (MergedT.isNull()) {
4658 // It's OK if we couldn't merge types if either type is dependent, for a
4659 // block-scope variable. In other cases (static data members of class
4660 // templates, variable templates, ...), we require the types to be
4661 // equivalent.
4662 // FIXME: The C++ standard doesn't say anything about this.
4663 if ((New->getType()->isDependentType() ||
4664 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4665 // If the old type was dependent, we can't merge with it, so the new type
4666 // becomes dependent for now. We'll reproduce the original type when we
4667 // instantiate the TypeSourceInfo for the variable.
4668 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4669 New->setType(Context.DependentTy);
4670 return;
4671 }
4672 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4673 }
4674
4675 // Don't actually update the type on the new declaration if the old
4676 // declaration was an extern declaration in a different scope.
4677 if (MergeTypeWithOld)
4678 New->setType(MergedT);
4679}
4680
4681static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4682 LookupResult &Previous) {
4683 // C11 6.2.7p4:
4684 // For an identifier with internal or external linkage declared
4685 // in a scope in which a prior declaration of that identifier is
4686 // visible, if the prior declaration specifies internal or
4687 // external linkage, the type of the identifier at the later
4688 // declaration becomes the composite type.
4689 //
4690 // If the variable isn't visible, we do not merge with its type.
4691 if (Previous.isShadowed())
4692 return false;
4693
4694 if (S.getLangOpts().CPlusPlus) {
4695 // C++11 [dcl.array]p3:
4696 // If there is a preceding declaration of the entity in the same
4697 // scope in which the bound was specified, an omitted array bound
4698 // is taken to be the same as in that earlier declaration.
4699 return NewVD->isPreviousDeclInSameBlockScope() ||
4700 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4701 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4702 } else {
4703 // If the old declaration was function-local, don't merge with its
4704 // type unless we're in the same function.
4705 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4706 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4707 }
4708}
4709
4710void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4711 // If the new decl is already invalid, don't do any other checking.
4712 if (New->isInvalidDecl())
4713 return;
4714
4715 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4716 return;
4717
4718 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4719
4720 // Verify the old decl was also a variable or variable template.
4721 VarDecl *Old = nullptr;
4722 VarTemplateDecl *OldTemplate = nullptr;
4723 if (Previous.isSingleResult()) {
4724 if (NewTemplate) {
4725 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4726 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4727
4728 if (auto *Shadow =
4729 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4730 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4731 return New->setInvalidDecl();
4732 } else {
4733 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4734
4735 if (auto *Shadow =
4736 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4737 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4738 return New->setInvalidDecl();
4739 }
4740 }
4741 if (!Old) {
4742 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4743 << New->getDeclName();
4744 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4745 New: New->getLocation());
4746 return New->setInvalidDecl();
4747 }
4748
4749 // If the old declaration was found in an inline namespace and the new
4750 // declaration was qualified, update the DeclContext to match.
4751 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4752
4753 // Ensure the template parameters are compatible.
4754 if (NewTemplate &&
4755 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4756 Old: OldTemplate->getTemplateParameters(),
4757 /*Complain=*/true, Kind: TPL_TemplateMatch))
4758 return New->setInvalidDecl();
4759
4760 // C++ [class.mem]p1:
4761 // A member shall not be declared twice in the member-specification [...]
4762 //
4763 // Here, we need only consider static data members.
4764 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4765 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4766 << New->getIdentifier();
4767 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4768 New->setInvalidDecl();
4769 }
4770
4771 if (NewTemplate && OldTemplate)
4772 mergeDeclAttributes(New: NewTemplate, Old: OldTemplate);
4773
4774 mergeDeclAttributes(New, Old);
4775
4776 // Warn if an already-defined variable is made a weak_import in a subsequent
4777 // declaration
4778 if (New->hasAttr<WeakImportAttr>())
4779 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4780 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4781 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4782 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4783 // Remove weak_import attribute on new declaration.
4784 New->dropAttr<WeakImportAttr>();
4785 break;
4786 }
4787 }
4788
4789 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4790 if (!Old->hasAttr<InternalLinkageAttr>()) {
4791 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4792 << ILA;
4793 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4794 New->dropAttr<InternalLinkageAttr>();
4795 }
4796
4797 // Merge the types.
4798 VarDecl *MostRecent = Old->getMostRecentDecl();
4799 if (MostRecent != Old) {
4800 MergeVarDeclTypes(New, Old: MostRecent,
4801 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4802 if (New->isInvalidDecl())
4803 return;
4804 }
4805
4806 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4807 if (New->isInvalidDecl())
4808 return;
4809
4810 diag::kind PrevDiag;
4811 SourceLocation OldLocation;
4812 std::tie(args&: PrevDiag, args&: OldLocation) =
4813 getNoteDiagForInvalidRedeclaration(Old, New);
4814
4815 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4816 if (New->getStorageClass() == SC_Static &&
4817 !New->isStaticDataMember() &&
4818 Old->hasExternalFormalLinkage()) {
4819 if (getLangOpts().MicrosoftExt) {
4820 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4821 << New->getDeclName();
4822 Diag(Loc: OldLocation, DiagID: PrevDiag);
4823 } else {
4824 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4825 << New->getDeclName();
4826 Diag(Loc: OldLocation, DiagID: PrevDiag);
4827 return New->setInvalidDecl();
4828 }
4829 }
4830 // C99 6.2.2p4:
4831 // For an identifier declared with the storage-class specifier
4832 // extern in a scope in which a prior declaration of that
4833 // identifier is visible,23) if the prior declaration specifies
4834 // internal or external linkage, the linkage of the identifier at
4835 // the later declaration is the same as the linkage specified at
4836 // the prior declaration. If no prior declaration is visible, or
4837 // if the prior declaration specifies no linkage, then the
4838 // identifier has external linkage.
4839 if (New->hasExternalStorage() && Old->hasLinkage())
4840 /* Okay */;
4841 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4842 !New->isStaticDataMember() &&
4843 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4844 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4845 Diag(Loc: OldLocation, DiagID: PrevDiag);
4846 return New->setInvalidDecl();
4847 }
4848
4849 // Check if extern is followed by non-extern and vice-versa.
4850 if (New->hasExternalStorage() &&
4851 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4852 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4853 Diag(Loc: OldLocation, DiagID: PrevDiag);
4854 return New->setInvalidDecl();
4855 }
4856 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4857 !New->hasExternalStorage()) {
4858 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4859 Diag(Loc: OldLocation, DiagID: PrevDiag);
4860 return New->setInvalidDecl();
4861 }
4862
4863 if (CheckRedeclarationInModule(New, Old))
4864 return;
4865
4866 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4867
4868 // FIXME: The test for external storage here seems wrong? We still
4869 // need to check for mismatches.
4870 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4871 // Don't complain about out-of-line definitions of static members.
4872 !(Old->getLexicalDeclContext()->isRecord() &&
4873 !New->getLexicalDeclContext()->isRecord())) {
4874 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4875 Diag(Loc: OldLocation, DiagID: PrevDiag);
4876 return New->setInvalidDecl();
4877 }
4878
4879 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4880 if (VarDecl *Def = Old->getDefinition()) {
4881 // C++1z [dcl.fcn.spec]p4:
4882 // If the definition of a variable appears in a translation unit before
4883 // its first declaration as inline, the program is ill-formed.
4884 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4885 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4886 }
4887 }
4888
4889 // If this redeclaration makes the variable inline, we may need to add it to
4890 // UndefinedButUsed.
4891 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4892 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4893 !Old->isInAnotherModuleUnit())
4894 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4895 y: SourceLocation()));
4896
4897 if (New->getTLSKind() != Old->getTLSKind()) {
4898 if (!Old->getTLSKind()) {
4899 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4900 Diag(Loc: OldLocation, DiagID: PrevDiag);
4901 } else if (!New->getTLSKind()) {
4902 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4903 Diag(Loc: OldLocation, DiagID: PrevDiag);
4904 } else {
4905 // Do not allow redeclaration to change the variable between requiring
4906 // static and dynamic initialization.
4907 // FIXME: GCC allows this, but uses the TLS keyword on the first
4908 // declaration to determine the kind. Do we need to be compatible here?
4909 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4910 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4911 Diag(Loc: OldLocation, DiagID: PrevDiag);
4912 }
4913 }
4914
4915 // C++ doesn't have tentative definitions, so go right ahead and check here.
4916 if (getLangOpts().CPlusPlus) {
4917 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4918 Old->getCanonicalDecl()->isConstexpr()) {
4919 // This definition won't be a definition any more once it's been merged.
4920 Diag(Loc: New->getLocation(),
4921 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4922 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4923 VarDecl *Def = Old->getDefinition();
4924 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4925 return;
4926 if (Old->isInvalidDecl())
4927 New->setInvalidDecl();
4928 }
4929 } else {
4930 // C++ may not have a tentative definition rule, but it has a different
4931 // rule about what constitutes a definition in the first place. See
4932 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4933 // contains the extern specifier and doesn't have an initializer, it's fine
4934 // in C++.
4935 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4936 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4937 << New;
4938 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4939 }
4940 }
4941
4942 if (haveIncompatibleLanguageLinkages(Old, New)) {
4943 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4944 Diag(Loc: OldLocation, DiagID: PrevDiag);
4945 New->setInvalidDecl();
4946 return;
4947 }
4948
4949 // Merge "used" flag.
4950 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4951 New->setIsUsed();
4952
4953 // Keep a chain of previous declarations.
4954 New->setPreviousDecl(Old);
4955 if (NewTemplate)
4956 NewTemplate->setPreviousDecl(OldTemplate);
4957
4958 // Inherit access appropriately.
4959 New->setAccess(Old->getAccess());
4960 if (NewTemplate)
4961 NewTemplate->setAccess(New->getAccess());
4962
4963 if (Old->isInline())
4964 New->setImplicitlyInline();
4965}
4966
4967void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4968 SourceManager &SrcMgr = getSourceManager();
4969 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4970 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4971 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4972 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4973 auto &HSI = PP.getHeaderSearchInfo();
4974 StringRef HdrFilename =
4975 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4976
4977 auto noteFromModuleOrInclude = [&](Module *Mod,
4978 SourceLocation IncLoc) -> bool {
4979 // Redefinition errors with modules are common with non modular mapped
4980 // headers, example: a non-modular header H in module A that also gets
4981 // included directly in a TU. Pointing twice to the same header/definition
4982 // is confusing, try to get better diagnostics when modules is on.
4983 if (IncLoc.isValid()) {
4984 if (Mod) {
4985 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4986 << HdrFilename.str() << Mod->getFullModuleName();
4987 if (!Mod->DefinitionLoc.isInvalid())
4988 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4989 << Mod->getFullModuleName();
4990 } else {
4991 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4992 << HdrFilename.str();
4993 }
4994 return true;
4995 }
4996
4997 return false;
4998 };
4999
5000 // Is it the same file and same offset? Provide more information on why
5001 // this leads to a redefinition error.
5002 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5003 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
5004 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5005 bool EmittedDiag =
5006 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5007 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5008
5009 // If the header has no guards, emit a note suggesting one.
5010 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5011 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5012
5013 if (EmittedDiag)
5014 return;
5015 }
5016
5017 // Redefinition coming from different files or couldn't do better above.
5018 if (Old->getLocation().isValid())
5019 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5020}
5021
5022bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5023 if (!hasVisibleDefinition(D: Old) &&
5024 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5025 isa<VarTemplateSpecializationDecl>(Val: New) ||
5026 New->getDescribedVarTemplate() ||
5027 !New->getTemplateParameterLists().empty() ||
5028 New->getDeclContext()->isDependentContext() ||
5029 New->hasAttr<SelectAnyAttr>())) {
5030 // The previous definition is hidden, and multiple definitions are
5031 // permitted (in separate TUs). Demote this to a declaration.
5032 New->demoteThisDefinitionToDeclaration();
5033
5034 // Make the canonical definition visible.
5035 if (auto *OldTD = Old->getDescribedVarTemplate())
5036 makeMergedDefinitionVisible(ND: OldTD);
5037 makeMergedDefinitionVisible(ND: Old);
5038 return false;
5039 } else {
5040 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5041 notePreviousDefinition(Old, New: New->getLocation());
5042 New->setInvalidDecl();
5043 return true;
5044 }
5045}
5046
5047Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5048 DeclSpec &DS,
5049 const ParsedAttributesView &DeclAttrs,
5050 RecordDecl *&AnonRecord) {
5051 return ParsedFreeStandingDeclSpec(
5052 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5053}
5054
5055// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5056// disambiguate entities defined in different scopes.
5057// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5058// compatibility.
5059// We will pick our mangling number depending on which version of MSVC is being
5060// targeted.
5061static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5062 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5063 ? S->getMSCurManglingNumber()
5064 : S->getMSLastManglingNumber();
5065}
5066
5067void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5068 if (!Context.getLangOpts().CPlusPlus)
5069 return;
5070
5071 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5072 // If this tag is the direct child of a class, number it if
5073 // it is anonymous.
5074 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5075 return;
5076 MangleNumberingContext &MCtx =
5077 Context.getManglingNumberContext(DC: Tag->getParent());
5078 Context.setManglingNumber(
5079 ND: Tag, Number: MCtx.getManglingNumber(
5080 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5081 return;
5082 }
5083
5084 // If this tag isn't a direct child of a class, number it if it is local.
5085 MangleNumberingContext *MCtx;
5086 Decl *ManglingContextDecl;
5087 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5088 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5089 if (MCtx) {
5090 Context.setManglingNumber(
5091 ND: Tag, Number: MCtx->getManglingNumber(
5092 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5093 }
5094}
5095
5096namespace {
5097struct NonCLikeKind {
5098 enum {
5099 None,
5100 BaseClass,
5101 DefaultMemberInit,
5102 Lambda,
5103 Friend,
5104 OtherMember,
5105 Invalid,
5106 } Kind = None;
5107 SourceRange Range;
5108
5109 explicit operator bool() { return Kind != None; }
5110};
5111}
5112
5113/// Determine whether a class is C-like, according to the rules of C++
5114/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5115static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5116 if (RD->isInvalidDecl())
5117 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5118
5119 // C++ [dcl.typedef]p9: [P1766R1]
5120 // An unnamed class with a typedef name for linkage purposes shall not
5121 //
5122 // -- have any base classes
5123 if (RD->getNumBases())
5124 return {.Kind: NonCLikeKind::BaseClass,
5125 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5126 RD->bases_end()[-1].getEndLoc())};
5127 bool Invalid = false;
5128 for (Decl *D : RD->decls()) {
5129 // Don't complain about things we already diagnosed.
5130 if (D->isInvalidDecl()) {
5131 Invalid = true;
5132 continue;
5133 }
5134
5135 // -- have any [...] default member initializers
5136 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5137 if (FD->hasInClassInitializer()) {
5138 auto *Init = FD->getInClassInitializer();
5139 return {.Kind: NonCLikeKind::DefaultMemberInit,
5140 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5141 }
5142 continue;
5143 }
5144
5145 // FIXME: We don't allow friend declarations. This violates the wording of
5146 // P1766, but not the intent.
5147 if (isa<FriendDecl>(Val: D))
5148 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5149
5150 // -- declare any members other than non-static data members, member
5151 // enumerations, or member classes,
5152 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5153 isa<EnumDecl>(Val: D))
5154 continue;
5155 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5156 if (!MemberRD) {
5157 if (D->isImplicit())
5158 continue;
5159 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5160 }
5161
5162 // -- contain a lambda-expression,
5163 if (MemberRD->isLambda())
5164 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5165
5166 // and all member classes shall also satisfy these requirements
5167 // (recursively).
5168 if (MemberRD->isThisDeclarationADefinition()) {
5169 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5170 return Kind;
5171 }
5172 }
5173
5174 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5175}
5176
5177void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5178 TypedefNameDecl *NewTD) {
5179 if (TagFromDeclSpec->isInvalidDecl())
5180 return;
5181
5182 // Do nothing if the tag already has a name for linkage purposes.
5183 if (TagFromDeclSpec->hasNameForLinkage())
5184 return;
5185
5186 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5187 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5188
5189 // The type must match the tag exactly; no qualifiers allowed.
5190 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5191 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5192 if (getLangOpts().CPlusPlus)
5193 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5194 return;
5195 }
5196
5197 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5198 // An unnamed class with a typedef name for linkage purposes shall [be
5199 // C-like].
5200 //
5201 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5202 // shouldn't happen, but there are constructs that the language rule doesn't
5203 // disallow for which we can't reasonably avoid computing linkage early.
5204 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5205 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5206 : NonCLikeKind();
5207 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5208 if (NonCLike || ChangesLinkage) {
5209 if (NonCLike.Kind == NonCLikeKind::Invalid)
5210 return;
5211
5212 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5213 if (ChangesLinkage) {
5214 // If the linkage changes, we can't accept this as an extension.
5215 if (NonCLike.Kind == NonCLikeKind::None)
5216 DiagID = diag::err_typedef_changes_linkage;
5217 else
5218 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5219 }
5220
5221 SourceLocation FixitLoc =
5222 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5223 llvm::SmallString<40> TextToInsert;
5224 TextToInsert += ' ';
5225 TextToInsert += NewTD->getIdentifier()->getName();
5226
5227 Diag(Loc: FixitLoc, DiagID)
5228 << isa<TypeAliasDecl>(Val: NewTD)
5229 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5230 if (NonCLike.Kind != NonCLikeKind::None) {
5231 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5232 << NonCLike.Kind - 1 << NonCLike.Range;
5233 }
5234 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5235 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5236
5237 if (ChangesLinkage)
5238 return;
5239 }
5240
5241 // Otherwise, set this as the anon-decl typedef for the tag.
5242 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5243
5244 // Now that we have a name for the tag, process API notes again.
5245 ProcessAPINotes(D: TagFromDeclSpec);
5246}
5247
5248static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5249 DeclSpec::TST T = DS.getTypeSpecType();
5250 switch (T) {
5251 case DeclSpec::TST_class:
5252 return 0;
5253 case DeclSpec::TST_struct:
5254 return 1;
5255 case DeclSpec::TST_interface:
5256 return 2;
5257 case DeclSpec::TST_union:
5258 return 3;
5259 case DeclSpec::TST_enum:
5260 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5261 if (ED->isScopedUsingClassTag())
5262 return 5;
5263 if (ED->isScoped())
5264 return 6;
5265 }
5266 return 4;
5267 default:
5268 llvm_unreachable("unexpected type specifier");
5269 }
5270}
5271
5272Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5273 DeclSpec &DS,
5274 const ParsedAttributesView &DeclAttrs,
5275 MultiTemplateParamsArg TemplateParams,
5276 bool IsExplicitInstantiation,
5277 RecordDecl *&AnonRecord,
5278 SourceLocation EllipsisLoc) {
5279 Decl *TagD = nullptr;
5280 TagDecl *Tag = nullptr;
5281 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5282 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5283 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5284 DS.getTypeSpecType() == DeclSpec::TST_union ||
5285 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5286 TagD = DS.getRepAsDecl();
5287
5288 if (!TagD) // We probably had an error
5289 return nullptr;
5290
5291 // Note that the above type specs guarantee that the
5292 // type rep is a Decl, whereas in many of the others
5293 // it's a Type.
5294 if (isa<TagDecl>(Val: TagD))
5295 Tag = cast<TagDecl>(Val: TagD);
5296 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5297 Tag = CTD->getTemplatedDecl();
5298 }
5299
5300 if (Tag) {
5301 handleTagNumbering(Tag, TagScope: S);
5302 Tag->setFreeStanding();
5303 if (Tag->isInvalidDecl())
5304 return Tag;
5305 }
5306
5307 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5308 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5309 // or incomplete types shall not be restrict-qualified."
5310 if (TypeQuals & DeclSpec::TQ_restrict)
5311 Diag(Loc: DS.getRestrictSpecLoc(),
5312 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5313 << DS.getSourceRange();
5314 }
5315
5316 if (DS.isInlineSpecified())
5317 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5318 << getLangOpts().CPlusPlus17;
5319
5320 if (DS.hasConstexprSpecifier()) {
5321 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5322 // and definitions of functions and variables.
5323 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5324 // the declaration of a function or function template
5325 if (Tag)
5326 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5327 << GetDiagnosticTypeSpecifierID(DS)
5328 << static_cast<int>(DS.getConstexprSpecifier());
5329 else if (getLangOpts().C23)
5330 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5331 else
5332 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5333 << static_cast<int>(DS.getConstexprSpecifier());
5334 // Don't emit warnings after this error.
5335 return TagD;
5336 }
5337
5338 DiagnoseFunctionSpecifiers(DS);
5339
5340 if (DS.isFriendSpecified()) {
5341 // If we're dealing with a decl but not a TagDecl, assume that
5342 // whatever routines created it handled the friendship aspect.
5343 if (TagD && !Tag)
5344 return nullptr;
5345 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5346 }
5347
5348 assert(EllipsisLoc.isInvalid() &&
5349 "Friend ellipsis but not friend-specified?");
5350
5351 // Track whether this decl-specifier declares anything.
5352 bool DeclaresAnything = true;
5353
5354 // Handle anonymous struct definitions.
5355 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5356 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5357 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5358 if (getLangOpts().CPlusPlus ||
5359 Record->getDeclContext()->isRecord()) {
5360 // If CurContext is a DeclContext that can contain statements,
5361 // RecursiveASTVisitor won't visit the decls that
5362 // BuildAnonymousStructOrUnion() will put into CurContext.
5363 // Also store them here so that they can be part of the
5364 // DeclStmt that gets created in this case.
5365 // FIXME: Also return the IndirectFieldDecls created by
5366 // BuildAnonymousStructOr union, for the same reason?
5367 if (CurContext->isFunctionOrMethod())
5368 AnonRecord = Record;
5369 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5370 Policy: Context.getPrintingPolicy());
5371 }
5372
5373 DeclaresAnything = false;
5374 }
5375 }
5376
5377 // C11 6.7.2.1p2:
5378 // A struct-declaration that does not declare an anonymous structure or
5379 // anonymous union shall contain a struct-declarator-list.
5380 //
5381 // This rule also existed in C89 and C99; the grammar for struct-declaration
5382 // did not permit a struct-declaration without a struct-declarator-list.
5383 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5384 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5385 // Check for Microsoft C extension: anonymous struct/union member.
5386 // Handle 2 kinds of anonymous struct/union:
5387 // struct STRUCT;
5388 // union UNION;
5389 // and
5390 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5391 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5392 if ((Tag && Tag->getDeclName()) ||
5393 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5394 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5395 : DS.getRepAsType().get()->getAsRecordDecl();
5396 if (Record && getLangOpts().MSAnonymousStructs) {
5397 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5398 << Record->isUnion() << DS.getSourceRange();
5399 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5400 }
5401
5402 DeclaresAnything = false;
5403 }
5404 }
5405
5406 // Skip all the checks below if we have a type error.
5407 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5408 (TagD && TagD->isInvalidDecl()))
5409 return TagD;
5410
5411 if (getLangOpts().CPlusPlus &&
5412 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5413 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5414 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5415 !Enum->isInvalidDecl())
5416 DeclaresAnything = false;
5417
5418 if (!DS.isMissingDeclaratorOk()) {
5419 // Customize diagnostic for a typedef missing a name.
5420 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5421 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5422 << DS.getSourceRange();
5423 else
5424 DeclaresAnything = false;
5425 }
5426
5427 if (DS.isModulePrivateSpecified() &&
5428 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5429 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5430 << Tag->getTagKind()
5431 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5432
5433 ActOnDocumentableDecl(D: TagD);
5434
5435 // C 6.7/2:
5436 // A declaration [...] shall declare at least a declarator [...], a tag,
5437 // or the members of an enumeration.
5438 // C++ [dcl.dcl]p3:
5439 // [If there are no declarators], and except for the declaration of an
5440 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5441 // names into the program, or shall redeclare a name introduced by a
5442 // previous declaration.
5443 if (!DeclaresAnything) {
5444 // In C, we allow this as a (popular) extension / bug. Don't bother
5445 // producing further diagnostics for redundant qualifiers after this.
5446 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5447 ? diag::err_no_declarators
5448 : diag::ext_no_declarators)
5449 << DS.getSourceRange();
5450 return TagD;
5451 }
5452
5453 // C++ [dcl.stc]p1:
5454 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5455 // init-declarator-list of the declaration shall not be empty.
5456 // C++ [dcl.fct.spec]p1:
5457 // If a cv-qualifier appears in a decl-specifier-seq, the
5458 // init-declarator-list of the declaration shall not be empty.
5459 //
5460 // Spurious qualifiers here appear to be valid in C.
5461 unsigned DiagID = diag::warn_standalone_specifier;
5462 if (getLangOpts().CPlusPlus)
5463 DiagID = diag::ext_standalone_specifier;
5464
5465 // Note that a linkage-specification sets a storage class, but
5466 // 'extern "C" struct foo;' is actually valid and not theoretically
5467 // useless.
5468 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5469 if (SCS == DeclSpec::SCS_mutable)
5470 // Since mutable is not a viable storage class specifier in C, there is
5471 // no reason to treat it as an extension. Instead, diagnose as an error.
5472 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5473 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5474 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5475 << DeclSpec::getSpecifierName(S: SCS);
5476 }
5477
5478 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5479 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5480 << DeclSpec::getSpecifierName(S: TSCS);
5481 if (DS.getTypeQualifiers()) {
5482 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5483 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5484 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5485 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5486 // Restrict is covered above.
5487 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5488 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5489 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5490 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5491 }
5492
5493 // Warn about ignored type attributes, for example:
5494 // __attribute__((aligned)) struct A;
5495 // Attributes should be placed after tag to apply to type declaration.
5496 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5497 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5498 if (TypeSpecType == DeclSpec::TST_class ||
5499 TypeSpecType == DeclSpec::TST_struct ||
5500 TypeSpecType == DeclSpec::TST_interface ||
5501 TypeSpecType == DeclSpec::TST_union ||
5502 TypeSpecType == DeclSpec::TST_enum) {
5503
5504 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5505 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5506 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5507 DiagnosticId = diag::warn_attribute_ignored;
5508 else if (AL.isRegularKeywordAttribute())
5509 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5510 else
5511 DiagnosticId = diag::warn_declspec_attribute_ignored;
5512 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5513 << AL << GetDiagnosticTypeSpecifierID(DS);
5514 };
5515
5516 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5517 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5518 }
5519 }
5520
5521 return TagD;
5522}
5523
5524/// We are trying to inject an anonymous member into the given scope;
5525/// check if there's an existing declaration that can't be overloaded.
5526///
5527/// \return true if this is a forbidden redeclaration
5528static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5529 DeclContext *Owner,
5530 DeclarationName Name,
5531 SourceLocation NameLoc, bool IsUnion,
5532 StorageClass SC) {
5533 LookupResult R(SemaRef, Name, NameLoc,
5534 Owner->isRecord() ? Sema::LookupMemberName
5535 : Sema::LookupOrdinaryName,
5536 RedeclarationKind::ForVisibleRedeclaration);
5537 if (!SemaRef.LookupName(R, S)) return false;
5538
5539 // Pick a representative declaration.
5540 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5541 assert(PrevDecl && "Expected a non-null Decl");
5542
5543 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5544 return false;
5545
5546 if (SC == StorageClass::SC_None &&
5547 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5548 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5549 if (!Owner->isRecord())
5550 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5551 return false;
5552 }
5553
5554 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5555 << IsUnion << Name;
5556 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5557
5558 return true;
5559}
5560
5561void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5562 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5563 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5564}
5565
5566void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5567 if (!getLangOpts().CPlusPlus)
5568 return;
5569
5570 // This function can be parsed before we have validated the
5571 // structure as an anonymous struct
5572 if (Record->isAnonymousStructOrUnion())
5573 return;
5574
5575 const NamedDecl *First = 0;
5576 for (const Decl *D : Record->decls()) {
5577 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5578 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5579 continue;
5580 if (!First)
5581 First = ND;
5582 else
5583 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5584 }
5585}
5586
5587/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5588/// anonymous struct or union AnonRecord into the owning context Owner
5589/// and scope S. This routine will be invoked just after we realize
5590/// that an unnamed union or struct is actually an anonymous union or
5591/// struct, e.g.,
5592///
5593/// @code
5594/// union {
5595/// int i;
5596/// float f;
5597/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5598/// // f into the surrounding scope.x
5599/// @endcode
5600///
5601/// This routine is recursive, injecting the names of nested anonymous
5602/// structs/unions into the owning context and scope as well.
5603static bool
5604InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5605 RecordDecl *AnonRecord, AccessSpecifier AS,
5606 StorageClass SC,
5607 SmallVectorImpl<NamedDecl *> &Chaining) {
5608 bool Invalid = false;
5609
5610 // Look every FieldDecl and IndirectFieldDecl with a name.
5611 for (auto *D : AnonRecord->decls()) {
5612 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5613 cast<NamedDecl>(Val: D)->getDeclName()) {
5614 ValueDecl *VD = cast<ValueDecl>(Val: D);
5615 // C++ [class.union]p2:
5616 // The names of the members of an anonymous union shall be
5617 // distinct from the names of any other entity in the
5618 // scope in which the anonymous union is declared.
5619
5620 bool FieldInvalid = CheckAnonMemberRedeclaration(
5621 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5622 IsUnion: AnonRecord->isUnion(), SC);
5623 if (FieldInvalid)
5624 Invalid = true;
5625
5626 // Inject the IndirectFieldDecl even if invalid, because later
5627 // diagnostics may depend on it being present, see findDefaultInitializer.
5628
5629 // C++ [class.union]p2:
5630 // For the purpose of name lookup, after the anonymous union
5631 // definition, the members of the anonymous union are
5632 // considered to have been defined in the scope in which the
5633 // anonymous union is declared.
5634 unsigned OldChainingSize = Chaining.size();
5635 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5636 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5637 else
5638 Chaining.push_back(Elt: VD);
5639
5640 assert(Chaining.size() >= 2);
5641 NamedDecl **NamedChain =
5642 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5643 for (unsigned i = 0; i < Chaining.size(); i++)
5644 NamedChain[i] = Chaining[i];
5645
5646 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5647 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5648 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5649
5650 for (const auto *Attr : VD->attrs())
5651 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5652
5653 IndirectField->setAccess(AS);
5654 IndirectField->setImplicit();
5655 IndirectField->setInvalidDecl(FieldInvalid);
5656 SemaRef.PushOnScopeChains(D: IndirectField, S);
5657
5658 // That includes picking up the appropriate access specifier.
5659 if (AS != AS_none)
5660 IndirectField->setAccess(AS);
5661
5662 Chaining.resize(N: OldChainingSize);
5663 }
5664 }
5665
5666 return Invalid;
5667}
5668
5669/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5670/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5671/// illegal input values are mapped to SC_None.
5672static StorageClass
5673StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5674 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5675 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5676 "Parser allowed 'typedef' as storage class VarDecl.");
5677 switch (StorageClassSpec) {
5678 case DeclSpec::SCS_unspecified: return SC_None;
5679 case DeclSpec::SCS_extern:
5680 if (DS.isExternInLinkageSpec())
5681 return SC_None;
5682 return SC_Extern;
5683 case DeclSpec::SCS_static: return SC_Static;
5684 case DeclSpec::SCS_auto: return SC_Auto;
5685 case DeclSpec::SCS_register: return SC_Register;
5686 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5687 // Illegal SCSs map to None: error reporting is up to the caller.
5688 case DeclSpec::SCS_mutable: // Fall through.
5689 case DeclSpec::SCS_typedef: return SC_None;
5690 }
5691 llvm_unreachable("unknown storage class specifier");
5692}
5693
5694static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5695 assert(Record->hasInClassInitializer());
5696
5697 for (const auto *I : Record->decls()) {
5698 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5699 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5700 FD = IFD->getAnonField();
5701 if (FD && FD->hasInClassInitializer())
5702 return FD->getLocation();
5703 }
5704
5705 llvm_unreachable("couldn't find in-class initializer");
5706}
5707
5708static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5709 SourceLocation DefaultInitLoc) {
5710 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5711 return;
5712
5713 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5714 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5715}
5716
5717static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5718 CXXRecordDecl *AnonUnion) {
5719 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5720 return;
5721
5722 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5723}
5724
5725Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5726 AccessSpecifier AS,
5727 RecordDecl *Record,
5728 const PrintingPolicy &Policy) {
5729 DeclContext *Owner = Record->getDeclContext();
5730
5731 // Diagnose whether this anonymous struct/union is an extension.
5732 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5733 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5734 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5735 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5736 else if (!Record->isUnion() && !getLangOpts().C11)
5737 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5738
5739 // C and C++ require different kinds of checks for anonymous
5740 // structs/unions.
5741 bool Invalid = false;
5742 if (getLangOpts().CPlusPlus) {
5743 const char *PrevSpec = nullptr;
5744 if (Record->isUnion()) {
5745 // C++ [class.union]p6:
5746 // C++17 [class.union.anon]p2:
5747 // Anonymous unions declared in a named namespace or in the
5748 // global namespace shall be declared static.
5749 unsigned DiagID;
5750 DeclContext *OwnerScope = Owner->getRedeclContext();
5751 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5752 (OwnerScope->isTranslationUnit() ||
5753 (OwnerScope->isNamespace() &&
5754 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5755 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5756 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5757
5758 // Recover by adding 'static'.
5759 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5760 PrevSpec, DiagID, Policy);
5761 }
5762 // C++ [class.union]p6:
5763 // A storage class is not allowed in a declaration of an
5764 // anonymous union in a class scope.
5765 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5766 isa<RecordDecl>(Val: Owner)) {
5767 Diag(Loc: DS.getStorageClassSpecLoc(),
5768 DiagID: diag::err_anonymous_union_with_storage_spec)
5769 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5770
5771 // Recover by removing the storage specifier.
5772 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5773 Loc: SourceLocation(),
5774 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5775 }
5776 }
5777
5778 // Ignore const/volatile/restrict qualifiers.
5779 if (DS.getTypeQualifiers()) {
5780 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5781 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5782 << Record->isUnion() << "const"
5783 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5784 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5785 Diag(Loc: DS.getVolatileSpecLoc(),
5786 DiagID: diag::ext_anonymous_struct_union_qualified)
5787 << Record->isUnion() << "volatile"
5788 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5789 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5790 Diag(Loc: DS.getRestrictSpecLoc(),
5791 DiagID: diag::ext_anonymous_struct_union_qualified)
5792 << Record->isUnion() << "restrict"
5793 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5794 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5795 Diag(Loc: DS.getAtomicSpecLoc(),
5796 DiagID: diag::ext_anonymous_struct_union_qualified)
5797 << Record->isUnion() << "_Atomic"
5798 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5799 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5800 Diag(Loc: DS.getUnalignedSpecLoc(),
5801 DiagID: diag::ext_anonymous_struct_union_qualified)
5802 << Record->isUnion() << "__unaligned"
5803 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5804
5805 DS.ClearTypeQualifiers();
5806 }
5807
5808 // C++ [class.union]p2:
5809 // The member-specification of an anonymous union shall only
5810 // define non-static data members. [Note: nested types and
5811 // functions cannot be declared within an anonymous union. ]
5812 for (auto *Mem : Record->decls()) {
5813 // Ignore invalid declarations; we already diagnosed them.
5814 if (Mem->isInvalidDecl())
5815 continue;
5816
5817 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5818 // C++ [class.union]p3:
5819 // An anonymous union shall not have private or protected
5820 // members (clause 11).
5821 assert(FD->getAccess() != AS_none);
5822 if (FD->getAccess() != AS_public) {
5823 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5824 << Record->isUnion() << (FD->getAccess() == AS_protected);
5825 Invalid = true;
5826 }
5827
5828 // C++ [class.union]p1
5829 // An object of a class with a non-trivial constructor, a non-trivial
5830 // copy constructor, a non-trivial destructor, or a non-trivial copy
5831 // assignment operator cannot be a member of a union, nor can an
5832 // array of such objects.
5833 if (CheckNontrivialField(FD))
5834 Invalid = true;
5835 } else if (Mem->isImplicit()) {
5836 // Any implicit members are fine.
5837 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5838 // This is a type that showed up in an
5839 // elaborated-type-specifier inside the anonymous struct or
5840 // union, but which actually declares a type outside of the
5841 // anonymous struct or union. It's okay.
5842 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5843 if (!MemRecord->isAnonymousStructOrUnion() &&
5844 MemRecord->getDeclName()) {
5845 // Visual C++ allows type definition in anonymous struct or union.
5846 if (getLangOpts().MicrosoftExt)
5847 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5848 << Record->isUnion();
5849 else {
5850 // This is a nested type declaration.
5851 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5852 << Record->isUnion();
5853 Invalid = true;
5854 }
5855 } else {
5856 // This is an anonymous type definition within another anonymous type.
5857 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5858 // not part of standard C++.
5859 Diag(Loc: MemRecord->getLocation(),
5860 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5861 << Record->isUnion();
5862 }
5863 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5864 // Any access specifier is fine.
5865 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5866 // In C++1z, static_assert declarations are also fine.
5867 } else {
5868 // We have something that isn't a non-static data
5869 // member. Complain about it.
5870 unsigned DK = diag::err_anonymous_record_bad_member;
5871 if (isa<TypeDecl>(Val: Mem))
5872 DK = diag::err_anonymous_record_with_type;
5873 else if (isa<FunctionDecl>(Val: Mem))
5874 DK = diag::err_anonymous_record_with_function;
5875 else if (isa<VarDecl>(Val: Mem))
5876 DK = diag::err_anonymous_record_with_static;
5877
5878 // Visual C++ allows type definition in anonymous struct or union.
5879 if (getLangOpts().MicrosoftExt &&
5880 DK == diag::err_anonymous_record_with_type)
5881 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5882 << Record->isUnion();
5883 else {
5884 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5885 Invalid = true;
5886 }
5887 }
5888 }
5889
5890 // C++11 [class.union]p8 (DR1460):
5891 // At most one variant member of a union may have a
5892 // brace-or-equal-initializer.
5893 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5894 Owner->isRecord())
5895 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5896 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5897 }
5898
5899 if (!Record->isUnion() && !Owner->isRecord()) {
5900 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5901 << getLangOpts().CPlusPlus;
5902 Invalid = true;
5903 }
5904
5905 // C++ [dcl.dcl]p3:
5906 // [If there are no declarators], and except for the declaration of an
5907 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5908 // names into the program
5909 // C++ [class.mem]p2:
5910 // each such member-declaration shall either declare at least one member
5911 // name of the class or declare at least one unnamed bit-field
5912 //
5913 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5914 if (getLangOpts().CPlusPlus && Record->field_empty())
5915 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5916
5917 // Mock up a declarator.
5918 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5919 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5920 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5921 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5922
5923 // Create a declaration for this anonymous struct/union.
5924 NamedDecl *Anon = nullptr;
5925 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5926 Anon = FieldDecl::Create(
5927 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5928 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5929 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5930 /*InitStyle=*/ICIS_NoInit);
5931 Anon->setAccess(AS);
5932 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5933
5934 if (getLangOpts().CPlusPlus)
5935 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5936 } else {
5937 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5938 if (SCSpec == DeclSpec::SCS_mutable) {
5939 // mutable can only appear on non-static class members, so it's always
5940 // an error here
5941 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5942 Invalid = true;
5943 SC = SC_None;
5944 }
5945
5946 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5947 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5948 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5949 if (Invalid)
5950 Anon->setInvalidDecl();
5951
5952 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5953
5954 // Default-initialize the implicit variable. This initialization will be
5955 // trivial in almost all cases, except if a union member has an in-class
5956 // initializer:
5957 // union { int n = 0; };
5958 ActOnUninitializedDecl(dcl: Anon);
5959 }
5960 Anon->setImplicit();
5961
5962 // Mark this as an anonymous struct/union type.
5963 Record->setAnonymousStructOrUnion(true);
5964
5965 // Add the anonymous struct/union object to the current
5966 // context. We'll be referencing this object when we refer to one of
5967 // its members.
5968 Owner->addDecl(D: Anon);
5969
5970 // Inject the members of the anonymous struct/union into the owning
5971 // context and into the identifier resolver chain for name lookup
5972 // purposes.
5973 SmallVector<NamedDecl*, 2> Chain;
5974 Chain.push_back(Elt: Anon);
5975
5976 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5977 Chaining&: Chain))
5978 Invalid = true;
5979
5980 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5981 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5982 MangleNumberingContext *MCtx;
5983 Decl *ManglingContextDecl;
5984 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5985 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5986 if (MCtx) {
5987 Context.setManglingNumber(
5988 ND: NewVD, Number: MCtx->getManglingNumber(
5989 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5990 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5991 }
5992 }
5993 }
5994
5995 if (Invalid)
5996 Anon->setInvalidDecl();
5997
5998 return Anon;
5999}
6000
6001Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
6002 RecordDecl *Record) {
6003 assert(Record && "expected a record!");
6004
6005 // Mock up a declarator.
6006 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6007 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6008 assert(TInfo && "couldn't build declarator info for anonymous struct");
6009
6010 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6011 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6012
6013 // Create a declaration for this anonymous struct.
6014 NamedDecl *Anon =
6015 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6016 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6017 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6018 /*InitStyle=*/ICIS_NoInit);
6019 Anon->setImplicit();
6020
6021 // Add the anonymous struct object to the current context.
6022 CurContext->addDecl(D: Anon);
6023
6024 // Inject the members of the anonymous struct into the current
6025 // context and into the identifier resolver chain for name lookup
6026 // purposes.
6027 SmallVector<NamedDecl*, 2> Chain;
6028 Chain.push_back(Elt: Anon);
6029
6030 RecordDecl *RecordDef = Record->getDefinition();
6031 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6032 DiagID: diag::err_field_incomplete_or_sizeless) ||
6033 InjectAnonymousStructOrUnionMembers(
6034 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6035 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6036 Anon->setInvalidDecl();
6037 ParentDecl->setInvalidDecl();
6038 }
6039
6040 return Anon;
6041}
6042
6043DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6044 return GetNameFromUnqualifiedId(Name: D.getName());
6045}
6046
6047DeclarationNameInfo
6048Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6049 DeclarationNameInfo NameInfo;
6050 NameInfo.setLoc(Name.StartLocation);
6051
6052 switch (Name.getKind()) {
6053
6054 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6055 case UnqualifiedIdKind::IK_Identifier:
6056 NameInfo.setName(Name.Identifier);
6057 return NameInfo;
6058
6059 case UnqualifiedIdKind::IK_DeductionGuideName: {
6060 // C++ [temp.deduct.guide]p3:
6061 // The simple-template-id shall name a class template specialization.
6062 // The template-name shall be the same identifier as the template-name
6063 // of the simple-template-id.
6064 // These together intend to imply that the template-name shall name a
6065 // class template.
6066 // FIXME: template<typename T> struct X {};
6067 // template<typename T> using Y = X<T>;
6068 // Y(int) -> Y<int>;
6069 // satisfies these rules but does not name a class template.
6070 TemplateName TN = Name.TemplateName.get().get();
6071 auto *Template = TN.getAsTemplateDecl();
6072 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6073 Diag(Loc: Name.StartLocation,
6074 DiagID: diag::err_deduction_guide_name_not_class_template)
6075 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6076 if (Template)
6077 NoteTemplateLocation(Decl: *Template);
6078 return DeclarationNameInfo();
6079 }
6080
6081 NameInfo.setName(
6082 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6083 return NameInfo;
6084 }
6085
6086 case UnqualifiedIdKind::IK_OperatorFunctionId:
6087 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6088 Op: Name.OperatorFunctionId.Operator));
6089 NameInfo.setCXXOperatorNameRange(SourceRange(
6090 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6091 return NameInfo;
6092
6093 case UnqualifiedIdKind::IK_LiteralOperatorId:
6094 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6095 II: Name.Identifier));
6096 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6097 return NameInfo;
6098
6099 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6100 TypeSourceInfo *TInfo;
6101 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6102 if (Ty.isNull())
6103 return DeclarationNameInfo();
6104 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6105 Ty: Context.getCanonicalType(T: Ty)));
6106 NameInfo.setNamedTypeInfo(TInfo);
6107 return NameInfo;
6108 }
6109
6110 case UnqualifiedIdKind::IK_ConstructorName: {
6111 TypeSourceInfo *TInfo;
6112 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6113 if (Ty.isNull())
6114 return DeclarationNameInfo();
6115 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6116 Ty: Context.getCanonicalType(T: Ty)));
6117 NameInfo.setNamedTypeInfo(TInfo);
6118 return NameInfo;
6119 }
6120
6121 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6122 // In well-formed code, we can only have a constructor
6123 // template-id that refers to the current context, so go there
6124 // to find the actual type being constructed.
6125 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6126 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6127 return DeclarationNameInfo();
6128
6129 // Determine the type of the class being constructed.
6130 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6131
6132 // FIXME: Check two things: that the template-id names the same type as
6133 // CurClassType, and that the template-id does not occur when the name
6134 // was qualified.
6135
6136 NameInfo.setName(
6137 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6138 // FIXME: should we retrieve TypeSourceInfo?
6139 NameInfo.setNamedTypeInfo(nullptr);
6140 return NameInfo;
6141 }
6142
6143 case UnqualifiedIdKind::IK_DestructorName: {
6144 TypeSourceInfo *TInfo;
6145 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6146 if (Ty.isNull())
6147 return DeclarationNameInfo();
6148 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6149 Ty: Context.getCanonicalType(T: Ty)));
6150 NameInfo.setNamedTypeInfo(TInfo);
6151 return NameInfo;
6152 }
6153
6154 case UnqualifiedIdKind::IK_TemplateId: {
6155 TemplateName TName = Name.TemplateId->Template.get();
6156 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6157 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6158 }
6159
6160 } // switch (Name.getKind())
6161
6162 llvm_unreachable("Unknown name kind");
6163}
6164
6165static QualType getCoreType(QualType Ty) {
6166 do {
6167 if (Ty->isPointerOrReferenceType())
6168 Ty = Ty->getPointeeType();
6169 else if (Ty->isArrayType())
6170 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6171 else
6172 return Ty.withoutLocalFastQualifiers();
6173 } while (true);
6174}
6175
6176/// hasSimilarParameters - Determine whether the C++ functions Declaration
6177/// and Definition have "nearly" matching parameters. This heuristic is
6178/// used to improve diagnostics in the case where an out-of-line function
6179/// definition doesn't match any declaration within the class or namespace.
6180/// Also sets Params to the list of indices to the parameters that differ
6181/// between the declaration and the definition. If hasSimilarParameters
6182/// returns true and Params is empty, then all of the parameters match.
6183static bool hasSimilarParameters(ASTContext &Context,
6184 FunctionDecl *Declaration,
6185 FunctionDecl *Definition,
6186 SmallVectorImpl<unsigned> &Params) {
6187 Params.clear();
6188 if (Declaration->param_size() != Definition->param_size())
6189 return false;
6190 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6191 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6192 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6193
6194 // The parameter types are identical
6195 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6196 continue;
6197
6198 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6199 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6200 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6201 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6202
6203 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6204 (DeclTyName && DeclTyName == DefTyName))
6205 Params.push_back(Elt: Idx);
6206 else // The two parameters aren't even close
6207 return false;
6208 }
6209
6210 return true;
6211}
6212
6213/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6214/// declarator needs to be rebuilt in the current instantiation.
6215/// Any bits of declarator which appear before the name are valid for
6216/// consideration here. That's specifically the type in the decl spec
6217/// and the base type in any member-pointer chunks.
6218static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6219 DeclarationName Name) {
6220 // The types we specifically need to rebuild are:
6221 // - typenames, typeofs, and decltypes
6222 // - types which will become injected class names
6223 // Of course, we also need to rebuild any type referencing such a
6224 // type. It's safest to just say "dependent", but we call out a
6225 // few cases here.
6226
6227 DeclSpec &DS = D.getMutableDeclSpec();
6228 switch (DS.getTypeSpecType()) {
6229 case DeclSpec::TST_typename:
6230 case DeclSpec::TST_typeofType:
6231 case DeclSpec::TST_typeof_unqualType:
6232#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6233#include "clang/Basic/Traits.inc"
6234 case DeclSpec::TST_atomic: {
6235 // Grab the type from the parser.
6236 TypeSourceInfo *TSI = nullptr;
6237 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6238 if (T.isNull() || !T->isInstantiationDependentType()) break;
6239
6240 // Make sure there's a type source info. This isn't really much
6241 // of a waste; most dependent types should have type source info
6242 // attached already.
6243 if (!TSI)
6244 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6245
6246 // Rebuild the type in the current instantiation.
6247 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6248 if (!TSI) return true;
6249
6250 // Store the new type back in the decl spec.
6251 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6252 DS.UpdateTypeRep(Rep: LocType);
6253 break;
6254 }
6255
6256 case DeclSpec::TST_decltype:
6257 case DeclSpec::TST_typeof_unqualExpr:
6258 case DeclSpec::TST_typeofExpr: {
6259 Expr *E = DS.getRepAsExpr();
6260 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6261 if (Result.isInvalid()) return true;
6262 DS.UpdateExprRep(Rep: Result.get());
6263 break;
6264 }
6265
6266 default:
6267 // Nothing to do for these decl specs.
6268 break;
6269 }
6270
6271 // It doesn't matter what order we do this in.
6272 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6273 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6274
6275 // The only type information in the declarator which can come
6276 // before the declaration name is the base type of a member
6277 // pointer.
6278 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6279 continue;
6280
6281 // Rebuild the scope specifier in-place.
6282 CXXScopeSpec &SS = Chunk.Mem.Scope();
6283 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6284 return true;
6285 }
6286
6287 return false;
6288}
6289
6290/// Returns true if the declaration is declared in a system header or from a
6291/// system macro.
6292static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6293 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6294 SM.isInSystemMacro(loc: D->getLocation());
6295}
6296
6297void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6298 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6299 // of system decl.
6300 if (D->getPreviousDecl() || D->isImplicit())
6301 return;
6302 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6303 if (Status != ReservedIdentifierStatus::NotReserved &&
6304 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6305 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6306 << D << static_cast<int>(Status);
6307 }
6308}
6309
6310Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6311 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6312
6313 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6314 // declaration only if the `bind_to_declaration` extension is set.
6315 SmallVector<FunctionDecl *, 4> Bases;
6316 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6317 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6318 TP: llvm::omp::TraitProperty::
6319 implementation_extension_bind_to_declaration))
6320 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6321 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6322
6323 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6324
6325 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6326 Dcl && Dcl->getDeclContext()->isFileContext())
6327 Dcl->setTopLevelDeclInObjCContainer();
6328
6329 if (!Bases.empty())
6330 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6331 Bases);
6332
6333 return Dcl;
6334}
6335
6336bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6337 DeclarationNameInfo NameInfo) {
6338 DeclarationName Name = NameInfo.getName();
6339
6340 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6341 while (Record && Record->isAnonymousStructOrUnion())
6342 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6343 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6344 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6345 return true;
6346 }
6347
6348 return false;
6349}
6350
6351bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6352 DeclarationName Name,
6353 SourceLocation Loc,
6354 TemplateIdAnnotation *TemplateId,
6355 bool IsMemberSpecialization) {
6356 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6357 "without nested-name-specifier");
6358 DeclContext *Cur = CurContext;
6359 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6360 Cur = Cur->getParent();
6361
6362 // If the user provided a superfluous scope specifier that refers back to the
6363 // class in which the entity is already declared, diagnose and ignore it.
6364 //
6365 // class X {
6366 // void X::f();
6367 // };
6368 //
6369 // Note, it was once ill-formed to give redundant qualification in all
6370 // contexts, but that rule was removed by DR482.
6371 if (Cur->Equals(DC)) {
6372 if (Cur->isRecord()) {
6373 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6374 : diag::err_member_extra_qualification)
6375 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6376 SS.clear();
6377 } else {
6378 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6379 }
6380 return false;
6381 }
6382
6383 // Check whether the qualifying scope encloses the scope of the original
6384 // declaration. For a template-id, we perform the checks in
6385 // CheckTemplateSpecializationScope.
6386 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6387 if (Cur->isRecord())
6388 Diag(Loc, DiagID: diag::err_member_qualification)
6389 << Name << SS.getRange();
6390 else if (isa<TranslationUnitDecl>(Val: DC))
6391 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6392 << Name << SS.getRange();
6393 else if (isa<FunctionDecl>(Val: Cur))
6394 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6395 << Name << SS.getRange();
6396 else if (isa<BlockDecl>(Val: Cur))
6397 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6398 << Name << SS.getRange();
6399 else if (isa<ExportDecl>(Val: Cur)) {
6400 if (!isa<NamespaceDecl>(Val: DC))
6401 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6402 << Name << SS.getRange();
6403 else
6404 // The cases that DC is not NamespaceDecl should be handled in
6405 // CheckRedeclarationExported.
6406 return false;
6407 } else
6408 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6409 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6410
6411 return true;
6412 }
6413
6414 if (Cur->isRecord()) {
6415 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6416 // An explicit specialization may be declared in any scope in which the
6417 // corresponding primary template may be defined.
6418 if (IsMemberSpecialization)
6419 return false;
6420
6421 // Cannot qualify members within a class.
6422 Diag(Loc, DiagID: diag::err_member_qualification)
6423 << Name << SS.getRange();
6424 SS.clear();
6425
6426 // C++ constructors and destructors with incorrect scopes can break
6427 // our AST invariants by having the wrong underlying types. If
6428 // that's the case, then drop this declaration entirely.
6429 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6430 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6431 !Context.hasSameType(
6432 T1: Name.getCXXNameType(),
6433 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6434 return true;
6435
6436 return false;
6437 }
6438
6439 // C++23 [temp.names]p5:
6440 // The keyword template shall not appear immediately after a declarative
6441 // nested-name-specifier.
6442 //
6443 // First check the template-id (if any), and then check each component of the
6444 // nested-name-specifier in reverse order.
6445 //
6446 // FIXME: nested-name-specifiers in friend declarations are declarative,
6447 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6448 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6449 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6450 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6451
6452 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6453 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6454 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6455 SourceLocation TemplateKeywordLoc;
6456 switch (TL.getTypeLocClass()) {
6457 case TypeLoc::TemplateSpecialization: {
6458 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6459 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6460 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6461 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6462 << TST.getLocalSourceRange();
6463 break;
6464 }
6465 case TypeLoc::Decltype:
6466 case TypeLoc::PackIndexing: {
6467 const Type *T = TL.getTypePtr();
6468 // C++23 [expr.prim.id.qual]p2:
6469 // [...] A declarative nested-name-specifier shall not have a
6470 // computed-type-specifier.
6471 //
6472 // CWG2858 changed this from 'decltype-specifier' to
6473 // 'computed-type-specifier'.
6474 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6475 << T->isDecltypeType() << TL.getSourceRange();
6476 break;
6477 }
6478 case TypeLoc::DependentName:
6479 NextTL =
6480 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6481 break;
6482 default:
6483 break;
6484 }
6485 if (TemplateKeywordLoc.isValid())
6486 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6487 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6488 }
6489
6490 return false;
6491}
6492
6493NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6494 MultiTemplateParamsArg TemplateParamLists) {
6495 // TODO: consider using NameInfo for diagnostic.
6496 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6497 DeclarationName Name = NameInfo.getName();
6498
6499 // All of these full declarators require an identifier. If it doesn't have
6500 // one, the ParsedFreeStandingDeclSpec action should be used.
6501 if (D.isDecompositionDeclarator()) {
6502 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6503 } else if (!Name) {
6504 if (!D.isInvalidType()) // Reject this if we think it is valid.
6505 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6506 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6507 return nullptr;
6508 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6509 return nullptr;
6510
6511 DeclContext *DC = CurContext;
6512 if (D.getCXXScopeSpec().isInvalid())
6513 D.setInvalidType();
6514 else if (D.getCXXScopeSpec().isSet()) {
6515 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6516 UPPC: UPPC_DeclarationQualifier))
6517 return nullptr;
6518
6519 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6520 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6521 if (!DC || isa<EnumDecl>(Val: DC)) {
6522 // If we could not compute the declaration context, it's because the
6523 // declaration context is dependent but does not refer to a class,
6524 // class template, or class template partial specialization. Complain
6525 // and return early, to avoid the coming semantic disaster.
6526 Diag(Loc: D.getIdentifierLoc(),
6527 DiagID: diag::err_template_qualified_declarator_no_match)
6528 << D.getCXXScopeSpec().getScopeRep()
6529 << D.getCXXScopeSpec().getRange();
6530 return nullptr;
6531 }
6532 bool IsDependentContext = DC->isDependentContext();
6533
6534 if (!IsDependentContext &&
6535 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6536 return nullptr;
6537
6538 // If a class is incomplete, do not parse entities inside it.
6539 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6540 Diag(Loc: D.getIdentifierLoc(),
6541 DiagID: diag::err_member_def_undefined_record)
6542 << Name << DC << D.getCXXScopeSpec().getRange();
6543 return nullptr;
6544 }
6545 if (!D.getDeclSpec().isFriendSpecified()) {
6546 TemplateIdAnnotation *TemplateId =
6547 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6548 ? D.getName().TemplateId
6549 : nullptr;
6550 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6551 Loc: D.getIdentifierLoc(), TemplateId,
6552 /*IsMemberSpecialization=*/false)) {
6553 if (DC->isRecord())
6554 return nullptr;
6555
6556 D.setInvalidType();
6557 }
6558 }
6559
6560 // Check whether we need to rebuild the type of the given
6561 // declaration in the current instantiation.
6562 if (EnteringContext && IsDependentContext &&
6563 TemplateParamLists.size() != 0) {
6564 ContextRAII SavedContext(*this, DC);
6565 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6566 D.setInvalidType();
6567 }
6568 }
6569
6570 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6571 QualType R = TInfo->getType();
6572
6573 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6574 UPPC: UPPC_DeclarationType))
6575 D.setInvalidType();
6576
6577 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6578 forRedeclarationInCurContext());
6579
6580 // See if this is a redefinition of a variable in the same scope.
6581 if (!D.getCXXScopeSpec().isSet()) {
6582 bool IsLinkageLookup = false;
6583 bool CreateBuiltins = false;
6584
6585 // If the declaration we're planning to build will be a function
6586 // or object with linkage, then look for another declaration with
6587 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6588 //
6589 // If the declaration we're planning to build will be declared with
6590 // external linkage in the translation unit, create any builtin with
6591 // the same name.
6592 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6593 /* Do nothing*/;
6594 else if (CurContext->isFunctionOrMethod() &&
6595 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6596 R->isFunctionType())) {
6597 IsLinkageLookup = true;
6598 CreateBuiltins =
6599 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6600 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6601 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6602 CreateBuiltins = true;
6603
6604 if (IsLinkageLookup) {
6605 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6606 Previous.setRedeclarationKind(
6607 RedeclarationKind::ForExternalRedeclaration);
6608 }
6609
6610 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6611 } else { // Something like "int foo::x;"
6612 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6613
6614 // C++ [dcl.meaning]p1:
6615 // When the declarator-id is qualified, the declaration shall refer to a
6616 // previously declared member of the class or namespace to which the
6617 // qualifier refers (or, in the case of a namespace, of an element of the
6618 // inline namespace set of that namespace (7.3.1)) or to a specialization
6619 // thereof; [...]
6620 //
6621 // Note that we already checked the context above, and that we do not have
6622 // enough information to make sure that Previous contains the declaration
6623 // we want to match. For example, given:
6624 //
6625 // class X {
6626 // void f();
6627 // void f(float);
6628 // };
6629 //
6630 // void X::f(int) { } // ill-formed
6631 //
6632 // In this case, Previous will point to the overload set
6633 // containing the two f's declared in X, but neither of them
6634 // matches.
6635
6636 RemoveUsingDecls(R&: Previous);
6637 }
6638
6639 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6640 TPD && TPD->isTemplateParameter()) {
6641 // Older versions of clang allowed the names of function/variable templates
6642 // to shadow the names of their template parameters. For the compatibility
6643 // purposes we detect such cases and issue a default-to-error warning that
6644 // can be disabled with -Wno-strict-primary-template-shadow.
6645 if (!D.isInvalidType()) {
6646 bool AllowForCompatibility = false;
6647 if (Scope *DeclParent = S->getDeclParent();
6648 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6649 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6650 TemplateParamParent->isDeclScope(D: TPD);
6651 }
6652 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6653 SupportedForCompatibility: AllowForCompatibility);
6654 }
6655
6656 // Just pretend that we didn't see the previous declaration.
6657 Previous.clear();
6658 }
6659
6660 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6661 // Forget that the previous declaration is the injected-class-name.
6662 Previous.clear();
6663
6664 // In C++, the previous declaration we find might be a tag type
6665 // (class or enum). In this case, the new declaration will hide the
6666 // tag type. Note that this applies to functions, function templates, and
6667 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6668 if (Previous.isSingleTagDecl() &&
6669 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6670 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6671 Previous.clear();
6672
6673 // Check that there are no default arguments other than in the parameters
6674 // of a function declaration (C++ only).
6675 if (getLangOpts().CPlusPlus)
6676 CheckExtraCXXDefaultArguments(D);
6677
6678 /// Get the innermost enclosing declaration scope.
6679 S = S->getDeclParent();
6680
6681 NamedDecl *New;
6682
6683 bool AddToScope = true;
6684 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6685 if (TemplateParamLists.size()) {
6686 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6687 return nullptr;
6688 }
6689
6690 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6691 } else if (R->isFunctionType()) {
6692 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6693 TemplateParamLists,
6694 AddToScope);
6695 } else {
6696 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6697 AddToScope);
6698 }
6699
6700 if (!New)
6701 return nullptr;
6702
6703 warnOnCTypeHiddenInCPlusPlus(D: New);
6704
6705 // If this has an identifier and is not a function template specialization,
6706 // add it to the scope stack.
6707 if (New->getDeclName() && AddToScope)
6708 PushOnScopeChains(D: New, S);
6709
6710 if (OpenMP().isInOpenMPDeclareTargetContext())
6711 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6712
6713 return New;
6714}
6715
6716/// Helper method to turn variable array types into constant array
6717/// types in certain situations which would otherwise be errors (for
6718/// GCC compatibility).
6719static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6720 ASTContext &Context,
6721 bool &SizeIsNegative,
6722 llvm::APSInt &Oversized) {
6723 // This method tries to turn a variable array into a constant
6724 // array even when the size isn't an ICE. This is necessary
6725 // for compatibility with code that depends on gcc's buggy
6726 // constant expression folding, like struct {char x[(int)(char*)2];}
6727 SizeIsNegative = false;
6728 Oversized = 0;
6729
6730 if (T->isDependentType())
6731 return QualType();
6732
6733 QualifierCollector Qs;
6734 const Type *Ty = Qs.strip(type: T);
6735
6736 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6737 QualType Pointee = PTy->getPointeeType();
6738 QualType FixedType =
6739 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6740 Oversized);
6741 if (FixedType.isNull()) return FixedType;
6742 FixedType = Context.getPointerType(T: FixedType);
6743 return Qs.apply(Context, QT: FixedType);
6744 }
6745 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6746 QualType Inner = PTy->getInnerType();
6747 QualType FixedType =
6748 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6749 Oversized);
6750 if (FixedType.isNull()) return FixedType;
6751 FixedType = Context.getParenType(NamedType: FixedType);
6752 return Qs.apply(Context, QT: FixedType);
6753 }
6754
6755 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6756 if (!VLATy)
6757 return QualType();
6758
6759 QualType ElemTy = VLATy->getElementType();
6760 if (ElemTy->isVariablyModifiedType()) {
6761 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6762 SizeIsNegative, Oversized);
6763 if (ElemTy.isNull())
6764 return QualType();
6765 }
6766
6767 Expr::EvalResult Result;
6768 if (!VLATy->getSizeExpr() ||
6769 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6770 return QualType();
6771
6772 llvm::APSInt Res = Result.Val.getInt();
6773
6774 // Check whether the array size is negative.
6775 if (Res.isSigned() && Res.isNegative()) {
6776 SizeIsNegative = true;
6777 return QualType();
6778 }
6779
6780 // Check whether the array is too large to be addressed.
6781 unsigned ActiveSizeBits =
6782 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6783 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6784 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6785 : Res.getActiveBits();
6786 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6787 Oversized = std::move(Res);
6788 return QualType();
6789 }
6790
6791 QualType FoldedArrayType = Context.getConstantArrayType(
6792 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6793 return Qs.apply(Context, QT: FoldedArrayType);
6794}
6795
6796static void
6797FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6798 SrcTL = SrcTL.getUnqualifiedLoc();
6799 DstTL = DstTL.getUnqualifiedLoc();
6800 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6801 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6802 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6803 DstTL: DstPTL.getPointeeLoc());
6804 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6805 return;
6806 }
6807 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6808 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6809 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6810 DstTL: DstPTL.getInnerLoc());
6811 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6812 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6813 return;
6814 }
6815 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6816 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6817 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6818 TypeLoc DstElemTL = DstATL.getElementLoc();
6819 if (VariableArrayTypeLoc SrcElemATL =
6820 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6821 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6822 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6823 } else {
6824 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6825 }
6826 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6827 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6828 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6829}
6830
6831/// Helper method to turn variable array types into constant array
6832/// types in certain situations which would otherwise be errors (for
6833/// GCC compatibility).
6834static TypeSourceInfo*
6835TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6836 ASTContext &Context,
6837 bool &SizeIsNegative,
6838 llvm::APSInt &Oversized) {
6839 QualType FixedTy
6840 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6841 SizeIsNegative, Oversized);
6842 if (FixedTy.isNull())
6843 return nullptr;
6844 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6845 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6846 DstTL: FixedTInfo->getTypeLoc());
6847 return FixedTInfo;
6848}
6849
6850bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6851 QualType &T, SourceLocation Loc,
6852 unsigned FailedFoldDiagID) {
6853 bool SizeIsNegative;
6854 llvm::APSInt Oversized;
6855 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6856 TInfo, Context, SizeIsNegative, Oversized);
6857 if (FixedTInfo) {
6858 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6859 TInfo = FixedTInfo;
6860 T = FixedTInfo->getType();
6861 return true;
6862 }
6863
6864 if (SizeIsNegative)
6865 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6866 else if (Oversized.getBoolValue())
6867 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6868 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6869 /*UpperCase=*/false, /*InsertSeparators=*/true);
6870 else if (FailedFoldDiagID)
6871 Diag(Loc, DiagID: FailedFoldDiagID);
6872 return false;
6873}
6874
6875void
6876Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6877 if (!getLangOpts().CPlusPlus &&
6878 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6879 // Don't need to track declarations in the TU in C.
6880 return;
6881
6882 // Note that we have a locally-scoped external with this name.
6883 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6884}
6885
6886NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6887 // FIXME: We can have multiple results via __attribute__((overloadable)).
6888 auto Result = Context.getExternCContextDecl()->lookup(Name);
6889 return Result.empty() ? nullptr : *Result.begin();
6890}
6891
6892void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6893 // FIXME: We should probably indicate the identifier in question to avoid
6894 // confusion for constructs like "virtual int a(), b;"
6895 if (DS.isVirtualSpecified())
6896 Diag(Loc: DS.getVirtualSpecLoc(),
6897 DiagID: diag::err_virtual_non_function);
6898
6899 if (DS.hasExplicitSpecifier())
6900 Diag(Loc: DS.getExplicitSpecLoc(),
6901 DiagID: diag::err_explicit_non_function);
6902
6903 if (DS.isNoreturnSpecified())
6904 Diag(Loc: DS.getNoreturnSpecLoc(),
6905 DiagID: diag::err_noreturn_non_function);
6906}
6907
6908NamedDecl*
6909Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6910 TypeSourceInfo *TInfo, LookupResult &Previous) {
6911 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6912 if (D.getCXXScopeSpec().isSet()) {
6913 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6914 << D.getCXXScopeSpec().getRange();
6915 D.setInvalidType();
6916 // Pretend we didn't see the scope specifier.
6917 DC = CurContext;
6918 Previous.clear();
6919 }
6920
6921 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6922
6923 if (D.getDeclSpec().isInlineSpecified())
6924 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6925 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6926 ? diag::warn_ms_inline_non_function
6927 : diag::err_inline_non_function)
6928 << getLangOpts().CPlusPlus17;
6929 if (D.getDeclSpec().hasConstexprSpecifier())
6930 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6931 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6932
6933 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6934 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6935 Diag(Loc: D.getName().StartLocation,
6936 DiagID: diag::err_deduction_guide_invalid_specifier)
6937 << "typedef";
6938 else
6939 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6940 << D.getName().getSourceRange();
6941 return nullptr;
6942 }
6943
6944 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6945 if (!NewTD) return nullptr;
6946
6947 // Handle attributes prior to checking for duplicates in MergeVarDecl
6948 ProcessDeclAttributes(S, D: NewTD, PD: D);
6949
6950 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6951
6952 bool Redeclaration = D.isRedeclaration();
6953 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6954 D.setRedeclaration(Redeclaration);
6955 return ND;
6956}
6957
6958void
6959Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6960 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6961 // then it shall have block scope.
6962 // Note that variably modified types must be fixed before merging the decl so
6963 // that redeclarations will match.
6964 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6965 QualType T = TInfo->getType();
6966 if (T->isVariablyModifiedType()) {
6967 setFunctionHasBranchProtectedScope();
6968
6969 if (S->getFnParent() == nullptr) {
6970 bool SizeIsNegative;
6971 llvm::APSInt Oversized;
6972 TypeSourceInfo *FixedTInfo =
6973 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6974 SizeIsNegative,
6975 Oversized);
6976 if (FixedTInfo) {
6977 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6978 NewTD->setTypeSourceInfo(FixedTInfo);
6979 } else {
6980 if (SizeIsNegative)
6981 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6982 else if (T->isVariableArrayType())
6983 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6984 else if (Oversized.getBoolValue())
6985 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6986 << toString(I: Oversized, Radix: 10);
6987 else
6988 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6989 NewTD->setInvalidDecl();
6990 }
6991 }
6992 }
6993}
6994
6995NamedDecl*
6996Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6997 LookupResult &Previous, bool &Redeclaration) {
6998
6999 // Find the shadowed declaration before filtering for scope.
7000 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
7001
7002 // Merge the decl with the existing one if appropriate. If the decl is
7003 // in an outer scope, it isn't the same thing.
7004 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
7005 /*AllowInlineNamespace*/false);
7006 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
7007 if (!Previous.empty()) {
7008 Redeclaration = true;
7009 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
7010 } else {
7011 inferGslPointerAttribute(TD: NewTD);
7012 }
7013
7014 if (ShadowedDecl && !Redeclaration)
7015 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7016
7017 // If this is the C FILE type, notify the AST context.
7018 if (IdentifierInfo *II = NewTD->getIdentifier())
7019 if (!NewTD->isInvalidDecl() &&
7020 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7021 switch (II->getNotableIdentifierID()) {
7022 case tok::NotableIdentifierKind::FILE:
7023 Context.setFILEDecl(NewTD);
7024 break;
7025 case tok::NotableIdentifierKind::jmp_buf:
7026 Context.setjmp_bufDecl(NewTD);
7027 break;
7028 case tok::NotableIdentifierKind::sigjmp_buf:
7029 Context.setsigjmp_bufDecl(NewTD);
7030 break;
7031 case tok::NotableIdentifierKind::ucontext_t:
7032 Context.setucontext_tDecl(NewTD);
7033 break;
7034 case tok::NotableIdentifierKind::float_t:
7035 case tok::NotableIdentifierKind::double_t:
7036 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7037 break;
7038 default:
7039 break;
7040 }
7041 }
7042
7043 return NewTD;
7044}
7045
7046/// Determines whether the given declaration is an out-of-scope
7047/// previous declaration.
7048///
7049/// This routine should be invoked when name lookup has found a
7050/// previous declaration (PrevDecl) that is not in the scope where a
7051/// new declaration by the same name is being introduced. If the new
7052/// declaration occurs in a local scope, previous declarations with
7053/// linkage may still be considered previous declarations (C99
7054/// 6.2.2p4-5, C++ [basic.link]p6).
7055///
7056/// \param PrevDecl the previous declaration found by name
7057/// lookup
7058///
7059/// \param DC the context in which the new declaration is being
7060/// declared.
7061///
7062/// \returns true if PrevDecl is an out-of-scope previous declaration
7063/// for a new delcaration with the same name.
7064static bool
7065isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7066 ASTContext &Context) {
7067 if (!PrevDecl)
7068 return false;
7069
7070 if (!PrevDecl->hasLinkage())
7071 return false;
7072
7073 if (Context.getLangOpts().CPlusPlus) {
7074 // C++ [basic.link]p6:
7075 // If there is a visible declaration of an entity with linkage
7076 // having the same name and type, ignoring entities declared
7077 // outside the innermost enclosing namespace scope, the block
7078 // scope declaration declares that same entity and receives the
7079 // linkage of the previous declaration.
7080 DeclContext *OuterContext = DC->getRedeclContext();
7081 if (!OuterContext->isFunctionOrMethod())
7082 // This rule only applies to block-scope declarations.
7083 return false;
7084
7085 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7086 if (PrevOuterContext->isRecord())
7087 // We found a member function: ignore it.
7088 return false;
7089
7090 // Find the innermost enclosing namespace for the new and
7091 // previous declarations.
7092 OuterContext = OuterContext->getEnclosingNamespaceContext();
7093 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7094
7095 // The previous declaration is in a different namespace, so it
7096 // isn't the same function.
7097 if (!OuterContext->Equals(DC: PrevOuterContext))
7098 return false;
7099 }
7100
7101 return true;
7102}
7103
7104static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7105 CXXScopeSpec &SS = D.getCXXScopeSpec();
7106 if (!SS.isSet()) return;
7107 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7108}
7109
7110void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7111 LangAS ImplAS = LangAS::opencl_private;
7112 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7113 // __opencl_c_program_scope_global_variables feature, the address space
7114 // for a variable at program scope or a static or extern variable inside
7115 // a function are inferred to be __global.
7116 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7117 Var->hasGlobalStorage())
7118 ImplAS = LangAS::opencl_global;
7119 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7120}
7121
7122static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7123 // 'weak' only applies to declarations with external linkage.
7124 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7125 if (!ND.isExternallyVisible()) {
7126 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7127 ND.dropAttr<WeakAttr>();
7128 }
7129 }
7130}
7131
7132static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7133 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7134 if (ND.isExternallyVisible()) {
7135 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7136 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7137 }
7138 }
7139}
7140
7141static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7142 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7143 if (VD->hasInit()) {
7144 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7145 assert(VD->isThisDeclarationADefinition() &&
7146 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7147 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7148 VD->dropAttr<AliasAttr>();
7149 }
7150 }
7151 }
7152}
7153
7154static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7155 // 'selectany' only applies to externally visible variable declarations.
7156 // It does not apply to functions.
7157 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7158 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7159 S.Diag(Loc: Attr->getLocation(),
7160 DiagID: diag::err_attribute_selectany_non_extern_data);
7161 ND.dropAttr<SelectAnyAttr>();
7162 }
7163 }
7164}
7165
7166static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7167 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7168 if (!ND.isExternallyVisible())
7169 S.Diag(Loc: Attr->getLocation(),
7170 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7171 }
7172}
7173
7174static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7175 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7176 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7177 bool IsAnonymousNS = false;
7178 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7179 if (VD) {
7180 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7181 while (NS && !IsAnonymousNS) {
7182 IsAnonymousNS = NS->isAnonymousNamespace();
7183 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7184 }
7185 }
7186 // dll attributes require external linkage. Static locals may have external
7187 // linkage but still cannot be explicitly imported or exported.
7188 // In Microsoft mode, a variable defined in anonymous namespace must have
7189 // external linkage in order to be exported.
7190 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7191 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7192 (!AnonNSInMicrosoftMode &&
7193 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7194 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7195 << &ND << Attr;
7196 ND.setInvalidDecl();
7197 }
7198 }
7199}
7200
7201static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7202 // Check the attributes on the function type and function params, if any.
7203 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7204 FD = FD->getMostRecentDecl();
7205 // Don't declare this variable in the second operand of the for-statement;
7206 // GCC miscompiles that by ending its lifetime before evaluating the
7207 // third operand. See gcc.gnu.org/PR86769.
7208 AttributedTypeLoc ATL;
7209 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7210 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7211 TL = ATL.getModifiedLoc()) {
7212 // The [[lifetimebound]] attribute can be applied to the implicit object
7213 // parameter of a non-static member function (other than a ctor or dtor)
7214 // by applying it to the function type.
7215 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7216 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7217 int NoImplicitObjectError = -1;
7218 if (!MD)
7219 NoImplicitObjectError = 0;
7220 else if (MD->isStatic())
7221 NoImplicitObjectError = 1;
7222 else if (MD->isExplicitObjectMemberFunction())
7223 NoImplicitObjectError = 2;
7224 if (NoImplicitObjectError != -1) {
7225 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7226 << NoImplicitObjectError << A->getRange();
7227 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7228 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7229 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7230 } else if (MD->getReturnType()->isVoidType()) {
7231 S.Diag(
7232 Loc: MD->getLocation(),
7233 DiagID: diag::
7234 err_lifetimebound_implicit_object_parameter_void_return_type);
7235 }
7236 }
7237 }
7238
7239 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7240 const ParmVarDecl *P = FD->getParamDecl(i: I);
7241
7242 // The [[lifetimebound]] attribute can be applied to a function parameter
7243 // only if the function returns a value.
7244 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7245 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7246 S.Diag(Loc: A->getLocation(),
7247 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7248 }
7249 }
7250 }
7251 }
7252}
7253
7254static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7255 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7256 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7257}
7258
7259static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7260 // Ensure that an auto decl is deduced otherwise the checks below might cache
7261 // the wrong linkage.
7262 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7263
7264 checkWeakAttr(S, ND);
7265 checkWeakRefAttr(S, ND);
7266 checkAliasAttr(S, ND);
7267 checkSelectAnyAttr(S, ND);
7268 checkHybridPatchableAttr(S, ND);
7269 checkInheritableAttr(S, ND);
7270 checkLifetimeBoundAttr(S, ND);
7271}
7272
7273static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7274 NamedDecl *NewDecl,
7275 bool IsSpecialization,
7276 bool IsDefinition) {
7277 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7278 return;
7279
7280 bool IsTemplate = false;
7281 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7282 OldDecl = OldTD->getTemplatedDecl();
7283 IsTemplate = true;
7284 if (!IsSpecialization)
7285 IsDefinition = false;
7286 }
7287 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7288 NewDecl = NewTD->getTemplatedDecl();
7289 IsTemplate = true;
7290 }
7291
7292 if (!OldDecl || !NewDecl)
7293 return;
7294
7295 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7296 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7297 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7298 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7299
7300 // dllimport and dllexport are inheritable attributes so we have to exclude
7301 // inherited attribute instances.
7302 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7303 (NewExportAttr && !NewExportAttr->isInherited());
7304
7305 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7306 // the only exception being explicit specializations.
7307 // Implicitly generated declarations are also excluded for now because there
7308 // is no other way to switch these to use dllimport or dllexport.
7309 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7310
7311 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7312 // Allow with a warning for free functions and global variables.
7313 bool JustWarn = false;
7314 if (!OldDecl->isCXXClassMember()) {
7315 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7316 if (VD && !VD->getDescribedVarTemplate())
7317 JustWarn = true;
7318 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7319 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7320 JustWarn = true;
7321 }
7322
7323 // We cannot change a declaration that's been used because IR has already
7324 // been emitted. Dllimported functions will still work though (modulo
7325 // address equality) as they can use the thunk.
7326 if (OldDecl->isUsed())
7327 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7328 JustWarn = false;
7329
7330 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7331 : diag::err_attribute_dll_redeclaration;
7332 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7333 << NewDecl
7334 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7335 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7336 if (!JustWarn) {
7337 NewDecl->setInvalidDecl();
7338 return;
7339 }
7340 }
7341
7342 // A redeclaration is not allowed to drop a dllimport attribute, the only
7343 // exceptions being inline function definitions (except for function
7344 // templates), local extern declarations, qualified friend declarations or
7345 // special MSVC extension: in the last case, the declaration is treated as if
7346 // it were marked dllexport.
7347 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7348 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7349 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7350 // Ignore static data because out-of-line definitions are diagnosed
7351 // separately.
7352 IsStaticDataMember = VD->isStaticDataMember();
7353 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7354 VarDecl::DeclarationOnly;
7355 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7356 IsInline = FD->isInlined();
7357 IsQualifiedFriend = FD->getQualifier() &&
7358 FD->getFriendObjectKind() == Decl::FOK_Declared;
7359 }
7360
7361 if (OldImportAttr && !HasNewAttr &&
7362 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7363 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7364 if (IsMicrosoftABI && IsDefinition) {
7365 if (IsSpecialization) {
7366 S.Diag(
7367 Loc: NewDecl->getLocation(),
7368 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7369 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7370 NewDecl->dropAttr<DLLImportAttr>();
7371 } else {
7372 S.Diag(Loc: NewDecl->getLocation(),
7373 DiagID: diag::warn_redeclaration_without_import_attribute)
7374 << NewDecl;
7375 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7376 NewDecl->dropAttr<DLLImportAttr>();
7377 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7378 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7379 }
7380 } else if (IsMicrosoftABI && IsSpecialization) {
7381 assert(!IsDefinition);
7382 // MSVC allows this. Keep the inherited attribute.
7383 } else {
7384 S.Diag(Loc: NewDecl->getLocation(),
7385 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7386 << NewDecl << OldImportAttr;
7387 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7388 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7389 OldDecl->dropAttr<DLLImportAttr>();
7390 NewDecl->dropAttr<DLLImportAttr>();
7391 }
7392 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7393 // In MinGW, seeing a function declared inline drops the dllimport
7394 // attribute.
7395 OldDecl->dropAttr<DLLImportAttr>();
7396 NewDecl->dropAttr<DLLImportAttr>();
7397 S.Diag(Loc: NewDecl->getLocation(),
7398 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7399 << NewDecl << OldImportAttr;
7400 }
7401
7402 // A specialization of a class template member function is processed here
7403 // since it's a redeclaration. If the parent class is dllexport, the
7404 // specialization inherits that attribute. This doesn't happen automatically
7405 // since the parent class isn't instantiated until later.
7406 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7407 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7408 !NewImportAttr && !NewExportAttr) {
7409 if (const DLLExportAttr *ParentExportAttr =
7410 MD->getParent()->getAttr<DLLExportAttr>()) {
7411 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7412 NewAttr->setInherited(true);
7413 NewDecl->addAttr(A: NewAttr);
7414 }
7415 }
7416 }
7417}
7418
7419/// Given that we are within the definition of the given function,
7420/// will that definition behave like C99's 'inline', where the
7421/// definition is discarded except for optimization purposes?
7422static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7423 // Try to avoid calling GetGVALinkageForFunction.
7424
7425 // All cases of this require the 'inline' keyword.
7426 if (!FD->isInlined()) return false;
7427
7428 // This is only possible in C++ with the gnu_inline attribute.
7429 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7430 return false;
7431
7432 // Okay, go ahead and call the relatively-more-expensive function.
7433 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7434}
7435
7436/// Determine whether a variable is extern "C" prior to attaching
7437/// an initializer. We can't just call isExternC() here, because that
7438/// will also compute and cache whether the declaration is externally
7439/// visible, which might change when we attach the initializer.
7440///
7441/// This can only be used if the declaration is known to not be a
7442/// redeclaration of an internal linkage declaration.
7443///
7444/// For instance:
7445///
7446/// auto x = []{};
7447///
7448/// Attaching the initializer here makes this declaration not externally
7449/// visible, because its type has internal linkage.
7450///
7451/// FIXME: This is a hack.
7452template<typename T>
7453static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7454 if (S.getLangOpts().CPlusPlus) {
7455 // In C++, the overloadable attribute negates the effects of extern "C".
7456 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7457 return false;
7458
7459 // So do CUDA's host/device attributes.
7460 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7461 D->template hasAttr<CUDAHostAttr>()))
7462 return false;
7463 }
7464 return D->isExternC();
7465}
7466
7467static bool shouldConsiderLinkage(const VarDecl *VD) {
7468 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7469 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7470 isa<OMPDeclareMapperDecl>(Val: DC))
7471 return VD->hasExternalStorage();
7472 if (DC->isFileContext())
7473 return true;
7474 if (DC->isRecord())
7475 return false;
7476 if (DC->getDeclKind() == Decl::HLSLBuffer)
7477 return false;
7478
7479 if (isa<RequiresExprBodyDecl, CXXExpansionStmtDecl>(Val: DC))
7480 return false;
7481 llvm_unreachable("Unexpected context");
7482}
7483
7484static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7485 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7486 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7487 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7488 return true;
7489 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(Val: DC))
7490 return false;
7491 llvm_unreachable("Unexpected context");
7492}
7493
7494static bool hasParsedAttr(Scope *S, const Declarator &PD,
7495 ParsedAttr::Kind Kind) {
7496 // Check decl attributes on the DeclSpec.
7497 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7498 return true;
7499
7500 // Walk the declarator structure, checking decl attributes that were in a type
7501 // position to the decl itself.
7502 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7503 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7504 return true;
7505 }
7506
7507 // Finally, check attributes on the decl itself.
7508 return PD.getAttributes().hasAttribute(K: Kind) ||
7509 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7510}
7511
7512bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7513 if (!DC->isFunctionOrMethod())
7514 return false;
7515
7516 // If this is a local extern function or variable declared within a function
7517 // template, don't add it into the enclosing namespace scope until it is
7518 // instantiated; it might have a dependent type right now.
7519 if (DC->isDependentContext())
7520 return true;
7521
7522 // C++11 [basic.link]p7:
7523 // When a block scope declaration of an entity with linkage is not found to
7524 // refer to some other declaration, then that entity is a member of the
7525 // innermost enclosing namespace.
7526 //
7527 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7528 // semantically-enclosing namespace, not a lexically-enclosing one.
7529 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7530 DC = DC->getParent();
7531 return true;
7532}
7533
7534/// Returns true if given declaration has external C language linkage.
7535static bool isDeclExternC(const Decl *D) {
7536 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7537 return FD->isExternC();
7538 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7539 return VD->isExternC();
7540
7541 llvm_unreachable("Unknown type of decl!");
7542}
7543
7544/// Returns true if there hasn't been any invalid type diagnosed.
7545static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7546 DeclContext *DC = NewVD->getDeclContext();
7547 QualType R = NewVD->getType();
7548
7549 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7550 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7551 // argument.
7552 if (R->isImageType() || R->isPipeType()) {
7553 Se.Diag(Loc: NewVD->getLocation(),
7554 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7555 << R;
7556 NewVD->setInvalidDecl();
7557 return false;
7558 }
7559
7560 // OpenCL v1.2 s6.9.r:
7561 // The event type cannot be used to declare a program scope variable.
7562 // OpenCL v2.0 s6.9.q:
7563 // The clk_event_t and reserve_id_t types cannot be declared in program
7564 // scope.
7565 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7566 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7567 Se.Diag(Loc: NewVD->getLocation(),
7568 DiagID: diag::err_invalid_type_for_program_scope_var)
7569 << R;
7570 NewVD->setInvalidDecl();
7571 return false;
7572 }
7573 }
7574
7575 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7576 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7577 LO: Se.getLangOpts())) {
7578 QualType NR = R.getCanonicalType();
7579 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7580 NR->isReferenceType()) {
7581 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7582 NR->isFunctionReferenceType()) {
7583 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7584 << NR->isReferenceType();
7585 NewVD->setInvalidDecl();
7586 return false;
7587 }
7588 NR = NR->getPointeeType();
7589 }
7590 }
7591
7592 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7593 LO: Se.getLangOpts())) {
7594 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7595 // half array type (unless the cl_khr_fp16 extension is enabled).
7596 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7597 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7598 NewVD->setInvalidDecl();
7599 return false;
7600 }
7601 }
7602
7603 // OpenCL v1.2 s6.9.r:
7604 // The event type cannot be used with the __local, __constant and __global
7605 // address space qualifiers.
7606 if (R->isEventT()) {
7607 if (R.getAddressSpace() != LangAS::opencl_private) {
7608 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7609 NewVD->setInvalidDecl();
7610 return false;
7611 }
7612 }
7613
7614 if (R->isSamplerT()) {
7615 // OpenCL v1.2 s6.9.b p4:
7616 // The sampler type cannot be used with the __local and __global address
7617 // space qualifiers.
7618 if (R.getAddressSpace() == LangAS::opencl_local ||
7619 R.getAddressSpace() == LangAS::opencl_global) {
7620 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7621 NewVD->setInvalidDecl();
7622 }
7623
7624 // OpenCL v1.2 s6.12.14.1:
7625 // A global sampler must be declared with either the constant address
7626 // space qualifier or with the const qualifier.
7627 if (DC->isTranslationUnit() &&
7628 !(R.getAddressSpace() == LangAS::opencl_constant ||
7629 R.isConstQualified())) {
7630 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7631 NewVD->setInvalidDecl();
7632 }
7633 if (NewVD->isInvalidDecl())
7634 return false;
7635 }
7636
7637 return true;
7638}
7639
7640template <typename AttrTy>
7641static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7642 const TypedefNameDecl *TND = TT->getDecl();
7643 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7644 AttrTy *Clone = Attribute->clone(S.Context);
7645 Clone->setInherited(true);
7646 D->addAttr(A: Clone);
7647 }
7648}
7649
7650// This function emits warning and a corresponding note based on the
7651// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7652// declarations of an annotated type must be const qualified.
7653static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7654 QualType VarType = VD->getType().getCanonicalType();
7655
7656 // Ignore local declarations (for now) and those with const qualification.
7657 // TODO: Local variables should not be allowed if their type declaration has
7658 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7659 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7660 return;
7661
7662 if (VarType->isArrayType()) {
7663 // Retrieve element type for array declarations.
7664 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7665 }
7666
7667 const RecordDecl *RD = VarType->getAsRecordDecl();
7668
7669 // Check if the record declaration is present and if it has any attributes.
7670 if (RD == nullptr)
7671 return;
7672
7673 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7674 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7675 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7676 return;
7677 }
7678}
7679
7680void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7681 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7682 "NewD is not a function or variable");
7683
7684 if (PendingExportedNames.empty())
7685 return;
7686 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7687 if (getLangOpts().CPlusPlus && !FD->isExternC())
7688 return;
7689 }
7690 IdentifierInfo *IdentName = NewD->getIdentifier();
7691 if (IdentName == nullptr)
7692 return;
7693 auto PendingName = PendingExportedNames.find(Val: IdentName);
7694 if (PendingName != PendingExportedNames.end()) {
7695 auto &Label = PendingName->second;
7696 if (!Label.Used) {
7697 Label.Used = true;
7698 if (NewD->hasExternalFormalLinkage())
7699 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7700 else
7701 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7702 }
7703 }
7704}
7705
7706// Checks if VD is declared at global scope or with C language linkage.
7707static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7708 return Name.getAsIdentifierInfo() &&
7709 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7710 !VD->getDescribedVarTemplate() &&
7711 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7712 VD->isExternC());
7713}
7714
7715void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7716 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7717
7718 // Quickly return if the function does not have an `asm` attribute.
7719 if (E == nullptr)
7720 return;
7721
7722 // The parser guarantees this is a string.
7723 StringLiteral *SE = cast<StringLiteral>(Val: E);
7724 StringRef Label = SE->getString();
7725 QualType R = TInfo->getType();
7726 if (S->getFnParent() != nullptr) {
7727 switch (SC) {
7728 case SC_None:
7729 case SC_Auto:
7730 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7731 break;
7732 case SC_Register:
7733 // Local Named register
7734 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7735 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7736 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7737 break;
7738 case SC_Static:
7739 case SC_Extern:
7740 case SC_PrivateExtern:
7741 break;
7742 }
7743 } else if (SC == SC_Register) {
7744 // Global Named register
7745 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7746 const auto &TI = Context.getTargetInfo();
7747 bool HasSizeMismatch;
7748
7749 if (!TI.isValidGCCRegisterName(Name: Label))
7750 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7751 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7752 HasSizeMismatch))
7753 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7754 else if (HasSizeMismatch)
7755 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7756 }
7757
7758 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7759 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7760 DiagID: diag::err_asm_unsupported_register_type)
7761 << TInfo->getTypeLoc().getSourceRange();
7762 NewVD->setInvalidDecl(true);
7763 }
7764 }
7765}
7766
7767NamedDecl *Sema::ActOnVariableDeclarator(
7768 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7769 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7770 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7771 QualType R = TInfo->getType();
7772 DeclarationName Name = GetNameForDeclarator(D).getName();
7773
7774 IdentifierInfo *II = Name.getAsIdentifierInfo();
7775 bool IsPlaceholderVariable = false;
7776
7777 if (D.isDecompositionDeclarator()) {
7778 // Take the name of the first declarator as our name for diagnostic
7779 // purposes.
7780 auto &Decomp = D.getDecompositionDeclarator();
7781 if (!Decomp.bindings().empty()) {
7782 II = Decomp.bindings()[0].Name;
7783 Name = II;
7784 }
7785 } else if (!II) {
7786 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7787 return nullptr;
7788 }
7789
7790
7791 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7792 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7793 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7794 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7795
7796 IsPlaceholderVariable = true;
7797
7798 if (!Previous.empty()) {
7799 NamedDecl *PrevDecl = *Previous.begin();
7800 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7801 DC: DC->getRedeclContext());
7802 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7803 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7804 if (IsPlaceholderVariable)
7805 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7806 }
7807 }
7808 }
7809
7810 // dllimport globals without explicit storage class are treated as extern. We
7811 // have to change the storage class this early to get the right DeclContext.
7812 if (SC == SC_None && !DC->isRecord() &&
7813 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7814 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7815 SC = SC_Extern;
7816
7817 DeclContext *OriginalDC = DC;
7818 bool IsLocalExternDecl = SC == SC_Extern &&
7819 adjustContextForLocalExternDecl(DC);
7820
7821 if (SCSpec == DeclSpec::SCS_mutable) {
7822 // mutable can only appear on non-static class members, so it's always
7823 // an error here
7824 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7825 D.setInvalidType();
7826 SC = SC_None;
7827 }
7828
7829 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7830 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7831 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7832 // In C++11, the 'register' storage class specifier is deprecated.
7833 // Suppress the warning in system macros, it's used in macros in some
7834 // popular C system headers, such as in glibc's htonl() macro.
7835 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7836 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7837 : diag::warn_deprecated_register)
7838 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7839 }
7840
7841 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7842
7843 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7844 // C99 6.9p2: The storage-class specifiers auto and register shall not
7845 // appear in the declaration specifiers in an external declaration.
7846 // Global Register+Asm is a GNU extension we support.
7847 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7848 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7849 D.setInvalidType();
7850 }
7851 }
7852
7853 // If this variable has a VLA type and an initializer, try to
7854 // fold to a constant-sized type. This is otherwise invalid.
7855 if (D.hasInitializer() && R->isVariableArrayType())
7856 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7857 /*DiagID=*/FailedFoldDiagID: 0);
7858
7859 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7860 const AutoType *AT = TL.getTypePtr();
7861 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7862 }
7863
7864 bool IsMemberSpecialization = false;
7865 bool IsVariableTemplateSpecialization = false;
7866 bool IsPartialSpecialization = false;
7867 bool IsVariableTemplate = false;
7868 VarDecl *NewVD = nullptr;
7869 VarTemplateDecl *NewTemplate = nullptr;
7870 TemplateParameterList *TemplateParams = nullptr;
7871 if (!getLangOpts().CPlusPlus) {
7872 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7873 Id: II, T: R, TInfo, S: SC);
7874
7875 if (R->getContainedDeducedType())
7876 ParsingInitForAutoVars.insert(Ptr: NewVD);
7877
7878 if (D.isInvalidType())
7879 NewVD->setInvalidDecl();
7880
7881 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7882 NewVD->hasLocalStorage())
7883 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7884 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7885 } else {
7886 bool Invalid = false;
7887 // Match up the template parameter lists with the scope specifier, then
7888 // determine whether we have a template or a template specialization.
7889 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7890 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7891 SS: D.getCXXScopeSpec(),
7892 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7893 ? D.getName().TemplateId
7894 : nullptr,
7895 ParamLists: TemplateParamLists,
7896 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7897
7898 if (TemplateParams) {
7899 if (DC->isDependentContext()) {
7900 ContextRAII SavedContext(*this, DC);
7901 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7902 Invalid = true;
7903 }
7904
7905 if (!TemplateParams->size() &&
7906 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7907 // There is an extraneous 'template<>' for this variable. Complain
7908 // about it, but allow the declaration of the variable.
7909 Diag(Loc: TemplateParams->getTemplateLoc(),
7910 DiagID: diag::err_template_variable_noparams)
7911 << II
7912 << SourceRange(TemplateParams->getTemplateLoc(),
7913 TemplateParams->getRAngleLoc());
7914 TemplateParams = nullptr;
7915 } else {
7916 // Check that we can declare a template here.
7917 if (CheckTemplateDeclScope(S, TemplateParams))
7918 return nullptr;
7919
7920 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7921 // This is an explicit specialization or a partial specialization.
7922 IsVariableTemplateSpecialization = true;
7923 IsPartialSpecialization = TemplateParams->size() > 0;
7924 } else { // if (TemplateParams->size() > 0)
7925 // This is a template declaration.
7926 IsVariableTemplate = true;
7927
7928 // Only C++1y supports variable templates (N3651).
7929 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7930 }
7931 }
7932 } else {
7933 // Check that we can declare a member specialization here.
7934 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7935 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7936 return nullptr;
7937 assert((Invalid ||
7938 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7939 "should have a 'template<>' for this decl");
7940 }
7941
7942 bool IsExplicitSpecialization =
7943 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7944
7945 // C++ [temp.expl.spec]p2:
7946 // The declaration in an explicit-specialization shall not be an
7947 // export-declaration. An explicit specialization shall not use a
7948 // storage-class-specifier other than thread_local.
7949 //
7950 // We use the storage-class-specifier from DeclSpec because we may have
7951 // added implicit 'extern' for declarations with __declspec(dllimport)!
7952 if (SCSpec != DeclSpec::SCS_unspecified &&
7953 (IsExplicitSpecialization || IsMemberSpecialization)) {
7954 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7955 DiagID: diag::ext_explicit_specialization_storage_class)
7956 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7957 }
7958
7959 if (CurContext->isRecord()) {
7960 if (SC == SC_Static) {
7961 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7962 // Walk up the enclosing DeclContexts to check for any that are
7963 // incompatible with static data members.
7964 const DeclContext *FunctionOrMethod = nullptr;
7965 const CXXRecordDecl *AnonStruct = nullptr;
7966 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7967 if (Ctxt->isFunctionOrMethod()) {
7968 FunctionOrMethod = Ctxt;
7969 break;
7970 }
7971 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7972 if (ParentDecl && !ParentDecl->getDeclName()) {
7973 AnonStruct = ParentDecl;
7974 break;
7975 }
7976 }
7977 if (FunctionOrMethod) {
7978 // C++ [class.static.data]p5: A local class shall not have static
7979 // data members.
7980 Diag(Loc: D.getIdentifierLoc(),
7981 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7982 << Name << RD->getDeclName() << RD->getTagKind();
7983 Invalid = true;
7984 } else if (AnonStruct) {
7985 // C++ [class.static.data]p4: Unnamed classes and classes contained
7986 // directly or indirectly within unnamed classes shall not contain
7987 // static data members.
7988 Diag(Loc: D.getIdentifierLoc(),
7989 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7990 << Name << AnonStruct->getTagKind();
7991 Invalid = true;
7992 } else if (RD->isUnion()) {
7993 // C++98 [class.union]p1: If a union contains a static data member,
7994 // the program is ill-formed. C++11 drops this restriction.
7995 DiagCompat(Loc: D.getIdentifierLoc(),
7996 CompatDiagId: diag_compat::static_data_member_in_union)
7997 << Name;
7998 }
7999 }
8000 } else if (IsVariableTemplate || IsPartialSpecialization) {
8001 // There is no such thing as a member field template.
8002 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
8003 << II << TemplateParams->getSourceRange();
8004 // Recover by pretending this is a static data member template.
8005 SC = SC_Static;
8006 }
8007 } else if (DC->isRecord()) {
8008 // This is an out-of-line definition of a static data member.
8009 switch (SC) {
8010 case SC_None:
8011 break;
8012 case SC_Static:
8013 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8014 DiagID: diag::err_static_out_of_line)
8015 << FixItHint::CreateRemoval(
8016 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8017 break;
8018 case SC_Auto:
8019 case SC_Register:
8020 case SC_Extern:
8021 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8022 // to names of variables declared in a block or to function parameters.
8023 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8024 // of class members
8025
8026 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8027 DiagID: diag::err_storage_class_for_static_member)
8028 << FixItHint::CreateRemoval(
8029 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8030 break;
8031 case SC_PrivateExtern:
8032 llvm_unreachable("C storage class in c++!");
8033 }
8034 }
8035
8036 if (IsVariableTemplateSpecialization) {
8037 SourceLocation TemplateKWLoc =
8038 TemplateParamLists.size() > 0
8039 ? TemplateParamLists[0]->getTemplateLoc()
8040 : SourceLocation();
8041 DeclResult Res = ActOnVarTemplateSpecialization(
8042 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8043 IsPartialSpecialization);
8044 if (Res.isInvalid())
8045 return nullptr;
8046 NewVD = cast<VarDecl>(Val: Res.get());
8047 AddToScope = false;
8048 } else if (D.isDecompositionDeclarator()) {
8049 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8050 LSquareLoc: D.getIdentifierLoc(), RSquareLoc: D.getEndLoc(), T: R,
8051 TInfo, S: SC, Bindings);
8052 } else
8053 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8054 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8055
8056 // If this is supposed to be a variable template, create it as such.
8057 if (IsVariableTemplate) {
8058 NewTemplate =
8059 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8060 Params: TemplateParams, Decl: NewVD);
8061 NewVD->setDescribedVarTemplate(NewTemplate);
8062 }
8063
8064 // If this decl has an auto type in need of deduction, make a note of the
8065 // Decl so we can diagnose uses of it in its own initializer.
8066 if (R->getContainedDeducedType())
8067 ParsingInitForAutoVars.insert(Ptr: NewVD);
8068
8069 if (D.isInvalidType() || Invalid) {
8070 NewVD->setInvalidDecl();
8071 if (NewTemplate)
8072 NewTemplate->setInvalidDecl();
8073 }
8074
8075 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8076
8077 // If we have any template parameter lists that don't directly belong to
8078 // the variable (matching the scope specifier), store them.
8079 // An explicit variable template specialization does not own any template
8080 // parameter lists.
8081 unsigned VDTemplateParamLists =
8082 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8083 if (TemplateParamLists.size() > VDTemplateParamLists)
8084 NewVD->setTemplateParameterListsInfo(
8085 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8086 }
8087
8088 if (D.getDeclSpec().isInlineSpecified()) {
8089 if (!getLangOpts().CPlusPlus) {
8090 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8091 << 0;
8092 } else if (CurContext->isFunctionOrMethod()) {
8093 // 'inline' is not allowed on block scope variable declaration.
8094 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8095 DiagID: diag::err_inline_declaration_block_scope) << Name
8096 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8097 } else {
8098 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8099 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8100 : diag::compat_pre_cxx17_inline_variable);
8101 NewVD->setInlineSpecified();
8102 }
8103 }
8104
8105 // Set the lexical context. If the declarator has a C++ scope specifier, the
8106 // lexical context will be different from the semantic context.
8107 NewVD->setLexicalDeclContext(CurContext);
8108 if (NewTemplate)
8109 NewTemplate->setLexicalDeclContext(CurContext);
8110
8111 if (IsLocalExternDecl) {
8112 if (D.isDecompositionDeclarator())
8113 for (auto *B : Bindings)
8114 B->setLocalExternDecl();
8115 else
8116 NewVD->setLocalExternDecl();
8117 }
8118
8119 bool EmitTLSUnsupportedError = false;
8120 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8121 // C++11 [dcl.stc]p4:
8122 // When thread_local is applied to a variable of block scope the
8123 // storage-class-specifier static is implied if it does not appear
8124 // explicitly.
8125 // Core issue: 'static' is not implied if the variable is declared
8126 // 'extern'.
8127 if (NewVD->hasLocalStorage() &&
8128 (SCSpec != DeclSpec::SCS_unspecified ||
8129 TSCS != DeclSpec::TSCS_thread_local ||
8130 !DC->isFunctionOrMethod()))
8131 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8132 DiagID: diag::err_thread_non_global)
8133 << DeclSpec::getSpecifierName(S: TSCS);
8134 else if (!Context.getTargetInfo().isTLSSupported()) {
8135 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8136 // Postpone error emission until we've collected attributes required to
8137 // figure out whether it's a host or device variable and whether the
8138 // error should be ignored.
8139 EmitTLSUnsupportedError = true;
8140 // We still need to mark the variable as TLS so it shows up in AST with
8141 // proper storage class for other tools to use even if we're not going
8142 // to emit any code for it.
8143 NewVD->setTSCSpec(TSCS);
8144 } else
8145 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8146 DiagID: diag::err_thread_unsupported);
8147 } else
8148 NewVD->setTSCSpec(TSCS);
8149 }
8150
8151 switch (D.getDeclSpec().getConstexprSpecifier()) {
8152 case ConstexprSpecKind::Unspecified:
8153 break;
8154
8155 case ConstexprSpecKind::Consteval:
8156 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8157 DiagID: diag::err_constexpr_wrong_decl_kind)
8158 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8159 [[fallthrough]];
8160
8161 case ConstexprSpecKind::Constexpr:
8162 NewVD->setConstexpr(true);
8163 // C++1z [dcl.spec.constexpr]p1:
8164 // A static data member declared with the constexpr specifier is
8165 // implicitly an inline variable.
8166 if (NewVD->isStaticDataMember() &&
8167 (getLangOpts().CPlusPlus17 ||
8168 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8169 NewVD->setImplicitlyInline();
8170 break;
8171
8172 case ConstexprSpecKind::Constinit:
8173 if (!NewVD->hasGlobalStorage())
8174 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8175 DiagID: diag::err_constinit_local_variable);
8176 else
8177 NewVD->addAttr(
8178 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8179 S: ConstInitAttr::Keyword_constinit));
8180 break;
8181 }
8182
8183 // C99 6.7.4p3
8184 // An inline definition of a function with external linkage shall
8185 // not contain a definition of a modifiable object with static or
8186 // thread storage duration...
8187 // We only apply this when the function is required to be defined
8188 // elsewhere, i.e. when the function is not 'extern inline'. Note
8189 // that a local variable with thread storage duration still has to
8190 // be marked 'static'. Also note that it's possible to get these
8191 // semantics in C++ using __attribute__((gnu_inline)).
8192 if (SC == SC_Static && S->getFnParent() != nullptr &&
8193 !NewVD->getType().isConstQualified()) {
8194 FunctionDecl *CurFD = getCurFunctionDecl();
8195 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8196 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8197 DiagID: diag::warn_static_local_in_extern_inline);
8198 MaybeSuggestAddingStaticToDecl(D: CurFD);
8199 }
8200 }
8201
8202 if (D.getDeclSpec().isModulePrivateSpecified()) {
8203 if (IsVariableTemplateSpecialization)
8204 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8205 << (IsPartialSpecialization ? 1 : 0)
8206 << FixItHint::CreateRemoval(
8207 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8208 else if (IsMemberSpecialization)
8209 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8210 << 2
8211 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8212 else if (NewVD->hasLocalStorage())
8213 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8214 << 0 << NewVD
8215 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8216 << FixItHint::CreateRemoval(
8217 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8218 else {
8219 NewVD->setModulePrivate();
8220 if (NewTemplate)
8221 NewTemplate->setModulePrivate();
8222 for (auto *B : Bindings)
8223 B->setModulePrivate();
8224 }
8225 }
8226
8227 if (getLangOpts().OpenCL) {
8228 deduceOpenCLAddressSpace(Var: NewVD);
8229
8230 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8231 if (TSC != TSCS_unspecified) {
8232 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8233 DiagID: diag::err_opencl_unknown_type_specifier)
8234 << getLangOpts().getOpenCLVersionString()
8235 << DeclSpec::getSpecifierName(S: TSC) << 1;
8236 NewVD->setInvalidDecl();
8237 }
8238 }
8239
8240 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8241 // address space if the table has local storage (semantic checks elsewhere
8242 // will produce an error anyway).
8243 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8244 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8245 !NewVD->hasLocalStorage()) {
8246 QualType Type = Context.getAddrSpaceQualType(
8247 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8248 NewVD->setType(Type);
8249 }
8250 }
8251
8252 LoadExternalExtnameUndeclaredIdentifiers();
8253
8254 if (Expr *E = D.getAsmLabel()) {
8255 // The parser guarantees this is a string.
8256 StringLiteral *SE = cast<StringLiteral>(Val: E);
8257 StringRef Label = SE->getString();
8258
8259 // Insert the asm attribute.
8260 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8261 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8262 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8263 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8264 if (I != ExtnameUndeclaredIdentifiers.end()) {
8265 if (isDeclExternC(D: NewVD)) {
8266 NewVD->addAttr(A: I->second);
8267 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8268 } else if (NewVD->getDeclContext()
8269 ->getRedeclContext()
8270 ->isTranslationUnit())
8271 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8272 << /*Variable*/ 1 << NewVD;
8273 }
8274 }
8275
8276 // Handle attributes prior to checking for duplicates in MergeVarDecl
8277 ProcessDeclAttributes(S, D: NewVD, PD: D);
8278
8279 if (getLangOpts().HLSL)
8280 HLSL().ActOnVariableDeclarator(VD: NewVD);
8281
8282 if (getLangOpts().OpenACC)
8283 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8284
8285 // FIXME: This is probably the wrong location to be doing this and we should
8286 // probably be doing this for more attributes (especially for function
8287 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8288 // the code to copy attributes would be generated by TableGen.
8289 if (R->isFunctionPointerType())
8290 if (const auto *TT = R->getAs<TypedefType>())
8291 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8292
8293 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8294 if (EmitTLSUnsupportedError &&
8295 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8296 (getLangOpts().OpenMPIsTargetDevice &&
8297 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8298 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8299 DiagID: diag::err_thread_unsupported);
8300
8301 if (EmitTLSUnsupportedError &&
8302 (LangOpts.SYCLIsDevice ||
8303 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8304 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8305 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8306 // storage [duration]."
8307 if (SC == SC_None && S->getFnParent() != nullptr &&
8308 (NewVD->hasAttr<CUDASharedAttr>() ||
8309 NewVD->hasAttr<CUDAConstantAttr>())) {
8310 NewVD->setStorageClass(SC_Static);
8311 }
8312 }
8313
8314 // Ensure that dllimport globals without explicit storage class are treated as
8315 // extern. The storage class is set above using parsed attributes. Now we can
8316 // check the VarDecl itself.
8317 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8318 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8319 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8320
8321 // In auto-retain/release, infer strong retension for variables of
8322 // retainable type.
8323 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8324 NewVD->setInvalidDecl();
8325
8326 // Check the ASM label here, as we need to know all other attributes of the
8327 // Decl first. Otherwise, we can't know if the asm label refers to the
8328 // host or device in a CUDA context. The device has other registers than
8329 // host and we must know where the function will be placed.
8330 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8331
8332 // Find the shadowed declaration before filtering for scope.
8333 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8334 ? getShadowedDeclaration(D: NewVD, R: Previous)
8335 : nullptr;
8336
8337 // Don't consider existing declarations that are in a different
8338 // scope and are out-of-semantic-context declarations (if the new
8339 // declaration has linkage).
8340 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8341 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8342 IsMemberSpecialization ||
8343 IsVariableTemplateSpecialization);
8344
8345 // Check whether the previous declaration is in the same block scope. This
8346 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8347 if (getLangOpts().CPlusPlus &&
8348 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8349 NewVD->setPreviousDeclInSameBlockScope(
8350 Previous.isSingleResult() && !Previous.isShadowed() &&
8351 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8352
8353 if (!getLangOpts().CPlusPlus) {
8354 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8355 } else {
8356 // If this is an explicit specialization of a static data member, check it.
8357 if (IsMemberSpecialization && !IsVariableTemplate &&
8358 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8359 CheckMemberSpecialization(Member: NewVD, Previous))
8360 NewVD->setInvalidDecl();
8361
8362 // Merge the decl with the existing one if appropriate.
8363 if (!Previous.empty()) {
8364 if (Previous.isSingleResult() &&
8365 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8366 D.getCXXScopeSpec().isSet()) {
8367 // The user tried to define a non-static data member
8368 // out-of-line (C++ [dcl.meaning]p1).
8369 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8370 << D.getCXXScopeSpec().getRange();
8371 Previous.clear();
8372 NewVD->setInvalidDecl();
8373 }
8374 } else if (D.getCXXScopeSpec().isSet() &&
8375 !IsVariableTemplateSpecialization) {
8376 // No previous declaration in the qualifying scope.
8377 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8378 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8379 << D.getCXXScopeSpec().getRange();
8380 NewVD->setInvalidDecl();
8381
8382 // if this is a member specialization, we don't have any primary template
8383 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8384 // that anything that attempts to refer to this invalid declaration can
8385 // act as if there IS a primary instantiation.
8386 if (NewTemplate && IsMemberSpecialization) {
8387 VarDecl *FakeVD =
8388 VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
8389 Id: II, T: R, TInfo, S: SC);
8390 FakeVD->setInvalidDecl();
8391 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8392 C&: Context, DC, L: D.getIdentifierLoc(), Name, Params: TemplateParams, Decl: FakeVD);
8393 FakeInstantiatedFrom->setInvalidDecl();
8394 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8395 }
8396 }
8397
8398 if (!IsPlaceholderVariable)
8399 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8400
8401 // CheckVariableDeclaration will set NewVD as invalid if something is in
8402 // error like WebAssembly tables being declared as arrays with a non-zero
8403 // size, but then parsing continues and emits further errors on that line.
8404 // To avoid that we check here if it happened and return nullptr.
8405 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8406 return nullptr;
8407
8408 if (NewTemplate) {
8409 VarTemplateDecl *PrevVarTemplate =
8410 NewVD->getPreviousDecl()
8411 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8412 : nullptr;
8413
8414 // Check the template parameter list of this declaration, possibly
8415 // merging in the template parameter list from the previous variable
8416 // template declaration.
8417 if (CheckTemplateParameterList(
8418 NewParams: TemplateParams,
8419 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8420 : nullptr,
8421 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8422 DC->isDependentContext())
8423 ? TPC_ClassTemplateMember
8424 : TPC_Other))
8425 NewVD->setInvalidDecl();
8426 }
8427 }
8428
8429 if (IsMemberSpecialization) {
8430 if (NewTemplate && NewVD->getPreviousDecl()) {
8431 NewTemplate->setMemberSpecialization();
8432 } else if (IsPartialSpecialization) {
8433 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8434 ->setMemberSpecialization();
8435 }
8436 }
8437
8438 // Diagnose shadowed variables iff this isn't a redeclaration.
8439 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8440 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8441
8442 ProcessPragmaWeak(S, D: NewVD);
8443 ProcessPragmaExport(NewD: NewVD);
8444
8445 // If this is the first declaration of an extern C variable, update
8446 // the map of such variables.
8447 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8448 isIncompleteDeclExternC(S&: *this, D: NewVD))
8449 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8450
8451 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8452 MangleNumberingContext *MCtx;
8453 Decl *ManglingContextDecl;
8454 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8455 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8456 if (MCtx) {
8457 Context.setManglingNumber(
8458 ND: NewVD, Number: MCtx->getManglingNumber(
8459 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8460 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8461 }
8462 }
8463
8464 // Special handling of variable named 'main'.
8465 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8466 // C++ [basic.start.main]p3:
8467 // A program that declares
8468 // - a variable main at global scope, or
8469 // - an entity named main with C language linkage (in any namespace)
8470 // is ill-formed
8471 if (getLangOpts().CPlusPlus)
8472 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8473 << NewVD->isExternC();
8474
8475 // In C, and external-linkage variable named main results in undefined
8476 // behavior.
8477 else if (NewVD->hasExternalFormalLinkage())
8478 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8479 }
8480
8481 if (D.isRedeclaration() && !Previous.empty()) {
8482 NamedDecl *Prev = Previous.getRepresentativeDecl();
8483 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8484 IsDefinition: D.isFunctionDefinition());
8485 }
8486
8487 if (NewTemplate) {
8488 if (NewVD->isInvalidDecl())
8489 NewTemplate->setInvalidDecl();
8490 ActOnDocumentableDecl(D: NewTemplate);
8491 return NewTemplate;
8492 }
8493
8494 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8495 CompleteMemberSpecialization(Member: NewVD, Previous);
8496
8497 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8498
8499 return NewVD;
8500}
8501
8502/// Enum describing the %select options in diag::warn_decl_shadow.
8503enum ShadowedDeclKind {
8504 SDK_Local,
8505 SDK_Global,
8506 SDK_StaticMember,
8507 SDK_Field,
8508 SDK_Typedef,
8509 SDK_Using,
8510 SDK_StructuredBinding
8511};
8512
8513/// Determine what kind of declaration we're shadowing.
8514static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8515 const DeclContext *OldDC) {
8516 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8517 return SDK_Using;
8518 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8519 return SDK_Typedef;
8520 else if (isa<BindingDecl>(Val: ShadowedDecl))
8521 return SDK_StructuredBinding;
8522 else if (isa<RecordDecl>(Val: OldDC))
8523 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8524
8525 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8526}
8527
8528/// Return the location of the capture if the given lambda captures the given
8529/// variable \p VD, or an invalid source location otherwise.
8530static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8531 const ValueDecl *VD) {
8532 for (const Capture &Capture : LSI->Captures) {
8533 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8534 return Capture.getLocation();
8535 }
8536 return SourceLocation();
8537}
8538
8539static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8540 const LookupResult &R) {
8541 // Only diagnose if we're shadowing an unambiguous field or variable.
8542 if (R.getResultKind() != LookupResultKind::Found)
8543 return false;
8544
8545 // Return false if warning is ignored.
8546 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8547}
8548
8549NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8550 const LookupResult &R) {
8551 if (!shouldWarnIfShadowedDecl(Diags, R))
8552 return nullptr;
8553
8554 // Don't diagnose declarations at file scope.
8555 if (D->hasGlobalStorage() && !D->isStaticLocal())
8556 return nullptr;
8557
8558 NamedDecl *ShadowedDecl = R.getFoundDecl();
8559 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8560 : nullptr;
8561}
8562
8563NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8564 const LookupResult &R) {
8565 // Don't warn if typedef declaration is part of a class
8566 if (D->getDeclContext()->isRecord())
8567 return nullptr;
8568
8569 if (!shouldWarnIfShadowedDecl(Diags, R))
8570 return nullptr;
8571
8572 NamedDecl *ShadowedDecl = R.getFoundDecl();
8573 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8574}
8575
8576NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8577 const LookupResult &R) {
8578 if (!shouldWarnIfShadowedDecl(Diags, R))
8579 return nullptr;
8580
8581 NamedDecl *ShadowedDecl = R.getFoundDecl();
8582 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8583 : nullptr;
8584}
8585
8586void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8587 const LookupResult &R) {
8588 DeclContext *NewDC = D->getDeclContext();
8589
8590 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8591 if (const auto *MD =
8592 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8593 // Fields aren't shadowed in C++ static members or in member functions
8594 // with an explicit object parameter.
8595 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8596 return;
8597 }
8598 // Fields shadowed by constructor parameters are a special case. Usually
8599 // the constructor initializes the field with the parameter.
8600 if (isa<CXXConstructorDecl>(Val: NewDC))
8601 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8602 // Remember that this was shadowed so we can either warn about its
8603 // modification or its existence depending on warning settings.
8604 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8605 return;
8606 }
8607 }
8608
8609 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8610 if (shadowedVar->isExternC()) {
8611 // For shadowing external vars, make sure that we point to the global
8612 // declaration, not a locally scoped extern declaration.
8613 for (auto *I : shadowedVar->redecls())
8614 if (I->isFileVarDecl()) {
8615 ShadowedDecl = I;
8616 break;
8617 }
8618 }
8619
8620 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8621
8622 unsigned WarningDiag = diag::warn_decl_shadow;
8623 SourceLocation CaptureLoc;
8624 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8625 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8626 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8627 // Handle both VarDecl and BindingDecl in lambda contexts
8628 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8629 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8630 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8631 if (RD->getLambdaCaptureDefault() == LCD_None) {
8632 // Try to avoid warnings for lambdas with an explicit capture
8633 // list. Warn only when the lambda captures the shadowed decl
8634 // explicitly.
8635 CaptureLoc = getCaptureLocation(LSI, VD);
8636 if (CaptureLoc.isInvalid())
8637 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8638 } else {
8639 // Remember that this was shadowed so we can avoid the warning if
8640 // the shadowed decl isn't captured and the warning settings allow
8641 // it.
8642 cast<LambdaScopeInfo>(Val: getCurFunction())
8643 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8644 return;
8645 }
8646 }
8647 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8648 // If lambda can capture this, then emit default shadowing warning,
8649 // Otherwise it is not really a shadowing case since field is not
8650 // available in lambda's body.
8651 // At this point we don't know that lambda can capture this, so
8652 // remember that this was shadowed and delay until we know.
8653 cast<LambdaScopeInfo>(Val: getCurFunction())
8654 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8655 return;
8656 }
8657 }
8658 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8659 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8660 bool HasLocalStorage = false;
8661 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8662 HasLocalStorage = VD->hasLocalStorage();
8663 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8664 HasLocalStorage =
8665 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8666
8667 if (HasLocalStorage) {
8668 // A variable can't shadow a local variable or binding in an enclosing
8669 // scope, if they are separated by a non-capturing declaration
8670 // context.
8671 for (DeclContext *ParentDC = NewDC;
8672 ParentDC && !ParentDC->Equals(DC: OldDC);
8673 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8674 // Only block literals, captured statements, and lambda expressions
8675 // can capture; other scopes don't.
8676 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8677 !isLambdaCallOperator(DC: ParentDC))
8678 return;
8679 }
8680 }
8681 }
8682 }
8683 }
8684
8685 // Never warn about shadowing a placeholder variable.
8686 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8687 return;
8688
8689 // Only warn about certain kinds of shadowing for class members.
8690 if (NewDC) {
8691 // In particular, don't warn about shadowing non-class members.
8692 if (NewDC->isRecord() && !OldDC->isRecord())
8693 return;
8694
8695 // Skip shadowing check if we're in a class scope, dealing with an enum
8696 // constant in a different context.
8697 DeclContext *ReDC = NewDC->getRedeclContext();
8698 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8699 return;
8700
8701 // TODO: should we warn about static data members shadowing
8702 // static data members from base classes?
8703
8704 // TODO: don't diagnose for inaccessible shadowed members.
8705 // This is hard to do perfectly because we might friend the
8706 // shadowing context, but that's just a false negative.
8707 }
8708
8709 DeclarationName Name = R.getLookupName();
8710
8711 // Emit warning and note.
8712 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8713 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8714 if (!CaptureLoc.isInvalid())
8715 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8716 << Name << /*explicitly*/ 1;
8717 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8718}
8719
8720void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8721 for (const auto &Shadow : LSI->ShadowingDecls) {
8722 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8723 // Try to avoid the warning when the shadowed decl isn't captured.
8724 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8725 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8726 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8727 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8728 Diag(Loc: Shadow.VD->getLocation(),
8729 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8730 : diag::warn_decl_shadow)
8731 << Shadow.VD->getDeclName()
8732 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8733 if (CaptureLoc.isValid())
8734 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8735 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8736 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8737 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8738 Diag(Loc: Shadow.VD->getLocation(),
8739 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8740 : diag::warn_decl_shadow_uncaptured_local)
8741 << Shadow.VD->getDeclName()
8742 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8743 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8744 }
8745 }
8746}
8747
8748void Sema::CheckShadow(Scope *S, VarDecl *D) {
8749 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8750 return;
8751
8752 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8753 Sema::LookupOrdinaryName,
8754 RedeclarationKind::ForVisibleRedeclaration);
8755 LookupName(R, S);
8756 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8757 CheckShadow(D, ShadowedDecl, R);
8758}
8759
8760/// Check if 'E', which is an expression that is about to be modified, refers
8761/// to a constructor parameter that shadows a field.
8762void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8763 // Quickly ignore expressions that can't be shadowing ctor parameters.
8764 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8765 return;
8766 E = E->IgnoreParenImpCasts();
8767 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8768 if (!DRE)
8769 return;
8770 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8771 auto I = ShadowingDecls.find(Val: D);
8772 if (I == ShadowingDecls.end())
8773 return;
8774 const NamedDecl *ShadowedDecl = I->second;
8775 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8776 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8777 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8778 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8779
8780 // Avoid issuing multiple warnings about the same decl.
8781 ShadowingDecls.erase(I);
8782}
8783
8784/// Check for conflict between this global or extern "C" declaration and
8785/// previous global or extern "C" declarations. This is only used in C++.
8786template<typename T>
8787static bool checkGlobalOrExternCConflict(
8788 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8789 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8790 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8791
8792 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8793 // The common case: this global doesn't conflict with any extern "C"
8794 // declaration.
8795 return false;
8796 }
8797
8798 if (Prev) {
8799 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8800 // Both the old and new declarations have C language linkage. This is a
8801 // redeclaration.
8802 Previous.clear();
8803 Previous.addDecl(D: Prev);
8804 return true;
8805 }
8806
8807 // This is a global, non-extern "C" declaration, and there is a previous
8808 // non-global extern "C" declaration. Diagnose if this is a variable
8809 // declaration.
8810 if (!isa<VarDecl>(ND))
8811 return false;
8812 } else {
8813 // The declaration is extern "C". Check for any declaration in the
8814 // translation unit which might conflict.
8815 if (IsGlobal) {
8816 // We have already performed the lookup into the translation unit.
8817 IsGlobal = false;
8818 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8819 I != E; ++I) {
8820 if (isa<VarDecl>(Val: *I)) {
8821 Prev = *I;
8822 break;
8823 }
8824 }
8825 } else {
8826 DeclContext::lookup_result R =
8827 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8828 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8829 I != E; ++I) {
8830 if (isa<VarDecl>(Val: *I)) {
8831 Prev = *I;
8832 break;
8833 }
8834 // FIXME: If we have any other entity with this name in global scope,
8835 // the declaration is ill-formed, but that is a defect: it breaks the
8836 // 'stat' hack, for instance. Only variables can have mangled name
8837 // clashes with extern "C" declarations, so only they deserve a
8838 // diagnostic.
8839 }
8840 }
8841
8842 if (!Prev)
8843 return false;
8844 }
8845
8846 // Use the first declaration's location to ensure we point at something which
8847 // is lexically inside an extern "C" linkage-spec.
8848 assert(Prev && "should have found a previous declaration to diagnose");
8849 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8850 Prev = FD->getFirstDecl();
8851 else
8852 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8853
8854 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8855 << IsGlobal << ND;
8856 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8857 << IsGlobal;
8858 return false;
8859}
8860
8861/// Apply special rules for handling extern "C" declarations. Returns \c true
8862/// if we have found that this is a redeclaration of some prior entity.
8863///
8864/// Per C++ [dcl.link]p6:
8865/// Two declarations [for a function or variable] with C language linkage
8866/// with the same name that appear in different scopes refer to the same
8867/// [entity]. An entity with C language linkage shall not be declared with
8868/// the same name as an entity in global scope.
8869template<typename T>
8870static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8871 LookupResult &Previous) {
8872 if (!S.getLangOpts().CPlusPlus) {
8873 // In C, when declaring a global variable, look for a corresponding 'extern'
8874 // variable declared in function scope. We don't need this in C++, because
8875 // we find local extern decls in the surrounding file-scope DeclContext.
8876 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8877 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8878 Previous.clear();
8879 Previous.addDecl(D: Prev);
8880 return true;
8881 }
8882 }
8883 return false;
8884 }
8885
8886 // A declaration in the translation unit can conflict with an extern "C"
8887 // declaration.
8888 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8889 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8890
8891 // An extern "C" declaration can conflict with a declaration in the
8892 // translation unit or can be a redeclaration of an extern "C" declaration
8893 // in another scope.
8894 if (isIncompleteDeclExternC(S,ND))
8895 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8896
8897 // Neither global nor extern "C": nothing to do.
8898 return false;
8899}
8900
8901static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8902 QualType T) {
8903 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8904 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8905 // any of its members, even recursively, shall not have an atomic type, or a
8906 // variably modified type, or a type that is volatile or restrict qualified.
8907 if (CanonT->isVariablyModifiedType()) {
8908 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8909 return true;
8910 }
8911
8912 // Arrays are qualified by their element type, so get the base type (this
8913 // works on non-arrays as well).
8914 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8915
8916 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8917 CanonT.isRestrictQualified()) {
8918 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8919 return true;
8920 }
8921
8922 if (CanonT->isRecordType()) {
8923 const RecordDecl *RD = CanonT->getAsRecordDecl();
8924 if (!RD->isInvalidDecl() &&
8925 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8926 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8927 }))
8928 return true;
8929 }
8930
8931 return false;
8932}
8933
8934void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8935 // If the decl is already known invalid, don't check it.
8936 if (NewVD->isInvalidDecl())
8937 return;
8938
8939 QualType T = NewVD->getType();
8940
8941 // Defer checking an 'auto' type until its initializer is attached.
8942 if (T->isUndeducedType())
8943 return;
8944
8945 if (NewVD->hasAttrs())
8946 CheckAlignasUnderalignment(D: NewVD);
8947
8948 if (T->isObjCObjectType()) {
8949 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8950 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8951 T = Context.getObjCObjectPointerType(OIT: T);
8952 NewVD->setType(T);
8953 }
8954
8955 // Emit an error if an address space was applied to decl with local storage.
8956 // This includes arrays of objects with address space qualifiers, but not
8957 // automatic variables that point to other address spaces.
8958 // ISO/IEC TR 18037 S5.1.2
8959 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8960 T.getAddressSpace() != LangAS::Default) {
8961 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8962 NewVD->setInvalidDecl();
8963 return;
8964 }
8965
8966 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8967 // scope.
8968 if (getLangOpts().OpenCLVersion == 120 &&
8969 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8970 LO: getLangOpts()) &&
8971 NewVD->isStaticLocal()) {
8972 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8973 NewVD->setInvalidDecl();
8974 return;
8975 }
8976
8977 if (getLangOpts().OpenCL) {
8978 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8979 return;
8980
8981 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8982 if (NewVD->hasAttr<BlocksAttr>()) {
8983 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8984 return;
8985 }
8986
8987 if (T->isBlockPointerType()) {
8988 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8989 // can't use 'extern' storage class.
8990 if (!T.isConstQualified()) {
8991 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8992 << 0 /*const*/;
8993 NewVD->setInvalidDecl();
8994 return;
8995 }
8996 if (NewVD->hasExternalStorage()) {
8997 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8998 NewVD->setInvalidDecl();
8999 return;
9000 }
9001 }
9002
9003 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9004 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9005 NewVD->hasExternalStorage()) {
9006 if (!T->isSamplerT() && !T->isDependentType() &&
9007 !(T.getAddressSpace() == LangAS::opencl_constant ||
9008 (T.getAddressSpace() == LangAS::opencl_global &&
9009 getOpenCLOptions().areProgramScopeVariablesSupported(
9010 Opts: getLangOpts())))) {
9011 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9012 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
9013 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9014 << Scope << "global or constant";
9015 else
9016 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9017 << Scope << "constant";
9018 NewVD->setInvalidDecl();
9019 return;
9020 }
9021 } else {
9022 if (T.getAddressSpace() == LangAS::opencl_global) {
9023 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9024 << 1 /*is any function*/ << "global";
9025 NewVD->setInvalidDecl();
9026 return;
9027 }
9028 // When this extension is enabled, 'local' variables are permitted in
9029 // non-kernel functions and within nested scopes of kernel functions,
9030 // bypassing standard OpenCL address space restrictions.
9031 bool AllowFunctionScopeLocalVariables =
9032 T.getAddressSpace() == LangAS::opencl_local &&
9033 getOpenCLOptions().isAvailableOption(
9034 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9035 if (AllowFunctionScopeLocalVariables) {
9036 // Direct pass: No further diagnostics needed for this specific case.
9037 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9038 T.getAddressSpace() == LangAS::opencl_local) {
9039 FunctionDecl *FD = getCurFunctionDecl();
9040 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9041 // in functions.
9042 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9043 if (T.getAddressSpace() == LangAS::opencl_constant)
9044 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9045 << 0 /*non-kernel only*/ << "constant";
9046 else
9047 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9048 << 0 /*non-kernel only*/ << "local";
9049 NewVD->setInvalidDecl();
9050 return;
9051 }
9052 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9053 // in the outermost scope of a kernel function.
9054 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9055 if (!getCurScope()->isFunctionScope()) {
9056 if (T.getAddressSpace() == LangAS::opencl_constant)
9057 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9058 << "constant";
9059 else
9060 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9061 << "local";
9062 NewVD->setInvalidDecl();
9063 return;
9064 }
9065 }
9066 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9067 // If we are parsing a template we didn't deduce an addr
9068 // space yet.
9069 T.getAddressSpace() != LangAS::Default) {
9070 // Do not allow other address spaces on automatic variable.
9071 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9072 NewVD->setInvalidDecl();
9073 return;
9074 }
9075 }
9076 }
9077
9078 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9079 && !NewVD->hasAttr<BlocksAttr>()) {
9080 if (getLangOpts().getGC() != LangOptions::NonGC)
9081 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9082 else {
9083 assert(!getLangOpts().ObjCAutoRefCount);
9084 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9085 }
9086 }
9087
9088 // WebAssembly tables must be static with a zero length and can't be
9089 // declared within functions.
9090 if (T->isWebAssemblyTableType()) {
9091 if (getCurScope()->getParent()) { // Parent is null at top-level
9092 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9093 NewVD->setInvalidDecl();
9094 return;
9095 }
9096 if (NewVD->getStorageClass() != SC_Static) {
9097 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9098 NewVD->setInvalidDecl();
9099 return;
9100 }
9101 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9102 if (!ATy || ATy->getZExtSize() != 0) {
9103 Diag(Loc: NewVD->getLocation(),
9104 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9105 NewVD->setInvalidDecl();
9106 return;
9107 }
9108 }
9109
9110 // zero sized static arrays are not allowed in HIP device functions
9111 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9112 if (FunctionDecl *FD = getCurFunctionDecl();
9113 FD &&
9114 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9115 if (const ConstantArrayType *ArrayT =
9116 getASTContext().getAsConstantArrayType(T);
9117 ArrayT && ArrayT->isZeroSize()) {
9118 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9119 }
9120 }
9121 }
9122
9123 bool isVM = T->isVariablyModifiedType();
9124 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9125 NewVD->hasAttr<BlocksAttr>())
9126 setFunctionHasBranchProtectedScope();
9127
9128 if ((isVM && NewVD->hasLinkage()) ||
9129 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9130 bool SizeIsNegative;
9131 llvm::APSInt Oversized;
9132 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9133 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9134 QualType FixedT;
9135 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9136 FixedT = FixedTInfo->getType();
9137 else if (FixedTInfo) {
9138 // Type and type-as-written are canonically different. We need to fix up
9139 // both types separately.
9140 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9141 Oversized);
9142 }
9143 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9144 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9145 // FIXME: This won't give the correct result for
9146 // int a[10][n];
9147 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9148
9149 if (NewVD->isFileVarDecl())
9150 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9151 << SizeRange;
9152 else if (NewVD->isStaticLocal())
9153 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9154 << SizeRange;
9155 else
9156 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9157 << SizeRange;
9158 NewVD->setInvalidDecl();
9159 return;
9160 }
9161
9162 if (!FixedTInfo) {
9163 if (NewVD->isFileVarDecl())
9164 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9165 else
9166 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9167 NewVD->setInvalidDecl();
9168 return;
9169 }
9170
9171 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9172 NewVD->setType(FixedT);
9173 NewVD->setTypeSourceInfo(FixedTInfo);
9174 }
9175
9176 if (T->isVoidType()) {
9177 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9178 // of objects and functions.
9179 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9180 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9181 << T;
9182 NewVD->setInvalidDecl();
9183 return;
9184 }
9185 }
9186
9187 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9188 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9189 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9190 NewVD->setInvalidDecl();
9191 return;
9192 }
9193
9194 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9195 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9196 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9197 NewVD->setInvalidDecl();
9198 return;
9199 }
9200
9201 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9202 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9203 NewVD->setInvalidDecl();
9204 return;
9205 }
9206
9207 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9208 !T->isDependentType() &&
9209 RequireLiteralType(Loc: NewVD->getLocation(), T,
9210 DiagID: diag::err_constexpr_var_non_literal)) {
9211 NewVD->setInvalidDecl();
9212 return;
9213 }
9214
9215 // PPC MMA non-pointer types are not allowed as non-local variable types.
9216 if (Context.getTargetInfo().getTriple().isPPC64() &&
9217 !NewVD->isLocalVarDecl() &&
9218 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9219 NewVD->setInvalidDecl();
9220 return;
9221 }
9222
9223 // Check that SVE types are only used in functions with SVE available.
9224 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9225 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9226 llvm::StringMap<bool> CallerFeatureMap;
9227 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9228 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9229 FeatureMap: CallerFeatureMap)) {
9230 NewVD->setInvalidDecl();
9231 return;
9232 }
9233 }
9234
9235 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9236 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9237 llvm::StringMap<bool> CallerFeatureMap;
9238 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9239 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9240 FeatureMap: CallerFeatureMap);
9241 }
9242
9243 if (T.hasAddressSpace() &&
9244 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9245 NewVD->setInvalidDecl();
9246 return;
9247 }
9248}
9249
9250bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9251 CheckVariableDeclarationType(NewVD);
9252
9253 // If the decl is already known invalid, don't check it.
9254 if (NewVD->isInvalidDecl())
9255 return false;
9256
9257 // If we did not find anything by this name, look for a non-visible
9258 // extern "C" declaration with the same name.
9259 if (Previous.empty() &&
9260 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9261 Previous.setShadowed();
9262
9263 if (!Previous.empty()) {
9264 MergeVarDecl(New: NewVD, Previous);
9265 return true;
9266 }
9267 return false;
9268}
9269
9270bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9271 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9272
9273 // Look for methods in base classes that this method might override.
9274 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9275 /*DetectVirtual=*/false);
9276 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9277 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9278 DeclarationName Name = MD->getDeclName();
9279
9280 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9281 // We really want to find the base class destructor here.
9282 Name = Context.DeclarationNames.getCXXDestructorName(
9283 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9284 }
9285
9286 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9287 CXXMethodDecl *BaseMD =
9288 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9289 if (!BaseMD || !BaseMD->isVirtual() ||
9290 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9291 /*ConsiderCudaAttrs=*/true))
9292 continue;
9293 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9294 continue;
9295 if (Overridden.insert(Ptr: BaseMD).second) {
9296 MD->addOverriddenMethod(MD: BaseMD);
9297 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9298 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9299 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9300 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9301 }
9302
9303 // A method can only override one function from each base class. We
9304 // don't track indirectly overridden methods from bases of bases.
9305 return true;
9306 }
9307
9308 return false;
9309 };
9310
9311 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9312 return !Overridden.empty();
9313}
9314
9315namespace {
9316 // Struct for holding all of the extra arguments needed by
9317 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9318 struct ActOnFDArgs {
9319 Scope *S;
9320 Declarator &D;
9321 MultiTemplateParamsArg TemplateParamLists;
9322 bool AddToScope;
9323 };
9324} // end anonymous namespace
9325
9326namespace {
9327
9328// Callback to only accept typo corrections that have a non-zero edit distance.
9329// Also only accept corrections that have the same parent decl.
9330class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9331 public:
9332 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9333 CXXRecordDecl *Parent)
9334 : Context(Context), OriginalFD(TypoFD),
9335 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9336
9337 bool ValidateCandidate(const TypoCorrection &candidate) override {
9338 if (candidate.getEditDistance() == 0)
9339 return false;
9340
9341 SmallVector<unsigned, 1> MismatchedParams;
9342 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9343 CDeclEnd = candidate.end();
9344 CDecl != CDeclEnd; ++CDecl) {
9345 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9346
9347 if (FD && !FD->hasBody() &&
9348 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9349 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9350 CXXRecordDecl *Parent = MD->getParent();
9351 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9352 return true;
9353 } else if (!ExpectedParent) {
9354 return true;
9355 }
9356 }
9357 }
9358
9359 return false;
9360 }
9361
9362 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9363 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9364 }
9365
9366 private:
9367 ASTContext &Context;
9368 FunctionDecl *OriginalFD;
9369 CXXRecordDecl *ExpectedParent;
9370};
9371
9372} // end anonymous namespace
9373
9374void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9375 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9376}
9377
9378/// Generate diagnostics for an invalid function redeclaration.
9379///
9380/// This routine handles generating the diagnostic messages for an invalid
9381/// function redeclaration, including finding possible similar declarations
9382/// or performing typo correction if there are no previous declarations with
9383/// the same name.
9384///
9385/// Returns a NamedDecl iff typo correction was performed and substituting in
9386/// the new declaration name does not cause new errors.
9387static NamedDecl *DiagnoseInvalidRedeclaration(
9388 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9389 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9390 DeclarationName Name = NewFD->getDeclName();
9391 DeclContext *NewDC = NewFD->getDeclContext();
9392 SmallVector<unsigned, 1> MismatchedParams;
9393 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9394 TypoCorrection Correction;
9395 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9396 unsigned DiagMsg =
9397 IsLocalFriend ? diag::err_no_matching_local_friend :
9398 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9399 diag::err_member_decl_does_not_match;
9400 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9401 IsLocalFriend ? Sema::LookupLocalFriendName
9402 : Sema::LookupOrdinaryName,
9403 RedeclarationKind::ForVisibleRedeclaration);
9404
9405 NewFD->setInvalidDecl();
9406 if (IsLocalFriend)
9407 SemaRef.LookupName(R&: Prev, S);
9408 else
9409 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9410 assert(!Prev.isAmbiguous() &&
9411 "Cannot have an ambiguity in previous-declaration lookup");
9412 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9413 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9414 MD ? MD->getParent() : nullptr);
9415 if (!Prev.empty()) {
9416 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9417 Func != FuncEnd; ++Func) {
9418 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9419 if (FD &&
9420 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9421 // Add 1 to the index so that 0 can mean the mismatch didn't
9422 // involve a parameter
9423 unsigned ParamNum =
9424 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9425 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9426 }
9427 }
9428 // If the qualified name lookup yielded nothing, try typo correction
9429 } else if ((Correction = SemaRef.CorrectTypo(
9430 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9431 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9432 Mode: CorrectTypoKind::ErrorRecovery,
9433 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9434 // Set up everything for the call to ActOnFunctionDeclarator
9435 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9436 IdLoc: ExtraArgs.D.getIdentifierLoc());
9437 Previous.clear();
9438 Previous.setLookupName(Correction.getCorrection());
9439 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9440 CDeclEnd = Correction.end();
9441 CDecl != CDeclEnd; ++CDecl) {
9442 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9443 if (FD && !FD->hasBody() &&
9444 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9445 Previous.addDecl(D: FD);
9446 }
9447 }
9448 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9449
9450 NamedDecl *Result;
9451 // Retry building the function declaration with the new previous
9452 // declarations, and with errors suppressed.
9453 {
9454 // Trap errors.
9455 Sema::SFINAETrap Trap(SemaRef);
9456
9457 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9458 // pieces need to verify the typo-corrected C++ declaration and hopefully
9459 // eliminate the need for the parameter pack ExtraArgs.
9460 Result = SemaRef.ActOnFunctionDeclarator(
9461 S: ExtraArgs.S, D&: ExtraArgs.D,
9462 DC: Correction.getCorrectionDecl()->getDeclContext(),
9463 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9464 AddToScope&: ExtraArgs.AddToScope);
9465
9466 if (Trap.hasErrorOccurred())
9467 Result = nullptr;
9468 }
9469
9470 if (Result) {
9471 // Determine which correction we picked.
9472 Decl *Canonical = Result->getCanonicalDecl();
9473 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9474 I != E; ++I)
9475 if ((*I)->getCanonicalDecl() == Canonical)
9476 Correction.setCorrectionDecl(*I);
9477
9478 // Let Sema know about the correction.
9479 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9480 SemaRef.diagnoseTypo(
9481 Correction,
9482 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9483 ? diag::err_no_matching_local_friend_suggest
9484 : diag::err_member_decl_does_not_match_suggest)
9485 << Name << NewDC << IsDefinition);
9486 return Result;
9487 }
9488
9489 // Pretend the typo correction never occurred
9490 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9491 IdLoc: ExtraArgs.D.getIdentifierLoc());
9492 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9493 Previous.clear();
9494 Previous.setLookupName(Name);
9495 }
9496
9497 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9498 << Name << NewDC << IsDefinition << NewFD->getLocation();
9499
9500 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9501 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9502 CXXRecordDecl *RD = NewMD->getParent();
9503 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9504 << RD->getName() << RD->getLocation();
9505 }
9506
9507 bool NewFDisConst = NewMD && NewMD->isConst();
9508
9509 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9510 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9511 NearMatch != NearMatchEnd; ++NearMatch) {
9512 FunctionDecl *FD = NearMatch->first;
9513 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9514 bool FDisConst = MD && MD->isConst();
9515 bool IsMember = MD || !IsLocalFriend;
9516
9517 // FIXME: These notes are poorly worded for the local friend case.
9518 if (unsigned Idx = NearMatch->second) {
9519 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9520 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9521 if (Loc.isInvalid()) Loc = FD->getLocation();
9522 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9523 : diag::note_local_decl_close_param_match)
9524 << Idx << FDParam->getType()
9525 << NewFD->getParamDecl(i: Idx - 1)->getType();
9526 } else if (FDisConst != NewFDisConst) {
9527 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9528 DiagID: diag::note_member_def_close_const_match)
9529 << NewFDisConst << FD->getSourceRange().getEnd();
9530 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9531 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9532 Code: " const");
9533 else if (FTI.hasMethodTypeQualifiers() &&
9534 FTI.getConstQualifierLoc().isValid())
9535 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9536 } else {
9537 SemaRef.Diag(Loc: FD->getLocation(),
9538 DiagID: IsMember ? diag::note_member_def_close_match
9539 : diag::note_local_decl_close_match);
9540 }
9541 }
9542 return nullptr;
9543}
9544
9545static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9546 switch (D.getDeclSpec().getStorageClassSpec()) {
9547 default: llvm_unreachable("Unknown storage class!");
9548 case DeclSpec::SCS_auto:
9549 case DeclSpec::SCS_register:
9550 case DeclSpec::SCS_mutable:
9551 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9552 DiagID: diag::err_typecheck_sclass_func);
9553 D.getMutableDeclSpec().ClearStorageClassSpecs();
9554 D.setInvalidType();
9555 break;
9556 case DeclSpec::SCS_unspecified: break;
9557 case DeclSpec::SCS_extern:
9558 if (D.getDeclSpec().isExternInLinkageSpec())
9559 return SC_None;
9560 return SC_Extern;
9561 case DeclSpec::SCS_static: {
9562 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9563 // C99 6.7.1p5:
9564 // The declaration of an identifier for a function that has
9565 // block scope shall have no explicit storage-class specifier
9566 // other than extern
9567 // See also (C++ [dcl.stc]p4).
9568 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9569 DiagID: diag::err_static_block_func);
9570 break;
9571 } else
9572 return SC_Static;
9573 }
9574 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9575 }
9576
9577 // No explicit storage class has already been returned
9578 return SC_None;
9579}
9580
9581static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9582 DeclContext *DC, QualType &R,
9583 TypeSourceInfo *TInfo,
9584 StorageClass SC,
9585 bool &IsVirtualOkay) {
9586 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9587 DeclarationName Name = NameInfo.getName();
9588
9589 FunctionDecl *NewFD = nullptr;
9590 bool isInline = D.getDeclSpec().isInlineSpecified();
9591
9592 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9593 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9594 (SemaRef.getLangOpts().C23 &&
9595 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9596
9597 if (SemaRef.getLangOpts().C23)
9598 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9599 DiagID: diag::err_c23_constexpr_not_variable);
9600 else
9601 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9602 DiagID: diag::err_constexpr_wrong_decl_kind)
9603 << static_cast<int>(ConstexprKind);
9604 ConstexprKind = ConstexprSpecKind::Unspecified;
9605 D.getMutableDeclSpec().ClearConstexprSpec();
9606 }
9607
9608 if (!SemaRef.getLangOpts().CPlusPlus) {
9609 // Determine whether the function was written with a prototype. This is
9610 // true when:
9611 // - there is a prototype in the declarator, or
9612 // - the type R of the function is some kind of typedef or other non-
9613 // attributed reference to a type name (which eventually refers to a
9614 // function type). Note, we can't always look at the adjusted type to
9615 // check this case because attributes may cause a non-function
9616 // declarator to still have a function type. e.g.,
9617 // typedef void func(int a);
9618 // __attribute__((noreturn)) func other_func; // This has a prototype
9619 bool HasPrototype =
9620 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9621 (D.getDeclSpec().isTypeRep() &&
9622 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9623 ->isFunctionProtoType()) ||
9624 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9625 assert(
9626 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9627 "Strict prototypes are required");
9628
9629 NewFD = FunctionDecl::Create(
9630 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9631 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9632 ConstexprKind: ConstexprSpecKind::Unspecified,
9633 /*TrailingRequiresClause=*/{});
9634 if (D.isInvalidType())
9635 NewFD->setInvalidDecl();
9636
9637 return NewFD;
9638 }
9639
9640 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9641 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9642
9643 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9644
9645 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9646 // This is a C++ constructor declaration.
9647 assert(DC->isRecord() &&
9648 "Constructors can only be declared in a member context");
9649
9650 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9651 return CXXConstructorDecl::Create(
9652 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9653 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9654 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9655 Inherited: InheritedConstructor(), TrailingRequiresClause);
9656
9657 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9658 // This is a C++ destructor declaration.
9659 if (DC->isRecord()) {
9660 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9661 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9662 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9663 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9664 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9665 /*isImplicitlyDeclared=*/false, ConstexprKind,
9666 TrailingRequiresClause);
9667 // User defined destructors start as not selected if the class definition is still
9668 // not done.
9669 if (Record->isBeingDefined())
9670 NewDD->setIneligibleOrNotSelected(true);
9671
9672 // If the destructor needs an implicit exception specification, set it
9673 // now. FIXME: It'd be nice to be able to create the right type to start
9674 // with, but the type needs to reference the destructor declaration.
9675 if (SemaRef.getLangOpts().CPlusPlus11)
9676 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9677
9678 IsVirtualOkay = true;
9679 return NewDD;
9680
9681 } else {
9682 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9683 D.setInvalidType();
9684
9685 // Create a FunctionDecl to satisfy the function definition parsing
9686 // code path.
9687 return FunctionDecl::Create(
9688 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9689 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9690 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9691 }
9692
9693 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9694 if (!DC->isRecord()) {
9695 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9696 DiagID: diag::err_conv_function_not_member);
9697 return nullptr;
9698 }
9699
9700 SemaRef.CheckConversionDeclarator(D, R, SC);
9701 if (D.isInvalidType())
9702 return nullptr;
9703
9704 IsVirtualOkay = true;
9705 return CXXConversionDecl::Create(
9706 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9707 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9708 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9709 TrailingRequiresClause);
9710
9711 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9712 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9713 return nullptr;
9714 return CXXDeductionGuideDecl::Create(
9715 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9716 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9717 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9718 } else if (DC->isRecord()) {
9719 // If the name of the function is the same as the name of the record,
9720 // then this must be an invalid constructor that has a return type.
9721 // (The parser checks for a return type and makes the declarator a
9722 // constructor if it has no return type).
9723 if (Name.getAsIdentifierInfo() &&
9724 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9725 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9726 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9727 << SourceRange(D.getIdentifierLoc());
9728 return nullptr;
9729 }
9730
9731 // This is a C++ method declaration.
9732 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9733 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9734 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9735 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9736 IsVirtualOkay = !Ret->isStatic();
9737 return Ret;
9738 } else {
9739 bool isFriend =
9740 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9741 if (!isFriend && SemaRef.CurContext->isRecord())
9742 return nullptr;
9743
9744 // Determine whether the function was written with a
9745 // prototype. This true when:
9746 // - we're in C++ (where every function has a prototype),
9747 return FunctionDecl::Create(
9748 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9749 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9750 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9751 }
9752}
9753
9754enum OpenCLParamType {
9755 ValidKernelParam,
9756 PtrPtrKernelParam,
9757 PtrKernelParam,
9758 InvalidAddrSpacePtrKernelParam,
9759 InvalidKernelParam,
9760 RecordKernelParam
9761};
9762
9763static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9764 // Size dependent types are just typedefs to normal integer types
9765 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9766 // integers other than by their names.
9767 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9768
9769 // Remove typedefs one by one until we reach a typedef
9770 // for a size dependent type.
9771 QualType DesugaredTy = Ty;
9772 do {
9773 ArrayRef<StringRef> Names(SizeTypeNames);
9774 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9775 if (Names.end() != Match)
9776 return true;
9777
9778 Ty = DesugaredTy;
9779 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9780 } while (DesugaredTy != Ty);
9781
9782 return false;
9783}
9784
9785static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9786 if (PT->isDependentType())
9787 return InvalidKernelParam;
9788
9789 if (PT->isPointerOrReferenceType()) {
9790 QualType PointeeType = PT->getPointeeType();
9791 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9792 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9793 PointeeType.getAddressSpace() == LangAS::Default)
9794 return InvalidAddrSpacePtrKernelParam;
9795
9796 if (PointeeType->isPointerType()) {
9797 // This is a pointer to pointer parameter.
9798 // Recursively check inner type.
9799 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9800 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9801 ParamKind == InvalidKernelParam)
9802 return ParamKind;
9803
9804 // OpenCL v3.0 s6.11.a:
9805 // A restriction to pass pointers to pointers only applies to OpenCL C
9806 // v1.2 or below.
9807 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9808 return ValidKernelParam;
9809
9810 return PtrPtrKernelParam;
9811 }
9812
9813 // C++ for OpenCL v1.0 s2.4:
9814 // Moreover the types used in parameters of the kernel functions must be:
9815 // Standard layout types for pointer parameters. The same applies to
9816 // reference if an implementation supports them in kernel parameters.
9817 if (S.getLangOpts().OpenCLCPlusPlus &&
9818 !S.getOpenCLOptions().isAvailableOption(
9819 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9820 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9821 bool IsStandardLayoutType = true;
9822 if (CXXRec) {
9823 // If template type is not ODR-used its definition is only available
9824 // in the template definition not its instantiation.
9825 // FIXME: This logic doesn't work for types that depend on template
9826 // parameter (PR58590).
9827 if (!CXXRec->hasDefinition())
9828 CXXRec = CXXRec->getTemplateInstantiationPattern();
9829 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9830 IsStandardLayoutType = false;
9831 }
9832 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9833 !IsStandardLayoutType)
9834 return InvalidKernelParam;
9835 }
9836
9837 // OpenCL v1.2 s6.9.p:
9838 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9839 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9840 return ValidKernelParam;
9841
9842 return PtrKernelParam;
9843 }
9844
9845 // OpenCL v1.2 s6.9.k:
9846 // Arguments to kernel functions in a program cannot be declared with the
9847 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9848 // uintptr_t or a struct and/or union that contain fields declared to be one
9849 // of these built-in scalar types.
9850 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9851 return InvalidKernelParam;
9852
9853 if (PT->isImageType())
9854 return PtrKernelParam;
9855
9856 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9857 return InvalidKernelParam;
9858
9859 // OpenCL extension spec v1.2 s9.5:
9860 // This extension adds support for half scalar and vector types as built-in
9861 // types that can be used for arithmetic operations, conversions etc.
9862 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9863 PT->isHalfType())
9864 return InvalidKernelParam;
9865
9866 // Look into an array argument to check if it has a forbidden type.
9867 if (PT->isArrayType()) {
9868 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9869 // Call ourself to check an underlying type of an array. Since the
9870 // getPointeeOrArrayElementType returns an innermost type which is not an
9871 // array, this recursive call only happens once.
9872 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9873 }
9874
9875 // C++ for OpenCL v1.0 s2.4:
9876 // Moreover the types used in parameters of the kernel functions must be:
9877 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9878 // types) for parameters passed by value;
9879 if (S.getLangOpts().OpenCLCPlusPlus &&
9880 !S.getOpenCLOptions().isAvailableOption(
9881 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9882 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9883 return InvalidKernelParam;
9884
9885 if (PT->isRecordType())
9886 return RecordKernelParam;
9887
9888 return ValidKernelParam;
9889}
9890
9891static void checkIsValidOpenCLKernelParameter(
9892 Sema &S,
9893 Declarator &D,
9894 ParmVarDecl *Param,
9895 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9896 QualType PT = Param->getType();
9897
9898 // Cache the valid types we encounter to avoid rechecking structs that are
9899 // used again
9900 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9901 return;
9902
9903 switch (getOpenCLKernelParameterType(S, PT)) {
9904 case PtrPtrKernelParam:
9905 // OpenCL v3.0 s6.11.a:
9906 // A kernel function argument cannot be declared as a pointer to a pointer
9907 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9908 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9909 D.setInvalidType();
9910 return;
9911
9912 case InvalidAddrSpacePtrKernelParam:
9913 // OpenCL v1.0 s6.5:
9914 // __kernel function arguments declared to be a pointer of a type can point
9915 // to one of the following address spaces only : __global, __local or
9916 // __constant.
9917 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9918 D.setInvalidType();
9919 return;
9920
9921 // OpenCL v1.2 s6.9.k:
9922 // Arguments to kernel functions in a program cannot be declared with the
9923 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9924 // uintptr_t or a struct and/or union that contain fields declared to be
9925 // one of these built-in scalar types.
9926
9927 case InvalidKernelParam:
9928 // OpenCL v1.2 s6.8 n:
9929 // A kernel function argument cannot be declared
9930 // of event_t type.
9931 // Do not diagnose half type since it is diagnosed as invalid argument
9932 // type for any function elsewhere.
9933 if (!PT->isHalfType()) {
9934 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9935
9936 // Explain what typedefs are involved.
9937 const TypedefType *Typedef = nullptr;
9938 while ((Typedef = PT->getAs<TypedefType>())) {
9939 SourceLocation Loc = Typedef->getDecl()->getLocation();
9940 // SourceLocation may be invalid for a built-in type.
9941 if (Loc.isValid())
9942 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9943 PT = Typedef->desugar();
9944 }
9945 }
9946
9947 D.setInvalidType();
9948 return;
9949
9950 case PtrKernelParam:
9951 case ValidKernelParam:
9952 ValidTypes.insert(Ptr: PT.getTypePtr());
9953 return;
9954
9955 case RecordKernelParam:
9956 break;
9957 }
9958
9959 // Track nested structs we will inspect
9960 SmallVector<const Decl *, 4> VisitStack;
9961
9962 // Track where we are in the nested structs. Items will migrate from
9963 // VisitStack to HistoryStack as we do the DFS for bad field.
9964 SmallVector<const FieldDecl *, 4> HistoryStack;
9965 HistoryStack.push_back(Elt: nullptr);
9966
9967 // At this point we already handled everything except of a RecordType.
9968 assert(PT->isRecordType() && "Unexpected type.");
9969 const auto *PD = PT->castAsRecordDecl();
9970 VisitStack.push_back(Elt: PD);
9971 assert(VisitStack.back() && "First decl null?");
9972
9973 do {
9974 const Decl *Next = VisitStack.pop_back_val();
9975 if (!Next) {
9976 assert(!HistoryStack.empty());
9977 // Found a marker, we have gone up a level
9978 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9979 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9980
9981 continue;
9982 }
9983
9984 // Adds everything except the original parameter declaration (which is not a
9985 // field itself) to the history stack.
9986 const RecordDecl *RD;
9987 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9988 HistoryStack.push_back(Elt: Field);
9989
9990 QualType FieldTy = Field->getType();
9991 // Other field types (known to be valid or invalid) are handled while we
9992 // walk around RecordDecl::fields().
9993 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9994 "Unexpected type.");
9995 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9996
9997 RD = FieldRecTy->castAsRecordDecl();
9998 } else {
9999 RD = cast<RecordDecl>(Val: Next);
10000 }
10001
10002 // Add a null marker so we know when we've gone back up a level
10003 VisitStack.push_back(Elt: nullptr);
10004
10005 for (const auto *FD : RD->fields()) {
10006 QualType QT = FD->getType();
10007
10008 if (ValidTypes.count(Ptr: QT.getTypePtr()))
10009 continue;
10010
10011 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
10012 if (ParamType == ValidKernelParam)
10013 continue;
10014
10015 if (ParamType == RecordKernelParam) {
10016 VisitStack.push_back(Elt: FD);
10017 continue;
10018 }
10019
10020 // OpenCL v1.2 s6.9.p:
10021 // Arguments to kernel functions that are declared to be a struct or union
10022 // do not allow OpenCL objects to be passed as elements of the struct or
10023 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10024 // of SVM.
10025 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10026 ParamType == InvalidAddrSpacePtrKernelParam) {
10027 S.Diag(Loc: Param->getLocation(),
10028 DiagID: diag::err_record_with_pointers_kernel_param)
10029 << PT->isUnionType()
10030 << PT;
10031 } else {
10032 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10033 }
10034
10035 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10036 << PD->getDeclName();
10037
10038 // We have an error, now let's go back up through history and show where
10039 // the offending field came from
10040 for (ArrayRef<const FieldDecl *>::const_iterator
10041 I = HistoryStack.begin() + 1,
10042 E = HistoryStack.end();
10043 I != E; ++I) {
10044 const FieldDecl *OuterField = *I;
10045 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10046 << OuterField->getType();
10047 }
10048
10049 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10050 << QT->isPointerType()
10051 << QT;
10052 D.setInvalidType();
10053 return;
10054 }
10055 } while (!VisitStack.empty());
10056}
10057
10058/// Find the DeclContext in which a tag is implicitly declared if we see an
10059/// elaborated type specifier in the specified context, and lookup finds
10060/// nothing.
10061static DeclContext *getTagInjectionContext(DeclContext *DC) {
10062 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10063 DC = DC->getParent();
10064 return DC;
10065}
10066
10067/// Find the Scope in which a tag is implicitly declared if we see an
10068/// elaborated type specifier in the specified context, and lookup finds
10069/// nothing.
10070static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10071 while (S->isClassScope() ||
10072 (LangOpts.CPlusPlus &&
10073 S->isFunctionPrototypeScope()) ||
10074 ((S->getFlags() & Scope::DeclScope) == 0) ||
10075 (S->getEntity() && S->getEntity()->isTransparentContext()))
10076 S = S->getParent();
10077 return S;
10078}
10079
10080/// Determine whether a declaration matches a known function in namespace std.
10081static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10082 unsigned BuiltinID) {
10083 switch (BuiltinID) {
10084 case Builtin::BI__GetExceptionInfo:
10085 // No type checking whatsoever.
10086 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10087
10088 case Builtin::BIaddressof:
10089 case Builtin::BI__addressof:
10090 case Builtin::BIforward:
10091 case Builtin::BIforward_like:
10092 case Builtin::BImove:
10093 case Builtin::BImove_if_noexcept:
10094 case Builtin::BIas_const: {
10095 // Ensure that we don't treat the algorithm
10096 // OutputIt std::move(InputIt, InputIt, OutputIt)
10097 // as the builtin std::move.
10098 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10099 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10100 }
10101
10102 default:
10103 return false;
10104 }
10105}
10106
10107NamedDecl*
10108Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10109 TypeSourceInfo *TInfo, LookupResult &Previous,
10110 MultiTemplateParamsArg TemplateParamListsRef,
10111 bool &AddToScope) {
10112 QualType R = TInfo->getType();
10113
10114 assert(R->isFunctionType());
10115 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10116 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10117
10118 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10119 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10120 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10121 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10122 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10123 TemplateParamLists.back() = Invented;
10124 else
10125 TemplateParamLists.push_back(Elt: Invented);
10126 }
10127
10128 // TODO: consider using NameInfo for diagnostic.
10129 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10130 DeclarationName Name = NameInfo.getName();
10131 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10132
10133 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10134 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10135 DiagID: diag::err_invalid_thread)
10136 << DeclSpec::getSpecifierName(S: TSCS);
10137
10138 if (D.isFirstDeclarationOfMember())
10139 adjustMemberFunctionCC(
10140 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10141 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10142
10143 bool isFriend = false;
10144 FunctionTemplateDecl *FunctionTemplate = nullptr;
10145 bool isMemberSpecialization = false;
10146 bool isFunctionTemplateSpecialization = false;
10147
10148 bool HasExplicitTemplateArgs = false;
10149 TemplateArgumentListInfo TemplateArgs;
10150
10151 bool isVirtualOkay = false;
10152
10153 DeclContext *OriginalDC = DC;
10154 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10155
10156 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10157 IsVirtualOkay&: isVirtualOkay);
10158 if (!NewFD) return nullptr;
10159
10160 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10161 NewFD->setTopLevelDeclInObjCContainer();
10162
10163 // Set the lexical context. If this is a function-scope declaration, or has a
10164 // C++ scope specifier, or is the object of a friend declaration, the lexical
10165 // context will be different from the semantic context.
10166 NewFD->setLexicalDeclContext(CurContext);
10167
10168 if (IsLocalExternDecl)
10169 NewFD->setLocalExternDecl();
10170
10171 if (getLangOpts().CPlusPlus) {
10172 // The rules for implicit inlines changed in C++20 for methods and friends
10173 // with an in-class definition (when such a definition is not attached to
10174 // the global module). This does not affect declarations that are already
10175 // inline (whether explicitly or implicitly by being declared constexpr,
10176 // consteval, etc).
10177 // FIXME: We need a better way to separate C++ standard and clang modules.
10178 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10179 !NewFD->getOwningModule() ||
10180 NewFD->isFromGlobalModule() ||
10181 NewFD->getOwningModule()->isHeaderLikeModule();
10182 bool isInline = D.getDeclSpec().isInlineSpecified();
10183 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10184 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10185 isFriend = D.getDeclSpec().isFriendSpecified();
10186 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10187 // Pre-C++20 [class.friend]p5
10188 // A function can be defined in a friend declaration of a
10189 // class . . . . Such a function is implicitly inline.
10190 // Post C++20 [class.friend]p7
10191 // Such a function is implicitly an inline function if it is attached
10192 // to the global module.
10193 NewFD->setImplicitlyInline();
10194 }
10195
10196 // If this is a method defined in an __interface, and is not a constructor
10197 // or an overloaded operator, then set the pure flag (isVirtual will already
10198 // return true).
10199 if (const CXXRecordDecl *Parent =
10200 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10201 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10202 NewFD->setIsPureVirtual(true);
10203
10204 // C++ [class.union]p2
10205 // A union can have member functions, but not virtual functions.
10206 if (isVirtual && Parent->isUnion()) {
10207 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10208 NewFD->setInvalidDecl();
10209 }
10210 if ((Parent->isClass() || Parent->isStruct()) &&
10211 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10212 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10213 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10214 if (auto *Def = Parent->getDefinition())
10215 Def->setInitMethod(true);
10216 }
10217 }
10218
10219 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10220 isMemberSpecialization = false;
10221 isFunctionTemplateSpecialization = false;
10222 if (D.isInvalidType())
10223 NewFD->setInvalidDecl();
10224
10225 // Match up the template parameter lists with the scope specifier, then
10226 // determine whether we have a template or a template specialization.
10227 bool Invalid = false;
10228 TemplateIdAnnotation *TemplateId =
10229 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10230 ? D.getName().TemplateId
10231 : nullptr;
10232 TemplateParameterList *TemplateParams =
10233 MatchTemplateParametersToScopeSpecifier(
10234 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10235 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10236 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10237 if (TemplateParams) {
10238 // Check that we can declare a template here.
10239 if (CheckTemplateDeclScope(S, TemplateParams))
10240 NewFD->setInvalidDecl();
10241
10242 if (TemplateParams->size() > 0) {
10243 // This is a function template
10244
10245 // A destructor cannot be a template.
10246 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10247 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10248 NewFD->setInvalidDecl();
10249 // Function template with explicit template arguments.
10250 } else if (TemplateId) {
10251 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10252 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10253 NewFD->setInvalidDecl();
10254 }
10255
10256 // If we're adding a template to a dependent context, we may need to
10257 // rebuilding some of the types used within the template parameter list,
10258 // now that we know what the current instantiation is.
10259 if (DC->isDependentContext()) {
10260 ContextRAII SavedContext(*this, DC);
10261 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10262 Invalid = true;
10263 }
10264
10265 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10266 L: NewFD->getLocation(),
10267 Name, Params: TemplateParams,
10268 Decl: NewFD);
10269 FunctionTemplate->setLexicalDeclContext(CurContext);
10270 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10271
10272 // For source fidelity, store the other template param lists.
10273 if (TemplateParamLists.size() > 1) {
10274 NewFD->setTemplateParameterListsInfo(Context,
10275 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10276 .drop_back(N: 1));
10277 }
10278 } else {
10279 // This is a function template specialization.
10280 isFunctionTemplateSpecialization = true;
10281 // For source fidelity, store all the template param lists.
10282 if (TemplateParamLists.size() > 0)
10283 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10284
10285 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10286 if (isFriend) {
10287 // We want to remove the "template<>", found here.
10288 SourceRange RemoveRange = TemplateParams->getSourceRange();
10289
10290 // If we remove the template<> and the name is not a
10291 // template-id, we're actually silently creating a problem:
10292 // the friend declaration will refer to an untemplated decl,
10293 // and clearly the user wants a template specialization. So
10294 // we need to insert '<>' after the name.
10295 SourceLocation InsertLoc;
10296 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10297 InsertLoc = D.getName().getSourceRange().getEnd();
10298 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10299 }
10300
10301 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10302 << Name << RemoveRange
10303 << FixItHint::CreateRemoval(RemoveRange)
10304 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10305 Invalid = true;
10306
10307 // Recover by faking up an empty template argument list.
10308 HasExplicitTemplateArgs = true;
10309 TemplateArgs.setLAngleLoc(InsertLoc);
10310 TemplateArgs.setRAngleLoc(InsertLoc);
10311 }
10312 }
10313 } else {
10314 // Check that we can declare a template here.
10315 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10316 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10317 NewFD->setInvalidDecl();
10318
10319 // All template param lists were matched against the scope specifier:
10320 // this is NOT (an explicit specialization of) a template.
10321 if (TemplateParamLists.size() > 0)
10322 // For source fidelity, store all the template param lists.
10323 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10324
10325 // "friend void foo<>(int);" is an implicit specialization decl.
10326 if (isFriend && TemplateId)
10327 isFunctionTemplateSpecialization = true;
10328 }
10329
10330 // If this is a function template specialization and the unqualified-id of
10331 // the declarator-id is a template-id, convert the template argument list
10332 // into our AST format and check for unexpanded packs.
10333 if (isFunctionTemplateSpecialization && TemplateId) {
10334 HasExplicitTemplateArgs = true;
10335
10336 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10337 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10338 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10339 TemplateId->NumArgs);
10340 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10341
10342 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10343 // declaration of a function template partial specialization? Should we
10344 // consider the unexpanded pack context to be a partial specialization?
10345 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10346 if (DiagnoseUnexpandedParameterPack(
10347 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10348 : UPPC_ExplicitSpecialization))
10349 NewFD->setInvalidDecl();
10350 }
10351 }
10352
10353 if (Invalid) {
10354 NewFD->setInvalidDecl();
10355 if (FunctionTemplate)
10356 FunctionTemplate->setInvalidDecl();
10357 }
10358
10359 // C++ [dcl.fct.spec]p5:
10360 // The virtual specifier shall only be used in declarations of
10361 // nonstatic class member functions that appear within a
10362 // member-specification of a class declaration; see 10.3.
10363 //
10364 if (isVirtual && !NewFD->isInvalidDecl()) {
10365 if (!isVirtualOkay) {
10366 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10367 DiagID: diag::err_virtual_non_function);
10368 } else if (!CurContext->isRecord()) {
10369 // 'virtual' was specified outside of the class.
10370 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10371 DiagID: diag::err_virtual_out_of_class)
10372 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10373 } else if (NewFD->getDescribedFunctionTemplate()) {
10374 // C++ [temp.mem]p3:
10375 // A member function template shall not be virtual.
10376 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10377 DiagID: diag::err_virtual_member_function_template)
10378 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10379 } else {
10380 // Okay: Add virtual to the method.
10381 NewFD->setVirtualAsWritten(true);
10382 }
10383
10384 if (getLangOpts().CPlusPlus14 &&
10385 NewFD->getReturnType()->isUndeducedType())
10386 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10387 }
10388
10389 // C++ [dcl.fct.spec]p3:
10390 // The inline specifier shall not appear on a block scope function
10391 // declaration.
10392 if (isInline && !NewFD->isInvalidDecl()) {
10393 if (CurContext->isFunctionOrMethod()) {
10394 // 'inline' is not allowed on block scope function declaration.
10395 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10396 DiagID: diag::err_inline_declaration_block_scope) << Name
10397 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10398 }
10399 }
10400
10401 // C++ [dcl.fct.spec]p6:
10402 // The explicit specifier shall be used only in the declaration of a
10403 // constructor or conversion function within its class definition;
10404 // see 12.3.1 and 12.3.2.
10405 if (hasExplicit && !NewFD->isInvalidDecl() &&
10406 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10407 if (!CurContext->isRecord()) {
10408 // 'explicit' was specified outside of the class.
10409 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10410 DiagID: diag::err_explicit_out_of_class)
10411 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10412 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10413 !isa<CXXConversionDecl>(Val: NewFD)) {
10414 // 'explicit' was specified on a function that wasn't a constructor
10415 // or conversion function.
10416 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10417 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10418 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10419 }
10420 }
10421
10422 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10423 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10424 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10425 // are implicitly inline.
10426 NewFD->setImplicitlyInline();
10427
10428 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10429 // be either constructors or to return a literal type. Therefore,
10430 // destructors cannot be declared constexpr.
10431 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10432 (!getLangOpts().CPlusPlus20 ||
10433 ConstexprKind == ConstexprSpecKind::Consteval)) {
10434 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10435 << static_cast<int>(ConstexprKind);
10436 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10437 ? ConstexprSpecKind::Unspecified
10438 : ConstexprSpecKind::Constexpr);
10439 }
10440 // C++20 [dcl.constexpr]p2: An allocation function, or a
10441 // deallocation function shall not be declared with the consteval
10442 // specifier.
10443 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10444 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10445 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10446 DiagID: diag::err_invalid_consteval_decl_kind)
10447 << NewFD;
10448 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10449 }
10450 }
10451
10452 // If __module_private__ was specified, mark the function accordingly.
10453 if (D.getDeclSpec().isModulePrivateSpecified()) {
10454 if (isFunctionTemplateSpecialization) {
10455 SourceLocation ModulePrivateLoc
10456 = D.getDeclSpec().getModulePrivateSpecLoc();
10457 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10458 << 0
10459 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10460 } else {
10461 NewFD->setModulePrivate();
10462 if (FunctionTemplate)
10463 FunctionTemplate->setModulePrivate();
10464 }
10465 }
10466
10467 if (isFriend) {
10468 if (FunctionTemplate) {
10469 FunctionTemplate->setObjectOfFriendDecl();
10470 FunctionTemplate->setAccess(AS_public);
10471 }
10472 NewFD->setObjectOfFriendDecl();
10473 NewFD->setAccess(AS_public);
10474 }
10475
10476 // If a function is defined as defaulted or deleted, mark it as such now.
10477 // We'll do the relevant checks on defaulted / deleted functions later.
10478 switch (D.getFunctionDefinitionKind()) {
10479 case FunctionDefinitionKind::Declaration:
10480 case FunctionDefinitionKind::Definition:
10481 break;
10482
10483 case FunctionDefinitionKind::Defaulted:
10484 NewFD->setDefaulted();
10485 break;
10486
10487 case FunctionDefinitionKind::Deleted:
10488 NewFD->setDeletedAsWritten();
10489 break;
10490 }
10491
10492 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10493 D.isFunctionDefinition()) {
10494 // Pre C++20 [class.mfct]p2:
10495 // A member function may be defined (8.4) in its class definition, in
10496 // which case it is an inline member function (7.1.2)
10497 // Post C++20 [class.mfct]p1:
10498 // If a member function is attached to the global module and is defined
10499 // in its class definition, it is inline.
10500 NewFD->setImplicitlyInline();
10501 }
10502
10503 if (!isFriend && SC != SC_None) {
10504 // C++ [temp.expl.spec]p2:
10505 // The declaration in an explicit-specialization shall not be an
10506 // export-declaration. An explicit specialization shall not use a
10507 // storage-class-specifier other than thread_local.
10508 //
10509 // We diagnose friend declarations with storage-class-specifiers
10510 // elsewhere.
10511 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10512 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10513 DiagID: diag::ext_explicit_specialization_storage_class)
10514 << FixItHint::CreateRemoval(
10515 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10516 }
10517
10518 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10519 assert(isa<CXXMethodDecl>(NewFD) &&
10520 "Out-of-line member function should be a CXXMethodDecl");
10521 // C++ [class.static]p1:
10522 // A data or function member of a class may be declared static
10523 // in a class definition, in which case it is a static member of
10524 // the class.
10525
10526 // Complain about the 'static' specifier if it's on an out-of-line
10527 // member function definition.
10528
10529 // MSVC permits the use of a 'static' storage specifier on an
10530 // out-of-line member function template declaration and class member
10531 // template declaration (MSVC versions before 2015), warn about this.
10532 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10533 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10534 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10535 (getLangOpts().MSVCCompat &&
10536 NewFD->getDescribedFunctionTemplate()))
10537 ? diag::ext_static_out_of_line
10538 : diag::err_static_out_of_line)
10539 << FixItHint::CreateRemoval(
10540 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10541 }
10542 }
10543
10544 // C++11 [except.spec]p15:
10545 // A deallocation function with no exception-specification is treated
10546 // as if it were specified with noexcept(true).
10547 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10548 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10549 !FPT->hasExceptionSpec())
10550 NewFD->setType(Context.getFunctionType(
10551 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10552 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10553
10554 // C++20 [dcl.inline]/7
10555 // If an inline function or variable that is attached to a named module
10556 // is declared in a definition domain, it shall be defined in that
10557 // domain.
10558 // So, if the current declaration does not have a definition, we must
10559 // check at the end of the TU (or when the PMF starts) to see that we
10560 // have a definition at that point.
10561 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10562 NewFD->isInNamedModule()) {
10563 PendingInlineFuncDecls.insert(Ptr: NewFD);
10564 }
10565 }
10566
10567 // Filter out previous declarations that don't match the scope.
10568 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10569 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10570 isMemberSpecialization ||
10571 isFunctionTemplateSpecialization);
10572
10573 LoadExternalExtnameUndeclaredIdentifiers();
10574
10575 // Handle GNU asm-label extension (encoded as an attribute).
10576 if (Expr *E = D.getAsmLabel()) {
10577 // The parser guarantees this is a string.
10578 StringLiteral *SE = cast<StringLiteral>(Val: E);
10579 NewFD->addAttr(
10580 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10581 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10582 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10583 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10584 if (I != ExtnameUndeclaredIdentifiers.end()) {
10585 if (isDeclExternC(D: NewFD)) {
10586 NewFD->addAttr(A: I->second);
10587 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10588 } else if (NewFD->getDeclContext()
10589 ->getRedeclContext()
10590 ->isTranslationUnit())
10591 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10592 << /*Variable*/0 << NewFD;
10593 }
10594 }
10595
10596 // Copy the parameter declarations from the declarator D to the function
10597 // declaration NewFD, if they are available. First scavenge them into Params.
10598 SmallVector<ParmVarDecl*, 16> Params;
10599 unsigned FTIIdx;
10600 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10601 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10602
10603 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10604 // function that takes no arguments, not a function that takes a
10605 // single void argument.
10606 // We let through "const void" here because Sema::GetTypeForDeclarator
10607 // already checks for that case.
10608 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10609 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10610 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10611 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10612 Param->setDeclContext(NewFD);
10613 Params.push_back(Elt: Param);
10614
10615 if (Param->isInvalidDecl())
10616 NewFD->setInvalidDecl();
10617 }
10618 }
10619
10620 if (!getLangOpts().CPlusPlus) {
10621 // In C, find all the tag declarations from the prototype and move them
10622 // into the function DeclContext. Remove them from the surrounding tag
10623 // injection context of the function, which is typically but not always
10624 // the TU.
10625 DeclContext *PrototypeTagContext =
10626 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10627 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10628 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10629
10630 // We don't want to reparent enumerators. Look at their parent enum
10631 // instead.
10632 if (!TD) {
10633 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10634 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10635 }
10636 if (!TD)
10637 continue;
10638 DeclContext *TagDC = TD->getLexicalDeclContext();
10639 if (!TagDC->containsDecl(D: TD))
10640 continue;
10641 TagDC->removeDecl(D: TD);
10642 TD->setDeclContext(NewFD);
10643 NewFD->addDecl(D: TD);
10644
10645 // Preserve the lexical DeclContext if it is not the surrounding tag
10646 // injection context of the FD. In this example, the semantic context of
10647 // E will be f and the lexical context will be S, while both the
10648 // semantic and lexical contexts of S will be f:
10649 // void f(struct S { enum E { a } f; } s);
10650 if (TagDC != PrototypeTagContext)
10651 TD->setLexicalDeclContext(TagDC);
10652 }
10653 }
10654 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10655 // When we're declaring a function with a typedef, typeof, etc as in the
10656 // following example, we'll need to synthesize (unnamed)
10657 // parameters for use in the declaration.
10658 //
10659 // @code
10660 // typedef void fn(int);
10661 // fn f;
10662 // @endcode
10663
10664 // Synthesize a parameter for each argument type.
10665 for (const auto &AI : FT->param_types()) {
10666 ParmVarDecl *Param =
10667 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10668 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10669 Params.push_back(Elt: Param);
10670 }
10671 } else {
10672 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10673 "Should not need args for typedef of non-prototype fn");
10674 }
10675
10676 // Finally, we know we have the right number of parameters, install them.
10677 NewFD->setParams(Params);
10678
10679 // If this declarator is a declaration and not a definition, its parameters
10680 // will not be pushed onto a scope chain. That means we will not issue any
10681 // reserved identifier warnings for the declaration, but we will for the
10682 // definition. Handle those here.
10683 if (!D.isFunctionDefinition()) {
10684 for (const ParmVarDecl *PVD : Params)
10685 warnOnReservedIdentifier(D: PVD);
10686 }
10687
10688 if (D.getDeclSpec().isNoreturnSpecified())
10689 NewFD->addAttr(
10690 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10691
10692 // Functions returning a variably modified type violate C99 6.7.5.2p2
10693 // because all functions have linkage.
10694 if (!NewFD->isInvalidDecl() &&
10695 NewFD->getReturnType()->isVariablyModifiedType()) {
10696 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10697 NewFD->setInvalidDecl();
10698 }
10699
10700 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10701 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10702 !NewFD->hasAttr<SectionAttr>())
10703 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10704 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10705 Range: PragmaClangTextSection.PragmaLocation));
10706
10707 // Apply an implicit SectionAttr if #pragma code_seg is active.
10708 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10709 !NewFD->hasAttr<SectionAttr>()) {
10710 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10711 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10712 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10713 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10714 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10715 ASTContext::PSF_Read,
10716 TheDecl: NewFD))
10717 NewFD->dropAttr<SectionAttr>();
10718 }
10719
10720 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10721 // active.
10722 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10723 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10724 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10725 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10726
10727 // Apply an implicit CodeSegAttr from class declspec or
10728 // apply an implicit SectionAttr from #pragma code_seg if active.
10729 if (!NewFD->hasAttr<CodeSegAttr>()) {
10730 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10731 IsDefinition: D.isFunctionDefinition())) {
10732 NewFD->addAttr(A: SAttr);
10733 }
10734 }
10735
10736 // Handle attributes.
10737 ProcessDeclAttributes(S, D: NewFD, PD: D);
10738 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10739 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10740 !NewTVA->isDefaultVersion() &&
10741 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10742 // Don't add to scope fmv functions declarations if fmv disabled
10743 AddToScope = false;
10744 return NewFD;
10745 }
10746
10747 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10748 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10749 // type.
10750 //
10751 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10752 // type declaration will generate a compilation error.
10753 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10754 if (AddressSpace != LangAS::Default) {
10755 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10756 NewFD->setInvalidDecl();
10757 }
10758 }
10759
10760 if (!getLangOpts().CPlusPlus) {
10761 // Perform semantic checking on the function declaration.
10762 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10763 CheckMain(FD: NewFD, D: D.getDeclSpec());
10764
10765 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10766 CheckMSVCRTEntryPoint(FD: NewFD);
10767
10768 if (!NewFD->isInvalidDecl())
10769 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10770 IsMemberSpecialization: isMemberSpecialization,
10771 DeclIsDefn: D.isFunctionDefinition()));
10772 else if (!Previous.empty())
10773 // Recover gracefully from an invalid redeclaration.
10774 D.setRedeclaration(true);
10775 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10776 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10777 "previous declaration set still overloaded");
10778
10779 // Diagnose no-prototype function declarations with calling conventions that
10780 // don't support variadic calls. Only do this in C and do it after merging
10781 // possibly prototyped redeclarations.
10782 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10783 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10784 CallingConv CC = FT->getExtInfo().getCC();
10785 if (!supportsVariadicCall(CC)) {
10786 // Windows system headers sometimes accidentally use stdcall without
10787 // (void) parameters, so we relax this to a warning.
10788 int DiagID =
10789 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10790 Diag(Loc: NewFD->getLocation(), DiagID)
10791 << FunctionType::getNameForCallConv(CC);
10792 }
10793 }
10794
10795 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10796 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10797 checkNonTrivialCUnion(
10798 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10799 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10800 } else {
10801 // C++11 [replacement.functions]p3:
10802 // The program's definitions shall not be specified as inline.
10803 //
10804 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10805 //
10806 // Suppress the diagnostic if the function is __attribute__((used)), since
10807 // that forces an external definition to be emitted.
10808 if (D.getDeclSpec().isInlineSpecified() &&
10809 NewFD->isReplaceableGlobalAllocationFunction() &&
10810 !NewFD->hasAttr<UsedAttr>())
10811 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10812 DiagID: diag::ext_operator_new_delete_declared_inline)
10813 << NewFD->getDeclName();
10814
10815 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10816 // C++20 [dcl.decl.general]p4:
10817 // The optional requires-clause in an init-declarator or
10818 // member-declarator shall be present only if the declarator declares a
10819 // templated function.
10820 //
10821 // C++20 [temp.pre]p8:
10822 // An entity is templated if it is
10823 // - a template,
10824 // - an entity defined or created in a templated entity,
10825 // - a member of a templated entity,
10826 // - an enumerator for an enumeration that is a templated entity, or
10827 // - the closure type of a lambda-expression appearing in the
10828 // declaration of a templated entity.
10829 //
10830 // [Note 6: A local class, a local or block variable, or a friend
10831 // function defined in a templated entity is a templated entity.
10832 // — end note]
10833 //
10834 // A templated function is a function template or a function that is
10835 // templated. A templated class is a class template or a class that is
10836 // templated. A templated variable is a variable template or a variable
10837 // that is templated.
10838 if (!FunctionTemplate) {
10839 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10840 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10841 // An explicit specialization shall not have a trailing
10842 // requires-clause unless it declares a function template.
10843 //
10844 // Since a friend function template specialization cannot be
10845 // definition, and since a non-template friend declaration with a
10846 // trailing requires-clause must be a definition, we diagnose
10847 // friend function template specializations with trailing
10848 // requires-clauses on the same path as explicit specializations
10849 // even though they aren't necessarily prohibited by the same
10850 // language rule.
10851 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10852 << isFriend;
10853 } else if (isFriend && NewFD->isTemplated() &&
10854 !D.isFunctionDefinition()) {
10855 // C++ [temp.friend]p9:
10856 // A non-template friend declaration with a requires-clause shall be
10857 // a definition.
10858 Diag(Loc: NewFD->getBeginLoc(),
10859 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10860 NewFD->setInvalidDecl();
10861 } else if (!NewFD->isTemplated() ||
10862 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10863 Diag(Loc: TRC->getBeginLoc(),
10864 DiagID: diag::err_constrained_non_templated_function);
10865 }
10866 }
10867 }
10868
10869 // We do not add HD attributes to specializations here because
10870 // they may have different constexpr-ness compared to their
10871 // templates and, after maybeAddHostDeviceAttrs() is applied,
10872 // may end up with different effective targets. Instead, a
10873 // specialization inherits its target attributes from its template
10874 // in the CheckFunctionTemplateSpecialization() call below.
10875 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10876 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10877
10878 // Handle explicit specializations of function templates
10879 // and friend function declarations with an explicit
10880 // template argument list.
10881 if (isFunctionTemplateSpecialization) {
10882 bool isDependentSpecialization = false;
10883 if (isFriend) {
10884 // For friend function specializations, this is a dependent
10885 // specialization if its semantic context is dependent, its
10886 // type is dependent, or if its template-id is dependent.
10887 isDependentSpecialization =
10888 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10889 (HasExplicitTemplateArgs &&
10890 TemplateSpecializationType::
10891 anyInstantiationDependentTemplateArguments(
10892 Args: TemplateArgs.arguments()));
10893 assert((!isDependentSpecialization ||
10894 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10895 "dependent friend function specialization without template "
10896 "args");
10897 } else {
10898 // For class-scope explicit specializations of function templates,
10899 // if the lexical context is dependent, then the specialization
10900 // is dependent.
10901 isDependentSpecialization =
10902 CurContext->isRecord() && CurContext->isDependentContext();
10903 }
10904
10905 TemplateArgumentListInfo *ExplicitTemplateArgs =
10906 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10907 if (isDependentSpecialization) {
10908 // If it's a dependent specialization, it may not be possible
10909 // to determine the primary template (for explicit specializations)
10910 // or befriended declaration (for friends) until the enclosing
10911 // template is instantiated. In such cases, we store the declarations
10912 // found by name lookup and defer resolution until instantiation.
10913 if (CheckDependentFunctionTemplateSpecialization(
10914 FD: NewFD, ExplicitTemplateArgs, Previous))
10915 NewFD->setInvalidDecl();
10916 } else if (!NewFD->isInvalidDecl()) {
10917 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10918 Previous))
10919 NewFD->setInvalidDecl();
10920 }
10921 } else if (isMemberSpecialization && !FunctionTemplate) {
10922 if (CheckMemberSpecialization(Member: NewFD, Previous))
10923 NewFD->setInvalidDecl();
10924 }
10925
10926 // Perform semantic checking on the function declaration.
10927 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10928 CheckMain(FD: NewFD, D: D.getDeclSpec());
10929
10930 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10931 CheckMSVCRTEntryPoint(FD: NewFD);
10932
10933 if (!NewFD->isInvalidDecl())
10934 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10935 IsMemberSpecialization: isMemberSpecialization,
10936 DeclIsDefn: D.isFunctionDefinition()));
10937 else if (!Previous.empty())
10938 // Recover gracefully from an invalid redeclaration.
10939 D.setRedeclaration(true);
10940
10941 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10942 !D.isRedeclaration() ||
10943 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10944 "previous declaration set still overloaded");
10945
10946 NamedDecl *PrincipalDecl = (FunctionTemplate
10947 ? cast<NamedDecl>(Val: FunctionTemplate)
10948 : NewFD);
10949
10950 if (isFriend && NewFD->getPreviousDecl()) {
10951 AccessSpecifier Access = AS_public;
10952 if (!NewFD->isInvalidDecl())
10953 Access = NewFD->getPreviousDecl()->getAccess();
10954
10955 NewFD->setAccess(Access);
10956 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10957 }
10958
10959 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10960 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10961 PrincipalDecl->setNonMemberOperator();
10962
10963 // If we have a function template, check the template parameter
10964 // list. This will check and merge default template arguments.
10965 if (FunctionTemplate) {
10966 FunctionTemplateDecl *PrevTemplate =
10967 FunctionTemplate->getPreviousDecl();
10968 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10969 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10970 : nullptr,
10971 TPC: D.getDeclSpec().isFriendSpecified()
10972 ? (D.isFunctionDefinition()
10973 ? TPC_FriendFunctionTemplateDefinition
10974 : TPC_FriendFunctionTemplate)
10975 : (D.getCXXScopeSpec().isSet() &&
10976 DC && DC->isRecord() &&
10977 DC->isDependentContext())
10978 ? TPC_ClassTemplateMember
10979 : TPC_FunctionTemplate);
10980 }
10981
10982 if (NewFD->isInvalidDecl()) {
10983 // Ignore all the rest of this.
10984 } else if (!D.isRedeclaration()) {
10985 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10986 .AddToScope: AddToScope };
10987 // Fake up an access specifier if it's supposed to be a class member.
10988 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10989 NewFD->setAccess(AS_public);
10990
10991 // Qualified decls generally require a previous declaration.
10992 if (D.getCXXScopeSpec().isSet()) {
10993 // ...with the major exception of templated-scope or
10994 // dependent-scope friend declarations.
10995
10996 // TODO: we currently also suppress this check in dependent
10997 // contexts because (1) the parameter depth will be off when
10998 // matching friend templates and (2) we might actually be
10999 // selecting a friend based on a dependent factor. But there
11000 // are situations where these conditions don't apply and we
11001 // can actually do this check immediately.
11002 //
11003 // Unless the scope is dependent, it's always an error if qualified
11004 // redeclaration lookup found nothing at all. Diagnose that now;
11005 // nothing will diagnose that error later.
11006 if (isFriend &&
11007 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
11008 (!Previous.empty() && CurContext->isDependentContext()))) {
11009 // ignore these
11010 } else if (NewFD->isCPUDispatchMultiVersion() ||
11011 NewFD->isCPUSpecificMultiVersion()) {
11012 // ignore this, we allow the redeclaration behavior here to create new
11013 // versions of the function.
11014 } else {
11015 // The user tried to provide an out-of-line definition for a
11016 // function that is a member of a class or namespace, but there
11017 // was no such member function declared (C++ [class.mfct]p2,
11018 // C++ [namespace.memdef]p2). For example:
11019 //
11020 // class X {
11021 // void f() const;
11022 // };
11023 //
11024 // void X::f() { } // ill-formed
11025 //
11026 // Complain about this problem, and attempt to suggest close
11027 // matches (e.g., those that differ only in cv-qualifiers and
11028 // whether the parameter types are references).
11029
11030 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11031 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11032 AddToScope = ExtraArgs.AddToScope;
11033 return Result;
11034 }
11035 }
11036
11037 // Unqualified local friend declarations are required to resolve
11038 // to something.
11039 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11040 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11041 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11042 AddToScope = ExtraArgs.AddToScope;
11043 return Result;
11044 }
11045 }
11046 } else if (!D.isFunctionDefinition() &&
11047 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11048 !isFriend && !isFunctionTemplateSpecialization &&
11049 !isMemberSpecialization) {
11050 // An out-of-line member function declaration must also be a
11051 // definition (C++ [class.mfct]p2).
11052 // Note that this is not the case for explicit specializations of
11053 // function templates or member functions of class templates, per
11054 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11055 // extension for compatibility with old SWIG code which likes to
11056 // generate them.
11057 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11058 << D.getCXXScopeSpec().getRange();
11059 }
11060 }
11061
11062 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11063 // Any top level function could potentially be specified as an entry.
11064 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11065 HLSL().ActOnTopLevelFunction(FD: NewFD);
11066
11067 if (NewFD->hasAttr<HLSLShaderAttr>())
11068 HLSL().CheckEntryPoint(FD: NewFD);
11069
11070 // Resources cannot be passed to functions that are not inlined.
11071 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11072 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11073 QualType ParamTy = PVD->getType().getNonReferenceType();
11074 QualType EltTy = Context.getBaseElementType(QT: ParamTy);
11075 // `isCompleteType` forces completion of the element type without
11076 // reporting an error (diagnosed elsewhere) so the resource parameter
11077 // check is valid.
11078 if (!EltTy->isDependentType() &&
11079 isCompleteType(Loc: PVD->getLocation(), T: EltTy) &&
11080 ParamTy->isHLSLIntangibleType()) {
11081 Diag(Loc: PVD->getLocation(),
11082 DiagID: diag::err_hlsl_resource_param_in_noinline_function)
11083 << ParamTy;
11084 Diag(Loc: NoInline->getLocation(), DiagID: diag::note_attribute);
11085 }
11086 }
11087 }
11088 }
11089
11090 // If this is the first declaration of a library builtin function, add
11091 // attributes as appropriate.
11092 if (!D.isRedeclaration()) {
11093 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11094 if (unsigned BuiltinID = II->getBuiltinID()) {
11095 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11096 if (!InStdNamespace &&
11097 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11098 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11099 // Validate the type matches unless this builtin is specified as
11100 // matching regardless of its declared type.
11101 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11102 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11103 } else {
11104 ASTContext::GetBuiltinTypeError Error;
11105 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11106 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11107
11108 if (!Error && !BuiltinType.isNull() &&
11109 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11110 T: NewFD->getType(), U: BuiltinType))
11111 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11112 }
11113 }
11114 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11115 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11116 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11117 }
11118 }
11119 }
11120 }
11121
11122 ProcessPragmaWeak(S, D: NewFD);
11123 ProcessPragmaExport(NewD: NewFD);
11124 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11125
11126 AddKnownFunctionAttributes(FD: NewFD);
11127 // The above can add the format attribute for known builtin/library functions
11128 // which is required by the modular_format attribute, thus
11129 // validate modular_format now after those attributes have been added.
11130 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11131
11132 if (NewFD->hasAttr<OverloadableAttr>() &&
11133 !NewFD->getType()->getAs<FunctionProtoType>()) {
11134 Diag(Loc: NewFD->getLocation(),
11135 DiagID: diag::err_attribute_overloadable_no_prototype)
11136 << NewFD;
11137 NewFD->dropAttr<OverloadableAttr>();
11138 }
11139
11140 // If there's a #pragma GCC visibility in scope, and this isn't a class
11141 // member, set the visibility of this function.
11142 if (!DC->isRecord() && NewFD->isExternallyVisible())
11143 AddPushedVisibilityAttribute(RD: NewFD);
11144
11145 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11146 // marking the function.
11147 ObjC().AddCFAuditedAttribute(D: NewFD);
11148
11149 // If this is a function definition, check if we have to apply any
11150 // attributes (i.e. optnone and no_builtin) due to a pragma.
11151 if (D.isFunctionDefinition()) {
11152 AddRangeBasedOptnone(FD: NewFD);
11153 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11154 AddSectionMSAllocText(FD: NewFD);
11155 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11156 }
11157
11158 // If this is the first declaration of an extern C variable, update
11159 // the map of such variables.
11160 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11161 isIncompleteDeclExternC(S&: *this, D: NewFD))
11162 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11163
11164 // Set this FunctionDecl's range up to the right paren.
11165 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11166
11167 if (D.isRedeclaration() && !Previous.empty()) {
11168 NamedDecl *Prev = Previous.getRepresentativeDecl();
11169 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11170 IsSpecialization: isMemberSpecialization ||
11171 isFunctionTemplateSpecialization,
11172 IsDefinition: D.isFunctionDefinition());
11173 }
11174
11175 if (getLangOpts().CUDA) {
11176 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11177 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11178 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11179 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11180 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11181 << CUDA().getConfigureFuncName();
11182 Context.setcudaConfigureCallDecl(NewFD);
11183 }
11184 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11185 !NewFD->isInvalidDecl() &&
11186 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11187 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11188 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11189 << CUDA().getConfigureFuncName();
11190 Context.setcudaGetParameterBufferDecl(NewFD);
11191 }
11192 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11193 !NewFD->isInvalidDecl() &&
11194 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11195 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11196 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11197 << CUDA().getConfigureFuncName();
11198 Context.setcudaLaunchDeviceDecl(NewFD);
11199 }
11200 }
11201 }
11202
11203 MarkUnusedFileScopedDecl(D: NewFD);
11204
11205 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11206 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11207 if (SC == SC_Static) {
11208 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11209 D.setInvalidType();
11210 }
11211
11212 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11213 if (!NewFD->getReturnType()->isVoidType()) {
11214 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11215 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11216 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11217 : FixItHint());
11218 D.setInvalidType();
11219 }
11220
11221 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11222 for (auto *Param : NewFD->parameters())
11223 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11224
11225 if (getLangOpts().OpenCLCPlusPlus) {
11226 if (DC->isRecord()) {
11227 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11228 D.setInvalidType();
11229 }
11230 if (FunctionTemplate) {
11231 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11232 D.setInvalidType();
11233 }
11234 }
11235 }
11236
11237 if (getLangOpts().CPlusPlus) {
11238 // Precalculate whether this is a friend function template with a constraint
11239 // that depends on an enclosing template, per [temp.friend]p9.
11240 if (isFriend && FunctionTemplate &&
11241 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11242 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11243
11244 // C++ [temp.friend]p9:
11245 // A friend function template with a constraint that depends on a
11246 // template parameter from an enclosing template shall be a definition.
11247 if (!D.isFunctionDefinition()) {
11248 Diag(Loc: NewFD->getBeginLoc(),
11249 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11250 NewFD->setInvalidDecl();
11251 }
11252 }
11253
11254 if (FunctionTemplate) {
11255 if (NewFD->isInvalidDecl())
11256 FunctionTemplate->setInvalidDecl();
11257 return FunctionTemplate;
11258 }
11259
11260 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11261 CompleteMemberSpecialization(Member: NewFD, Previous);
11262 }
11263
11264 for (const ParmVarDecl *Param : NewFD->parameters()) {
11265 QualType PT = Param->getType();
11266
11267 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11268 // types.
11269 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11270 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11271 QualType ElemTy = PipeTy->getElementType();
11272 if (ElemTy->isPointerOrReferenceType()) {
11273 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11274 D.setInvalidType();
11275 }
11276 }
11277 }
11278 // WebAssembly tables can't be used as function parameters.
11279 if (Context.getTargetInfo().getTriple().isWasm()) {
11280 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11281 Diag(Loc: Param->getTypeSpecStartLoc(),
11282 DiagID: diag::err_wasm_table_as_function_parameter);
11283 D.setInvalidType();
11284 }
11285 }
11286 }
11287
11288 // Diagnose availability attributes. Availability cannot be used on functions
11289 // that are run during load/unload.
11290 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11291 if (NewFD->hasAttr<ConstructorAttr>()) {
11292 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11293 << 1;
11294 NewFD->dropAttr<AvailabilityAttr>();
11295 }
11296 if (NewFD->hasAttr<DestructorAttr>()) {
11297 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11298 << 2;
11299 NewFD->dropAttr<AvailabilityAttr>();
11300 }
11301 }
11302
11303 // Diagnose no_builtin attribute on function declaration that are not a
11304 // definition.
11305 // FIXME: We should really be doing this in
11306 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11307 // the FunctionDecl and at this point of the code
11308 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11309 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11310 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11311 switch (D.getFunctionDefinitionKind()) {
11312 case FunctionDefinitionKind::Defaulted:
11313 case FunctionDefinitionKind::Deleted:
11314 Diag(Loc: NBA->getLocation(),
11315 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11316 << NBA->getSpelling();
11317 break;
11318 case FunctionDefinitionKind::Declaration:
11319 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11320 << NBA->getSpelling();
11321 break;
11322 case FunctionDefinitionKind::Definition:
11323 break;
11324 }
11325
11326 // Similar to no_builtin logic above, at this point of the code
11327 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11328 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11329 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11330 !NewFD->isInvalidDecl() &&
11331 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11332 ExternalDeclarations.push_back(Elt: NewFD);
11333
11334 // Used for a warning on the 'next' declaration when used with a
11335 // `routine(name)`.
11336 if (getLangOpts().OpenACC)
11337 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11338
11339 return NewFD;
11340}
11341
11342/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11343/// when __declspec(code_seg) "is applied to a class, all member functions of
11344/// the class and nested classes -- this includes compiler-generated special
11345/// member functions -- are put in the specified segment."
11346/// The actual behavior is a little more complicated. The Microsoft compiler
11347/// won't check outer classes if there is an active value from #pragma code_seg.
11348/// The CodeSeg is always applied from the direct parent but only from outer
11349/// classes when the #pragma code_seg stack is empty. See:
11350/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11351/// available since MS has removed the page.
11352static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11353 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11354 if (!Method)
11355 return nullptr;
11356 const CXXRecordDecl *Parent = Method->getParent();
11357 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11358 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11359 NewAttr->setImplicit(true);
11360 return NewAttr;
11361 }
11362
11363 // The Microsoft compiler won't check outer classes for the CodeSeg
11364 // when the #pragma code_seg stack is active.
11365 if (S.CodeSegStack.CurrentValue)
11366 return nullptr;
11367
11368 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11369 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11370 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11371 NewAttr->setImplicit(true);
11372 return NewAttr;
11373 }
11374 }
11375 return nullptr;
11376}
11377
11378Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11379 bool IsDefinition) {
11380 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11381 return A;
11382 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11383 CodeSegStack.CurrentValue)
11384 return SectionAttr::CreateImplicit(
11385 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11386 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11387 return nullptr;
11388}
11389
11390bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11391 QualType NewT, QualType OldT) {
11392 if (!NewD->getLexicalDeclContext()->isDependentContext())
11393 return true;
11394
11395 // For dependently-typed local extern declarations and friends, we can't
11396 // perform a correct type check in general until instantiation:
11397 //
11398 // int f();
11399 // template<typename T> void g() { T f(); }
11400 //
11401 // (valid if g() is only instantiated with T = int).
11402 if (NewT->isDependentType() &&
11403 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11404 return false;
11405
11406 // Similarly, if the previous declaration was a dependent local extern
11407 // declaration, we don't really know its type yet.
11408 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11409 return false;
11410
11411 return true;
11412}
11413
11414bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11415 if (!D->getLexicalDeclContext()->isDependentContext())
11416 return true;
11417
11418 // Don't chain dependent friend function definitions until instantiation, to
11419 // permit cases like
11420 //
11421 // void func();
11422 // template<typename T> class C1 { friend void func() {} };
11423 // template<typename T> class C2 { friend void func() {} };
11424 //
11425 // ... which is valid if only one of C1 and C2 is ever instantiated.
11426 //
11427 // FIXME: This need only apply to function definitions. For now, we proxy
11428 // this by checking for a file-scope function. We do not want this to apply
11429 // to friend declarations nominating member functions, because that gets in
11430 // the way of access checks.
11431 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11432 return false;
11433
11434 auto *VD = dyn_cast<ValueDecl>(Val: D);
11435 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11436 return !VD || !PrevVD ||
11437 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11438 OldT: PrevVD->getType());
11439}
11440
11441/// Check the target or target_version attribute of the function for
11442/// MultiVersion validity.
11443///
11444/// Returns true if there was an error, false otherwise.
11445static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11446 const auto *TA = FD->getAttr<TargetAttr>();
11447 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11448
11449 assert((TA || TVA) && "Expecting target or target_version attribute");
11450
11451 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11452 enum ErrType { Feature = 0, Architecture = 1 };
11453
11454 if (TA) {
11455 ParsedTargetAttr ParseInfo =
11456 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11457 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11458 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11459 << Architecture << ParseInfo.CPU;
11460 return true;
11461 }
11462 for (const auto &Feat : ParseInfo.Features) {
11463 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11464 if (Feat[0] == '-') {
11465 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11466 << Feature << ("no-" + BareFeat);
11467 return true;
11468 }
11469
11470 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11471 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11472 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11473 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11474 << Feature << BareFeat;
11475 return true;
11476 }
11477 }
11478 }
11479
11480 if (TVA) {
11481 llvm::SmallVector<StringRef, 8> Feats;
11482 ParsedTargetAttr ParseInfo;
11483 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11484 ParseInfo =
11485 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11486 for (auto &Feat : ParseInfo.Features)
11487 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11488 } else {
11489 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11490 TVA->getFeatures(Out&: Feats);
11491 }
11492 for (const auto &Feat : Feats) {
11493 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11494 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11495 << Feature << Feat;
11496 return true;
11497 }
11498 }
11499 }
11500 return false;
11501}
11502
11503// Provide a white-list of attributes that are allowed to be combined with
11504// multiversion functions.
11505static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11506 MultiVersionKind MVKind) {
11507 // Note: this list/diagnosis must match the list in
11508 // checkMultiversionAttributesAllSame.
11509 switch (Kind) {
11510 default:
11511 return false;
11512 case attr::ArmLocallyStreaming:
11513 return MVKind == MultiVersionKind::TargetVersion ||
11514 MVKind == MultiVersionKind::TargetClones;
11515 case attr::Used:
11516 return MVKind == MultiVersionKind::Target;
11517 case attr::NonNull:
11518 case attr::NoThrow:
11519 return true;
11520 }
11521}
11522
11523static bool checkNonMultiVersionCompatAttributes(Sema &S,
11524 const FunctionDecl *FD,
11525 const FunctionDecl *CausedFD,
11526 MultiVersionKind MVKind) {
11527 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11528 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11529 << static_cast<unsigned>(MVKind) << A;
11530 if (CausedFD)
11531 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11532 return true;
11533 };
11534
11535 for (const Attr *A : FD->attrs()) {
11536 switch (A->getKind()) {
11537 case attr::CPUDispatch:
11538 case attr::CPUSpecific:
11539 if (MVKind != MultiVersionKind::CPUDispatch &&
11540 MVKind != MultiVersionKind::CPUSpecific)
11541 return Diagnose(S, A);
11542 break;
11543 case attr::Target:
11544 if (MVKind != MultiVersionKind::Target)
11545 return Diagnose(S, A);
11546 break;
11547 case attr::TargetVersion:
11548 if (MVKind != MultiVersionKind::TargetVersion &&
11549 MVKind != MultiVersionKind::TargetClones)
11550 return Diagnose(S, A);
11551 break;
11552 case attr::TargetClones:
11553 if (MVKind != MultiVersionKind::TargetClones &&
11554 MVKind != MultiVersionKind::TargetVersion)
11555 return Diagnose(S, A);
11556 break;
11557 default:
11558 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11559 return Diagnose(S, A);
11560 break;
11561 }
11562 }
11563 return false;
11564}
11565
11566bool Sema::areMultiversionVariantFunctionsCompatible(
11567 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11568 const PartialDiagnostic &NoProtoDiagID,
11569 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11570 const PartialDiagnosticAt &NoSupportDiagIDAt,
11571 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11572 bool ConstexprSupported, bool CLinkageMayDiffer) {
11573 enum DoesntSupport {
11574 FuncTemplates = 0,
11575 VirtFuncs = 1,
11576 DeducedReturn = 2,
11577 Constructors = 3,
11578 Destructors = 4,
11579 DeletedFuncs = 5,
11580 DefaultedFuncs = 6,
11581 ConstexprFuncs = 7,
11582 ConstevalFuncs = 8,
11583 Lambda = 9,
11584 };
11585 enum Different {
11586 CallingConv = 0,
11587 ReturnType = 1,
11588 ConstexprSpec = 2,
11589 InlineSpec = 3,
11590 Linkage = 4,
11591 LanguageLinkage = 5,
11592 };
11593
11594 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11595 !OldFD->getType()->getAs<FunctionProtoType>()) {
11596 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11597 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11598 return true;
11599 }
11600
11601 if (NoProtoDiagID.getDiagID() != 0 &&
11602 !NewFD->getType()->getAs<FunctionProtoType>())
11603 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11604
11605 if (!TemplatesSupported &&
11606 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11607 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11608 << FuncTemplates;
11609
11610 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11611 if (NewCXXFD->isVirtual())
11612 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11613 << VirtFuncs;
11614
11615 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11616 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11617 << Constructors;
11618
11619 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11620 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11621 << Destructors;
11622 }
11623
11624 if (NewFD->isDeleted())
11625 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11626 << DeletedFuncs;
11627
11628 if (NewFD->isDefaulted())
11629 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11630 << DefaultedFuncs;
11631
11632 if (!ConstexprSupported && NewFD->isConstexpr())
11633 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11634 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11635
11636 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11637 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11638 QualType NewReturnType = NewType->getReturnType();
11639
11640 if (NewReturnType->isUndeducedType())
11641 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11642 << DeducedReturn;
11643
11644 // Ensure the return type is identical.
11645 if (OldFD) {
11646 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11647 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11648 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11649 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11650
11651 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11652 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11653
11654 bool ArmStreamingCCMismatched = false;
11655 if (OldFPT && NewFPT) {
11656 unsigned Diff =
11657 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11658 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11659 // cannot be mixed.
11660 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11661 FunctionType::SME_PStateSMCompatibleMask))
11662 ArmStreamingCCMismatched = true;
11663 }
11664
11665 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11666 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11667
11668 QualType OldReturnType = OldType->getReturnType();
11669
11670 if (OldReturnType != NewReturnType)
11671 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11672
11673 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11674 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11675
11676 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11677 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11678
11679 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11680 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11681
11682 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11683 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11684
11685 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11686 NewLoc: NewFD->getLocation()))
11687 return true;
11688 }
11689 return false;
11690}
11691
11692static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11693 const FunctionDecl *NewFD,
11694 bool CausesMV,
11695 MultiVersionKind MVKind) {
11696 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11697 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11698 if (OldFD)
11699 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11700 return true;
11701 }
11702
11703 bool IsCPUSpecificCPUDispatchMVKind =
11704 MVKind == MultiVersionKind::CPUDispatch ||
11705 MVKind == MultiVersionKind::CPUSpecific;
11706
11707 if (CausesMV && OldFD &&
11708 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11709 return true;
11710
11711 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11712 return true;
11713
11714 // Only allow transition to MultiVersion if it hasn't been used.
11715 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11716 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11717 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11718 return true;
11719 }
11720
11721 return S.areMultiversionVariantFunctionsCompatible(
11722 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11723 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11724 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11725 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11726 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11727 << static_cast<unsigned>(MVKind)),
11728 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11729 S.PDiag(DiagID: diag::err_multiversion_diff)),
11730 /*TemplatesSupported=*/false,
11731 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11732 /*CLinkageMayDiffer=*/false);
11733}
11734
11735/// Check the validity of a multiversion function declaration that is the
11736/// first of its kind. Also sets the multiversion'ness' of the function itself.
11737///
11738/// This sets NewFD->isInvalidDecl() to true if there was an error.
11739///
11740/// Returns true if there was an error, false otherwise.
11741static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11742 MultiVersionKind MVKind = FD->getMultiVersionKind();
11743 assert(MVKind != MultiVersionKind::None &&
11744 "Function lacks multiversion attribute");
11745 const auto *TA = FD->getAttr<TargetAttr>();
11746 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11747 // The target attribute only causes MV if this declaration is the default,
11748 // otherwise it is treated as a normal function.
11749 if (TA && !TA->isDefaultVersion())
11750 return false;
11751
11752 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11753 FD->setInvalidDecl();
11754 return true;
11755 }
11756
11757 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11758 FD->setInvalidDecl();
11759 return true;
11760 }
11761
11762 FD->setIsMultiVersion();
11763 return false;
11764}
11765
11766static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11767 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11768 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11769 return true;
11770 }
11771
11772 return false;
11773}
11774
11775static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11776 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11777 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11778 return;
11779
11780 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11781 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11782
11783 if (MVKindTo == MultiVersionKind::None &&
11784 (MVKindFrom == MultiVersionKind::TargetVersion ||
11785 MVKindFrom == MultiVersionKind::TargetClones))
11786 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11787 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11788}
11789
11790static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11791 FunctionDecl *NewFD,
11792 bool &Redeclaration,
11793 NamedDecl *&OldDecl,
11794 LookupResult &Previous) {
11795 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11796
11797 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11798 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11799 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11800 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11801
11802 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11803
11804 // The definitions should be allowed in any order. If we have discovered
11805 // a new target version and the preceeding was the default, then add the
11806 // corresponding attribute to it.
11807 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11808
11809 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11810 // to change, this is a simple redeclaration.
11811 if (NewTA && !NewTA->isDefaultVersion() &&
11812 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11813 return false;
11814
11815 // Otherwise, this decl causes MultiVersioning.
11816 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11817 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11818 : MultiVersionKind::Target)) {
11819 NewFD->setInvalidDecl();
11820 return true;
11821 }
11822
11823 if (CheckMultiVersionValue(S, FD: NewFD)) {
11824 NewFD->setInvalidDecl();
11825 return true;
11826 }
11827
11828 // If this is 'default', permit the forward declaration.
11829 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11830 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11831 Redeclaration = true;
11832 OldDecl = OldFD;
11833 OldFD->setIsMultiVersion();
11834 NewFD->setIsMultiVersion();
11835 return false;
11836 }
11837
11838 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11839 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11840 NewFD->setInvalidDecl();
11841 return true;
11842 }
11843
11844 if (NewTA) {
11845 ParsedTargetAttr OldParsed =
11846 S.getASTContext().getTargetInfo().parseTargetAttr(
11847 Str: OldTA->getFeaturesStr());
11848 llvm::sort(C&: OldParsed.Features);
11849 ParsedTargetAttr NewParsed =
11850 S.getASTContext().getTargetInfo().parseTargetAttr(
11851 Str: NewTA->getFeaturesStr());
11852 // Sort order doesn't matter, it just needs to be consistent.
11853 llvm::sort(C&: NewParsed.Features);
11854 if (OldParsed == NewParsed) {
11855 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11856 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11857 NewFD->setInvalidDecl();
11858 return true;
11859 }
11860 }
11861
11862 for (const auto *FD : OldFD->redecls()) {
11863 const auto *CurTA = FD->getAttr<TargetAttr>();
11864 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11865 // We allow forward declarations before ANY multiversioning attributes, but
11866 // nothing after the fact.
11867 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11868 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11869 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11870 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11871 << (NewTA ? 0 : 2);
11872 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11873 NewFD->setInvalidDecl();
11874 return true;
11875 }
11876 }
11877
11878 OldFD->setIsMultiVersion();
11879 NewFD->setIsMultiVersion();
11880 Redeclaration = false;
11881 OldDecl = nullptr;
11882 Previous.clear();
11883 return false;
11884}
11885
11886static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11887 MultiVersionKind OldKind = Old->getMultiVersionKind();
11888 MultiVersionKind NewKind = New->getMultiVersionKind();
11889
11890 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11891 NewKind == MultiVersionKind::None)
11892 return true;
11893
11894 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11895 switch (OldKind) {
11896 case MultiVersionKind::TargetVersion:
11897 return NewKind == MultiVersionKind::TargetClones;
11898 case MultiVersionKind::TargetClones:
11899 return NewKind == MultiVersionKind::TargetVersion;
11900 default:
11901 return false;
11902 }
11903 } else {
11904 switch (OldKind) {
11905 case MultiVersionKind::CPUDispatch:
11906 return NewKind == MultiVersionKind::CPUSpecific;
11907 case MultiVersionKind::CPUSpecific:
11908 return NewKind == MultiVersionKind::CPUDispatch;
11909 default:
11910 return false;
11911 }
11912 }
11913}
11914
11915/// Check the validity of a new function declaration being added to an existing
11916/// multiversioned declaration collection.
11917static bool CheckMultiVersionAdditionalDecl(
11918 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11919 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11920 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11921 LookupResult &Previous) {
11922
11923 // Disallow mixing of multiversioning types.
11924 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11925 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11926 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11927 NewFD->setInvalidDecl();
11928 return true;
11929 }
11930
11931 // Add the default target_version attribute if it's missing.
11932 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11933 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11934
11935 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11936 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11937 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11938 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11939
11940 ParsedTargetAttr NewParsed;
11941 if (NewTA) {
11942 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11943 Str: NewTA->getFeaturesStr());
11944 llvm::sort(C&: NewParsed.Features);
11945 }
11946 llvm::SmallVector<StringRef, 8> NewFeats;
11947 if (NewTVA) {
11948 NewTVA->getFeatures(Out&: NewFeats);
11949 llvm::sort(C&: NewFeats);
11950 }
11951
11952 bool UseMemberUsingDeclRules =
11953 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11954
11955 bool MayNeedOverloadableChecks =
11956 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11957
11958 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11959 // of a previous member of the MultiVersion set.
11960 for (NamedDecl *ND : Previous) {
11961 FunctionDecl *CurFD = ND->getAsFunction();
11962 if (!CurFD || CurFD->isInvalidDecl())
11963 continue;
11964 if (MayNeedOverloadableChecks &&
11965 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11966 continue;
11967
11968 switch (NewMVKind) {
11969 case MultiVersionKind::None:
11970 assert(OldMVKind == MultiVersionKind::TargetClones &&
11971 "Only target_clones can be omitted in subsequent declarations");
11972 break;
11973 case MultiVersionKind::Target: {
11974 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11975 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11976 NewFD->setIsMultiVersion();
11977 Redeclaration = true;
11978 OldDecl = ND;
11979 return false;
11980 }
11981
11982 ParsedTargetAttr CurParsed =
11983 S.getASTContext().getTargetInfo().parseTargetAttr(
11984 Str: CurTA->getFeaturesStr());
11985 llvm::sort(C&: CurParsed.Features);
11986 if (CurParsed == NewParsed) {
11987 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11988 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11989 NewFD->setInvalidDecl();
11990 return true;
11991 }
11992 break;
11993 }
11994 case MultiVersionKind::TargetVersion: {
11995 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11996 if (CurTVA->getName() == NewTVA->getName()) {
11997 NewFD->setIsMultiVersion();
11998 Redeclaration = true;
11999 OldDecl = ND;
12000 return false;
12001 }
12002 llvm::SmallVector<StringRef, 8> CurFeats;
12003 CurTVA->getFeatures(Out&: CurFeats);
12004 llvm::sort(C&: CurFeats);
12005
12006 if (CurFeats == NewFeats) {
12007 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12008 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12009 NewFD->setInvalidDecl();
12010 return true;
12011 }
12012 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12013 // Default
12014 if (NewFeats.empty())
12015 break;
12016
12017 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12018 llvm::SmallVector<StringRef, 8> CurFeats;
12019 CurClones->getFeatures(Out&: CurFeats, Index: I);
12020 llvm::sort(C&: CurFeats);
12021
12022 if (CurFeats == NewFeats) {
12023 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12024 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12025 NewFD->setInvalidDecl();
12026 return true;
12027 }
12028 }
12029 }
12030 break;
12031 }
12032 case MultiVersionKind::TargetClones: {
12033 assert(NewClones && "MultiVersionKind does not match attribute type");
12034 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12035 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12036 !std::equal(first1: CurClones->featuresStrs_begin(),
12037 last1: CurClones->featuresStrs_end(),
12038 first2: NewClones->featuresStrs_begin())) {
12039 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
12040 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12041 NewFD->setInvalidDecl();
12042 return true;
12043 }
12044 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12045 llvm::SmallVector<StringRef, 8> CurFeats;
12046 CurTVA->getFeatures(Out&: CurFeats);
12047 llvm::sort(C&: CurFeats);
12048
12049 // Default
12050 if (CurFeats.empty())
12051 break;
12052
12053 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12054 NewFeats.clear();
12055 NewClones->getFeatures(Out&: NewFeats, Index: I);
12056 llvm::sort(C&: NewFeats);
12057
12058 if (CurFeats == NewFeats) {
12059 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12060 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12061 NewFD->setInvalidDecl();
12062 return true;
12063 }
12064 }
12065 break;
12066 }
12067 Redeclaration = true;
12068 OldDecl = CurFD;
12069 NewFD->setIsMultiVersion();
12070 return false;
12071 }
12072 case MultiVersionKind::CPUSpecific:
12073 case MultiVersionKind::CPUDispatch: {
12074 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12075 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12076 // Handle CPUDispatch/CPUSpecific versions.
12077 // Only 1 CPUDispatch function is allowed, this will make it go through
12078 // the redeclaration errors.
12079 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12080 CurFD->hasAttr<CPUDispatchAttr>()) {
12081 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12082 std::equal(
12083 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12084 first2: NewCPUDisp->cpus_begin(),
12085 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12086 return Cur->getName() == New->getName();
12087 })) {
12088 NewFD->setIsMultiVersion();
12089 Redeclaration = true;
12090 OldDecl = ND;
12091 return false;
12092 }
12093
12094 // If the declarations don't match, this is an error condition.
12095 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12096 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12097 NewFD->setInvalidDecl();
12098 return true;
12099 }
12100 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12101 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12102 std::equal(
12103 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12104 first2: NewCPUSpec->cpus_begin(),
12105 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12106 return Cur->getName() == New->getName();
12107 })) {
12108 NewFD->setIsMultiVersion();
12109 Redeclaration = true;
12110 OldDecl = ND;
12111 return false;
12112 }
12113
12114 // Only 1 version of CPUSpecific is allowed for each CPU.
12115 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12116 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12117 if (CurII == NewII) {
12118 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12119 << NewII;
12120 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12121 NewFD->setInvalidDecl();
12122 return true;
12123 }
12124 }
12125 }
12126 }
12127 break;
12128 }
12129 }
12130 }
12131
12132 // Redeclarations of a target_clones function may omit the attribute, in which
12133 // case it will be inherited during declaration merging.
12134 if (NewMVKind == MultiVersionKind::None &&
12135 OldMVKind == MultiVersionKind::TargetClones) {
12136 NewFD->setIsMultiVersion();
12137 Redeclaration = true;
12138 OldDecl = OldFD;
12139 return false;
12140 }
12141
12142 // Else, this is simply a non-redecl case. Checking the 'value' is only
12143 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12144 // handled in the attribute adding step.
12145 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12146 NewFD->setInvalidDecl();
12147 return true;
12148 }
12149
12150 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12151 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12152 NewFD->setInvalidDecl();
12153 return true;
12154 }
12155
12156 // Permit forward declarations in the case where these two are compatible.
12157 if (!OldFD->isMultiVersion()) {
12158 OldFD->setIsMultiVersion();
12159 NewFD->setIsMultiVersion();
12160 Redeclaration = true;
12161 OldDecl = OldFD;
12162 return false;
12163 }
12164
12165 NewFD->setIsMultiVersion();
12166 Redeclaration = false;
12167 OldDecl = nullptr;
12168 Previous.clear();
12169 return false;
12170}
12171
12172/// Check the validity of a mulitversion function declaration.
12173/// Also sets the multiversion'ness' of the function itself.
12174///
12175/// This sets NewFD->isInvalidDecl() to true if there was an error.
12176///
12177/// Returns true if there was an error, false otherwise.
12178static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12179 bool &Redeclaration, NamedDecl *&OldDecl,
12180 LookupResult &Previous) {
12181 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12182
12183 // Check if FMV is disabled.
12184 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12185 return false;
12186
12187 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12188 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12189 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12190 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12191 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12192 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12193
12194 // Main isn't allowed to become a multiversion function, however it IS
12195 // permitted to have 'main' be marked with the 'target' optimization hint,
12196 // for 'target_version' only default is allowed.
12197 if (NewFD->isMain()) {
12198 if (MVKind != MultiVersionKind::None &&
12199 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12200 !(MVKind == MultiVersionKind::TargetVersion &&
12201 NewTVA->isDefaultVersion())) {
12202 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12203 NewFD->setInvalidDecl();
12204 return true;
12205 }
12206 return false;
12207 }
12208
12209 // Target attribute on AArch64 is not used for multiversioning
12210 if (NewTA && TI.getTriple().isAArch64())
12211 return false;
12212
12213 // Target attribute on RISCV is not used for multiversioning
12214 if (NewTA && TI.getTriple().isRISCV())
12215 return false;
12216
12217 if (!OldDecl || !OldDecl->getAsFunction() ||
12218 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12219 DC: NewFD->getDeclContext()->getRedeclContext())) {
12220 // If there's no previous declaration, AND this isn't attempting to cause
12221 // multiversioning, this isn't an error condition.
12222 if (MVKind == MultiVersionKind::None)
12223 return false;
12224 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12225 }
12226
12227 FunctionDecl *OldFD = OldDecl->getAsFunction();
12228
12229 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12230 return false;
12231
12232 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12233 // for target_clones and target_version.
12234 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12235 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12236 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12237 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12238 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12239 NewFD->setInvalidDecl();
12240 return true;
12241 }
12242
12243 if (!OldFD->isMultiVersion()) {
12244 switch (MVKind) {
12245 case MultiVersionKind::Target:
12246 case MultiVersionKind::TargetVersion:
12247 return CheckDeclarationCausesMultiVersioning(
12248 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12249 case MultiVersionKind::TargetClones:
12250 if (OldFD->isUsed(CheckUsedAttr: false)) {
12251 NewFD->setInvalidDecl();
12252 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12253 }
12254 OldFD->setIsMultiVersion();
12255 break;
12256
12257 case MultiVersionKind::CPUDispatch:
12258 case MultiVersionKind::CPUSpecific:
12259 case MultiVersionKind::None:
12260 break;
12261 }
12262 }
12263
12264 // At this point, we have a multiversion function decl (in OldFD) AND an
12265 // appropriate attribute in the current function decl (unless it's allowed to
12266 // omit the attribute). Resolve that these are still compatible with previous
12267 // declarations.
12268 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12269 NewCPUSpec, NewClones, Redeclaration,
12270 OldDecl, Previous);
12271}
12272
12273static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12274 bool IsPure = NewFD->hasAttr<PureAttr>();
12275 bool IsConst = NewFD->hasAttr<ConstAttr>();
12276
12277 // If there are no pure or const attributes, there's nothing to check.
12278 if (!IsPure && !IsConst)
12279 return;
12280
12281 // If the function is marked both pure and const, we retain the const
12282 // attribute because it makes stronger guarantees than the pure attribute, and
12283 // we drop the pure attribute explicitly to prevent later confusion about
12284 // semantics.
12285 if (IsPure && IsConst) {
12286 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12287 NewFD->dropAttrs<PureAttr>();
12288 }
12289
12290 // Constructors and destructors are functions which return void, so are
12291 // handled here as well.
12292 if (NewFD->getReturnType()->isVoidType()) {
12293 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12294 << IsConst;
12295 NewFD->dropAttrs<PureAttr, ConstAttr>();
12296 }
12297}
12298
12299bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12300 LookupResult &Previous,
12301 bool IsMemberSpecialization,
12302 bool DeclIsDefn) {
12303 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12304 "Variably modified return types are not handled here");
12305
12306 // Determine whether the type of this function should be merged with
12307 // a previous visible declaration. This never happens for functions in C++,
12308 // and always happens in C if the previous declaration was visible.
12309 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12310 !Previous.isShadowed();
12311
12312 bool Redeclaration = false;
12313 NamedDecl *OldDecl = nullptr;
12314 bool MayNeedOverloadableChecks = false;
12315
12316 inferLifetimeCaptureByAttribute(FD: NewFD);
12317 // Merge or overload the declaration with an existing declaration of
12318 // the same name, if appropriate.
12319 if (!Previous.empty()) {
12320 // Determine whether NewFD is an overload of PrevDecl or
12321 // a declaration that requires merging. If it's an overload,
12322 // there's no more work to do here; we'll just add the new
12323 // function to the scope.
12324 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12325 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12326 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12327 Redeclaration = true;
12328 OldDecl = Candidate;
12329 }
12330 } else {
12331 MayNeedOverloadableChecks = true;
12332 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12333 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12334 case OverloadKind::Match:
12335 Redeclaration = true;
12336 break;
12337
12338 case OverloadKind::NonFunction:
12339 Redeclaration = true;
12340 break;
12341
12342 case OverloadKind::Overload:
12343 Redeclaration = false;
12344 break;
12345 }
12346 }
12347 }
12348
12349 // Check for a previous extern "C" declaration with this name.
12350 if (!Redeclaration &&
12351 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12352 if (!Previous.empty()) {
12353 // This is an extern "C" declaration with the same name as a previous
12354 // declaration, and thus redeclares that entity...
12355 Redeclaration = true;
12356 OldDecl = Previous.getFoundDecl();
12357 MergeTypeWithPrevious = false;
12358
12359 // ... except in the presence of __attribute__((overloadable)).
12360 if (OldDecl->hasAttr<OverloadableAttr>() ||
12361 NewFD->hasAttr<OverloadableAttr>()) {
12362 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12363 MayNeedOverloadableChecks = true;
12364 Redeclaration = false;
12365 OldDecl = nullptr;
12366 }
12367 }
12368 }
12369 }
12370
12371 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12372 return Redeclaration;
12373
12374 // PPC MMA non-pointer types are not allowed as function return types.
12375 if (Context.getTargetInfo().getTriple().isPPC64() &&
12376 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12377 NewFD->setInvalidDecl();
12378 }
12379
12380 CheckConstPureAttributesUsage(S&: *this, NewFD);
12381
12382 // C++ [dcl.spec.auto.general]p12:
12383 // Return type deduction for a templated function with a placeholder in its
12384 // declared type occurs when the definition is instantiated even if the
12385 // function body contains a return statement with a non-type-dependent
12386 // operand.
12387 //
12388 // C++ [temp.dep.expr]p3:
12389 // An id-expression is type-dependent if it is a template-id that is not a
12390 // concept-id and is dependent; or if its terminal name is:
12391 // - [...]
12392 // - associated by name lookup with one or more declarations of member
12393 // functions of a class that is the current instantiation declared with a
12394 // return type that contains a placeholder type,
12395 // - [...]
12396 //
12397 // If this is a templated function with a placeholder in its return type,
12398 // make the placeholder type dependent since it won't be deduced until the
12399 // definition is instantiated. We do this here because it needs to happen
12400 // for implicitly instantiated member functions/member function templates.
12401 if (getLangOpts().CPlusPlus14 &&
12402 (NewFD->isDependentContext() &&
12403 NewFD->getReturnType()->isUndeducedType())) {
12404 const FunctionProtoType *FPT =
12405 NewFD->getType()->castAs<FunctionProtoType>();
12406 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12407 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12408 EPI: FPT->getExtProtoInfo()));
12409 }
12410
12411 // C++11 [dcl.constexpr]p8:
12412 // A constexpr specifier for a non-static member function that is not
12413 // a constructor declares that member function to be const.
12414 //
12415 // This needs to be delayed until we know whether this is an out-of-line
12416 // definition of a static member function.
12417 //
12418 // This rule is not present in C++1y, so we produce a backwards
12419 // compatibility warning whenever it happens in C++11.
12420 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12421 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12422 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12423 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12424 CXXMethodDecl *OldMD = nullptr;
12425 if (OldDecl)
12426 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12427 if (!OldMD || !OldMD->isStatic()) {
12428 const FunctionProtoType *FPT =
12429 MD->getType()->castAs<FunctionProtoType>();
12430 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12431 EPI.TypeQuals.addConst();
12432 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12433 Args: FPT->getParamTypes(), EPI));
12434
12435 // Warn that we did this, if we're not performing template instantiation.
12436 // In that case, we'll have warned already when the template was defined.
12437 if (!inTemplateInstantiation()) {
12438 SourceLocation AddConstLoc;
12439 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12440 .IgnoreParens().getAs<FunctionTypeLoc>())
12441 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12442
12443 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12444 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12445 }
12446 }
12447 }
12448
12449 if (Redeclaration) {
12450 // NewFD and OldDecl represent declarations that need to be
12451 // merged.
12452 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12453 NewDeclIsDefn: DeclIsDefn)) {
12454 NewFD->setInvalidDecl();
12455 return Redeclaration;
12456 }
12457
12458 Previous.clear();
12459 Previous.addDecl(D: OldDecl);
12460
12461 if (FunctionTemplateDecl *OldTemplateDecl =
12462 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12463 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12464 FunctionTemplateDecl *NewTemplateDecl
12465 = NewFD->getDescribedFunctionTemplate();
12466 assert(NewTemplateDecl && "Template/non-template mismatch");
12467
12468 // The call to MergeFunctionDecl above may have created some state in
12469 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12470 // can add it as a redeclaration.
12471 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12472
12473 NewFD->setPreviousDeclaration(OldFD);
12474 if (NewFD->isCXXClassMember()) {
12475 NewFD->setAccess(OldTemplateDecl->getAccess());
12476 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12477 }
12478
12479 // If this is an explicit specialization of a member that is a function
12480 // template, mark it as a member specialization.
12481 if (IsMemberSpecialization &&
12482 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12483 NewTemplateDecl->setMemberSpecialization();
12484 assert(OldTemplateDecl->isMemberSpecialization());
12485 // Explicit specializations of a member template do not inherit deleted
12486 // status from the parent member template that they are specializing.
12487 if (OldFD->isDeleted()) {
12488 // FIXME: This assert will not hold in the presence of modules.
12489 assert(OldFD->getCanonicalDecl() == OldFD);
12490 // FIXME: We need an update record for this AST mutation.
12491 OldFD->setDeletedAsWritten(D: false);
12492 }
12493 }
12494
12495 } else {
12496 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12497 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12498 // This needs to happen first so that 'inline' propagates.
12499 NewFD->setPreviousDeclaration(OldFD);
12500 if (NewFD->isCXXClassMember())
12501 NewFD->setAccess(OldFD->getAccess());
12502 }
12503 }
12504 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12505 !NewFD->getAttr<OverloadableAttr>()) {
12506 assert((Previous.empty() ||
12507 llvm::any_of(Previous,
12508 [](const NamedDecl *ND) {
12509 return ND->hasAttr<OverloadableAttr>();
12510 })) &&
12511 "Non-redecls shouldn't happen without overloadable present");
12512
12513 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12514 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12515 return FD && !FD->hasAttr<OverloadableAttr>();
12516 });
12517
12518 if (OtherUnmarkedIter != Previous.end()) {
12519 Diag(Loc: NewFD->getLocation(),
12520 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12521 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12522 DiagID: diag::note_attribute_overloadable_prev_overload)
12523 << false;
12524
12525 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12526 }
12527 }
12528
12529 if (LangOpts.OpenMP)
12530 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12531
12532 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12533 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12534
12535 if (NewFD->hasAttr<SYCLExternalAttr>())
12536 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12537
12538 // Semantic checking for this function declaration (in isolation).
12539
12540 if (getLangOpts().CPlusPlus) {
12541 // C++-specific checks.
12542 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12543 CheckConstructor(Constructor);
12544 } else if (CXXDestructorDecl *Destructor =
12545 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12546 // We check here for invalid destructor names.
12547 // If we have a friend destructor declaration that is dependent, we can't
12548 // diagnose right away because cases like this are still valid:
12549 // template <class T> struct A { friend T::X::~Y(); };
12550 // struct B { struct Y { ~Y(); }; using X = Y; };
12551 // template struct A<B>;
12552 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12553 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12554 CanQualType ClassType =
12555 Context.getCanonicalTagType(TD: Destructor->getParent());
12556
12557 DeclarationName Name =
12558 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12559 if (NewFD->getDeclName() != Name) {
12560 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12561 NewFD->setInvalidDecl();
12562 return Redeclaration;
12563 }
12564 }
12565 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12566 if (auto *TD = Guide->getDescribedFunctionTemplate())
12567 CheckDeductionGuideTemplate(TD);
12568
12569 // A deduction guide is not on the list of entities that can be
12570 // explicitly specialized.
12571 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12572 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12573 << /*explicit specialization*/ 1;
12574 }
12575
12576 // Find any virtual functions that this function overrides.
12577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12578 if (!Method->isFunctionTemplateSpecialization() &&
12579 !Method->getDescribedFunctionTemplate() &&
12580 Method->isCanonicalDecl()) {
12581 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12582 }
12583 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12584 // C++2a [class.virtual]p6
12585 // A virtual method shall not have a requires-clause.
12586 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12587 DiagID: diag::err_constrained_virtual_method);
12588
12589 if (Method->isStatic())
12590 checkThisInStaticMemberFunctionType(Method);
12591 }
12592
12593 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12594 ActOnConversionDeclarator(Conversion);
12595
12596 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12597 if (NewFD->isOverloadedOperator() &&
12598 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12599 NewFD->setInvalidDecl();
12600 return Redeclaration;
12601 }
12602
12603 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12604 if (NewFD->getLiteralIdentifier() &&
12605 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12606 NewFD->setInvalidDecl();
12607 return Redeclaration;
12608 }
12609
12610 // In C++, check default arguments now that we have merged decls. Unless
12611 // the lexical context is the class, because in this case this is done
12612 // during delayed parsing anyway.
12613 if (!CurContext->isRecord())
12614 CheckCXXDefaultArguments(FD: NewFD);
12615
12616 // If this function is declared as being extern "C", then check to see if
12617 // the function returns a UDT (class, struct, or union type) that is not C
12618 // compatible, and if it does, warn the user.
12619 // But, issue any diagnostic on the first declaration only.
12620 if (Previous.empty() && NewFD->isExternC()) {
12621 QualType R = NewFD->getReturnType();
12622 if (R->isIncompleteType() && !R->isVoidType())
12623 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12624 << NewFD << R;
12625 else if (!R.isPODType(Context) && !R->isVoidType() &&
12626 !R->isObjCObjectPointerType())
12627 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12628 }
12629
12630 // C++1z [dcl.fct]p6:
12631 // [...] whether the function has a non-throwing exception-specification
12632 // [is] part of the function type
12633 //
12634 // This results in an ABI break between C++14 and C++17 for functions whose
12635 // declared type includes an exception-specification in a parameter or
12636 // return type. (Exception specifications on the function itself are OK in
12637 // most cases, and exception specifications are not permitted in most other
12638 // contexts where they could make it into a mangling.)
12639 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12640 auto HasNoexcept = [&](QualType T) -> bool {
12641 // Strip off declarator chunks that could be between us and a function
12642 // type. We don't need to look far, exception specifications are very
12643 // restricted prior to C++17.
12644 if (auto *RT = T->getAs<ReferenceType>())
12645 T = RT->getPointeeType();
12646 else if (T->isAnyPointerType())
12647 T = T->getPointeeType();
12648 else if (auto *MPT = T->getAs<MemberPointerType>())
12649 T = MPT->getPointeeType();
12650 if (auto *FPT = T->getAs<FunctionProtoType>())
12651 if (FPT->isNothrow())
12652 return true;
12653 return false;
12654 };
12655
12656 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12657 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12658 for (QualType T : FPT->param_types())
12659 AnyNoexcept |= HasNoexcept(T);
12660 if (AnyNoexcept)
12661 Diag(Loc: NewFD->getLocation(),
12662 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12663 << NewFD;
12664 }
12665
12666 if (!Redeclaration && LangOpts.CUDA) {
12667 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12668 for (auto *Parm : NewFD->parameters()) {
12669 if (!Parm->getType()->isDependentType() &&
12670 Parm->hasAttr<CUDAGridConstantAttr>() &&
12671 !(IsKernel && Parm->getType().isConstQualified()))
12672 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12673 DiagID: diag::err_cuda_grid_constant_not_allowed);
12674 }
12675 CUDA().checkTargetOverload(NewFD, Previous);
12676 }
12677 }
12678
12679 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12680 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12681
12682 return Redeclaration;
12683}
12684
12685void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12686 // [basic.start.main]p3
12687 // The main function shall not be declared with C linkage-specification.
12688 if (FD->isExternCContext())
12689 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12690
12691 // C++11 [basic.start.main]p3:
12692 // A program that [...] declares main to be inline, static or
12693 // constexpr is ill-formed.
12694 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12695 // appear in a declaration of main.
12696 // static main is not an error under C99, but we should warn about it.
12697 // We accept _Noreturn main as an extension.
12698 if (FD->getStorageClass() == SC_Static)
12699 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12700 ? diag::err_static_main : diag::warn_static_main)
12701 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12702 if (FD->isInlineSpecified())
12703 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12704 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12705 if (DS.isNoreturnSpecified()) {
12706 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12707 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12708 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12709 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12710 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12711 }
12712 if (FD->isConstexpr()) {
12713 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12714 << FD->isConsteval()
12715 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12716 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12717 }
12718
12719 if (getLangOpts().OpenCL) {
12720 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12721 << FD->hasAttr<DeviceKernelAttr>();
12722 FD->setInvalidDecl();
12723 return;
12724 }
12725
12726 if (FD->hasAttr<SYCLExternalAttr>()) {
12727 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12728 << FD->getAttr<SYCLExternalAttr>();
12729 FD->setInvalidDecl();
12730 return;
12731 }
12732
12733 // Functions named main in hlsl are default entries, but don't have specific
12734 // signatures they are required to conform to.
12735 if (getLangOpts().HLSL)
12736 return;
12737
12738 QualType T = FD->getType();
12739 assert(T->isFunctionType() && "function decl is not of function type");
12740 const FunctionType* FT = T->castAs<FunctionType>();
12741
12742 // Set default calling convention for main()
12743 if (FT->getCallConv() != CC_C) {
12744 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12745 FD->setType(QualType(FT, 0));
12746 T = Context.getCanonicalType(T: FD->getType());
12747 }
12748
12749 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12750 // In C with GNU extensions we allow main() to have non-integer return
12751 // type, but we should warn about the extension, and we disable the
12752 // implicit-return-zero rule.
12753
12754 // GCC in C mode accepts qualified 'int'.
12755 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12756 FD->setHasImplicitReturnZero(true);
12757 else {
12758 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12759 SourceRange RTRange = FD->getReturnTypeSourceRange();
12760 if (RTRange.isValid())
12761 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12762 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12763 }
12764 } else {
12765 // In C and C++, main magically returns 0 if you fall off the end;
12766 // set the flag which tells us that.
12767 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12768
12769 // All the standards say that main() should return 'int'.
12770 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12771 FD->setHasImplicitReturnZero(true);
12772 else {
12773 // Otherwise, this is just a flat-out error.
12774 SourceRange RTRange = FD->getReturnTypeSourceRange();
12775 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12776 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12777 : FixItHint());
12778 FD->setInvalidDecl(true);
12779 }
12780
12781 // [basic.start.main]p3:
12782 // A program that declares a function main that belongs to the global scope
12783 // and is attached to a named module is ill-formed.
12784 if (FD->isInNamedModule()) {
12785 const SourceLocation start = FD->getTypeSpecStartLoc();
12786 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12787 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12788 }
12789 }
12790
12791 // Treat protoless main() as nullary.
12792 if (isa<FunctionNoProtoType>(Val: FT)) return;
12793
12794 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12795 unsigned nparams = FTP->getNumParams();
12796 assert(FD->getNumParams() == nparams);
12797
12798 bool HasExtraParameters = (nparams > 3);
12799
12800 if (FTP->isVariadic()) {
12801 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12802 // FIXME: if we had information about the location of the ellipsis, we
12803 // could add a FixIt hint to remove it as a parameter.
12804 }
12805
12806 // Darwin passes an undocumented fourth argument of type char**. If
12807 // other platforms start sprouting these, the logic below will start
12808 // getting shifty.
12809 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12810 HasExtraParameters = false;
12811
12812 if (HasExtraParameters) {
12813 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12814 FD->setInvalidDecl(true);
12815 nparams = 3;
12816 }
12817
12818 // FIXME: a lot of the following diagnostics would be improved
12819 // if we had some location information about types.
12820
12821 QualType CharPP =
12822 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12823 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12824
12825 for (unsigned i = 0; i < nparams; ++i) {
12826 QualType AT = FTP->getParamType(i);
12827
12828 bool mismatch = true;
12829
12830 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12831 mismatch = false;
12832 else if (Expected[i] == CharPP) {
12833 // As an extension, the following forms are okay:
12834 // char const **
12835 // char const * const *
12836 // char * const *
12837
12838 QualifierCollector qs;
12839 const PointerType* PT;
12840 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12841 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12842 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12843 T2: Context.CharTy)) {
12844 qs.removeConst();
12845 mismatch = !qs.empty();
12846 }
12847 }
12848
12849 if (mismatch) {
12850 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12851 // TODO: suggest replacing given type with expected type
12852 FD->setInvalidDecl(true);
12853 }
12854 }
12855
12856 if (nparams == 1 && !FD->isInvalidDecl()) {
12857 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12858 }
12859
12860 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12861 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12862 FD->setInvalidDecl();
12863 }
12864}
12865
12866static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12867
12868 // Default calling convention for main and wmain is __cdecl
12869 if (FD->getName() == "main" || FD->getName() == "wmain")
12870 return false;
12871
12872 // Default calling convention for MinGW and Cygwin is __cdecl
12873 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12874 if (T.isOSCygMing())
12875 return false;
12876
12877 // Default calling convention for WinMain, wWinMain and DllMain
12878 // is __stdcall on 32 bit Windows
12879 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12880 return true;
12881
12882 return false;
12883}
12884
12885void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12886 QualType T = FD->getType();
12887 assert(T->isFunctionType() && "function decl is not of function type");
12888 const FunctionType *FT = T->castAs<FunctionType>();
12889
12890 // Set an implicit return of 'zero' if the function can return some integral,
12891 // enumeration, pointer or nullptr type.
12892 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12893 FT->getReturnType()->isAnyPointerType() ||
12894 FT->getReturnType()->isNullPtrType())
12895 // DllMain is exempt because a return value of zero means it failed.
12896 if (FD->getName() != "DllMain")
12897 FD->setHasImplicitReturnZero(true);
12898
12899 // Explicitly specified calling conventions are applied to MSVC entry points
12900 if (!hasExplicitCallingConv(T)) {
12901 if (isDefaultStdCall(FD, S&: *this)) {
12902 if (FT->getCallConv() != CC_X86StdCall) {
12903 FT = Context.adjustFunctionType(
12904 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12905 FD->setType(QualType(FT, 0));
12906 }
12907 } else if (FT->getCallConv() != CC_C) {
12908 FT = Context.adjustFunctionType(Fn: FT,
12909 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12910 FD->setType(QualType(FT, 0));
12911 }
12912 }
12913
12914 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12915 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12916 FD->setInvalidDecl();
12917 }
12918}
12919
12920bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12921 // FIXME: Need strict checking. In C89, we need to check for
12922 // any assignment, increment, decrement, function-calls, or
12923 // commas outside of a sizeof. In C99, it's the same list,
12924 // except that the aforementioned are allowed in unevaluated
12925 // expressions. Everything else falls under the
12926 // "may accept other forms of constant expressions" exception.
12927 //
12928 // Regular C++ code will not end up here (exceptions: language extensions,
12929 // OpenCL C++ etc), so the constant expression rules there don't matter.
12930 if (Init->isValueDependent()) {
12931 assert(Init->containsErrors() &&
12932 "Dependent code should only occur in error-recovery path.");
12933 return true;
12934 }
12935 const Expr *Culprit;
12936 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
12937 return false;
12938
12939 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12940 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Val: Culprit)) {
12941
12942 // For collection literals iterate the elements to highlight which one is
12943 // the offender.
12944 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Val: Init)) {
12945 for (auto *Elm : ALE->elements()) {
12946 if (!Elm->isConstantInitializer(Ctx&: Context)) {
12947 Diag(Loc: Elm->getExprLoc(),
12948 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12949 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
12950 return true;
12951 }
12952 }
12953 }
12954
12955 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Val: Init)) {
12956 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12957 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
12958
12959 // Check that the key is a string literal and is constant.
12960 if (!isa<ObjCStringLiteral>(Val: Elm.Key) ||
12961 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
12962 Diag(Loc: Elm.Key->getExprLoc(),
12963 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12964 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
12965 return true;
12966 }
12967
12968 if (!Elm.Value->isConstantInitializer(Ctx&: Context)) {
12969 Diag(Loc: Elm.Value->getExprLoc(),
12970 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12971 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
12972 return true;
12973 }
12974 }
12975 }
12976
12977 Diag(Loc: Culprit->getExprLoc(),
12978 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12979 << ObjC().CheckLiteralKind(FromE: Init) << Culprit->getSourceRange();
12980 return true;
12981 }
12982
12983 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12984 return true;
12985}
12986
12987namespace {
12988 // Visits an initialization expression to see if OrigDecl is evaluated in
12989 // its own initialization and throws a warning if it does.
12990 class SelfReferenceChecker
12991 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12992 Sema &S;
12993 Decl *OrigDecl;
12994 bool isRecordType;
12995 bool isPODType;
12996 bool isReferenceType;
12997 bool isInCXXOperatorCall;
12998
12999 bool isInitList;
13000 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13001
13002 public:
13003 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
13004
13005 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13006 S(S), OrigDecl(OrigDecl) {
13007 isPODType = false;
13008 isRecordType = false;
13009 isReferenceType = false;
13010 isInCXXOperatorCall = false;
13011 isInitList = false;
13012 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
13013 isPODType = VD->getType().isPODType(Context: S.Context);
13014 isRecordType = VD->getType()->isRecordType();
13015 isReferenceType = VD->getType()->isReferenceType();
13016 }
13017 }
13018
13019 // For most expressions, just call the visitor. For initializer lists,
13020 // track the index of the field being initialized since fields are
13021 // initialized in order allowing use of previously initialized fields.
13022 void CheckExpr(Expr *E) {
13023 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
13024 if (!InitList) {
13025 Visit(S: E);
13026 return;
13027 }
13028
13029 // Track and increment the index here.
13030 isInitList = true;
13031 InitFieldIndex.push_back(Elt: 0);
13032 for (auto *Child : InitList->children()) {
13033 CheckExpr(E: cast<Expr>(Val: Child));
13034 ++InitFieldIndex.back();
13035 }
13036 InitFieldIndex.pop_back();
13037 }
13038
13039 // Returns true if MemberExpr is checked and no further checking is needed.
13040 // Returns false if additional checking is required.
13041 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13042 llvm::SmallVector<FieldDecl*, 4> Fields;
13043 Expr *Base = E;
13044 bool ReferenceField = false;
13045
13046 // Get the field members used.
13047 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13048 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13049 if (!FD)
13050 return false;
13051 Fields.push_back(Elt: FD);
13052 if (FD->getType()->isReferenceType())
13053 ReferenceField = true;
13054 Base = ME->getBase()->IgnoreParenImpCasts();
13055 }
13056
13057 // Keep checking only if the base Decl is the same.
13058 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13059 if (!DRE || DRE->getDecl() != OrigDecl)
13060 return false;
13061
13062 // A reference field can be bound to an unininitialized field.
13063 if (CheckReference && !ReferenceField)
13064 return true;
13065
13066 // Convert FieldDecls to their index number.
13067 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13068 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13069 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13070
13071 // See if a warning is needed by checking the first difference in index
13072 // numbers. If field being used has index less than the field being
13073 // initialized, then the use is safe.
13074 for (auto UsedIter = UsedFieldIndex.begin(),
13075 UsedEnd = UsedFieldIndex.end(),
13076 OrigIter = InitFieldIndex.begin(),
13077 OrigEnd = InitFieldIndex.end();
13078 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13079 if (*UsedIter < *OrigIter)
13080 return true;
13081 if (*UsedIter > *OrigIter)
13082 break;
13083 }
13084
13085 // TODO: Add a different warning which will print the field names.
13086 HandleDeclRefExpr(DRE);
13087 return true;
13088 }
13089
13090 // For most expressions, the cast is directly above the DeclRefExpr.
13091 // For conditional operators, the cast can be outside the conditional
13092 // operator if both expressions are DeclRefExpr's.
13093 void HandleValue(Expr *E) {
13094 E = E->IgnoreParens();
13095 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13096 HandleDeclRefExpr(DRE);
13097 return;
13098 }
13099
13100 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13101 Visit(S: CO->getCond());
13102 HandleValue(E: CO->getTrueExpr());
13103 HandleValue(E: CO->getFalseExpr());
13104 return;
13105 }
13106
13107 if (BinaryConditionalOperator *BCO =
13108 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13109 Visit(S: BCO->getCond());
13110 HandleValue(E: BCO->getFalseExpr());
13111 return;
13112 }
13113
13114 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13115 if (Expr *SE = OVE->getSourceExpr())
13116 HandleValue(E: SE);
13117 return;
13118 }
13119
13120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13121 if (BO->getOpcode() == BO_Comma) {
13122 Visit(S: BO->getLHS());
13123 HandleValue(E: BO->getRHS());
13124 return;
13125 }
13126 }
13127
13128 if (isa<MemberExpr>(Val: E)) {
13129 if (isInitList) {
13130 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13131 CheckReference: false /*CheckReference*/))
13132 return;
13133 }
13134
13135 Expr *Base = E->IgnoreParenImpCasts();
13136 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13137 // Check for static member variables and don't warn on them.
13138 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13139 return;
13140 Base = ME->getBase()->IgnoreParenImpCasts();
13141 }
13142 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13143 HandleDeclRefExpr(DRE);
13144 return;
13145 }
13146
13147 Visit(S: E);
13148 }
13149
13150 // Reference types not handled in HandleValue are handled here since all
13151 // uses of references are bad, not just r-value uses.
13152 void VisitDeclRefExpr(DeclRefExpr *E) {
13153 if (isReferenceType)
13154 HandleDeclRefExpr(DRE: E);
13155 }
13156
13157 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13158 if (E->getCastKind() == CK_LValueToRValue) {
13159 HandleValue(E: E->getSubExpr());
13160 return;
13161 }
13162
13163 Inherited::VisitImplicitCastExpr(S: E);
13164 }
13165
13166 void VisitMemberExpr(MemberExpr *E) {
13167 if (isInitList) {
13168 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13169 return;
13170 }
13171
13172 // Don't warn on arrays since they can be treated as pointers.
13173 if (E->getType()->canDecayToPointerType()) return;
13174
13175 // Warn when a non-static method call is followed by non-static member
13176 // field accesses, which is followed by a DeclRefExpr.
13177 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13178 bool Warn = (MD && !MD->isStatic());
13179 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13180 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13181 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13182 Warn = false;
13183 Base = ME->getBase()->IgnoreParenImpCasts();
13184 }
13185
13186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13187 if (Warn)
13188 HandleDeclRefExpr(DRE);
13189 return;
13190 }
13191
13192 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13193 // Visit that expression.
13194 Visit(S: Base);
13195 }
13196
13197 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13198 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13199 Expr *Callee = E->getCallee();
13200
13201 if (isa<UnresolvedLookupExpr>(Val: Callee))
13202 return Inherited::VisitCXXOperatorCallExpr(S: E);
13203
13204 Visit(S: Callee);
13205 for (auto Arg: E->arguments())
13206 HandleValue(E: Arg->IgnoreParenImpCasts());
13207 }
13208
13209 void VisitLambdaExpr(LambdaExpr *E) {
13210 if (!isInCXXOperatorCall) {
13211 Inherited::VisitLambdaExpr(LE: E);
13212 return;
13213 }
13214
13215 for (Expr *Init : E->capture_inits())
13216 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13217 HandleDeclRefExpr(DRE);
13218 else if (Init)
13219 Visit(S: Init);
13220 }
13221
13222 void VisitUnaryOperator(UnaryOperator *E) {
13223 // For POD record types, addresses of its own members are well-defined.
13224 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13225 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13226 if (!isPODType)
13227 HandleValue(E: E->getSubExpr());
13228 return;
13229 }
13230
13231 if (E->isIncrementDecrementOp()) {
13232 HandleValue(E: E->getSubExpr());
13233 return;
13234 }
13235
13236 Inherited::VisitUnaryOperator(S: E);
13237 }
13238
13239 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13240
13241 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13242 if (E->getConstructor()->isCopyConstructor()) {
13243 Expr *ArgExpr = E->getArg(Arg: 0);
13244 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13245 if (ILE->getNumInits() == 1)
13246 ArgExpr = ILE->getInit(Init: 0);
13247 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13248 if (ICE->getCastKind() == CK_NoOp)
13249 ArgExpr = ICE->getSubExpr();
13250 HandleValue(E: ArgExpr);
13251 return;
13252 }
13253 Inherited::VisitCXXConstructExpr(S: E);
13254 }
13255
13256 void VisitCallExpr(CallExpr *E) {
13257 // Treat std::move as a use.
13258 if (E->isCallToStdMove()) {
13259 HandleValue(E: E->getArg(Arg: 0));
13260 return;
13261 }
13262
13263 Inherited::VisitCallExpr(CE: E);
13264 }
13265
13266 void VisitBinaryOperator(BinaryOperator *E) {
13267 if (E->isCompoundAssignmentOp()) {
13268 HandleValue(E: E->getLHS());
13269 Visit(S: E->getRHS());
13270 return;
13271 }
13272
13273 Inherited::VisitBinaryOperator(S: E);
13274 }
13275
13276 // A custom visitor for BinaryConditionalOperator is needed because the
13277 // regular visitor would check the condition and true expression separately
13278 // but both point to the same place giving duplicate diagnostics.
13279 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13280 Visit(S: E->getCond());
13281 Visit(S: E->getFalseExpr());
13282 }
13283
13284 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13285 Decl* ReferenceDecl = DRE->getDecl();
13286 if (OrigDecl != ReferenceDecl) return;
13287 unsigned diag;
13288 if (isReferenceType) {
13289 diag = diag::warn_uninit_self_reference_in_reference_init;
13290 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13291 diag = diag::warn_static_self_reference_in_init;
13292 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13293 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13294 DRE->getDecl()->getType()->isRecordType()) {
13295 diag = diag::warn_uninit_self_reference_in_init;
13296 } else {
13297 // Local variables will be handled by the CFG analysis.
13298 return;
13299 }
13300
13301 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13302 PD: S.PDiag(DiagID: diag)
13303 << DRE->getDecl() << OrigDecl->getLocation()
13304 << DRE->getSourceRange());
13305 }
13306 };
13307
13308 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13309 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13310 bool DirectInit) {
13311 // Parameters arguments are occassionially constructed with itself,
13312 // for instance, in recursive functions. Skip them.
13313 if (isa<ParmVarDecl>(Val: OrigDecl))
13314 return;
13315
13316 // Skip checking for file-scope constexpr variables - constant evaluation
13317 // will produce appropriate errors without needing runtime diagnostics.
13318 // Local constexpr should still emit runtime warnings.
13319 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13320 VD && VD->isConstexpr() && VD->isFileVarDecl())
13321 return;
13322
13323 E = E->IgnoreParens();
13324
13325 // Skip checking T a = a where T is not a record or reference type.
13326 // Doing so is a way to silence uninitialized warnings.
13327 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13328 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13329 if (ICE->getCastKind() == CK_LValueToRValue)
13330 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13331 if (DRE->getDecl() == OrigDecl)
13332 return;
13333
13334 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13335 }
13336} // end anonymous namespace
13337
13338namespace {
13339 // Simple wrapper to add the name of a variable or (if no variable is
13340 // available) a DeclarationName into a diagnostic.
13341 struct VarDeclOrName {
13342 VarDecl *VDecl;
13343 DeclarationName Name;
13344
13345 friend const Sema::SemaDiagnosticBuilder &
13346 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13347 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13348 }
13349 };
13350} // end anonymous namespace
13351
13352QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13353 DeclarationName Name, QualType Type,
13354 TypeSourceInfo *TSI,
13355 SourceRange Range, bool DirectInit,
13356 Expr *Init) {
13357 bool IsInitCapture = !VDecl;
13358 assert((!VDecl || !VDecl->isInitCapture()) &&
13359 "init captures are expected to be deduced prior to initialization");
13360
13361 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13362
13363 DeducedType *Deduced = Type->getContainedDeducedType();
13364 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13365
13366 // Diagnose auto array declarations in C23, unless it's a supported extension.
13367 if (getLangOpts().C23 && Type->isArrayType() &&
13368 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13369 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13370 << (int)Deduced->getContainedAutoType()->getKeyword()
13371 << /*in array decl*/ 23 << Range;
13372 return QualType();
13373 }
13374
13375 // C++11 [dcl.spec.auto]p3
13376 if (!Init) {
13377 assert(VDecl && "no init for init capture deduction?");
13378
13379 // Except for class argument deduction, and then for an initializing
13380 // declaration only, i.e. no static at class scope or extern.
13381 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13382 VDecl->hasExternalStorage() ||
13383 VDecl->isStaticDataMember()) {
13384 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13385 << VDecl->getDeclName() << Type;
13386 return QualType();
13387 }
13388 }
13389
13390 ArrayRef<Expr*> DeduceInits;
13391 if (Init)
13392 DeduceInits = Init;
13393
13394 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13395 if (DirectInit && PL)
13396 DeduceInits = PL->exprs();
13397
13398 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13399 assert(VDecl && "non-auto type for init capture deduction?");
13400 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13401 InitializationKind Kind = InitializationKind::CreateForInit(
13402 Loc: VDecl->getLocation(), DirectInit, Init);
13403 // FIXME: Initialization should not be taking a mutable list of inits.
13404 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13405 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13406 Init: InitsCopy);
13407 }
13408
13409 if (DirectInit) {
13410 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13411 DeduceInits = IL->inits();
13412 }
13413
13414 // Deduction only works if we have exactly one source expression.
13415 if (DeduceInits.empty()) {
13416 // It isn't possible to write this directly, but it is possible to
13417 // end up in this situation with "auto x(some_pack...);"
13418 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13419 ? diag::err_init_capture_no_expression
13420 : diag::err_auto_var_init_no_expression)
13421 << VN << Type << Range;
13422 return QualType();
13423 }
13424
13425 if (DeduceInits.size() > 1) {
13426 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13427 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13428 : diag::err_auto_var_init_multiple_expressions)
13429 << VN << Type << Range;
13430 return QualType();
13431 }
13432
13433 Expr *DeduceInit = DeduceInits[0];
13434 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13435 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13436 ? diag::err_init_capture_paren_braces
13437 : diag::err_auto_var_init_paren_braces)
13438 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13439 return QualType();
13440 }
13441
13442 // Expressions default to 'id' when we're in a debugger.
13443 bool DefaultedAnyToId = false;
13444 if (getLangOpts().DebuggerCastResultToId &&
13445 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13446 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13447 if (Result.isInvalid()) {
13448 return QualType();
13449 }
13450 Init = Result.get();
13451 DefaultedAnyToId = true;
13452 }
13453
13454 // C++ [dcl.decomp]p1:
13455 // If the assignment-expression [...] has array type A and no ref-qualifier
13456 // is present, e has type cv A
13457 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13458 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13459 DeduceInit->getType()->isConstantArrayType())
13460 return Context.getQualifiedType(T: DeduceInit->getType(),
13461 Qs: Type.getQualifiers());
13462
13463 QualType DeducedType;
13464 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13465 TemplateDeductionResult Result =
13466 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13467 if (Result != TemplateDeductionResult::Success &&
13468 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13469 if (!IsInitCapture)
13470 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13471 else if (isa<InitListExpr>(Val: Init))
13472 Diag(Loc: Range.getBegin(),
13473 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13474 << VN
13475 << (DeduceInit->getType().isNull() ? TSI->getType()
13476 : DeduceInit->getType())
13477 << DeduceInit->getSourceRange();
13478 else
13479 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13480 << VN << TSI->getType()
13481 << (DeduceInit->getType().isNull() ? TSI->getType()
13482 : DeduceInit->getType())
13483 << DeduceInit->getSourceRange();
13484 }
13485
13486 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13487 // 'id' instead of a specific object type prevents most of our usual
13488 // checks.
13489 // We only want to warn outside of template instantiations, though:
13490 // inside a template, the 'id' could have come from a parameter.
13491 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13492 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13493 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13494 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13495 }
13496
13497 return DeducedType;
13498}
13499
13500bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13501 Expr *Init) {
13502 assert(!Init || !Init->containsErrors());
13503 QualType DeducedType = deduceVarTypeFromInitializer(
13504 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13505 Range: VDecl->getSourceRange(), DirectInit, Init);
13506 if (DeducedType.isNull()) {
13507 VDecl->setInvalidDecl();
13508 return true;
13509 }
13510
13511 VDecl->setType(DeducedType);
13512 assert(VDecl->isLinkageValid());
13513
13514 // In ARC, infer lifetime.
13515 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13516 VDecl->setInvalidDecl();
13517
13518 if (getLangOpts().OpenCL)
13519 deduceOpenCLAddressSpace(Var: VDecl);
13520
13521 if (getLangOpts().HLSL)
13522 HLSL().deduceAddressSpace(Decl: VDecl);
13523
13524 // If this is a redeclaration, check that the type we just deduced matches
13525 // the previously declared type.
13526 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13527 // We never need to merge the type, because we cannot form an incomplete
13528 // array of auto, nor deduce such a type.
13529 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13530 }
13531
13532 // Check the deduced type is valid for a variable declaration.
13533 CheckVariableDeclarationType(NewVD: VDecl);
13534 return VDecl->isInvalidDecl();
13535}
13536
13537void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13538 SourceLocation Loc) {
13539 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13540 Init = EWC->getSubExpr();
13541
13542 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13543 Init = CE->getSubExpr();
13544
13545 QualType InitType = Init->getType();
13546 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13547 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13548 "shouldn't be called if type doesn't have a non-trivial C struct");
13549 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13550 for (auto *I : ILE->inits()) {
13551 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13552 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13553 continue;
13554 SourceLocation SL = I->getExprLoc();
13555 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13556 }
13557 return;
13558 }
13559
13560 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13561 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13562 checkNonTrivialCUnion(QT: InitType, Loc,
13563 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13564 NonTrivialKind: NTCUK_Init);
13565 } else {
13566 // Assume all other explicit initializers involving copying some existing
13567 // object.
13568 // TODO: ignore any explicit initializers where we can guarantee
13569 // copy-elision.
13570 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13571 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13572 NonTrivialKind: NTCUK_Copy);
13573 }
13574}
13575
13576namespace {
13577
13578bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13579 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13580 // in the source code or implicitly by the compiler if it is in a union
13581 // defined in a system header and has non-trivial ObjC ownership
13582 // qualifications. We don't want those fields to participate in determining
13583 // whether the containing union is non-trivial.
13584 return FD->hasAttr<UnavailableAttr>();
13585}
13586
13587struct DiagNonTrivalCUnionDefaultInitializeVisitor
13588 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13589 void> {
13590 using Super =
13591 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13592 void>;
13593
13594 DiagNonTrivalCUnionDefaultInitializeVisitor(
13595 QualType OrigTy, SourceLocation OrigLoc,
13596 NonTrivialCUnionContext UseContext, Sema &S)
13597 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13598
13599 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13600 const FieldDecl *FD, bool InNonTrivialUnion) {
13601 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13602 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13603 Args&: InNonTrivialUnion);
13604 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13605 }
13606
13607 void visitARCStrong(QualType QT, const FieldDecl *FD,
13608 bool InNonTrivialUnion) {
13609 if (InNonTrivialUnion)
13610 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13611 << 1 << 0 << QT << FD->getName();
13612 }
13613
13614 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13615 if (InNonTrivialUnion)
13616 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13617 << 1 << 0 << QT << FD->getName();
13618 }
13619
13620 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13621 const auto *RD = QT->castAsRecordDecl();
13622 if (RD->isUnion()) {
13623 if (OrigLoc.isValid()) {
13624 bool IsUnion = false;
13625 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13626 IsUnion = OrigRD->isUnion();
13627 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13628 << 0 << OrigTy << IsUnion << UseContext;
13629 // Reset OrigLoc so that this diagnostic is emitted only once.
13630 OrigLoc = SourceLocation();
13631 }
13632 InNonTrivialUnion = true;
13633 }
13634
13635 if (InNonTrivialUnion)
13636 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13637 << 0 << 0 << QT.getUnqualifiedType() << "";
13638
13639 for (const FieldDecl *FD : RD->fields())
13640 if (!shouldIgnoreForRecordTriviality(FD))
13641 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13642 }
13643
13644 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13645
13646 // The non-trivial C union type or the struct/union type that contains a
13647 // non-trivial C union.
13648 QualType OrigTy;
13649 SourceLocation OrigLoc;
13650 NonTrivialCUnionContext UseContext;
13651 Sema &S;
13652};
13653
13654struct DiagNonTrivalCUnionDestructedTypeVisitor
13655 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13656 using Super =
13657 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13658
13659 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13660 SourceLocation OrigLoc,
13661 NonTrivialCUnionContext UseContext,
13662 Sema &S)
13663 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13664
13665 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13666 const FieldDecl *FD, bool InNonTrivialUnion) {
13667 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13668 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13669 Args&: InNonTrivialUnion);
13670 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13671 }
13672
13673 void visitARCStrong(QualType QT, const FieldDecl *FD,
13674 bool InNonTrivialUnion) {
13675 if (InNonTrivialUnion)
13676 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13677 << 1 << 1 << QT << FD->getName();
13678 }
13679
13680 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13681 if (InNonTrivialUnion)
13682 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13683 << 1 << 1 << QT << FD->getName();
13684 }
13685
13686 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13687 const auto *RD = QT->castAsRecordDecl();
13688 if (RD->isUnion()) {
13689 if (OrigLoc.isValid()) {
13690 bool IsUnion = false;
13691 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13692 IsUnion = OrigRD->isUnion();
13693 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13694 << 1 << OrigTy << IsUnion << UseContext;
13695 // Reset OrigLoc so that this diagnostic is emitted only once.
13696 OrigLoc = SourceLocation();
13697 }
13698 InNonTrivialUnion = true;
13699 }
13700
13701 if (InNonTrivialUnion)
13702 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13703 << 0 << 1 << QT.getUnqualifiedType() << "";
13704
13705 for (const FieldDecl *FD : RD->fields())
13706 if (!shouldIgnoreForRecordTriviality(FD))
13707 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13708 }
13709
13710 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13711 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13712 bool InNonTrivialUnion) {}
13713
13714 // The non-trivial C union type or the struct/union type that contains a
13715 // non-trivial C union.
13716 QualType OrigTy;
13717 SourceLocation OrigLoc;
13718 NonTrivialCUnionContext UseContext;
13719 Sema &S;
13720};
13721
13722struct DiagNonTrivalCUnionCopyVisitor
13723 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13724 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13725
13726 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13727 NonTrivialCUnionContext UseContext, Sema &S)
13728 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13729
13730 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13731 const FieldDecl *FD, bool InNonTrivialUnion) {
13732 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13733 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13734 Args&: InNonTrivialUnion);
13735 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13736 }
13737
13738 void visitARCStrong(QualType QT, const FieldDecl *FD,
13739 bool InNonTrivialUnion) {
13740 if (InNonTrivialUnion)
13741 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13742 << 1 << 2 << QT << FD->getName();
13743 }
13744
13745 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13746 if (InNonTrivialUnion)
13747 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13748 << 1 << 2 << QT << FD->getName();
13749 }
13750
13751 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13752 const auto *RD = QT->castAsRecordDecl();
13753 if (RD->isUnion()) {
13754 if (OrigLoc.isValid()) {
13755 bool IsUnion = false;
13756 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13757 IsUnion = OrigRD->isUnion();
13758 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13759 << 2 << OrigTy << IsUnion << UseContext;
13760 // Reset OrigLoc so that this diagnostic is emitted only once.
13761 OrigLoc = SourceLocation();
13762 }
13763 InNonTrivialUnion = true;
13764 }
13765
13766 if (InNonTrivialUnion)
13767 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13768 << 0 << 2 << QT.getUnqualifiedType() << "";
13769
13770 for (const FieldDecl *FD : RD->fields())
13771 if (!shouldIgnoreForRecordTriviality(FD))
13772 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13773 }
13774
13775 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13776 if (InNonTrivialUnion)
13777 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13778 << 1 << 2 << QT << FD->getName();
13779 }
13780
13781 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13782 const FieldDecl *FD, bool InNonTrivialUnion) {}
13783 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13784 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13785 bool InNonTrivialUnion) {}
13786
13787 // The non-trivial C union type or the struct/union type that contains a
13788 // non-trivial C union.
13789 QualType OrigTy;
13790 SourceLocation OrigLoc;
13791 NonTrivialCUnionContext UseContext;
13792 Sema &S;
13793};
13794
13795} // namespace
13796
13797void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13798 NonTrivialCUnionContext UseContext,
13799 unsigned NonTrivialKind) {
13800 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13801 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13802 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13803 "shouldn't be called if type doesn't have a non-trivial C union");
13804
13805 if ((NonTrivialKind & NTCUK_Init) &&
13806 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13807 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13808 .visit(FT: QT, Args: nullptr, Args: false);
13809 if ((NonTrivialKind & NTCUK_Destruct) &&
13810 QT.hasNonTrivialToPrimitiveDestructCUnion())
13811 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13812 .visit(FT: QT, Args: nullptr, Args: false);
13813 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13814 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13815 .visit(FT: QT, Args: nullptr, Args: false);
13816}
13817
13818bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13819 const VarDecl *Dcl) {
13820 if (!getLangOpts().CPlusPlus)
13821 return false;
13822
13823 // We only need to warn if the definition is in a header file, so wait to
13824 // diagnose until we've seen the definition.
13825 if (!Dcl->isThisDeclarationADefinition())
13826 return false;
13827
13828 // If an object is defined in a source file, its definition can't get
13829 // duplicated since it will never appear in more than one TU.
13830 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13831 return false;
13832
13833 // If the variable we're looking at is a static local, then we actually care
13834 // about the properties of the function containing it.
13835 const ValueDecl *Target = Dcl;
13836 // VarDecls and FunctionDecls have different functions for checking
13837 // inline-ness, and whether they were originally templated, so we have to
13838 // call the appropriate functions manually.
13839 bool TargetIsInline = Dcl->isInline();
13840 bool TargetWasTemplated =
13841 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13842
13843 // Update the Target and TargetIsInline property if necessary
13844 if (Dcl->isStaticLocal()) {
13845 const DeclContext *Ctx = Dcl->getDeclContext();
13846 if (!Ctx)
13847 return false;
13848
13849 const FunctionDecl *FunDcl =
13850 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13851 if (!FunDcl)
13852 return false;
13853
13854 Target = FunDcl;
13855 // IsInlined() checks for the C++ inline property
13856 TargetIsInline = FunDcl->isInlined();
13857 TargetWasTemplated =
13858 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13859 }
13860
13861 // Non-inline functions/variables can only legally appear in one TU
13862 // unless they were part of a template. Unfortunately, making complex
13863 // template instantiations visible is infeasible in practice, since
13864 // everything the template depends on also has to be visible. To avoid
13865 // giving impractical-to-fix warnings, don't warn if we're inside
13866 // something that was templated, even on inline stuff.
13867 if (!TargetIsInline || TargetWasTemplated)
13868 return false;
13869
13870 // If the object isn't hidden, the dynamic linker will prevent duplication.
13871 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13872
13873 // The target is "hidden" (from the dynamic linker) if:
13874 // 1. On posix, it has hidden visibility, or
13875 // 2. On windows, it has no import/export annotation, and neither does the
13876 // class which directly contains it.
13877 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13878 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13879 return false;
13880
13881 // If the variable isn't directly annotated, check to see if it's a member
13882 // of an annotated class.
13883 const CXXRecordDecl *Ctx =
13884 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13885 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13886 return false;
13887
13888 } else if (Lnk.getVisibility() != HiddenVisibility) {
13889 // Posix case
13890 return false;
13891 }
13892
13893 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13894 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13895 return false;
13896
13897 return true;
13898}
13899
13900// Determine whether the object seems mutable for the purpose of diagnosing
13901// possible unique object duplication, i.e. non-const-qualified, and
13902// not an always-constant type like a function.
13903// Not perfect: doesn't account for mutable members, for example, or
13904// elements of container types.
13905// For nested pointers, any individual level being non-const is sufficient.
13906static bool looksMutable(QualType T, const ASTContext &Ctx) {
13907 T = T.getNonReferenceType();
13908 if (T->isFunctionType())
13909 return false;
13910 if (!T.isConstant(Ctx))
13911 return true;
13912 if (T->isPointerType())
13913 return looksMutable(T: T->getPointeeType(), Ctx);
13914 return false;
13915}
13916
13917void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13918 // If this object has external linkage and hidden visibility, it might be
13919 // duplicated when built into a shared library, which causes problems if it's
13920 // mutable (since the copies won't be in sync) or its initialization has side
13921 // effects (since it will run once per copy instead of once globally).
13922
13923 // Don't diagnose if we're inside a template, because it's not practical to
13924 // fix the warning in most cases.
13925 if (!VD->isTemplated() &&
13926 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13927
13928 QualType Type = VD->getType();
13929 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13930 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13931 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13932 }
13933
13934 // To keep false positives low, only warn if we're certain that the
13935 // initializer has side effects. Don't warn on operator new, since a mutable
13936 // pointer will trigger the previous warning, and an immutable pointer
13937 // getting duplicated just results in a little extra memory usage.
13938 const Expr *Init = VD->getAnyInitializer();
13939 if (Init &&
13940 Init->HasSideEffects(Ctx: VD->getASTContext(),
13941 /*IncludePossibleEffects=*/false) &&
13942 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13943 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13944 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13945 }
13946 }
13947}
13948
13949void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13950 llvm::scope_exit ResetDeclForInitializer([this]() {
13951 if (!this->ExprEvalContexts.empty())
13952 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13953 });
13954
13955 // If there is no declaration, there was an error parsing it. Just ignore
13956 // the initializer.
13957 if (!RealDecl) {
13958 return;
13959 }
13960
13961 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13962 if (!Method->isInvalidDecl()) {
13963 // Pure-specifiers are handled in ActOnPureSpecifier.
13964 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13965 << Method->getDeclName() << Init->getSourceRange();
13966 Method->setInvalidDecl();
13967 }
13968 return;
13969 }
13970
13971 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13972 if (!VDecl) {
13973 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13974 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13975 RealDecl->setInvalidDecl();
13976 return;
13977 }
13978
13979 if (VDecl->isInvalidDecl()) {
13980 ExprResult Recovery =
13981 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13982 if (Expr *E = Recovery.get())
13983 VDecl->setInit(E);
13984 return;
13985 }
13986
13987 // __amdgpu_feature_predicate_t cannot be initialised
13988 if (VDecl->getType().getDesugaredType(Context) ==
13989 Context.AMDGPUFeaturePredicateTy) {
13990 Diag(Loc: VDecl->getLocation(),
13991 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
13992 << VDecl;
13993 VDecl->setInvalidDecl();
13994 return;
13995 }
13996
13997 // WebAssembly tables can't be used to initialise a variable.
13998 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13999 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
14000 VDecl->setInvalidDecl();
14001 return;
14002 }
14003
14004 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14005 if (VDecl->getType()->isUndeducedType()) {
14006 if (Init->containsErrors()) {
14007 // Invalidate the decl as we don't know the type for recovery-expr yet.
14008 RealDecl->setInvalidDecl();
14009 VDecl->setInit(Init);
14010 return;
14011 }
14012
14013 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
14014 assert(VDecl->isInvalidDecl() &&
14015 "decl should be invalidated when deduce fails");
14016 if (auto *RecoveryExpr =
14017 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
14018 .get())
14019 VDecl->setInit(RecoveryExpr);
14020 return;
14021 }
14022 }
14023
14024 this->CheckAttributesOnDeducedType(D: RealDecl);
14025
14026 // we don't initialize groupshared variables so warn and return
14027 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14028 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
14029 return;
14030 }
14031
14032 // dllimport cannot be used on variable definitions.
14033 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14034 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
14035 VDecl->setInvalidDecl();
14036 return;
14037 }
14038
14039 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14040 // the identifier has external or internal linkage, the declaration shall
14041 // have no initializer for the identifier.
14042 // C++14 [dcl.init]p5 is the same restriction for C++.
14043 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14044 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14045 VDecl->setInvalidDecl();
14046 return;
14047 }
14048
14049 if (!VDecl->getType()->isDependentType()) {
14050 // A definition must end up with a complete type, which means it must be
14051 // complete with the restriction that an array type might be completed by
14052 // the initializer; note that later code assumes this restriction.
14053 QualType BaseDeclType = VDecl->getType();
14054 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14055 BaseDeclType = Array->getElementType();
14056 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14057 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14058 RealDecl->setInvalidDecl();
14059 return;
14060 }
14061
14062 // The variable can not have an abstract class type.
14063 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14064 DiagID: diag::err_abstract_type_in_decl,
14065 Args: AbstractVariableType))
14066 VDecl->setInvalidDecl();
14067 }
14068
14069 // C++ [module.import/6]
14070 // ...
14071 // A header unit shall not contain a definition of a non-inline function or
14072 // variable whose name has external linkage.
14073 //
14074 // We choose to allow weak & selectany definitions, as they are common in
14075 // headers, and have semantics similar to inline definitions which are allowed
14076 // in header units.
14077 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14078 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14079 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14080 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14081 !VDecl->getInstantiatedFromStaticDataMember() &&
14082 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14083 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14084 VDecl->setInvalidDecl();
14085 }
14086
14087 // If adding the initializer will turn this declaration into a definition,
14088 // and we already have a definition for this variable, diagnose or otherwise
14089 // handle the situation.
14090 if (VarDecl *Def = VDecl->getDefinition())
14091 if (Def != VDecl &&
14092 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14093 !VDecl->isThisDeclarationADemotedDefinition() &&
14094 checkVarDeclRedefinition(Old: Def, New: VDecl))
14095 return;
14096
14097 if (getLangOpts().CPlusPlus) {
14098 // C++ [class.static.data]p4
14099 // If a static data member is of const integral or const
14100 // enumeration type, its declaration in the class definition can
14101 // specify a constant-initializer which shall be an integral
14102 // constant expression (5.19). In that case, the member can appear
14103 // in integral constant expressions. The member shall still be
14104 // defined in a namespace scope if it is used in the program and the
14105 // namespace scope definition shall not contain an initializer.
14106 //
14107 // We already performed a redefinition check above, but for static
14108 // data members we also need to check whether there was an in-class
14109 // declaration with an initializer.
14110 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14111 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14112 << VDecl->getDeclName();
14113 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14114 DiagID: diag::note_previous_initializer)
14115 << 0;
14116 return;
14117 }
14118
14119 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14120 VDecl->setInvalidDecl();
14121 return;
14122 }
14123 }
14124
14125 // If the variable has an initializer and local storage, check whether
14126 // anything jumps over the initialization.
14127 if (VDecl->hasLocalStorage())
14128 setFunctionHasBranchProtectedScope();
14129
14130 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14131 // a kernel function cannot be initialized."
14132 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14133 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14134 VDecl->setInvalidDecl();
14135 return;
14136 }
14137
14138 // The LoaderUninitialized attribute acts as a definition (of undef).
14139 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14140 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14141 VDecl->setInvalidDecl();
14142 return;
14143 }
14144
14145 if (getLangOpts().HLSL)
14146 if (!HLSL().handleInitialization(VDecl, Init))
14147 return;
14148
14149 // Get the decls type and save a reference for later, since
14150 // CheckInitializerTypes may change it.
14151 QualType DclT = VDecl->getType(), SavT = DclT;
14152
14153 // Expressions default to 'id' when we're in a debugger
14154 // and we are assigning it to a variable of Objective-C pointer type.
14155 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14156 Init->getType() == Context.UnknownAnyTy) {
14157 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14158 if (!Result.isUsable()) {
14159 VDecl->setInvalidDecl();
14160 return;
14161 }
14162 Init = Result.get();
14163 }
14164
14165 // Perform the initialization.
14166 bool InitializedFromParenListExpr = false;
14167 bool IsParenListInit = false;
14168 if (!VDecl->isInvalidDecl()) {
14169 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14170 InitializationKind Kind = InitializationKind::CreateForInit(
14171 Loc: VDecl->getLocation(), DirectInit, Init);
14172
14173 MultiExprArg Args = Init;
14174 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14175 Args =
14176 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14177 InitializedFromParenListExpr = true;
14178 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14179 Args = CXXDirectInit->getInitExprs();
14180 InitializedFromParenListExpr = true;
14181 }
14182
14183 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14184 /*TopLevelOfInitList=*/false,
14185 /*TreatUnavailableAsInvalid=*/false);
14186 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14187 if (!Result.isUsable()) {
14188 // If the provided initializer fails to initialize the var decl,
14189 // we attach a recovery expr for better recovery.
14190 auto RecoveryExpr =
14191 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14192 if (RecoveryExpr.get())
14193 VDecl->setInit(RecoveryExpr.get());
14194 // In general, for error recovery purposes, the initializer doesn't play
14195 // part in the valid bit of the declaration. There are a few exceptions:
14196 // 1) if the var decl has a deduced auto type, and the type cannot be
14197 // deduced by an invalid initializer;
14198 // 2) if the var decl is a decomposition decl with a non-deduced type,
14199 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14200 // Case 1) was already handled elsewhere.
14201 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14202 VDecl->setInvalidDecl();
14203 return;
14204 }
14205
14206 Init = Result.getAs<Expr>();
14207 IsParenListInit = !InitSeq.steps().empty() &&
14208 InitSeq.step_begin()->Kind ==
14209 InitializationSequence::SK_ParenthesizedListInit;
14210 QualType VDeclType = VDecl->getType();
14211 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14212 !VDeclType->isDependentType() &&
14213 Context.getAsIncompleteArrayType(T: VDeclType) &&
14214 Context.getAsIncompleteArrayType(T: Init->getType())) {
14215 // Bail out if it is not possible to deduce array size from the
14216 // initializer.
14217 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14218 << VDeclType;
14219 VDecl->setInvalidDecl();
14220 return;
14221 }
14222 }
14223
14224 // Check for self-references within variable initializers.
14225 // Variables declared within a function/method body (except for references)
14226 // are handled by a dataflow analysis.
14227 // This is undefined behavior in C++, but valid in C.
14228 if (getLangOpts().CPlusPlus)
14229 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14230 VDecl->getType()->isReferenceType())
14231 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14232
14233 // If the type changed, it means we had an incomplete type that was
14234 // completed by the initializer. For example:
14235 // int ary[] = { 1, 3, 5 };
14236 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14237 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14238 VDecl->setType(DclT);
14239
14240 if (!VDecl->isInvalidDecl()) {
14241 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14242
14243 if (VDecl->hasAttr<BlocksAttr>())
14244 ObjC().checkRetainCycles(Var: VDecl, Init);
14245
14246 // It is safe to assign a weak reference into a strong variable.
14247 // Although this code can still have problems:
14248 // id x = self.weakProp;
14249 // id y = self.weakProp;
14250 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14251 // paths through the function. This should be revisited if
14252 // -Wrepeated-use-of-weak is made flow-sensitive.
14253 if (FunctionScopeInfo *FSI = getCurFunction())
14254 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14255 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14256 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14257 Loc: Init->getBeginLoc()))
14258 FSI->markSafeWeakUse(E: Init);
14259 }
14260
14261 // The initialization is usually a full-expression.
14262 //
14263 // FIXME: If this is a braced initialization of an aggregate, it is not
14264 // an expression, and each individual field initializer is a separate
14265 // full-expression. For instance, in:
14266 //
14267 // struct Temp { ~Temp(); };
14268 // struct S { S(Temp); };
14269 // struct T { S a, b; } t = { Temp(), Temp() }
14270 //
14271 // we should destroy the first Temp before constructing the second.
14272
14273 // Set context flag for OverflowBehaviorType initialization analysis
14274 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14275 true);
14276 ExprResult Result =
14277 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14278 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14279 if (!Result.isUsable()) {
14280 VDecl->setInvalidDecl();
14281 return;
14282 }
14283 Init = Result.get();
14284
14285 // Attach the initializer to the decl.
14286 VDecl->setInit(Init);
14287
14288 if (VDecl->isLocalVarDecl()) {
14289 // Don't check the initializer if the declaration is malformed.
14290 if (VDecl->isInvalidDecl()) {
14291 // do nothing
14292
14293 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14294 // This is true even in C++ for OpenCL.
14295 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14296 CheckForConstantInitializer(Init);
14297
14298 // Otherwise, C++ does not restrict the initializer.
14299 } else if (getLangOpts().CPlusPlus) {
14300 // do nothing
14301
14302 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14303 // static storage duration shall be constant expressions or string literals.
14304 } else if (VDecl->getStorageClass() == SC_Static) {
14305 // Avoid evaluating the initializer twice for constexpr variables. It will
14306 // be evaluated later.
14307 if (!VDecl->isConstexpr())
14308 CheckForConstantInitializer(Init);
14309
14310 // C89 is stricter than C99 for aggregate initializers.
14311 // C89 6.5.7p3: All the expressions [...] in an initializer list
14312 // for an object that has aggregate or union type shall be
14313 // constant expressions.
14314 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14315 isa<InitListExpr>(Val: Init)) {
14316 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14317 }
14318
14319 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14320 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14321 if (VDecl->hasLocalStorage())
14322 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14323 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14324 VDecl->getLexicalDeclContext()->isRecord()) {
14325 // This is an in-class initialization for a static data member, e.g.,
14326 //
14327 // struct S {
14328 // static const int value = 17;
14329 // };
14330
14331 // C++ [class.mem]p4:
14332 // A member-declarator can contain a constant-initializer only
14333 // if it declares a static member (9.4) of const integral or
14334 // const enumeration type, see 9.4.2.
14335 //
14336 // C++11 [class.static.data]p3:
14337 // If a non-volatile non-inline const static data member is of integral
14338 // or enumeration type, its declaration in the class definition can
14339 // specify a brace-or-equal-initializer in which every initializer-clause
14340 // that is an assignment-expression is a constant expression. A static
14341 // data member of literal type can be declared in the class definition
14342 // with the constexpr specifier; if so, its declaration shall specify a
14343 // brace-or-equal-initializer in which every initializer-clause that is
14344 // an assignment-expression is a constant expression.
14345
14346 // Do nothing on dependent types.
14347 if (DclT->isDependentType()) {
14348
14349 // Allow any 'static constexpr' members, whether or not they are of literal
14350 // type. We separately check that every constexpr variable is of literal
14351 // type.
14352 } else if (VDecl->isConstexpr()) {
14353
14354 // Require constness.
14355 } else if (!DclT.isConstQualified()) {
14356 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14357 << Init->getSourceRange();
14358 VDecl->setInvalidDecl();
14359
14360 // We allow integer constant expressions in all cases.
14361 } else if (DclT->isIntegralOrEnumerationType()) {
14362 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14363 // In C++11, a non-constexpr const static data member with an
14364 // in-class initializer cannot be volatile.
14365 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14366
14367 // We allow foldable floating-point constants as an extension.
14368 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14369 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14370 // it anyway and provide a fixit to add the 'constexpr'.
14371 if (getLangOpts().CPlusPlus11) {
14372 Diag(Loc: VDecl->getLocation(),
14373 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14374 << DclT << Init->getSourceRange();
14375 Diag(Loc: VDecl->getBeginLoc(),
14376 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14377 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14378 } else {
14379 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14380 << DclT << Init->getSourceRange();
14381
14382 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14383 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14384 << Init->getSourceRange();
14385 VDecl->setInvalidDecl();
14386 }
14387 }
14388
14389 // Suggest adding 'constexpr' in C++11 for literal types.
14390 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14391 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14392 << DclT << Init->getSourceRange()
14393 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14394 VDecl->setConstexpr(true);
14395
14396 } else {
14397 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14398 << DclT << Init->getSourceRange();
14399 VDecl->setInvalidDecl();
14400 }
14401 } else if (VDecl->isFileVarDecl()) {
14402 // In C, extern is typically used to avoid tentative definitions when
14403 // declaring variables in headers, but adding an initializer makes it a
14404 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14405 // In C++, extern is often used to give implicitly static const variables
14406 // external linkage, so don't warn in that case. If selectany is present,
14407 // this might be header code intended for C and C++ inclusion, so apply the
14408 // C++ rules.
14409 if (VDecl->getStorageClass() == SC_Extern &&
14410 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14411 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14412 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14413 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14414 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14415
14416 // In Microsoft C++ mode, a const variable defined in namespace scope has
14417 // external linkage by default if the variable is declared with
14418 // __declspec(dllexport).
14419 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14420 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14421 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14422 VDecl->setStorageClass(SC_Extern);
14423
14424 // C99 6.7.8p4. All file scoped initializers need to be constant.
14425 // Avoid duplicate diagnostics for constexpr variables.
14426 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14427 !VDecl->isConstexpr())
14428 CheckForConstantInitializer(Init);
14429 }
14430
14431 QualType InitType = Init->getType();
14432 if (!InitType.isNull() &&
14433 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14434 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14435 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14436
14437 // We will represent direct-initialization similarly to copy-initialization:
14438 // int x(1); -as-> int x = 1;
14439 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14440 //
14441 // Clients that want to distinguish between the two forms, can check for
14442 // direct initializer using VarDecl::getInitStyle().
14443 // A major benefit is that clients that don't particularly care about which
14444 // exactly form was it (like the CodeGen) can handle both cases without
14445 // special case code.
14446
14447 // C++ 8.5p11:
14448 // The form of initialization (using parentheses or '=') matters
14449 // when the entity being initialized has class type.
14450 if (InitializedFromParenListExpr) {
14451 assert(DirectInit && "Call-style initializer must be direct init.");
14452 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14453 : VarDecl::CallInit);
14454 } else if (DirectInit) {
14455 // This must be list-initialization. No other way is direct-initialization.
14456 VDecl->setInitStyle(VarDecl::ListInit);
14457 }
14458
14459 if (LangOpts.OpenMP &&
14460 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14461 VDecl->isFileVarDecl())
14462 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14463 CheckCompleteVariableDeclaration(VD: VDecl);
14464
14465 if (LangOpts.OpenACC && !InitType.isNull())
14466 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14467}
14468
14469void Sema::ActOnInitializerError(Decl *D) {
14470 // Our main concern here is re-establishing invariants like "a
14471 // variable's type is either dependent or complete".
14472 if (!D || D->isInvalidDecl()) return;
14473
14474 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14475 if (!VD) return;
14476
14477 // Bindings are not usable if we can't make sense of the initializer.
14478 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14479 for (auto *BD : DD->bindings())
14480 BD->setInvalidDecl();
14481
14482 // Auto types are meaningless if we can't make sense of the initializer.
14483 if (VD->getType()->isUndeducedType()) {
14484 D->setInvalidDecl();
14485 return;
14486 }
14487
14488 QualType Ty = VD->getType();
14489 if (Ty->isDependentType()) return;
14490
14491 // Require a complete type.
14492 if (RequireCompleteType(Loc: VD->getLocation(),
14493 T: Context.getBaseElementType(QT: Ty),
14494 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14495 VD->setInvalidDecl();
14496 return;
14497 }
14498
14499 // Require a non-abstract type.
14500 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14501 DiagID: diag::err_abstract_type_in_decl,
14502 Args: AbstractVariableType)) {
14503 VD->setInvalidDecl();
14504 return;
14505 }
14506
14507 // Don't bother complaining about constructors or destructors,
14508 // though.
14509}
14510
14511void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14512 // If there is no declaration, there was an error parsing it. Just ignore it.
14513 if (!RealDecl)
14514 return;
14515
14516 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14517 QualType Type = Var->getType();
14518
14519 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14520 Diag(Loc: Var->getLocation(),
14521 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14522 << Var;
14523 Var->setInvalidDecl();
14524 return;
14525 }
14526 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14527 if (isa<DecompositionDecl>(Val: RealDecl)) {
14528 // Point the caret to the token immediately after the closing bracket if
14529 // it can be found; otherwise fall back to the declaration's location.
14530 SourceLocation Loc = Var->getLocation();
14531 SourceLocation RSquareLoc =
14532 dyn_cast<DecompositionDecl>(Val: RealDecl)->getRSquareLoc();
14533 if (std::optional<Token> Next = Lexer::findNextToken(
14534 Loc: RSquareLoc, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()))
14535 Loc = Next->getLocation();
14536 Diag(Loc, DiagID: diag::err_decomp_decl_requires_init) << Var;
14537 Var->setInvalidDecl();
14538 return;
14539 }
14540
14541 if (Type->isUndeducedType() &&
14542 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14543 return;
14544
14545 this->CheckAttributesOnDeducedType(D: RealDecl);
14546
14547 // C++11 [class.static.data]p3: A static data member can be declared with
14548 // the constexpr specifier; if so, its declaration shall specify
14549 // a brace-or-equal-initializer.
14550 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14551 // the definition of a variable [...] or the declaration of a static data
14552 // member.
14553 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14554 !Var->isThisDeclarationADemotedDefinition()) {
14555 if (Var->isStaticDataMember()) {
14556 // C++1z removes the relevant rule; the in-class declaration is always
14557 // a definition there.
14558 if (!getLangOpts().CPlusPlus17 &&
14559 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14560 Diag(Loc: Var->getLocation(),
14561 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14562 << Var;
14563 Var->setInvalidDecl();
14564 return;
14565 }
14566 } else {
14567 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14568 Var->setInvalidDecl();
14569 return;
14570 }
14571 }
14572
14573 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14574 // be initialized.
14575 if (!Var->isInvalidDecl() &&
14576 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14577 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14578 bool HasConstExprDefaultConstructor = false;
14579 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14580 for (auto *Ctor : RD->ctors()) {
14581 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14582 Ctor->getMethodQualifiers().getAddressSpace() ==
14583 LangAS::opencl_constant) {
14584 HasConstExprDefaultConstructor = true;
14585 }
14586 }
14587 }
14588 if (!HasConstExprDefaultConstructor) {
14589 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14590 Var->setInvalidDecl();
14591 return;
14592 }
14593 }
14594
14595 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14596 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14597 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14598 Var->setInvalidDecl();
14599 return;
14600 }
14601
14602 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14603 if (Var->getStorageClass() == SC_Extern) {
14604 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14605 << Var;
14606 Var->setInvalidDecl();
14607 return;
14608 }
14609 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14610 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14611 Var->setInvalidDecl();
14612 return;
14613 }
14614 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14615 if (!RD->hasTrivialDefaultConstructor()) {
14616 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14617 Var->setInvalidDecl();
14618 return;
14619 }
14620 }
14621 // The declaration is uninitialized, no need for further checks.
14622 return;
14623 }
14624
14625 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14626 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14627 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14628 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14629 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14630 NonTrivialKind: NTCUK_Init);
14631
14632 switch (DefKind) {
14633 case VarDecl::Definition:
14634 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14635 break;
14636
14637 // We have an out-of-line definition of a static data member
14638 // that has an in-class initializer, so we type-check this like
14639 // a declaration.
14640 //
14641 [[fallthrough]];
14642
14643 case VarDecl::DeclarationOnly:
14644 // It's only a declaration.
14645
14646 // Block scope. C99 6.7p7: If an identifier for an object is
14647 // declared with no linkage (C99 6.2.2p6), the type for the
14648 // object shall be complete.
14649 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14650 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14651 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14652 DiagID: diag::err_typecheck_decl_incomplete_type))
14653 Var->setInvalidDecl();
14654
14655 // Make sure that the type is not abstract.
14656 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14657 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14658 DiagID: diag::err_abstract_type_in_decl,
14659 Args: AbstractVariableType))
14660 Var->setInvalidDecl();
14661 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14662 Var->getStorageClass() == SC_PrivateExtern) {
14663 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14664 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14665 }
14666
14667 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14668 !Var->isInvalidDecl())
14669 ExternalDeclarations.push_back(Elt: Var);
14670
14671 return;
14672
14673 case VarDecl::TentativeDefinition:
14674 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14675 // object that has file scope without an initializer, and without a
14676 // storage-class specifier or with the storage-class specifier "static",
14677 // constitutes a tentative definition. Note: A tentative definition with
14678 // external linkage is valid (C99 6.2.2p5).
14679 if (!Var->isInvalidDecl()) {
14680 if (const IncompleteArrayType *ArrayT
14681 = Context.getAsIncompleteArrayType(T: Type)) {
14682 if (RequireCompleteSizedType(
14683 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14684 DiagID: diag::err_array_incomplete_or_sizeless_type))
14685 Var->setInvalidDecl();
14686 }
14687 if (Var->getStorageClass() == SC_Static) {
14688 // C99 6.9.2p3: If the declaration of an identifier for an object is
14689 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14690 // declared type shall not be an incomplete type.
14691 // NOTE: code such as the following
14692 // static struct s;
14693 // struct s { int a; };
14694 // is accepted by gcc. Hence here we issue a warning instead of
14695 // an error and we do not invalidate the static declaration.
14696 // NOTE: to avoid multiple warnings, only check the first declaration.
14697 if (Var->isFirstDecl())
14698 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14699 DiagID: diag::ext_typecheck_decl_incomplete_type,
14700 Args: Type->isArrayType());
14701 }
14702 }
14703
14704 // Record the tentative definition; we're done.
14705 if (!Var->isInvalidDecl())
14706 TentativeDefinitions.push_back(LocalValue: Var);
14707 return;
14708 }
14709
14710 // Provide a specific diagnostic for uninitialized variable definitions
14711 // with incomplete array type, unless it is a global unbounded HLSL resource
14712 // array.
14713 if (Type->isIncompleteArrayType() &&
14714 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14715 Type->isHLSLResourceRecordArray())) {
14716 if (Var->isConstexpr())
14717 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14718 << Var;
14719 else
14720 Diag(Loc: Var->getLocation(),
14721 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14722 Var->setInvalidDecl();
14723 return;
14724 }
14725
14726 // Provide a specific diagnostic for uninitialized variable
14727 // definitions with reference type.
14728 if (Type->isReferenceType()) {
14729 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14730 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14731 return;
14732 }
14733
14734 // Do not attempt to type-check the default initializer for a
14735 // variable with dependent type.
14736 if (Type->isDependentType())
14737 return;
14738
14739 if (Var->isInvalidDecl())
14740 return;
14741
14742 if (!Var->hasAttr<AliasAttr>()) {
14743 if (RequireCompleteType(Loc: Var->getLocation(),
14744 T: Context.getBaseElementType(QT: Type),
14745 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14746 Var->setInvalidDecl();
14747 return;
14748 }
14749 } else {
14750 return;
14751 }
14752
14753 // The variable can not have an abstract class type.
14754 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14755 DiagID: diag::err_abstract_type_in_decl,
14756 Args: AbstractVariableType)) {
14757 Var->setInvalidDecl();
14758 return;
14759 }
14760
14761 // In C, if the definition is const-qualified and has no initializer, it
14762 // is left uninitialized unless it has static or thread storage duration.
14763 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14764 unsigned DiagID = diag::warn_default_init_const_unsafe;
14765 if (Var->getStorageDuration() == SD_Static ||
14766 Var->getStorageDuration() == SD_Thread)
14767 DiagID = diag::warn_default_init_const;
14768
14769 bool EmitCppCompat = !Diags.isIgnored(
14770 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14771 Loc: Var->getLocation());
14772
14773 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14774 }
14775
14776 // Check for jumps past the implicit initializer. C++0x
14777 // clarifies that this applies to a "variable with automatic
14778 // storage duration", not a "local variable".
14779 // C++11 [stmt.dcl]p3
14780 // A program that jumps from a point where a variable with automatic
14781 // storage duration is not in scope to a point where it is in scope is
14782 // ill-formed unless the variable has scalar type, class type with a
14783 // trivial default constructor and a trivial destructor, a cv-qualified
14784 // version of one of these types, or an array of one of the preceding
14785 // types and is declared without an initializer.
14786 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14787 if (const auto *CXXRecord =
14788 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14789 // Mark the function (if we're in one) for further checking even if the
14790 // looser rules of C++11 do not require such checks, so that we can
14791 // diagnose incompatibilities with C++98.
14792 if (!CXXRecord->isPOD())
14793 setFunctionHasBranchProtectedScope();
14794 }
14795 }
14796 // In OpenCL, we can't initialize objects in the __local address space,
14797 // even implicitly, so don't synthesize an implicit initializer.
14798 if (getLangOpts().OpenCL &&
14799 Var->getType().getAddressSpace() == LangAS::opencl_local)
14800 return;
14801
14802 // Handle HLSL uninitialized decls
14803 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14804 return;
14805
14806 // HLSL input & push-constant variables are expected to be externally
14807 // initialized, even when marked `static`.
14808 if (getLangOpts().HLSL &&
14809 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14810 return;
14811
14812 // C++03 [dcl.init]p9:
14813 // If no initializer is specified for an object, and the
14814 // object is of (possibly cv-qualified) non-POD class type (or
14815 // array thereof), the object shall be default-initialized; if
14816 // the object is of const-qualified type, the underlying class
14817 // type shall have a user-declared default
14818 // constructor. Otherwise, if no initializer is specified for
14819 // a non- static object, the object and its subobjects, if
14820 // any, have an indeterminate initial value); if the object
14821 // or any of its subobjects are of const-qualified type, the
14822 // program is ill-formed.
14823 // C++0x [dcl.init]p11:
14824 // If no initializer is specified for an object, the object is
14825 // default-initialized; [...].
14826 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14827 InitializationKind Kind
14828 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14829
14830 InitializationSequence InitSeq(*this, Entity, Kind, {});
14831 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14832
14833 if (Init.get()) {
14834 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14835 // This is important for template substitution.
14836 Var->setInitStyle(VarDecl::CallInit);
14837 } else if (Init.isInvalid()) {
14838 // If default-init fails, attach a recovery-expr initializer to track
14839 // that initialization was attempted and failed.
14840 auto RecoveryExpr =
14841 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14842 if (RecoveryExpr.get())
14843 Var->setInit(RecoveryExpr.get());
14844 }
14845
14846 CheckCompleteVariableDeclaration(VD: Var);
14847 }
14848}
14849
14850void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
14851 // If there is no declaration, there was an error parsing it. Ignore it.
14852 if (!D)
14853 return;
14854
14855 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14856 if (!VD) {
14857 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var)
14858 << InExpansionStmt;
14859 D->setInvalidDecl();
14860 return;
14861 }
14862
14863 VD->setCXXForRangeDecl(true);
14864
14865 // for-range-declaration cannot be given a storage class specifier.
14866 int Error = -1;
14867 switch (VD->getStorageClass()) {
14868 case SC_None:
14869 break;
14870 case SC_Extern:
14871 Error = 0;
14872 break;
14873 case SC_Static:
14874 Error = 1;
14875 break;
14876 case SC_PrivateExtern:
14877 Error = 2;
14878 break;
14879 case SC_Auto:
14880 Error = 3;
14881 break;
14882 case SC_Register:
14883 Error = 4;
14884 break;
14885 }
14886
14887 // for-range-declaration cannot be given a storage class specifier con't.
14888 switch (VD->getTSCSpec()) {
14889 case TSCS_thread_local:
14890 Error = 6;
14891 break;
14892 case TSCS___thread:
14893 case TSCS__Thread_local:
14894 case TSCS_unspecified:
14895 break;
14896 }
14897
14898 if (Error != -1) {
14899 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14900 << InExpansionStmt << VD << Error;
14901 D->setInvalidDecl();
14902 }
14903}
14904
14905StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14906 IdentifierInfo *Ident,
14907 ParsedAttributes &Attrs) {
14908 // C++1y [stmt.iter]p1:
14909 // A range-based for statement of the form
14910 // for ( for-range-identifier : for-range-initializer ) statement
14911 // is equivalent to
14912 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14913 DeclSpec DS(Attrs.getPool().getFactory());
14914
14915 const char *PrevSpec;
14916 unsigned DiagID;
14917 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14918 Policy: getPrintingPolicy());
14919
14920 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14921 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14922 D.takeAttributesAppending(attrs&: Attrs);
14923
14924 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14925 EndLoc: IdentLoc);
14926 Decl *Var = ActOnDeclarator(S, D);
14927 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14928 FinalizeDeclaration(D: Var);
14929 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14930 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14931 : IdentLoc);
14932}
14933
14934void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
14935 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
14936 return;
14937 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
14938 QualType MethodType = MD->getType();
14939 QualType AttributedType =
14940 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
14941 TypeLocBuilder TLB;
14942 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14943 TLB.pushFullCopy(L: TSI->getTypeLoc());
14944 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
14945 TyLoc.setAttr(Attr);
14946 MD->setType(AttributedType);
14947 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
14948}
14949
14950void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14951 if (var->isInvalidDecl()) return;
14952
14953 CUDA().MaybeAddConstantAttr(VD: var);
14954
14955 if (getLangOpts().OpenCL) {
14956 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14957 // initialiser
14958 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14959 !var->hasInit()) {
14960 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14961 << 1 /*Init*/;
14962 var->setInvalidDecl();
14963 return;
14964 }
14965 }
14966
14967 // In Objective-C, don't allow jumps past the implicit initialization of a
14968 // local retaining variable.
14969 if (getLangOpts().ObjC &&
14970 var->hasLocalStorage()) {
14971 switch (var->getType().getObjCLifetime()) {
14972 case Qualifiers::OCL_None:
14973 case Qualifiers::OCL_ExplicitNone:
14974 case Qualifiers::OCL_Autoreleasing:
14975 break;
14976
14977 case Qualifiers::OCL_Weak:
14978 case Qualifiers::OCL_Strong:
14979 setFunctionHasBranchProtectedScope();
14980 break;
14981 }
14982 }
14983
14984 if (var->hasLocalStorage() &&
14985 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14986 setFunctionHasBranchProtectedScope();
14987
14988 // Warn about externally-visible variables being defined without a
14989 // prior declaration. We only want to do this for global
14990 // declarations, but we also specifically need to avoid doing it for
14991 // class members because the linkage of an anonymous class can
14992 // change if it's later given a typedef name.
14993 if (var->isThisDeclarationADefinition() &&
14994 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14995 var->isExternallyVisible() && var->hasLinkage() &&
14996 !var->isInline() && !var->getDescribedVarTemplate() &&
14997 var->getStorageClass() != SC_Register &&
14998 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14999 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
15000 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
15001 Loc: var->getLocation())) {
15002 // Find a previous declaration that's not a definition.
15003 VarDecl *prev = var->getPreviousDecl();
15004 while (prev && prev->isThisDeclarationADefinition())
15005 prev = prev->getPreviousDecl();
15006
15007 if (!prev) {
15008 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
15009 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
15010 << /* variable */ 0;
15011 }
15012 }
15013
15014 // Cache the result of checking for constant initialization.
15015 std::optional<bool> CacheHasConstInit;
15016 const Expr *CacheCulprit = nullptr;
15017 auto checkConstInit = [&]() mutable {
15018 const Expr *Init = var->getInit();
15019 if (Init->isInstantiationDependent())
15020 return true;
15021
15022 if (!CacheHasConstInit)
15023 CacheHasConstInit = var->getInit()->isConstantInitializer(
15024 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
15025 return *CacheHasConstInit;
15026 };
15027
15028 if (var->getTLSKind() == VarDecl::TLS_Static) {
15029 if (var->getType().isDestructedType()) {
15030 // GNU C++98 edits for __thread, [basic.start.term]p3:
15031 // The type of an object with thread storage duration shall not
15032 // have a non-trivial destructor.
15033 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
15034 if (getLangOpts().CPlusPlus11)
15035 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15036 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15037 if (!checkConstInit()) {
15038 // GNU C++98 edits for __thread, [basic.start.init]p4:
15039 // An object of thread storage duration shall not require dynamic
15040 // initialization.
15041 // FIXME: Need strict checking here.
15042 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
15043 << CacheCulprit->getSourceRange();
15044 if (getLangOpts().CPlusPlus11)
15045 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15046 }
15047 }
15048 }
15049
15050
15051 if (!var->getType()->isStructureType() && var->hasInit() &&
15052 isa<InitListExpr>(Val: var->getInit())) {
15053 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15054 unsigned NumInits = ILE->getNumInits();
15055 if (NumInits > 2)
15056 for (unsigned I = 0; I < NumInits; ++I) {
15057 const auto *Init = ILE->getInit(Init: I);
15058 if (!Init)
15059 break;
15060 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15061 if (!SL)
15062 break;
15063
15064 unsigned NumConcat = SL->getNumConcatenated();
15065 // Diagnose missing comma in string array initialization.
15066 // Do not warn when all the elements in the initializer are concatenated
15067 // together. Do not warn for macros too.
15068 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15069 bool OnlyOneMissingComma = true;
15070 for (unsigned J = I + 1; J < NumInits; ++J) {
15071 const auto *Init = ILE->getInit(Init: J);
15072 if (!Init)
15073 break;
15074 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15075 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15076 OnlyOneMissingComma = false;
15077 break;
15078 }
15079 }
15080
15081 if (OnlyOneMissingComma) {
15082 SmallVector<FixItHint, 1> Hints;
15083 for (unsigned i = 0; i < NumConcat - 1; ++i)
15084 Hints.push_back(Elt: FixItHint::CreateInsertion(
15085 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15086
15087 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15088 DiagID: diag::warn_concatenated_literal_array_init)
15089 << Hints;
15090 Diag(Loc: SL->getBeginLoc(),
15091 DiagID: diag::note_concatenated_string_literal_silence);
15092 }
15093 // In any case, stop now.
15094 break;
15095 }
15096 }
15097 }
15098
15099
15100 QualType type = var->getType();
15101
15102 if (var->hasAttr<BlocksAttr>())
15103 getCurFunction()->addByrefBlockVar(VD: var);
15104
15105 Expr *Init = var->getInit();
15106 bool GlobalStorage = var->hasGlobalStorage();
15107 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15108 QualType baseType = Context.getBaseElementType(QT: type);
15109 bool HasConstInit = true;
15110
15111 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15112 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15113 << var;
15114
15115 // Check whether the initializer is sufficiently constant.
15116 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15117 !type->isDependentType() && Init && !Init->isValueDependent() &&
15118 (GlobalStorage || var->isConstexpr() ||
15119 var->mightBeUsableInConstantExpressions(C: Context))) {
15120 // If this variable might have a constant initializer or might be usable in
15121 // constant expressions, check whether or not it actually is now. We can't
15122 // do this lazily, because the result might depend on things that change
15123 // later, such as which constexpr functions happen to be defined.
15124 SmallVector<PartialDiagnosticAt, 8> Notes;
15125 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15126 // Prior to C++11, in contexts where a constant initializer is required,
15127 // the set of valid constant initializers is described by syntactic rules
15128 // in [expr.const]p2-6.
15129 // FIXME: Stricter checking for these rules would be useful for constinit /
15130 // -Wglobal-constructors.
15131 HasConstInit = checkConstInit();
15132
15133 // Compute and cache the constant value, and remember that we have a
15134 // constant initializer.
15135 if (HasConstInit) {
15136 if (var->isStaticDataMember() && !var->isInline() &&
15137 var->getLexicalDeclContext()->isRecord() &&
15138 type->isIntegralOrEnumerationType()) {
15139 // In C++98, in-class initialization for a static data member must
15140 // be an integer constant expression.
15141 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15142 Diag(Loc: Init->getExprLoc(),
15143 DiagID: diag::ext_in_class_initializer_non_constant)
15144 << Init->getSourceRange();
15145 }
15146 }
15147 (void)var->checkForConstantInitialization(Notes);
15148 Notes.clear();
15149 } else if (CacheCulprit) {
15150 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15151 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15152 Notes.back().second << CacheCulprit->getSourceRange();
15153 }
15154 } else {
15155 // Evaluate the initializer to see if it's a constant initializer.
15156 HasConstInit = var->checkForConstantInitialization(Notes);
15157 }
15158
15159 if (HasConstInit) {
15160 // FIXME: Consider replacing the initializer with a ConstantExpr.
15161 } else if (var->isConstexpr()) {
15162 SourceLocation DiagLoc = var->getLocation();
15163 // If the note doesn't add any useful information other than a source
15164 // location, fold it into the primary diagnostic.
15165 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15166 diag::note_invalid_subexpr_in_const_expr) {
15167 DiagLoc = Notes[0].first;
15168 Notes.clear();
15169 }
15170 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15171 << var << Init->getSourceRange();
15172 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15173 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15174 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15175 auto *Attr = var->getAttr<ConstInitAttr>();
15176 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15177 << Init->getSourceRange();
15178 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15179 << Attr->getRange() << Attr->isConstinit();
15180 for (auto &it : Notes)
15181 Diag(Loc: it.first, PD: it.second);
15182 } else if (var->isStaticDataMember() && !var->isInline() &&
15183 var->getLexicalDeclContext()->isRecord()) {
15184 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15185 << Init->getSourceRange();
15186 for (auto &it : Notes)
15187 Diag(Loc: it.first, PD: it.second);
15188 var->setInvalidDecl();
15189 } else if (IsGlobal &&
15190 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15191 Loc: var->getLocation())) {
15192 // Warn about globals which don't have a constant initializer. Don't
15193 // warn about globals with a non-trivial destructor because we already
15194 // warned about them.
15195 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15196 if (!(RD && !RD->hasTrivialDestructor())) {
15197 // checkConstInit() here permits trivial default initialization even in
15198 // C++11 onwards, where such an initializer is not a constant initializer
15199 // but nonetheless doesn't require a global constructor.
15200 if (!checkConstInit())
15201 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15202 << Init->getSourceRange();
15203 }
15204 }
15205 }
15206
15207 // Apply section attributes and pragmas to global variables.
15208 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15209 !inTemplateInstantiation()) {
15210 PragmaStack<StringLiteral *> *Stack = nullptr;
15211 int SectionFlags = ASTContext::PSF_Read;
15212 bool MSVCEnv =
15213 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15214 std::optional<QualType::NonConstantStorageReason> Reason;
15215 if (HasConstInit &&
15216 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15217 Stack = &ConstSegStack;
15218 } else {
15219 SectionFlags |= ASTContext::PSF_Write;
15220 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15221 }
15222 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15223 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15224 SectionFlags |= ASTContext::PSF_Implicit;
15225 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15226 } else if (Stack->CurrentValue) {
15227 if (Stack != &ConstSegStack && MSVCEnv &&
15228 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15229 var->getType().isConstQualified()) {
15230 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15231 NonConstNonReferenceType) &&
15232 "This case should've already been handled elsewhere");
15233 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15234 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15235 ? QualType::NonConstantStorageReason::NonTrivialCtor
15236 : *Reason);
15237 }
15238 SectionFlags |= ASTContext::PSF_Implicit;
15239 auto SectionName = Stack->CurrentValue->getString();
15240 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15241 Range: Stack->CurrentPragmaLocation,
15242 S: SectionAttr::Declspec_allocate));
15243 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15244 var->dropAttr<SectionAttr>();
15245 }
15246
15247 // Apply the init_seg attribute if this has an initializer. If the
15248 // initializer turns out to not be dynamic, we'll end up ignoring this
15249 // attribute.
15250 if (CurInitSeg && var->getInit())
15251 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15252 Range: CurInitSegLoc));
15253 }
15254
15255 // All the following checks are C++ only.
15256 if (!getLangOpts().CPlusPlus) {
15257 // If this variable must be emitted, add it as an initializer for the
15258 // current module.
15259 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15260 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15261 return;
15262 }
15263
15264 DiagnoseUniqueObjectDuplication(VD: var);
15265
15266 // Require the destructor.
15267 if (!type->isDependentType())
15268 if (auto *RD = baseType->getAsCXXRecordDecl())
15269 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15270
15271 // If this variable must be emitted, add it as an initializer for the current
15272 // module.
15273 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty() &&
15274 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15275 // For named modules, we may only emit non discardable variables.
15276 !isDiscardableGVALinkage(L: Context.GetGVALinkageForVariable(VD: var))))
15277 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15278
15279 // Build the bindings if this is a structured binding declaration.
15280 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15281 CheckCompleteDecompositionDeclaration(DD);
15282}
15283
15284void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15285 assert(VD->isStaticLocal());
15286
15287 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15288
15289 // Find outermost function when VD is in lambda function.
15290 while (FD && !getDLLAttr(D: FD) &&
15291 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15292 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15293 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15294 }
15295
15296 if (!FD)
15297 return;
15298
15299 // Static locals inherit dll attributes from their function.
15300 if (Attr *A = getDLLAttr(D: FD)) {
15301 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15302 NewAttr->setInherited(true);
15303 VD->addAttr(A: NewAttr);
15304 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15305 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15306 NewAttr->setInherited(true);
15307 VD->addAttr(A: NewAttr);
15308
15309 // Export this function to enforce exporting this static variable even
15310 // if it is not used in this compilation unit.
15311 if (!FD->hasAttr<DLLExportAttr>())
15312 FD->addAttr(A: NewAttr);
15313
15314 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15315 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15316 NewAttr->setInherited(true);
15317 VD->addAttr(A: NewAttr);
15318 }
15319}
15320
15321void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15322 assert(VD->getTLSKind());
15323
15324 // Perform TLS alignment check here after attributes attached to the variable
15325 // which may affect the alignment have been processed. Only perform the check
15326 // if the target has a maximum TLS alignment (zero means no constraints).
15327 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15328 // Protect the check so that it's not performed on dependent types and
15329 // dependent alignments (we can't determine the alignment in that case).
15330 if (!VD->hasDependentAlignment()) {
15331 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15332 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15333 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15334 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15335 << (unsigned)MaxAlignChars.getQuantity();
15336 }
15337 }
15338 }
15339}
15340
15341void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15342 // Note that we are no longer parsing the initializer for this declaration.
15343 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15344
15345 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15346 if (!VD)
15347 return;
15348
15349 // Emit any deferred warnings for the variable's initializer, even if the
15350 // variable is invalid
15351 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15352
15353 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15354 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15355 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15356 if (PragmaClangBSSSection.Valid)
15357 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15358 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15359 Range: PragmaClangBSSSection.PragmaLocation));
15360 if (PragmaClangDataSection.Valid)
15361 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15362 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15363 Range: PragmaClangDataSection.PragmaLocation));
15364 if (PragmaClangRodataSection.Valid)
15365 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15366 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15367 Range: PragmaClangRodataSection.PragmaLocation));
15368 if (PragmaClangRelroSection.Valid)
15369 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15370 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15371 Range: PragmaClangRelroSection.PragmaLocation));
15372 }
15373
15374 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15375 for (auto *BD : DD->bindings()) {
15376 FinalizeDeclaration(ThisDecl: BD);
15377 }
15378 }
15379
15380 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15381 K: BuiltinCountedByRefKind::Initializer);
15382
15383 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15384
15385 if (VD->isStaticLocal())
15386 CheckStaticLocalForDllExport(VD);
15387
15388 if (VD->getTLSKind())
15389 CheckThreadLocalForLargeAlignment(VD);
15390
15391 // Perform check for initializers of device-side global variables.
15392 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15393 // 7.5). We must also apply the same checks to all __shared__
15394 // variables whether they are local or not. CUDA also allows
15395 // constant initializers for __constant__ and __device__ variables.
15396 if (getLangOpts().CUDA)
15397 CUDA().checkAllowedInitializer(VD);
15398
15399 // Grab the dllimport or dllexport attribute off of the VarDecl.
15400 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15401
15402 // Imported static data members cannot be defined out-of-line.
15403 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15404 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15405 VD->isThisDeclarationADefinition()) {
15406 // We allow definitions of dllimport class template static data members
15407 // with a warning.
15408 CXXRecordDecl *Context =
15409 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15410 bool IsClassTemplateMember =
15411 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15412 Context->getDescribedClassTemplate();
15413
15414 Diag(Loc: VD->getLocation(),
15415 DiagID: IsClassTemplateMember
15416 ? diag::warn_attribute_dllimport_static_field_definition
15417 : diag::err_attribute_dllimport_static_field_definition);
15418 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15419 if (!IsClassTemplateMember)
15420 VD->setInvalidDecl();
15421 }
15422 }
15423
15424 // dllimport/dllexport variables cannot be thread local, their TLS index
15425 // isn't exported with the variable.
15426 if (DLLAttr && VD->getTLSKind()) {
15427 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15428 if (F && getDLLAttr(D: F)) {
15429 assert(VD->isStaticLocal());
15430 // But if this is a static local in a dlimport/dllexport function, the
15431 // function will never be inlined, which means the var would never be
15432 // imported, so having it marked import/export is safe.
15433 } else {
15434 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15435 << DLLAttr;
15436 VD->setInvalidDecl();
15437 }
15438 }
15439
15440 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15441 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15442 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15443 << Attr;
15444 VD->dropAttr<UsedAttr>();
15445 }
15446 }
15447 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15448 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15449 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15450 << Attr;
15451 VD->dropAttr<RetainAttr>();
15452 }
15453 }
15454
15455 const DeclContext *DC = VD->getDeclContext();
15456 // If there's a #pragma GCC visibility in scope, and this isn't a class
15457 // member, set the visibility of this variable.
15458 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15459 AddPushedVisibilityAttribute(RD: VD);
15460
15461 // FIXME: Warn on unused var template partial specializations.
15462 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15463 MarkUnusedFileScopedDecl(D: VD);
15464
15465 // Now we have parsed the initializer and can update the table of magic
15466 // tag values.
15467 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15468 !VD->getType()->isIntegralOrEnumerationType())
15469 return;
15470
15471 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15472 const Expr *MagicValueExpr = VD->getInit();
15473 if (!MagicValueExpr) {
15474 continue;
15475 }
15476 std::optional<llvm::APSInt> MagicValueInt;
15477 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15478 Diag(Loc: I->getRange().getBegin(),
15479 DiagID: diag::err_type_tag_for_datatype_not_ice)
15480 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15481 continue;
15482 }
15483 if (MagicValueInt->getActiveBits() > 64) {
15484 Diag(Loc: I->getRange().getBegin(),
15485 DiagID: diag::err_type_tag_for_datatype_too_large)
15486 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15487 continue;
15488 }
15489 uint64_t MagicValue = MagicValueInt->getZExtValue();
15490 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15491 MagicValue,
15492 Type: I->getMatchingCType(),
15493 LayoutCompatible: I->getLayoutCompatible(),
15494 MustBeNull: I->getMustBeNull());
15495 }
15496}
15497
15498static bool hasDeducedAuto(DeclaratorDecl *DD) {
15499 auto *VD = dyn_cast<VarDecl>(Val: DD);
15500 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15501}
15502
15503Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15504 ArrayRef<Decl *> Group) {
15505 SmallVector<Decl*, 8> Decls;
15506
15507 if (DS.isTypeSpecOwned())
15508 Decls.push_back(Elt: DS.getRepAsDecl());
15509
15510 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15511 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15512 bool DiagnosedMultipleDecomps = false;
15513 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15514 bool DiagnosedNonDeducedAuto = false;
15515
15516 for (Decl *D : Group) {
15517 if (!D)
15518 continue;
15519 // Check if the Decl has been declared in '#pragma omp declare target'
15520 // directive and has static storage duration.
15521 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15522 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15523 VD->hasGlobalStorage())
15524 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15525 // For declarators, there are some additional syntactic-ish checks we need
15526 // to perform.
15527 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15528 if (!FirstDeclaratorInGroup)
15529 FirstDeclaratorInGroup = DD;
15530 if (!FirstDecompDeclaratorInGroup)
15531 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15532 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15533 !hasDeducedAuto(DD))
15534 FirstNonDeducedAutoInGroup = DD;
15535
15536 if (FirstDeclaratorInGroup != DD) {
15537 // A decomposition declaration cannot be combined with any other
15538 // declaration in the same group.
15539 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15540 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15541 DiagID: diag::err_decomp_decl_not_alone)
15542 << FirstDeclaratorInGroup->getSourceRange()
15543 << DD->getSourceRange();
15544 DiagnosedMultipleDecomps = true;
15545 }
15546
15547 // A declarator that uses 'auto' in any way other than to declare a
15548 // variable with a deduced type cannot be combined with any other
15549 // declarator in the same group.
15550 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15551 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15552 DiagID: diag::err_auto_non_deduced_not_alone)
15553 << FirstNonDeducedAutoInGroup->getType()
15554 ->hasAutoForTrailingReturnType()
15555 << FirstDeclaratorInGroup->getSourceRange()
15556 << DD->getSourceRange();
15557 DiagnosedNonDeducedAuto = true;
15558 }
15559 }
15560 }
15561
15562 Decls.push_back(Elt: D);
15563 }
15564
15565 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15566 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15567 handleTagNumbering(Tag, TagScope: S);
15568 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15569 getLangOpts().CPlusPlus)
15570 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15571 }
15572 }
15573
15574 return BuildDeclaratorGroup(Group: Decls);
15575}
15576
15577Sema::DeclGroupPtrTy
15578Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15579 // C++14 [dcl.spec.auto]p7: (DR1347)
15580 // If the type that replaces the placeholder type is not the same in each
15581 // deduction, the program is ill-formed.
15582 if (Group.size() > 1) {
15583 QualType Deduced;
15584 VarDecl *DeducedDecl = nullptr;
15585 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15586 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15587 if (!D || D->isInvalidDecl())
15588 break;
15589 DeducedType *DT = D->getType()->getContainedDeducedType();
15590 if (!DT || DT->getDeducedType().isNull())
15591 continue;
15592 if (Deduced.isNull()) {
15593 Deduced = DT->getDeducedType();
15594 DeducedDecl = D;
15595 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15596 auto *AT = dyn_cast<AutoType>(Val: DT);
15597 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15598 DiagID: diag::err_auto_different_deductions)
15599 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15600 << DeducedDecl->getDeclName() << DT->getDeducedType()
15601 << D->getDeclName();
15602 if (DeducedDecl->hasInit())
15603 Dia << DeducedDecl->getInit()->getSourceRange();
15604 if (D->getInit())
15605 Dia << D->getInit()->getSourceRange();
15606 D->setInvalidDecl();
15607 break;
15608 }
15609 }
15610 }
15611
15612 ActOnDocumentableDecls(Group);
15613
15614 return DeclGroupPtrTy::make(
15615 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15616}
15617
15618void Sema::ActOnDocumentableDecl(Decl *D) {
15619 ActOnDocumentableDecls(Group: D);
15620}
15621
15622void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15623 // Don't parse the comment if Doxygen diagnostics are ignored.
15624 if (Group.empty() || !Group[0])
15625 return;
15626
15627 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15628 Loc: Group[0]->getLocation()) &&
15629 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15630 Loc: Group[0]->getLocation()))
15631 return;
15632
15633 if (Group.size() >= 2) {
15634 // This is a decl group. Normally it will contain only declarations
15635 // produced from declarator list. But in case we have any definitions or
15636 // additional declaration references:
15637 // 'typedef struct S {} S;'
15638 // 'typedef struct S *S;'
15639 // 'struct S *pS;'
15640 // FinalizeDeclaratorGroup adds these as separate declarations.
15641 Decl *MaybeTagDecl = Group[0];
15642 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15643 Group = Group.slice(N: 1);
15644 }
15645 }
15646
15647 // FIXME: We assume every Decl in the group is in the same file.
15648 // This is false when preprocessor constructs the group from decls in
15649 // different files (e. g. macros or #include).
15650 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15651}
15652
15653void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15654 // Check that there are no default arguments inside the type of this
15655 // parameter.
15656 if (getLangOpts().CPlusPlus)
15657 CheckExtraCXXDefaultArguments(D);
15658
15659 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15660 if (D.getCXXScopeSpec().isSet()) {
15661 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15662 << D.getCXXScopeSpec().getRange();
15663 }
15664
15665 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15666 // simple identifier except [...irrelevant cases...].
15667 switch (D.getName().getKind()) {
15668 case UnqualifiedIdKind::IK_Identifier:
15669 break;
15670
15671 case UnqualifiedIdKind::IK_OperatorFunctionId:
15672 case UnqualifiedIdKind::IK_ConversionFunctionId:
15673 case UnqualifiedIdKind::IK_LiteralOperatorId:
15674 case UnqualifiedIdKind::IK_ConstructorName:
15675 case UnqualifiedIdKind::IK_DestructorName:
15676 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15677 case UnqualifiedIdKind::IK_DeductionGuideName:
15678 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15679 << GetNameForDeclarator(D).getName();
15680 break;
15681
15682 case UnqualifiedIdKind::IK_TemplateId:
15683 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15684 // GetNameForDeclarator would not produce a useful name in this case.
15685 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15686 break;
15687 }
15688}
15689
15690void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15691 // This only matters in C.
15692 if (getLangOpts().CPlusPlus)
15693 return;
15694
15695 // This only matters if the declaration has a type.
15696 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15697 if (!VD)
15698 return;
15699
15700 // Get the type, this only matters for tag types.
15701 QualType QT = VD->getType();
15702 const auto *TD = QT->getAsTagDecl();
15703 if (!TD)
15704 return;
15705
15706 // Check if the tag declaration is lexically declared somewhere different
15707 // from the lexical declaration of the given object, then it will be hidden
15708 // in C++ and we should warn on it.
15709 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15710 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15711 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15712 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15713 }
15714}
15715
15716static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15717 SourceLocation ExplicitThisLoc) {
15718 if (!ExplicitThisLoc.isValid())
15719 return;
15720 assert(S.getLangOpts().CPlusPlus &&
15721 "explicit parameter in non-cplusplus mode");
15722 if (!S.getLangOpts().CPlusPlus23)
15723 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15724 << P->getSourceRange();
15725
15726 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15727 // parameter pack.
15728 if (P->isParameterPack()) {
15729 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15730 << P->getSourceRange();
15731 return;
15732 }
15733 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15734 if (LambdaScopeInfo *LSI = S.getCurLambda())
15735 LSI->ExplicitObjectParameter = P;
15736}
15737
15738Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15739 SourceLocation ExplicitThisLoc) {
15740 const DeclSpec &DS = D.getDeclSpec();
15741
15742 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15743 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15744 // except for the special case of a single unnamed parameter of type void
15745 // with no storage class specifier, no type qualifier, and no following
15746 // ellipsis terminator.
15747 // Clang applies the C2y rules for 'register void' in all C language modes,
15748 // same as GCC, because it's questionable what that could possibly mean.
15749
15750 // C++03 [dcl.stc]p2 also permits 'auto'.
15751 StorageClass SC = SC_None;
15752 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15753 SC = SC_Register;
15754 // In C++11, the 'register' storage class specifier is deprecated.
15755 // In C++17, it is not allowed, but we tolerate it as an extension.
15756 if (getLangOpts().CPlusPlus11) {
15757 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15758 ? diag::ext_register_storage_class
15759 : diag::warn_deprecated_register)
15760 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15761 } else if (!getLangOpts().CPlusPlus &&
15762 DS.getTypeSpecType() == DeclSpec::TST_void &&
15763 D.getNumTypeObjects() == 0) {
15764 Diag(Loc: DS.getStorageClassSpecLoc(),
15765 DiagID: diag::err_invalid_storage_class_in_func_decl)
15766 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15767 D.getMutableDeclSpec().ClearStorageClassSpecs();
15768 }
15769 } else if (getLangOpts().CPlusPlus &&
15770 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15771 SC = SC_Auto;
15772 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15773 Diag(Loc: DS.getStorageClassSpecLoc(),
15774 DiagID: diag::err_invalid_storage_class_in_func_decl);
15775 D.getMutableDeclSpec().ClearStorageClassSpecs();
15776 }
15777
15778 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15779 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15780 << DeclSpec::getSpecifierName(S: TSCS);
15781 if (DS.isInlineSpecified())
15782 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15783 << getLangOpts().CPlusPlus17;
15784 if (DS.hasConstexprSpecifier())
15785 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15786 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15787
15788 DiagnoseFunctionSpecifiers(DS);
15789
15790 CheckFunctionOrTemplateParamDeclarator(S, D);
15791
15792 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15793 QualType parmDeclType = TInfo->getType();
15794
15795 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15796 const IdentifierInfo *II = D.getIdentifier();
15797 if (II) {
15798 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15799 RedeclarationKind::ForVisibleRedeclaration);
15800 LookupName(R, S);
15801 if (!R.empty()) {
15802 NamedDecl *PrevDecl = *R.begin();
15803 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15804 // Maybe we will complain about the shadowed template parameter.
15805 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15806 // Just pretend that we didn't see the previous declaration.
15807 PrevDecl = nullptr;
15808 }
15809 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15810 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15811 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15812 // Recover by removing the name
15813 II = nullptr;
15814 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15815 D.setInvalidType(true);
15816 }
15817 }
15818 }
15819
15820 // Incomplete resource arrays are not allowed as function parameters in HLSL
15821 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15822 QualType EltTy = Context.getBaseElementType(QT: parmDeclType);
15823 // `isCompleteType` forces completion of the element type so the resource
15824 // check is valid.
15825 if (!EltTy->isDependentType() &&
15826 isCompleteType(Loc: D.getIdentifierLoc(), T: EltTy) &&
15827 parmDeclType->isHLSLResourceRecordArray()) {
15828 Diag(Loc: D.getIdentifierLoc(),
15829 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15830 D.setInvalidType(true);
15831 }
15832 }
15833
15834 // Temporarily put parameter variables in the translation unit, not
15835 // the enclosing context. This prevents them from accidentally
15836 // looking like class members in C++.
15837 ParmVarDecl *New =
15838 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15839 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15840
15841 if (D.isInvalidType())
15842 New->setInvalidDecl();
15843
15844 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15845
15846 assert(S->isFunctionPrototypeScope());
15847 assert(S->getFunctionPrototypeDepth() >= 1);
15848 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15849 parameterIndex: S->getNextFunctionPrototypeIndex());
15850
15851 warnOnCTypeHiddenInCPlusPlus(D: New);
15852
15853 // Add the parameter declaration into this scope.
15854 S->AddDecl(D: New);
15855 if (II)
15856 IdResolver.AddDecl(D: New);
15857
15858 ProcessDeclAttributes(S, D: New, PD: D);
15859
15860 if (D.getDeclSpec().isModulePrivateSpecified())
15861 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15862 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15863 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15864
15865 if (New->hasAttr<BlocksAttr>())
15866 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
15867 << diag::NotAllowedBlockVarReason::NonlocalVariable;
15868
15869 New->deduceParmAddressSpace(Ctxt: Context);
15870
15871 return New;
15872}
15873
15874ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15875 SourceLocation Loc,
15876 QualType T) {
15877 /* FIXME: setting StartLoc == Loc.
15878 Would it be worth to modify callers so as to provide proper source
15879 location for the unnamed parameters, embedding the parameter's type? */
15880 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15881 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15882 S: SC_None, DefArg: nullptr);
15883 Param->setImplicit();
15884 return Param;
15885}
15886
15887void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15888 // Don't diagnose unused-parameter errors in template instantiations; we
15889 // will already have done so in the template itself.
15890 if (inTemplateInstantiation())
15891 return;
15892
15893 for (const ParmVarDecl *Parameter : Parameters) {
15894 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15895 !Parameter->hasAttr<UnusedAttr>() &&
15896 !Parameter->getIdentifier()->isPlaceholder()) {
15897 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15898 << Parameter->getDeclName();
15899 }
15900 }
15901}
15902
15903void Sema::DiagnoseSizeOfParametersAndReturnValue(
15904 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15905 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15906 return;
15907
15908 // Warn if the return value is pass-by-value and larger than the specified
15909 // threshold.
15910 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15911 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15912 if (Size > LangOpts.NumLargeByValueCopy)
15913 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15914 }
15915
15916 // Warn if any parameter is pass-by-value and larger than the specified
15917 // threshold.
15918 for (const ParmVarDecl *Parameter : Parameters) {
15919 QualType T = Parameter->getType();
15920 if (T->isDependentType() || !T.isPODType(Context))
15921 continue;
15922 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15923 if (Size > LangOpts.NumLargeByValueCopy)
15924 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15925 << Parameter << Size;
15926 }
15927}
15928
15929ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15930 SourceLocation NameLoc,
15931 const IdentifierInfo *Name, QualType T,
15932 TypeSourceInfo *TSInfo, StorageClass SC) {
15933 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15934 if (getLangOpts().ObjCAutoRefCount &&
15935 T.getObjCLifetime() == Qualifiers::OCL_None &&
15936 T->isObjCLifetimeType()) {
15937
15938 Qualifiers::ObjCLifetime lifetime;
15939
15940 // Special cases for arrays:
15941 // - if it's const, use __unsafe_unretained
15942 // - otherwise, it's an error
15943 if (T->isArrayType()) {
15944 if (!T.isConstQualified()) {
15945 if (DelayedDiagnostics.shouldDelayDiagnostics())
15946 DelayedDiagnostics.add(
15947 diag: sema::DelayedDiagnostic::makeForbiddenType(
15948 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15949 else
15950 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15951 << TSInfo->getTypeLoc().getSourceRange();
15952 }
15953 lifetime = Qualifiers::OCL_ExplicitNone;
15954 } else {
15955 lifetime = T->getObjCARCImplicitLifetime();
15956 }
15957 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15958 }
15959
15960 if (getLangOpts().OpenCL) {
15961 assert(!isa<DecayedType>(T));
15962 if (T->isArrayType() && !T.hasAddressSpace()) {
15963 QualType ET = Context.getAsArrayType(T)->getElementType();
15964 if (!ET.hasAddressSpace()) {
15965 // Add the private address space to the contents of the pointer when a
15966 // pointer parameter is declared as an array and not declared.
15967 LangAS ImplAS = LangAS::opencl_private;
15968 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
15969 T = QualType(Context.getAsArrayType(T), 0);
15970 }
15971 }
15972 }
15973
15974 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15975 T: Context.getAdjustedParameterType(T),
15976 TInfo: TSInfo, S: SC, DefArg: nullptr);
15977
15978 // Make a note if we created a new pack in the scope of a lambda, so that
15979 // we know that references to that pack must also be expanded within the
15980 // lambda scope.
15981 if (New->isParameterPack())
15982 if (auto *CSI = getEnclosingLambdaOrBlock())
15983 CSI->LocalPacks.push_back(Elt: New);
15984
15985 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15986 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15987 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15988 UseContext: NonTrivialCUnionContext::FunctionParam,
15989 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15990
15991 // Parameter declarators cannot be interface types. All ObjC objects are
15992 // passed by reference.
15993 if (T->isObjCObjectType()) {
15994 SourceLocation TypeEndLoc =
15995 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15996 Diag(Loc: NameLoc,
15997 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15998 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15999 T = Context.getObjCObjectPointerType(OIT: T);
16000 New->setType(T);
16001 }
16002
16003 // __ptrauth is forbidden on parameters.
16004 if (T.getPointerAuth()) {
16005 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
16006 New->setInvalidDecl();
16007 }
16008
16009 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16010 // duration shall not be qualified by an address-space qualifier."
16011 // Since all parameters have automatic store duration, they can not have
16012 // an address space.
16013 if (T.getAddressSpace() != LangAS::Default &&
16014 // OpenCL allows function arguments declared to be an array of a type
16015 // to be qualified with an address space.
16016 !(getLangOpts().OpenCL &&
16017 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16018 // WebAssembly allows reference types as parameters. Funcref in particular
16019 // lives in a different address space.
16020 !(T->isFunctionPointerType() &&
16021 T.getAddressSpace() == LangAS::wasm_funcref) &&
16022 // HLSL allows function arguments to be qualified with an address space
16023 // if the groupshared annotation is used.
16024 !(getLangOpts().HLSL &&
16025 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16026 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
16027 New->setInvalidDecl();
16028 }
16029
16030 // PPC MMA non-pointer types are not allowed as function argument types.
16031 if (Context.getTargetInfo().getTriple().isPPC64() &&
16032 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
16033 New->setInvalidDecl();
16034 }
16035
16036 return New;
16037}
16038
16039void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
16040 SourceLocation LocAfterDecls) {
16041 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
16042
16043 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16044 // in the declaration list shall have at least one declarator, those
16045 // declarators shall only declare identifiers from the identifier list, and
16046 // every identifier in the identifier list shall be declared.
16047 //
16048 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16049 // identifiers it names shall be declared in the declaration list."
16050 //
16051 // This is why we only diagnose in C99 and later. Note, the other conditions
16052 // listed are checked elsewhere.
16053 if (!FTI.hasPrototype) {
16054 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16055 --i;
16056 if (FTI.Params[i].Param == nullptr) {
16057 if (getLangOpts().C99) {
16058 SmallString<256> Code;
16059 llvm::raw_svector_ostream(Code)
16060 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16061 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16062 << FTI.Params[i].Ident
16063 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16064 }
16065
16066 // Implicitly declare the argument as type 'int' for lack of a better
16067 // type.
16068 AttributeFactory attrs;
16069 DeclSpec DS(attrs);
16070 const char* PrevSpec; // unused
16071 unsigned DiagID; // unused
16072 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16073 DiagID, Policy: Context.getPrintingPolicy());
16074 // Use the identifier location for the type source range.
16075 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16076 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16077 Declarator ParamD(DS, ParsedAttributesView::none(),
16078 DeclaratorContext::KNRTypeList);
16079 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16080 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16081 }
16082 }
16083 }
16084}
16085
16086Decl *
16087Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16088 MultiTemplateParamsArg TemplateParameterLists,
16089 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16090 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16091 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16092 Scope *ParentScope = FnBodyScope->getParent();
16093
16094 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16095 // we define a non-templated function definition, we will create a declaration
16096 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16097 // The base function declaration will have the equivalent of an `omp declare
16098 // variant` annotation which specifies the mangled definition as a
16099 // specialization function under the OpenMP context defined as part of the
16100 // `omp begin declare variant`.
16101 SmallVector<FunctionDecl *, 4> Bases;
16102 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16103 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16104 S: ParentScope, D, TemplateParameterLists, Bases);
16105
16106 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16107 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16108 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16109
16110 if (!Bases.empty())
16111 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16112 Bases);
16113
16114 return Dcl;
16115}
16116
16117void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16118 Consumer.HandleInlineFunctionDefinition(D);
16119}
16120
16121static bool FindPossiblePrototype(const FunctionDecl *FD,
16122 const FunctionDecl *&PossiblePrototype) {
16123 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16124 Prev = Prev->getPreviousDecl()) {
16125 // Ignore any declarations that occur in function or method
16126 // scope, because they aren't visible from the header.
16127 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16128 continue;
16129
16130 PossiblePrototype = Prev;
16131 return Prev->getType()->isFunctionProtoType();
16132 }
16133 return false;
16134}
16135
16136static bool
16137ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16138 const FunctionDecl *&PossiblePrototype) {
16139 // Don't warn about invalid declarations.
16140 if (FD->isInvalidDecl())
16141 return false;
16142
16143 // Or declarations that aren't global.
16144 if (!FD->isGlobal())
16145 return false;
16146
16147 // Don't warn about C++ member functions.
16148 if (isa<CXXMethodDecl>(Val: FD))
16149 return false;
16150
16151 // Don't warn about 'main'.
16152 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16153 if (IdentifierInfo *II = FD->getIdentifier())
16154 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16155 return false;
16156
16157 if (FD->isMSVCRTEntryPoint())
16158 return false;
16159
16160 // Don't warn about inline functions.
16161 if (FD->isInlined())
16162 return false;
16163
16164 // Don't warn about function templates.
16165 if (FD->getDescribedFunctionTemplate())
16166 return false;
16167
16168 // Don't warn about function template specializations.
16169 if (FD->isFunctionTemplateSpecialization())
16170 return false;
16171
16172 // Don't warn for OpenCL kernels.
16173 if (FD->hasAttr<DeviceKernelAttr>())
16174 return false;
16175
16176 // Don't warn on explicitly deleted functions.
16177 if (FD->isDeleted())
16178 return false;
16179
16180 // Don't warn on implicitly local functions (such as having local-typed
16181 // parameters).
16182 if (!FD->isExternallyVisible())
16183 return false;
16184
16185 // If we were able to find a potential prototype, don't warn.
16186 if (FindPossiblePrototype(FD, PossiblePrototype))
16187 return false;
16188
16189 return true;
16190}
16191
16192void
16193Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16194 const FunctionDecl *EffectiveDefinition,
16195 SkipBodyInfo *SkipBody) {
16196 const FunctionDecl *Definition = EffectiveDefinition;
16197 if (!Definition &&
16198 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16199 return;
16200
16201 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16202 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16203 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16204 // A merged copy of the same function, instantiated as a member of
16205 // the same class, is OK.
16206 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16207 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16208 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16209 return;
16210 }
16211 }
16212 }
16213
16214 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16215 return;
16216
16217 // Don't emit an error when this is redefinition of a typo-corrected
16218 // definition.
16219 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16220 return;
16221
16222 bool DefinitionVisible = false;
16223 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16224 (Definition->getFormalLinkage() == Linkage::Internal ||
16225 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16226 !Definition->getTemplateParameterLists().empty())) {
16227 SkipBody->ShouldSkip = true;
16228 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16229 if (!DefinitionVisible) {
16230 if (auto *TD = Definition->getDescribedFunctionTemplate())
16231 makeMergedDefinitionVisible(ND: TD);
16232 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16233 }
16234 return;
16235 }
16236
16237 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16238 Definition->getStorageClass() == SC_Extern)
16239 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16240 << FD << getLangOpts().CPlusPlus;
16241 else
16242 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16243
16244 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16245 FD->setInvalidDecl();
16246}
16247
16248LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16249 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16250
16251 LambdaScopeInfo *LSI = PushLambdaScope();
16252 LSI->CallOperator = CallOperator;
16253 LSI->Lambda = LambdaClass;
16254 LSI->ReturnType = CallOperator->getReturnType();
16255 // When this function is called in situation where the context of the call
16256 // operator is not entered, we set AfterParameterList to false, so that
16257 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16258 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16259 // where we would set the CurContext to the lambda operator before
16260 // substituting into it. In this case the flag needs to be true such that
16261 // tryCaptureVariable can correctly handle potential captures thereof.
16262 LSI->AfterParameterList = CurContext == CallOperator;
16263
16264 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16265 // used at the point of dealing with potential captures.
16266 //
16267 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16268 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16269 // associated. (Technically, we could recover that list from their
16270 // instantiation patterns, but for now, the GLTemplateParameterList seems
16271 // unnecessary in these cases.)
16272 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16273 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16274 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16275
16276 if (LCD == LCD_None)
16277 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16278 else if (LCD == LCD_ByCopy)
16279 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16280 else if (LCD == LCD_ByRef)
16281 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16282 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16283
16284 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16285 LSI->Mutable = !CallOperator->isConst();
16286 if (CallOperator->isExplicitObjectMemberFunction())
16287 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16288
16289 // Add the captures to the LSI so they can be noted as already
16290 // captured within tryCaptureVar.
16291 auto I = LambdaClass->field_begin();
16292 for (const auto &C : LambdaClass->captures()) {
16293 if (C.capturesVariable()) {
16294 ValueDecl *VD = C.getCapturedVar();
16295 if (VD->isInitCapture())
16296 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16297 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16298 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16299 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16300 /*EllipsisLoc*/C.isPackExpansion()
16301 ? C.getEllipsisLoc() : SourceLocation(),
16302 CaptureType: I->getType(), /*Invalid*/false);
16303
16304 } else if (C.capturesThis()) {
16305 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16306 ByCopy: C.getCaptureKind() == LCK_StarThis);
16307 } else {
16308 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16309 CaptureType: I->getType());
16310 }
16311 ++I;
16312 }
16313 return LSI;
16314}
16315
16316Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16317 SkipBodyInfo *SkipBody,
16318 FnBodyKind BodyKind) {
16319 if (!D) {
16320 // Parsing the function declaration failed in some way. Push on a fake scope
16321 // anyway so we can try to parse the function body.
16322 PushFunctionScope();
16323 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16324 return D;
16325 }
16326
16327 FunctionDecl *FD = nullptr;
16328
16329 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16330 FD = FunTmpl->getTemplatedDecl();
16331 else
16332 FD = cast<FunctionDecl>(Val: D);
16333
16334 // Do not push if it is a lambda because one is already pushed when building
16335 // the lambda in ActOnStartOfLambdaDefinition().
16336 if (!isLambdaCallOperator(DC: FD))
16337 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16338 FD);
16339
16340 // Check for defining attributes before the check for redefinition.
16341 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16342 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16343 FD->dropAttr<AliasAttr>();
16344 FD->setInvalidDecl();
16345 }
16346 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16347 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16348 FD->dropAttr<IFuncAttr>();
16349 FD->setInvalidDecl();
16350 }
16351 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16352 if (Context.getTargetInfo().getTriple().isAArch64() &&
16353 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16354 !Attr->isDefaultVersion()) {
16355 // If function multi versioning disabled skip parsing function body
16356 // defined with non-default target_version attribute
16357 if (SkipBody)
16358 SkipBody->ShouldSkip = true;
16359 return nullptr;
16360 }
16361 }
16362
16363 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16364 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16365 Ctor->isDefaultConstructor() &&
16366 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16367 // If this is an MS ABI dllexport default constructor, instantiate any
16368 // default arguments.
16369 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16370 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
16371 }
16372 }
16373
16374 // See if this is a redefinition. If 'will have body' (or similar) is already
16375 // set, then these checks were already performed when it was set.
16376 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16377 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16378 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16379
16380 // If we're skipping the body, we're done. Don't enter the scope.
16381 if (SkipBody && SkipBody->ShouldSkip)
16382 return D;
16383 }
16384
16385 // Mark this function as "will have a body eventually". This lets users to
16386 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16387 // this function.
16388 FD->setWillHaveBody();
16389
16390 // If we are instantiating a generic lambda call operator, push
16391 // a LambdaScopeInfo onto the function stack. But use the information
16392 // that's already been calculated (ActOnLambdaExpr) to prime the current
16393 // LambdaScopeInfo.
16394 // When the template operator is being specialized, the LambdaScopeInfo,
16395 // has to be properly restored so that tryCaptureVariable doesn't try
16396 // and capture any new variables. In addition when calculating potential
16397 // captures during transformation of nested lambdas, it is necessary to
16398 // have the LSI properly restored.
16399 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16400 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16401 // specialized.
16402 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16403 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16404 << /*specialization*/ 0;
16405 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16406 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16407
16408 FD->setInvalidDecl();
16409 PushFunctionScope();
16410 } else {
16411 assert(inTemplateInstantiation() &&
16412 "There should be an active template instantiation on the stack "
16413 "when instantiating a generic lambda!");
16414 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16415 }
16416 } else {
16417 // Enter a new function scope
16418 PushFunctionScope();
16419 }
16420
16421 // Builtin functions cannot be defined.
16422 if (unsigned BuiltinID = FD->getBuiltinID()) {
16423 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16424 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16425 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16426 FD->setInvalidDecl();
16427 }
16428 }
16429
16430 // The return type of a function definition must be complete (C99 6.9.1p3).
16431 // C++23 [dcl.fct.def.general]/p2
16432 // The type of [...] the return for a function definition
16433 // shall not be a (possibly cv-qualified) class type that is incomplete
16434 // or abstract within the function body unless the function is deleted.
16435 QualType ResultType = FD->getReturnType();
16436 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16437 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16438 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16439 DiagID: diag::err_func_def_incomplete_result) ||
16440 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16441 DiagID: diag::err_abstract_type_in_decl,
16442 Args: AbstractReturnType)))
16443 FD->setInvalidDecl();
16444
16445 if (FnBodyScope)
16446 PushDeclContext(S: FnBodyScope, DC: FD);
16447
16448 // Check the validity of our function parameters
16449 if (BodyKind != FnBodyKind::Delete)
16450 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16451 /*CheckParameterNames=*/true);
16452
16453 // Add non-parameter declarations already in the function to the current
16454 // scope.
16455 if (FnBodyScope) {
16456 for (Decl *NPD : FD->decls()) {
16457 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16458 if (!NonParmDecl)
16459 continue;
16460 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16461 "parameters should not be in newly created FD yet");
16462
16463 // If the decl has a name, make it accessible in the current scope.
16464 if (NonParmDecl->getDeclName())
16465 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16466
16467 // Similarly, dive into enums and fish their constants out, making them
16468 // accessible in this scope.
16469 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16470 for (auto *EI : ED->enumerators())
16471 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16472 }
16473 }
16474 }
16475
16476 // Introduce our parameters into the function scope
16477 for (auto *Param : FD->parameters()) {
16478 Param->setOwningFunction(FD);
16479
16480 // If this has an identifier, add it to the scope stack.
16481 if (Param->getIdentifier() && FnBodyScope) {
16482 CheckShadow(S: FnBodyScope, D: Param);
16483
16484 PushOnScopeChains(D: Param, S: FnBodyScope);
16485 }
16486 }
16487
16488 // C++ [module.import/6]
16489 // ...
16490 // A header unit shall not contain a definition of a non-inline function or
16491 // variable whose name has external linkage.
16492 //
16493 // Deleted and Defaulted functions are implicitly inline (but the
16494 // inline state is not set at this point, so check the BodyKind explicitly).
16495 // We choose to allow weak & selectany definitions, as they are common in
16496 // headers, and have semantics similar to inline definitions which are allowed
16497 // in header units.
16498 // FIXME: Consider an alternate location for the test where the inlined()
16499 // state is complete.
16500 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16501 !FD->isInvalidDecl() && !FD->isInlined() &&
16502 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16503 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16504 !FD->isTemplateInstantiation() &&
16505 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16506 assert(FD->isThisDeclarationADefinition());
16507 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16508 FD->setInvalidDecl();
16509 }
16510
16511 // Ensure that the function's exception specification is instantiated.
16512 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16513 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16514
16515 // dllimport cannot be applied to non-inline function definitions.
16516 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16517 !FD->isTemplateInstantiation()) {
16518 assert(!FD->hasAttr<DLLExportAttr>());
16519 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16520 FD->setInvalidDecl();
16521 return D;
16522 }
16523
16524 // Some function attributes (like OptimizeNoneAttr) need actions before
16525 // parsing body started.
16526 applyFunctionAttributesBeforeParsingBody(FD: D);
16527
16528 // We want to attach documentation to original Decl (which might be
16529 // a function template).
16530 ActOnDocumentableDecl(D);
16531 if (getCurLexicalContext()->isObjCContainer() &&
16532 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16533 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16534 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16535
16536 maybeAddDeclWithEffects(D: FD);
16537
16538 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16539 FnBodyScope) {
16540 // An implicit call expression is synthesized for functions declared with
16541 // the sycl_kernel_entry_point attribute. The call may resolve to a
16542 // function template, a member function template, or a call operator
16543 // of a variable template depending on the results of unqualified lookup
16544 // for 'sycl_kernel_launch' from the beginning of the function body.
16545 // Performing that lookup requires the stack of parsing scopes active
16546 // when the definition is parsed and is thus done here; the result is
16547 // cached in FunctionScopeInfo and used to synthesize the (possibly
16548 // unresolved) call expression after the function body has been parsed.
16549 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16550 if (!SKEPAttr->isInvalidAttr()) {
16551 ExprResult LaunchIdExpr =
16552 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16553 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16554 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16555 // treated as an error in the definition of 'FD'; treating it as an error
16556 // of the declaration would affect overload resolution which would
16557 // potentially result in additional errors. If construction of
16558 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16559 // a null pointer value below; that is expected.
16560 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16561 }
16562 }
16563
16564 return D;
16565}
16566
16567void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16568 if (!FD || FD->isInvalidDecl())
16569 return;
16570 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16571 FD = TD->getTemplatedDecl();
16572 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16573 FPOptionsOverride FPO;
16574 FPO.setDisallowOptimizations();
16575 CurFPFeatures.applyChanges(FPO);
16576 FpPragmaStack.CurrentValue =
16577 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16578 }
16579}
16580
16581void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16582 ReturnStmt **Returns = Scope->Returns.data();
16583
16584 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16585 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16586 if (!NRVOCandidate->isNRVOVariable()) {
16587 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16588 DiagID: diag::warn_not_eliding_copy_on_return);
16589 Returns[I]->setNRVOCandidate(nullptr);
16590 }
16591 }
16592 }
16593}
16594
16595bool Sema::canDelayFunctionBody(const Declarator &D) {
16596 // We can't delay parsing the body of a constexpr function template (yet).
16597 if (D.getDeclSpec().hasConstexprSpecifier())
16598 return false;
16599
16600 // We can't delay parsing the body of a function template with a deduced
16601 // return type (yet).
16602 if (D.getDeclSpec().hasAutoTypeSpec()) {
16603 // If the placeholder introduces a non-deduced trailing return type,
16604 // we can still delay parsing it.
16605 if (D.getNumTypeObjects()) {
16606 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16607 if (Outer.Kind == DeclaratorChunk::Function &&
16608 Outer.Fun.hasTrailingReturnType()) {
16609 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16610 return Ty.isNull() || !Ty->isUndeducedType();
16611 }
16612 }
16613 return false;
16614 }
16615
16616 return true;
16617}
16618
16619bool Sema::canSkipFunctionBody(Decl *D) {
16620 // We cannot skip the body of a function (or function template) which is
16621 // constexpr, since we may need to evaluate its body in order to parse the
16622 // rest of the file.
16623 // We cannot skip the body of a function with an undeduced return type,
16624 // because any callers of that function need to know the type.
16625 if (const FunctionDecl *FD = D->getAsFunction()) {
16626 if (FD->isConstexpr())
16627 return false;
16628 // We can't simply call Type::isUndeducedType here, because inside template
16629 // auto can be deduced to a dependent type, which is not considered
16630 // "undeduced".
16631 if (FD->getReturnType()->getContainedDeducedType())
16632 return false;
16633 }
16634 return Consumer.shouldSkipFunctionBody(D);
16635}
16636
16637Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16638 if (!Decl)
16639 return nullptr;
16640 if (FunctionDecl *FD = Decl->getAsFunction())
16641 FD->setHasSkippedBody();
16642 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16643 MD->setHasSkippedBody();
16644 return Decl;
16645}
16646
16647/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16648/// body.
16649class ExitFunctionBodyRAII {
16650public:
16651 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16652 ~ExitFunctionBodyRAII() {
16653 if (!IsLambda)
16654 S.PopExpressionEvaluationContext();
16655 }
16656
16657private:
16658 Sema &S;
16659 bool IsLambda = false;
16660};
16661
16662static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16663 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16664
16665 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16666 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16667 if (!Inserted)
16668 return It->second;
16669
16670 bool R = false;
16671 const BlockDecl *CurBD = BD;
16672
16673 do {
16674 R = !CurBD->doesNotEscape();
16675 if (R)
16676 break;
16677 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16678 } while (CurBD);
16679
16680 return It->second = R;
16681 };
16682
16683 // If the location where 'self' is implicitly retained is inside a escaping
16684 // block, emit a diagnostic.
16685 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16686 S.ImplicitlyRetainedSelfLocs)
16687 if (IsOrNestedInEscapingBlock(P.second))
16688 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16689 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16690}
16691
16692static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16693 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16694 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16695}
16696
16697bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16698 return methodHasName(FD, Name: "get_return_object");
16699}
16700
16701bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16702 return FD->isStatic() &&
16703 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16704}
16705
16706void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16707 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16708 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16709 return;
16710 // Allow some_promise_type::get_return_object().
16711 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16712 return;
16713 if (!FD->hasAttr<CoroWrapperAttr>())
16714 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16715}
16716
16717Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16718 bool RetainFunctionScopeInfo) {
16719 FunctionScopeInfo *FSI = getCurFunction();
16720 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16721
16722 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16723 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16724
16725 SourceLocation AnalysisLoc;
16726 if (Body)
16727 AnalysisLoc = Body->getEndLoc();
16728 else if (FD)
16729 AnalysisLoc = FD->getEndLoc();
16730 sema::AnalysisBasedWarnings::Policy WP =
16731 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16732 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16733
16734 // If we skip function body, we can't tell if a function is a coroutine.
16735 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16736 if (FSI->isCoroutine())
16737 CheckCompletedCoroutineBody(FD, Body);
16738 else
16739 CheckCoroutineWrapper(FD);
16740 }
16741
16742 // Diagnose invalid SYCL kernel entry point function declarations
16743 // and build SYCLKernelCallStmts for valid ones.
16744 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16745 SYCLKernelEntryPointAttr *SKEPAttr =
16746 FD->getAttr<SYCLKernelEntryPointAttr>();
16747 if (FD->isDefaulted()) {
16748 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16749 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16750 SKEPAttr->setInvalidAttr();
16751 } else if (FD->isDeleted()) {
16752 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16753 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16754 SKEPAttr->setInvalidAttr();
16755 } else if (FSI->isCoroutine()) {
16756 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16757 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16758 SKEPAttr->setInvalidAttr();
16759 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16760 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16761 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16762 SKEPAttr->setInvalidAttr();
16763 }
16764
16765 // Build an unresolved SYCL kernel call statement for a function template,
16766 // validate that a SYCL kernel call statement was instantiated for an
16767 // (implicit or explicit) instantiation of a function template, or otherwise
16768 // build a (resolved) SYCL kernel call statement for a non-templated
16769 // function or an explicit specialization.
16770 if (Body && !SKEPAttr->isInvalidAttr()) {
16771 StmtResult SR;
16772 if (FD->isTemplateInstantiation()) {
16773 // The function body should already be a SYCLKernelCallStmt in this
16774 // case, but might not be if there were previous errors.
16775 SR = Body;
16776 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16777 // If name lookup for a template named sycl_kernel_launch failed
16778 // earlier, don't try to build a SYCL kernel call statement as that
16779 // would cause additional errors to be issued; just proceed with the
16780 // original function body.
16781 SR = Body;
16782 } else if (FD->isTemplated()) {
16783 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16784 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16785 } else {
16786 SR = SYCL().BuildSYCLKernelCallStmt(
16787 FD, Body: cast<CompoundStmt>(Val: Body),
16788 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16789 }
16790 // If construction of the replacement body fails, just continue with the
16791 // original function body. An early error return here is not valid; the
16792 // current declaration context and function scopes must be popped before
16793 // returning.
16794 if (SR.isUsable())
16795 Body = SR.get();
16796 }
16797 }
16798
16799 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16800 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16801 if (FD->isDeletedAsWritten())
16802 Diag(Loc: SEAttr->getLocation(),
16803 DiagID: diag::err_sycl_external_invalid_deleted_function)
16804 << SEAttr;
16805 }
16806
16807 {
16808 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16809 // one is already popped when finishing the lambda in BuildLambdaExpr().
16810 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16811 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16812 if (FD) {
16813 // The function body and the DefaultedOrDeletedInfo, if present, use
16814 // the same storage; don't overwrite the latter if the former is null
16815 // (the body is initialised to null anyway, so even if the latter isn't
16816 // present, this would still be a no-op).
16817 if (Body)
16818 FD->setBody(Body);
16819 FD->setWillHaveBody(false);
16820
16821 if (getLangOpts().CPlusPlus14) {
16822 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16823 FD->getReturnType()->isUndeducedType()) {
16824 // For a function with a deduced result type to return void,
16825 // the result type as written must be 'auto' or 'decltype(auto)',
16826 // possibly cv-qualified or constrained, but not ref-qualified.
16827 if (!FD->getReturnType()->getAs<AutoType>()) {
16828 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16829 << FD->getReturnType();
16830 FD->setInvalidDecl();
16831 } else {
16832 // Falling off the end of the function is the same as 'return;'.
16833 Expr *Dummy = nullptr;
16834 if (DeduceFunctionTypeFromReturnExpr(
16835 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16836 AT: FD->getReturnType()->getAs<AutoType>()))
16837 FD->setInvalidDecl();
16838 }
16839 }
16840 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16841 // In C++11, we don't use 'auto' deduction rules for lambda call
16842 // operators because we don't support return type deduction.
16843 auto *LSI = getCurLambda();
16844 if (LSI->HasImplicitReturnType) {
16845 deduceClosureReturnType(CSI&: *LSI);
16846
16847 // C++11 [expr.prim.lambda]p4:
16848 // [...] if there are no return statements in the compound-statement
16849 // [the deduced type is] the type void
16850 QualType RetType =
16851 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16852
16853 // Update the return type to the deduced type.
16854 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16855 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16856 EPI: Proto->getExtProtoInfo()));
16857 }
16858 }
16859
16860 // If the function implicitly returns zero (like 'main') or is naked,
16861 // don't complain about missing return statements.
16862 // Clang implicitly returns 0 in C89 mode, but that's considered an
16863 // extension. The check is necessary to ensure the expected extension
16864 // warning is emitted in C89 mode.
16865 if ((FD->hasImplicitReturnZero() &&
16866 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16867 FD->hasAttr<NakedAttr>())
16868 WP.disableCheckFallThrough();
16869
16870 // MSVC permits the use of pure specifier (=0) on function definition,
16871 // defined at class scope, warn about this non-standard construct.
16872 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16873 !FD->isOutOfLine())
16874 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16875
16876 if (!FD->isInvalidDecl()) {
16877 // Don't diagnose unused parameters of defaulted, deleted or naked
16878 // functions.
16879 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16880 !FD->hasAttr<NakedAttr>())
16881 DiagnoseUnusedParameters(Parameters: FD->parameters());
16882 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16883 ReturnTy: FD->getReturnType(), D: FD);
16884
16885 // If this is a structor, we need a vtable.
16886 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16887 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16888 else if (CXXDestructorDecl *Destructor =
16889 dyn_cast<CXXDestructorDecl>(Val: FD))
16890 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16891
16892 // Try to apply the named return value optimization. We have to check
16893 // if we can do this here because lambdas keep return statements around
16894 // to deduce an implicit return type.
16895 if (FD->getReturnType()->isRecordType() &&
16896 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16897 computeNRVO(Body, Scope: FSI);
16898 }
16899
16900 // GNU warning -Wmissing-prototypes:
16901 // Warn if a global function is defined without a previous
16902 // prototype declaration. This warning is issued even if the
16903 // definition itself provides a prototype. The aim is to detect
16904 // global functions that fail to be declared in header files.
16905 const FunctionDecl *PossiblePrototype = nullptr;
16906 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16907 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16908
16909 if (PossiblePrototype) {
16910 // We found a declaration that is not a prototype,
16911 // but that could be a zero-parameter prototype
16912 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16913 TypeLoc TL = TI->getTypeLoc();
16914 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16915 Diag(Loc: PossiblePrototype->getLocation(),
16916 DiagID: diag::note_declaration_not_a_prototype)
16917 << (FD->getNumParams() != 0)
16918 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16919 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16920 : FixItHint{});
16921 }
16922 } else {
16923 // Returns true if the token beginning at this Loc is `const`.
16924 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16925 const LangOptions &LangOpts) {
16926 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16927 if (LocInfo.first.isInvalid())
16928 return false;
16929
16930 bool Invalid = false;
16931 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16932 if (Invalid)
16933 return false;
16934
16935 if (LocInfo.second > Buffer.size())
16936 return false;
16937
16938 const char *LexStart = Buffer.data() + LocInfo.second;
16939 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16940
16941 return StartTok.consume_front(Prefix: "const") &&
16942 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16943 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16944 };
16945
16946 auto findBeginLoc = [&]() {
16947 // If the return type has `const` qualifier, we want to insert
16948 // `static` before `const` (and not before the typename).
16949 if ((FD->getReturnType()->isAnyPointerType() &&
16950 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16951 FD->getReturnType().isConstQualified()) {
16952 // But only do this if we can determine where the `const` is.
16953
16954 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16955 getLangOpts()))
16956
16957 return FD->getBeginLoc();
16958 }
16959 return FD->getTypeSpecStartLoc();
16960 };
16961 Diag(Loc: FD->getTypeSpecStartLoc(),
16962 DiagID: diag::note_static_for_internal_linkage)
16963 << /* function */ 1
16964 << (FD->getStorageClass() == SC_None
16965 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16966 : FixItHint{});
16967 }
16968 }
16969
16970 // We might not have found a prototype because we didn't wish to warn on
16971 // the lack of a missing prototype. Try again without the checks for
16972 // whether we want to warn on the missing prototype.
16973 if (!PossiblePrototype)
16974 (void)FindPossiblePrototype(FD, PossiblePrototype);
16975
16976 // If the function being defined does not have a prototype, then we may
16977 // need to diagnose it as changing behavior in C23 because we now know
16978 // whether the function accepts arguments or not. This only handles the
16979 // case where the definition has no prototype but does have parameters
16980 // and either there is no previous potential prototype, or the previous
16981 // potential prototype also has no actual prototype. This handles cases
16982 // like:
16983 // void f(); void f(a) int a; {}
16984 // void g(a) int a; {}
16985 // See MergeFunctionDecl() for other cases of the behavior change
16986 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16987 // type without a prototype.
16988 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16989 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16990 !PossiblePrototype->isImplicit()))) {
16991 // The function definition has parameters, so this will change behavior
16992 // in C23. If there is a possible prototype, it comes before the
16993 // function definition.
16994 // FIXME: The declaration may have already been diagnosed as being
16995 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16996 // there's no way to test for the "changes behavior" condition in
16997 // SemaType.cpp when forming the declaration's function type. So, we do
16998 // this awkward dance instead.
16999 //
17000 // If we have a possible prototype and it declares a function with a
17001 // prototype, we don't want to diagnose it; if we have a possible
17002 // prototype and it has no prototype, it may have already been
17003 // diagnosed in SemaType.cpp as deprecated depending on whether
17004 // -Wstrict-prototypes is enabled. If we already warned about it being
17005 // deprecated, add a note that it also changes behavior. If we didn't
17006 // warn about it being deprecated (because the diagnostic is not
17007 // enabled), warn now that it is deprecated and changes behavior.
17008
17009 // This K&R C function definition definitely changes behavior in C23,
17010 // so diagnose it.
17011 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
17012 << /*definition*/ 1 << /* not supported in C23 */ 0;
17013
17014 // If we have a possible prototype for the function which is a user-
17015 // visible declaration, we already tested that it has no prototype.
17016 // This will change behavior in C23. This gets a warning rather than a
17017 // note because it's the same behavior-changing problem as with the
17018 // definition.
17019 if (PossiblePrototype)
17020 Diag(Loc: PossiblePrototype->getLocation(),
17021 DiagID: diag::warn_non_prototype_changes_behavior)
17022 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17023 << /*definition*/ 1;
17024 }
17025
17026 // Warn on CPUDispatch with an actual body.
17027 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17028 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
17029 if (!CmpndBody->body_empty())
17030 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
17031 DiagID: diag::warn_dispatch_body_ignored);
17032
17033 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
17034 const CXXMethodDecl *KeyFunction;
17035 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17036 MD->isVirtual() &&
17037 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
17038 MD == KeyFunction->getCanonicalDecl()) {
17039 // Update the key-function state if necessary for this ABI.
17040 if (FD->isInlined() &&
17041 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17042 Context.setNonKeyFunction(MD);
17043
17044 // If the newly-chosen key function is already defined, then we
17045 // need to mark the vtable as used retroactively.
17046 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
17047 const FunctionDecl *Definition;
17048 if (KeyFunction && KeyFunction->isDefined(Definition))
17049 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17050 } else {
17051 // We just defined they key function; mark the vtable as used.
17052 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17053 }
17054 }
17055 }
17056
17057 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17058 "Function parsing confused");
17059 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
17060 assert(MD == getCurMethodDecl() && "Method parsing confused");
17061 MD->setBody(Body);
17062 if (!MD->isInvalidDecl()) {
17063 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17064 ReturnTy: MD->getReturnType(), D: MD);
17065
17066 if (Body)
17067 computeNRVO(Body, Scope: FSI);
17068 }
17069 if (FSI->ObjCShouldCallSuper) {
17070 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17071 << MD->getSelector().getAsString();
17072 FSI->ObjCShouldCallSuper = false;
17073 }
17074 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17075 const ObjCMethodDecl *InitMethod = nullptr;
17076 bool isDesignated =
17077 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17078 assert(isDesignated && InitMethod);
17079 (void)isDesignated;
17080
17081 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17082 auto IFace = MD->getClassInterface();
17083 if (!IFace)
17084 return false;
17085 auto SuperD = IFace->getSuperClass();
17086 if (!SuperD)
17087 return false;
17088 return SuperD->getIdentifier() ==
17089 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17090 };
17091 // Don't issue this warning for unavailable inits or direct subclasses
17092 // of NSObject.
17093 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17094 Diag(Loc: MD->getLocation(),
17095 DiagID: diag::warn_objc_designated_init_missing_super_call);
17096 Diag(Loc: InitMethod->getLocation(),
17097 DiagID: diag::note_objc_designated_init_marked_here);
17098 }
17099 FSI->ObjCWarnForNoDesignatedInitChain = false;
17100 }
17101 if (FSI->ObjCWarnForNoInitDelegation) {
17102 // Don't issue this warning for unavailable inits.
17103 if (!MD->isUnavailable())
17104 Diag(Loc: MD->getLocation(),
17105 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17106 FSI->ObjCWarnForNoInitDelegation = false;
17107 }
17108
17109 diagnoseImplicitlyRetainedSelf(S&: *this);
17110 } else {
17111 // Parsing the function declaration failed in some way. Pop the fake scope
17112 // we pushed on.
17113 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17114 return nullptr;
17115 }
17116
17117 if (Body) {
17118 if (FSI->HasPotentialAvailabilityViolations)
17119 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17120 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17121 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17122 }
17123
17124 assert(!FSI->ObjCShouldCallSuper &&
17125 "This should only be set for ObjC methods, which should have been "
17126 "handled in the block above.");
17127
17128 // Verify and clean out per-function state.
17129 if (Body && (!FD || !FD->isDefaulted())) {
17130 // C++ constructors that have function-try-blocks can't have return
17131 // statements in the handlers of that block. (C++ [except.handle]p14)
17132 // Verify this.
17133 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17134 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17135
17136 // Verify that gotos and switch cases don't jump into scopes illegally.
17137 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17138 DiagnoseInvalidJumps(Body);
17139
17140 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17141 if (!Destructor->getParent()->isDependentType())
17142 CheckDestructor(Destructor);
17143
17144 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17145 Record: Destructor->getParent());
17146 }
17147
17148 // If any errors have occurred, clear out any temporaries that may have
17149 // been leftover. This ensures that these temporaries won't be picked up
17150 // for deletion in some later function.
17151 if (hasUncompilableErrorOccurred() ||
17152 hasAnyUnrecoverableErrorsInThisFunction() ||
17153 getDiagnostics().getSuppressAllDiagnostics()) {
17154 DiscardCleanupsInEvaluationContext();
17155 }
17156 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17157 // Since the body is valid, issue any analysis-based warnings that are
17158 // enabled.
17159 ActivePolicy = &WP;
17160 }
17161
17162 if (!IsInstantiation && FD &&
17163 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17164 !FD->isInvalidDecl() &&
17165 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17166 FD->setInvalidDecl();
17167
17168 if (FD && FD->hasAttr<NakedAttr>()) {
17169 for (const Stmt *S : Body->children()) {
17170 // Allow local register variables without initializer as they don't
17171 // require prologue.
17172 bool RegisterVariables = false;
17173 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17174 for (const auto *Decl : DS->decls()) {
17175 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17176 RegisterVariables =
17177 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17178 if (!RegisterVariables)
17179 break;
17180 }
17181 }
17182 }
17183 if (RegisterVariables)
17184 continue;
17185 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17186 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17187 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17188 FD->setInvalidDecl();
17189 break;
17190 }
17191 }
17192 }
17193
17194 assert(ExprCleanupObjects.size() ==
17195 ExprEvalContexts.back().NumCleanupObjects &&
17196 "Leftover temporaries in function");
17197 assert(!Cleanup.exprNeedsCleanups() &&
17198 "Unaccounted cleanups in function");
17199 assert(MaybeODRUseExprs.empty() &&
17200 "Leftover expressions for odr-use checking");
17201 }
17202 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17203 // the declaration context below. Otherwise, we're unable to transform
17204 // 'this' expressions when transforming immediate context functions.
17205
17206 if (FD)
17207 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17208
17209 if (!IsInstantiation)
17210 PopDeclContext();
17211
17212 if (!RetainFunctionScopeInfo)
17213 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17214 // If any errors have occurred, clear out any temporaries that may have
17215 // been leftover. This ensures that these temporaries won't be picked up for
17216 // deletion in some later function.
17217 if (hasUncompilableErrorOccurred()) {
17218 DiscardCleanupsInEvaluationContext();
17219 }
17220
17221 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17222 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17223 auto ES = getEmissionStatus(Decl: FD);
17224 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17225 ES == Sema::FunctionEmissionStatus::Unknown)
17226 DeclsToCheckForDeferredDiags.insert(X: FD);
17227 }
17228
17229 if (FD && !FD->isDeleted())
17230 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17231
17232 return dcl;
17233}
17234
17235/// When we finish delayed parsing of an attribute, we must attach it to the
17236/// relevant Decl.
17237void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17238 ParsedAttributes &Attrs) {
17239 // Always attach attributes to the underlying decl.
17240 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17241 D = TD->getTemplatedDecl();
17242 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17243 ProcessAPINotes(D);
17244
17245 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17246 if (Method->isStatic())
17247 checkThisInStaticMemberFunctionAttributes(Method);
17248}
17249
17250NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17251 IdentifierInfo &II, Scope *S) {
17252 // It is not valid to implicitly define a function in C23.
17253 assert(LangOpts.implicitFunctionsAllowed() &&
17254 "Implicit function declarations aren't allowed in this language mode");
17255
17256 // Find the scope in which the identifier is injected and the corresponding
17257 // DeclContext.
17258 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17259 // In that case, we inject the declaration into the translation unit scope
17260 // instead.
17261 Scope *BlockScope = S;
17262 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17263 BlockScope = BlockScope->getParent();
17264
17265 // Loop until we find a DeclContext that is either a function/method or the
17266 // translation unit, which are the only two valid places to implicitly define
17267 // a function. This avoids accidentally defining the function within a tag
17268 // declaration, for example.
17269 Scope *ContextScope = BlockScope;
17270 while (!ContextScope->getEntity() ||
17271 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17272 !ContextScope->getEntity()->isTranslationUnit()))
17273 ContextScope = ContextScope->getParent();
17274 ContextRAII SavedContext(*this, ContextScope->getEntity());
17275
17276 // Before we produce a declaration for an implicitly defined
17277 // function, see whether there was a locally-scoped declaration of
17278 // this name as a function or variable. If so, use that
17279 // (non-visible) declaration, and complain about it.
17280 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17281 if (ExternCPrev) {
17282 // We still need to inject the function into the enclosing block scope so
17283 // that later (non-call) uses can see it.
17284 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17285
17286 // C89 footnote 38:
17287 // If in fact it is not defined as having type "function returning int",
17288 // the behavior is undefined.
17289 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17290 !Context.typesAreCompatible(
17291 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17292 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17293 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17294 << ExternCPrev << !getLangOpts().C99;
17295 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17296 return ExternCPrev;
17297 }
17298 }
17299
17300 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17301 unsigned diag_id;
17302 if (II.getName().starts_with(Prefix: "__builtin_"))
17303 diag_id = diag::warn_builtin_unknown;
17304 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17305 else if (getLangOpts().C99)
17306 diag_id = diag::ext_implicit_function_decl_c99;
17307 else
17308 diag_id = diag::warn_implicit_function_decl;
17309
17310 TypoCorrection Corrected;
17311 // Because typo correction is expensive, only do it if the implicit
17312 // function declaration is going to be treated as an error.
17313 //
17314 // Perform the correction before issuing the main diagnostic, as some
17315 // consumers use typo-correction callbacks to enhance the main diagnostic.
17316 if (S && !ExternCPrev &&
17317 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17318 DeclFilterCCC<FunctionDecl> CCC{};
17319 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17320 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17321 }
17322
17323 Diag(Loc, DiagID: diag_id) << &II;
17324 if (Corrected) {
17325 // If the correction is going to suggest an implicitly defined function,
17326 // skip the correction as not being a particularly good idea.
17327 bool Diagnose = true;
17328 if (const auto *D = Corrected.getCorrectionDecl())
17329 Diagnose = !D->isImplicit();
17330 if (Diagnose)
17331 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17332 /*ErrorRecovery*/ false);
17333 }
17334
17335 // If we found a prior declaration of this function, don't bother building
17336 // another one. We've already pushed that one into scope, so there's nothing
17337 // more to do.
17338 if (ExternCPrev)
17339 return ExternCPrev;
17340
17341 // Set a Declarator for the implicit definition: int foo();
17342 const char *Dummy;
17343 AttributeFactory attrFactory;
17344 DeclSpec DS(attrFactory);
17345 unsigned DiagID;
17346 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17347 Policy: Context.getPrintingPolicy());
17348 (void)Error; // Silence warning.
17349 assert(!Error && "Error setting up implicit decl!");
17350 SourceLocation NoLoc;
17351 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17352 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17353 /*IsAmbiguous=*/false,
17354 /*LParenLoc=*/NoLoc,
17355 /*Params=*/nullptr,
17356 /*NumParams=*/0,
17357 /*EllipsisLoc=*/NoLoc,
17358 /*RParenLoc=*/NoLoc,
17359 /*RefQualifierIsLvalueRef=*/true,
17360 /*RefQualifierLoc=*/NoLoc,
17361 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17362 /*ESpecRange=*/SourceRange(),
17363 /*Exceptions=*/nullptr,
17364 /*ExceptionRanges=*/nullptr,
17365 /*NumExceptions=*/0,
17366 /*NoexceptExpr=*/nullptr,
17367 /*ExceptionSpecTokens=*/nullptr,
17368 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17369 TheDeclarator&: D),
17370 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17371 D.SetIdentifier(Id: &II, IdLoc: Loc);
17372
17373 // Insert this function into the enclosing block scope.
17374 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17375 FD->setImplicit();
17376
17377 AddKnownFunctionAttributes(FD);
17378
17379 return FD;
17380}
17381
17382void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17383 FunctionDecl *FD) {
17384 if (FD->isInvalidDecl())
17385 return;
17386
17387 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17388 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17389 return;
17390
17391 UnsignedOrNone AlignmentParam = std::nullopt;
17392 bool IsNothrow = false;
17393 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17394 return;
17395
17396 // C++2a [basic.stc.dynamic.allocation]p4:
17397 // An allocation function that has a non-throwing exception specification
17398 // indicates failure by returning a null pointer value. Any other allocation
17399 // function never returns a null pointer value and indicates failure only by
17400 // throwing an exception [...]
17401 //
17402 // However, -fcheck-new invalidates this possible assumption, so don't add
17403 // NonNull when that is enabled.
17404 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17405 !getLangOpts().CheckNew)
17406 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17407
17408 // C++2a [basic.stc.dynamic.allocation]p2:
17409 // An allocation function attempts to allocate the requested amount of
17410 // storage. [...] If the request succeeds, the value returned by a
17411 // replaceable allocation function is a [...] pointer value p0 different
17412 // from any previously returned value p1 [...]
17413 //
17414 // However, this particular information is being added in codegen,
17415 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17416
17417 // C++2a [basic.stc.dynamic.allocation]p2:
17418 // An allocation function attempts to allocate the requested amount of
17419 // storage. If it is successful, it returns the address of the start of a
17420 // block of storage whose length in bytes is at least as large as the
17421 // requested size.
17422 if (!FD->hasAttr<AllocSizeAttr>()) {
17423 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17424 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17425 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17426 }
17427
17428 // C++2a [basic.stc.dynamic.allocation]p3:
17429 // For an allocation function [...], the pointer returned on a successful
17430 // call shall represent the address of storage that is aligned as follows:
17431 // (3.1) If the allocation function takes an argument of type
17432 // std​::​align_­val_­t, the storage will have the alignment
17433 // specified by the value of this argument.
17434 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17435 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17436 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17437 }
17438
17439 // FIXME:
17440 // C++2a [basic.stc.dynamic.allocation]p3:
17441 // For an allocation function [...], the pointer returned on a successful
17442 // call shall represent the address of storage that is aligned as follows:
17443 // (3.2) Otherwise, if the allocation function is named operator new[],
17444 // the storage is aligned for any object that does not have
17445 // new-extended alignment ([basic.align]) and is no larger than the
17446 // requested size.
17447 // (3.3) Otherwise, the storage is aligned for any object that does not
17448 // have new-extended alignment and is of the requested size.
17449}
17450
17451void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17452 if (FD->isInvalidDecl())
17453 return;
17454
17455 // If this is a built-in function, map its builtin attributes to
17456 // actual attributes.
17457 if (unsigned BuiltinID = FD->getBuiltinID()) {
17458 // Handle printf-formatting attributes.
17459 unsigned FormatIdx;
17460 bool HasVAListArg;
17461 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17462 if (!FD->hasAttr<FormatAttr>()) {
17463 const char *fmt = "printf";
17464 unsigned int NumParams = FD->getNumParams();
17465 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17466 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17467 fmt = "NSString";
17468 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17469 Type: &Context.Idents.get(Name: fmt),
17470 FormatIdx: FormatIdx+1,
17471 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17472 Range: FD->getLocation()));
17473 }
17474 }
17475 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17476 HasVAListArg)) {
17477 if (!FD->hasAttr<FormatAttr>())
17478 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17479 Type: &Context.Idents.get(Name: "scanf"),
17480 FormatIdx: FormatIdx+1,
17481 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17482 Range: FD->getLocation()));
17483 }
17484
17485 // Handle automatically recognized callbacks.
17486 SmallVector<int, 4> Encoding;
17487 if (!FD->hasAttr<CallbackAttr>() &&
17488 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17489 FD->addAttr(A: CallbackAttr::CreateImplicit(
17490 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17491
17492 // Mark const if we don't care about errno and/or floating point exceptions
17493 // that are the only thing preventing the function from being const. This
17494 // allows IRgen to use LLVM intrinsics for such functions.
17495 bool NoExceptions =
17496 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17497 bool ConstWithoutErrnoAndExceptions =
17498 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17499 bool ConstWithoutExceptions =
17500 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17501 if (!FD->hasAttr<ConstAttr>() &&
17502 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17503 (!ConstWithoutErrnoAndExceptions ||
17504 (!getLangOpts().MathErrno && NoExceptions)) &&
17505 (!ConstWithoutExceptions || NoExceptions))
17506 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17507
17508 // We make "fma" on GNU or Windows const because we know it does not set
17509 // errno in those environments even though it could set errno based on the
17510 // C standard.
17511 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17512 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17513 !FD->hasAttr<ConstAttr>()) {
17514 switch (BuiltinID) {
17515 case Builtin::BI__builtin_fma:
17516 case Builtin::BI__builtin_fmaf:
17517 case Builtin::BI__builtin_fmal:
17518 case Builtin::BIfma:
17519 case Builtin::BIfmaf:
17520 case Builtin::BIfmal:
17521 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17522 break;
17523 default:
17524 break;
17525 }
17526 }
17527
17528 SmallVector<int, 4> Indxs;
17529 Builtin::Info::NonNullMode OptMode;
17530 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17531 !FD->hasAttr<NonNullAttr>()) {
17532 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17533 for (int I : Indxs) {
17534 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17535 QualType T = PVD->getType();
17536 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17537 PVD->setType(T);
17538 }
17539 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17540 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17541 for (int I : Indxs)
17542 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17543 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17544 ArgsSize: ParamIndxs.size()));
17545 }
17546 }
17547 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17548 !FD->hasAttr<ReturnsTwiceAttr>())
17549 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17550 Range: FD->getLocation()));
17551 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17552 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17553 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17554 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17555 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17556 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17557 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17558 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17559 // Add the appropriate attribute, depending on the CUDA compilation mode
17560 // and which target the builtin belongs to. For example, during host
17561 // compilation, aux builtins are __device__, while the rest are __host__.
17562 if (getLangOpts().CUDAIsDevice !=
17563 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17564 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17565 else
17566 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17567 }
17568
17569 // Add known guaranteed alignment for allocation functions.
17570 switch (BuiltinID) {
17571 case Builtin::BImemalign:
17572 case Builtin::BIaligned_alloc:
17573 if (!FD->hasAttr<AllocAlignAttr>())
17574 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17575 Range: FD->getLocation()));
17576 break;
17577 default:
17578 break;
17579 }
17580
17581 // Add allocsize attribute for allocation functions.
17582 switch (BuiltinID) {
17583 case Builtin::BIcalloc:
17584 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17585 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17586 break;
17587 case Builtin::BImemalign:
17588 case Builtin::BIaligned_alloc:
17589 case Builtin::BIrealloc:
17590 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17591 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17592 break;
17593 case Builtin::BImalloc:
17594 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17595 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17596 break;
17597 default:
17598 break;
17599 }
17600 }
17601
17602 LazyProcessLifetimeCaptureByParams(FD);
17603 inferLifetimeBoundAttribute(FD);
17604 inferLifetimeCaptureByAttribute(FD);
17605 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17606
17607 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17608 // throw, add an implicit nothrow attribute to any extern "C" function we come
17609 // across.
17610 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17611 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17612 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17613 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17614 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17615 }
17616
17617 IdentifierInfo *Name = FD->getIdentifier();
17618 if (!Name)
17619 return;
17620 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17621 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17622 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17623 LinkageSpecLanguageIDs::C)) {
17624 // Okay: this could be a libc/libm/Objective-C function we know
17625 // about.
17626 } else
17627 return;
17628
17629 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17630 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17631 // target-specific builtins, perhaps?
17632 if (!FD->hasAttr<FormatAttr>())
17633 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17634 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17635 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17636 Range: FD->getLocation()));
17637 }
17638
17639 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17640 // We already have a __builtin___CFStringMakeConstantString,
17641 // but builds that use -fno-constant-cfstrings don't go through that.
17642 if (!FD->hasAttr<FormatArgAttr>())
17643 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17644 Range: FD->getLocation()));
17645 }
17646}
17647
17648TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17649 TypeSourceInfo *TInfo) {
17650 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17651 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17652
17653 if (!TInfo) {
17654 assert(D.isInvalidType() && "no declarator info for valid type");
17655 TInfo = Context.getTrivialTypeSourceInfo(T);
17656 }
17657
17658 // Scope manipulation handled by caller.
17659 TypedefDecl *NewTD =
17660 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17661 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17662
17663 // Bail out immediately if we have an invalid declaration.
17664 if (D.isInvalidType()) {
17665 NewTD->setInvalidDecl();
17666 return NewTD;
17667 }
17668
17669 if (D.getDeclSpec().isModulePrivateSpecified()) {
17670 if (CurContext->isFunctionOrMethod())
17671 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17672 << 2 << NewTD
17673 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17674 << FixItHint::CreateRemoval(
17675 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17676 else
17677 NewTD->setModulePrivate();
17678 }
17679
17680 // C++ [dcl.typedef]p8:
17681 // If the typedef declaration defines an unnamed class (or
17682 // enum), the first typedef-name declared by the declaration
17683 // to be that class type (or enum type) is used to denote the
17684 // class type (or enum type) for linkage purposes only.
17685 // We need to check whether the type was declared in the declaration.
17686 switch (D.getDeclSpec().getTypeSpecType()) {
17687 case TST_enum:
17688 case TST_struct:
17689 case TST_interface:
17690 case TST_union:
17691 case TST_class: {
17692 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17693 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17694 break;
17695 }
17696
17697 default:
17698 break;
17699 }
17700
17701 return NewTD;
17702}
17703
17704bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17705 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17706 QualType T = TI->getType();
17707
17708 if (T->isDependentType())
17709 return false;
17710
17711 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17712 // integral type; any cv-qualification is ignored.
17713 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17714 // non-atomic version of the type specified by the type specifiers in the
17715 // specifier qualifier list.
17716 // Because of how odd C's rule is, we'll let the user know that operations
17717 // involving the enumeration type will be non-atomic.
17718 if (T->isAtomicType())
17719 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17720
17721 Qualifiers Q = T.getQualifiers();
17722 std::optional<unsigned> QualSelect;
17723 if (Q.hasConst() && Q.hasVolatile())
17724 QualSelect = diag::CVQualList::Both;
17725 else if (Q.hasConst())
17726 QualSelect = diag::CVQualList::Const;
17727 else if (Q.hasVolatile())
17728 QualSelect = diag::CVQualList::Volatile;
17729
17730 if (QualSelect)
17731 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17732
17733 T = T.getAtomicUnqualifiedType();
17734
17735 // This doesn't use 'isIntegralType' despite the error message mentioning
17736 // integral type because isIntegralType would also allow enum types in C.
17737 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17738 if (BT->isInteger())
17739 return false;
17740
17741 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17742 << T << T->isBitIntType();
17743}
17744
17745bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17746 QualType EnumUnderlyingTy, bool IsFixed,
17747 const EnumDecl *Prev) {
17748 if (IsScoped != Prev->isScoped()) {
17749 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17750 << Prev->isScoped();
17751 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17752 return true;
17753 }
17754
17755 if (IsFixed && Prev->isFixed()) {
17756 if (!EnumUnderlyingTy->isDependentType() &&
17757 !Prev->getIntegerType()->isDependentType() &&
17758 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17759 T2: Prev->getIntegerType())) {
17760 // TODO: Highlight the underlying type of the redeclaration.
17761 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17762 << EnumUnderlyingTy << Prev->getIntegerType();
17763 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17764 << Prev->getIntegerTypeRange();
17765 return true;
17766 }
17767 } else if (IsFixed != Prev->isFixed()) {
17768 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17769 << Prev->isFixed();
17770 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17771 return true;
17772 }
17773
17774 return false;
17775}
17776
17777/// Get diagnostic %select index for tag kind for
17778/// redeclaration diagnostic message.
17779/// WARNING: Indexes apply to particular diagnostics only!
17780///
17781/// \returns diagnostic %select index.
17782static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17783 switch (Tag) {
17784 case TagTypeKind::Struct:
17785 return 0;
17786 case TagTypeKind::Interface:
17787 return 1;
17788 case TagTypeKind::Class:
17789 return 2;
17790 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17791 }
17792}
17793
17794/// Determine if tag kind is a class-key compatible with
17795/// class for redeclaration (class, struct, or __interface).
17796///
17797/// \returns true iff the tag kind is compatible.
17798static bool isClassCompatTagKind(TagTypeKind Tag)
17799{
17800 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17801 Tag == TagTypeKind::Interface;
17802}
17803
17804NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17805 if (isa<TypedefDecl>(Val: PrevDecl))
17806 return NonTagKind::Typedef;
17807 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17808 return NonTagKind::TypeAlias;
17809 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17810 return NonTagKind::Template;
17811 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17812 return NonTagKind::TypeAliasTemplate;
17813 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17814 return NonTagKind::TemplateTemplateArgument;
17815 switch (TTK) {
17816 case TagTypeKind::Struct:
17817 case TagTypeKind::Interface:
17818 case TagTypeKind::Class:
17819 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17820 : NonTagKind::NonStruct;
17821 case TagTypeKind::Union:
17822 return NonTagKind::NonUnion;
17823 case TagTypeKind::Enum:
17824 return NonTagKind::NonEnum;
17825 }
17826 llvm_unreachable("invalid TTK");
17827}
17828
17829bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17830 TagTypeKind NewTag, bool isDefinition,
17831 SourceLocation NewTagLoc,
17832 const IdentifierInfo *Name) {
17833 // C++ [dcl.type.elab]p3:
17834 // The class-key or enum keyword present in the
17835 // elaborated-type-specifier shall agree in kind with the
17836 // declaration to which the name in the elaborated-type-specifier
17837 // refers. This rule also applies to the form of
17838 // elaborated-type-specifier that declares a class-name or
17839 // friend class since it can be construed as referring to the
17840 // definition of the class. Thus, in any
17841 // elaborated-type-specifier, the enum keyword shall be used to
17842 // refer to an enumeration (7.2), the union class-key shall be
17843 // used to refer to a union (clause 9), and either the class or
17844 // struct class-key shall be used to refer to a class (clause 9)
17845 // declared using the class or struct class-key.
17846 TagTypeKind OldTag = Previous->getTagKind();
17847 if (OldTag != NewTag &&
17848 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17849 return false;
17850
17851 // Tags are compatible, but we might still want to warn on mismatched tags.
17852 // Non-class tags can't be mismatched at this point.
17853 if (!isClassCompatTagKind(Tag: NewTag))
17854 return true;
17855
17856 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17857 // by our warning analysis. We don't want to warn about mismatches with (eg)
17858 // declarations in system headers that are designed to be specialized, but if
17859 // a user asks us to warn, we should warn if their code contains mismatched
17860 // declarations.
17861 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17862 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17863 Loc);
17864 };
17865 if (IsIgnoredLoc(NewTagLoc))
17866 return true;
17867
17868 auto IsIgnored = [&](const TagDecl *Tag) {
17869 return IsIgnoredLoc(Tag->getLocation());
17870 };
17871 while (IsIgnored(Previous)) {
17872 Previous = Previous->getPreviousDecl();
17873 if (!Previous)
17874 return true;
17875 OldTag = Previous->getTagKind();
17876 }
17877
17878 bool isTemplate = false;
17879 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17880 isTemplate = Record->getDescribedClassTemplate();
17881
17882 if (inTemplateInstantiation()) {
17883 if (OldTag != NewTag) {
17884 // In a template instantiation, do not offer fix-its for tag mismatches
17885 // since they usually mess up the template instead of fixing the problem.
17886 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17887 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17888 << getRedeclDiagFromTagKind(Tag: OldTag);
17889 // FIXME: Note previous location?
17890 }
17891 return true;
17892 }
17893
17894 if (isDefinition) {
17895 // On definitions, check all previous tags and issue a fix-it for each
17896 // one that doesn't match the current tag.
17897 if (Previous->getDefinition()) {
17898 // Don't suggest fix-its for redefinitions.
17899 return true;
17900 }
17901
17902 bool previousMismatch = false;
17903 for (const TagDecl *I : Previous->redecls()) {
17904 if (I->getTagKind() != NewTag) {
17905 // Ignore previous declarations for which the warning was disabled.
17906 if (IsIgnored(I))
17907 continue;
17908
17909 if (!previousMismatch) {
17910 previousMismatch = true;
17911 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17912 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17913 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17914 }
17915 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17916 << getRedeclDiagFromTagKind(Tag: NewTag)
17917 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17918 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17919 }
17920 }
17921 return true;
17922 }
17923
17924 // Identify the prevailing tag kind: this is the kind of the definition (if
17925 // there is a non-ignored definition), or otherwise the kind of the prior
17926 // (non-ignored) declaration.
17927 const TagDecl *PrevDef = Previous->getDefinition();
17928 if (PrevDef && IsIgnored(PrevDef))
17929 PrevDef = nullptr;
17930 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17931 if (Redecl->getTagKind() != NewTag) {
17932 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17933 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17934 << getRedeclDiagFromTagKind(Tag: OldTag);
17935 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17936
17937 // If there is a previous definition, suggest a fix-it.
17938 if (PrevDef) {
17939 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17940 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17941 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17942 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17943 }
17944 }
17945
17946 return true;
17947}
17948
17949/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17950/// from an outer enclosing namespace or file scope inside a friend declaration.
17951/// This should provide the commented out code in the following snippet:
17952/// namespace N {
17953/// struct X;
17954/// namespace M {
17955/// struct Y { friend struct /*N::*/ X; };
17956/// }
17957/// }
17958static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17959 SourceLocation NameLoc) {
17960 // While the decl is in a namespace, do repeated lookup of that name and see
17961 // if we get the same namespace back. If we do not, continue until
17962 // translation unit scope, at which point we have a fully qualified NNS.
17963 SmallVector<IdentifierInfo *, 4> Namespaces;
17964 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17965 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17966 // This tag should be declared in a namespace, which can only be enclosed by
17967 // other namespaces. Bail if there's an anonymous namespace in the chain.
17968 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17969 if (!Namespace || Namespace->isAnonymousNamespace())
17970 return FixItHint();
17971 IdentifierInfo *II = Namespace->getIdentifier();
17972 Namespaces.push_back(Elt: II);
17973 NamedDecl *Lookup = SemaRef.LookupSingleName(
17974 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17975 if (Lookup == Namespace)
17976 break;
17977 }
17978
17979 // Once we have all the namespaces, reverse them to go outermost first, and
17980 // build an NNS.
17981 SmallString<64> Insertion;
17982 llvm::raw_svector_ostream OS(Insertion);
17983 if (DC->isTranslationUnit())
17984 OS << "::";
17985 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17986 for (auto *II : Namespaces)
17987 OS << II->getName() << "::";
17988 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17989}
17990
17991/// Determine whether a tag originally declared in context \p OldDC can
17992/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17993/// found a declaration in \p OldDC as a previous decl, perhaps through a
17994/// using-declaration).
17995static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17996 DeclContext *NewDC) {
17997 OldDC = OldDC->getRedeclContext();
17998 NewDC = NewDC->getRedeclContext();
17999
18000 if (OldDC->Equals(DC: NewDC))
18001 return true;
18002
18003 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18004 // encloses the other).
18005 if (S.getLangOpts().MSVCCompat &&
18006 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
18007 return true;
18008
18009 return false;
18010}
18011
18012DeclResult
18013Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18014 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18015 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18016 SourceLocation ModulePrivateLoc,
18017 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18018 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18019 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18020 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18021 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18022 // If this is not a definition, it must have a name.
18023 IdentifierInfo *OrigName = Name;
18024 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18025 "Nameless record must be a definition!");
18026 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18027
18028 OwnedDecl = false;
18029 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18030 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18031
18032 // FIXME: Check member specializations more carefully.
18033 bool isMemberSpecialization = false;
18034 bool IsInjectedClassName = false;
18035 bool Invalid = false;
18036
18037 // We only need to do this matching if we have template parameters
18038 // or a scope specifier, which also conveniently avoids this work
18039 // for non-C++ cases.
18040 if (TemplateParameterLists.size() > 0 ||
18041 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18042 TemplateParameterList *TemplateParams =
18043 MatchTemplateParametersToScopeSpecifier(
18044 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
18045 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
18046
18047 // C++23 [dcl.type.elab] p2:
18048 // If an elaborated-type-specifier is the sole constituent of a
18049 // declaration, the declaration is ill-formed unless it is an explicit
18050 // specialization, an explicit instantiation or it has one of the
18051 // following forms: [...]
18052 // C++23 [dcl.enum] p1:
18053 // If the enum-head-name of an opaque-enum-declaration contains a
18054 // nested-name-specifier, the declaration shall be an explicit
18055 // specialization.
18056 //
18057 // FIXME: Class template partial specializations can be forward declared
18058 // per CWG2213, but the resolution failed to allow qualified forward
18059 // declarations. This is almost certainly unintentional, so we allow them.
18060 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18061 !isMemberSpecialization)
18062 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18063 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18064
18065 if (TemplateParams) {
18066 if (Kind == TagTypeKind::Enum) {
18067 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18068 return true;
18069 }
18070
18071 if (TemplateParams->size() > 0) {
18072 // This is a declaration or definition of a class template (which may
18073 // be a member of another template).
18074
18075 if (Invalid)
18076 return true;
18077
18078 OwnedDecl = false;
18079 DeclResult Result = CheckClassTemplate(
18080 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18081 AS, ModulePrivateLoc,
18082 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18083 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18084 return Result.get();
18085 } else {
18086 // The "template<>" header is extraneous.
18087 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18088 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18089 isMemberSpecialization = true;
18090 }
18091 }
18092
18093 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18094 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18095 return true;
18096 }
18097
18098 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18099 // C++23 [dcl.type.elab]p4:
18100 // If an elaborated-type-specifier appears with the friend specifier as
18101 // an entire member-declaration, the member-declaration shall have one
18102 // of the following forms:
18103 // friend class-key nested-name-specifier(opt) identifier ;
18104 // friend class-key simple-template-id ;
18105 // friend class-key nested-name-specifier template(opt)
18106 // simple-template-id ;
18107 //
18108 // Since enum is not a class-key, so declarations like "friend enum E;"
18109 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18110 // invalid, most implementations accept so we issue a pedantic warning.
18111 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18112 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18113 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18114 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18115 << (ScopedEnum + ScopedEnumUsesClassTag);
18116 }
18117
18118 // Figure out the underlying type if this a enum declaration. We need to do
18119 // this early, because it's needed to detect if this is an incompatible
18120 // redeclaration.
18121 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18122 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18123
18124 if (Kind == TagTypeKind::Enum) {
18125 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18126 Invalid) {
18127 // No underlying type explicitly specified, or we failed to parse the
18128 // type, default to int.
18129 EnumUnderlying = Context.IntTy.getTypePtr();
18130 } else if (UnderlyingType.get()) {
18131 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18132 // integral type; any cv-qualification is ignored.
18133 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18134 // unqualified, non-atomic version of the type specified by the type
18135 // specifiers in the specifier qualifier list.
18136 TypeSourceInfo *TI = nullptr;
18137 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18138 EnumUnderlying = TI;
18139
18140 if (CheckEnumUnderlyingType(TI))
18141 // Recover by falling back to int.
18142 EnumUnderlying = Context.IntTy.getTypePtr();
18143
18144 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18145 UPPC: UPPC_FixedUnderlyingType))
18146 EnumUnderlying = Context.IntTy.getTypePtr();
18147
18148 // If the underlying type is atomic, we need to adjust the type before
18149 // continuing. This only happens in the case we stored a TypeSourceInfo
18150 // into EnumUnderlying because the other cases are error recovery up to
18151 // this point. But because it's not possible to gin up a TypeSourceInfo
18152 // for a non-atomic type from an atomic one, we'll store into the Type
18153 // field instead. FIXME: it would be nice to have an easy way to get a
18154 // derived TypeSourceInfo which strips qualifiers including the weird
18155 // ones like _Atomic where it forms a different type.
18156 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18157 TI && TI->getType()->isAtomicType())
18158 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18159
18160 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18161 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18162 // of 'int'. However, if this is an unfixed forward declaration, don't set
18163 // the underlying type unless the user enables -fms-compatibility. This
18164 // makes unfixed forward declared enums incomplete and is more conforming.
18165 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18166 EnumUnderlying = Context.IntTy.getTypePtr();
18167 }
18168 }
18169
18170 DeclContext *SearchDC = CurContext;
18171 DeclContext *DC = CurContext;
18172 bool isStdBadAlloc = false;
18173 bool isStdAlignValT = false;
18174
18175 RedeclarationKind Redecl = forRedeclarationInCurContext();
18176 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18177 Redecl = RedeclarationKind::NotForRedeclaration;
18178
18179 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18180 /// implemented asks for structural equivalence checking, the returned decl
18181 /// here is passed back to the parser, allowing the tag body to be parsed.
18182 auto createTagFromNewDecl = [&]() -> TagDecl * {
18183 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18184 // If there is an identifier, use the location of the identifier as the
18185 // location of the decl, otherwise use the location of the struct/union
18186 // keyword.
18187 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18188 TagDecl *New = nullptr;
18189
18190 if (Kind == TagTypeKind::Enum) {
18191 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18192 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18193 // If this is an undefined enum, bail.
18194 if (TUK != TagUseKind::Definition && !Invalid)
18195 return nullptr;
18196 if (EnumUnderlying) {
18197 EnumDecl *ED = cast<EnumDecl>(Val: New);
18198 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18199 ED->setIntegerTypeSourceInfo(TI);
18200 else
18201 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18202 QualType EnumTy = ED->getIntegerType();
18203 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18204 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18205 : EnumTy);
18206 }
18207 } else { // struct/union
18208 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18209 PrevDecl: nullptr);
18210 }
18211
18212 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18213 // Add alignment attributes if necessary; these attributes are checked
18214 // when the ASTContext lays out the structure.
18215 //
18216 // It is important for implementing the correct semantics that this
18217 // happen here (in ActOnTag). The #pragma pack stack is
18218 // maintained as a result of parser callbacks which can occur at
18219 // many points during the parsing of a struct declaration (because
18220 // the #pragma tokens are effectively skipped over during the
18221 // parsing of the struct).
18222 if (TUK == TagUseKind::Definition &&
18223 (!SkipBody || !SkipBody->ShouldSkip)) {
18224 if (LangOpts.HLSL)
18225 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18226 AddAlignmentAttributesForRecord(RD);
18227 AddMsStructLayoutForRecord(RD);
18228 }
18229 }
18230 New->setLexicalDeclContext(CurContext);
18231 return New;
18232 };
18233
18234 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18235 if (Name && SS.isNotEmpty()) {
18236 // We have a nested-name tag ('struct foo::bar').
18237
18238 // Check for invalid 'foo::'.
18239 if (SS.isInvalid()) {
18240 Name = nullptr;
18241 goto CreateNewDecl;
18242 }
18243
18244 // If this is a friend or a reference to a class in a dependent
18245 // context, don't try to make a decl for it.
18246 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18247 DC = computeDeclContext(SS, EnteringContext: false);
18248 if (!DC) {
18249 IsDependent = true;
18250 return true;
18251 }
18252 } else {
18253 DC = computeDeclContext(SS, EnteringContext: true);
18254 if (!DC) {
18255 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18256 << SS.getRange();
18257 return true;
18258 }
18259 }
18260
18261 if (RequireCompleteDeclContext(SS, DC))
18262 return true;
18263
18264 SearchDC = DC;
18265 // Look-up name inside 'foo::'.
18266 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18267
18268 if (Previous.isAmbiguous())
18269 return true;
18270
18271 if (Previous.empty()) {
18272 // Name lookup did not find anything. However, if the
18273 // nested-name-specifier refers to the current instantiation,
18274 // and that current instantiation has any dependent base
18275 // classes, we might find something at instantiation time: treat
18276 // this as a dependent elaborated-type-specifier.
18277 // But this only makes any sense for reference-like lookups.
18278 if (Previous.wasNotFoundInCurrentInstantiation() &&
18279 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18280 IsDependent = true;
18281 return true;
18282 }
18283
18284 // A tag 'foo::bar' must already exist.
18285 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18286 << Kind << Name << DC << SS.getRange();
18287 Name = nullptr;
18288 Invalid = true;
18289 goto CreateNewDecl;
18290 }
18291 } else if (Name) {
18292 // C++14 [class.mem]p14:
18293 // If T is the name of a class, then each of the following shall have a
18294 // name different from T:
18295 // -- every member of class T that is itself a type
18296 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18297 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18298 return true;
18299
18300 // If this is a named struct, check to see if there was a previous forward
18301 // declaration or definition.
18302 // FIXME: We're looking into outer scopes here, even when we
18303 // shouldn't be. Doing so can result in ambiguities that we
18304 // shouldn't be diagnosing.
18305 LookupName(R&: Previous, S);
18306
18307 // When declaring or defining a tag, ignore ambiguities introduced
18308 // by types using'ed into this scope.
18309 if (Previous.isAmbiguous() &&
18310 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18311 LookupResult::Filter F = Previous.makeFilter();
18312 while (F.hasNext()) {
18313 NamedDecl *ND = F.next();
18314 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18315 DC: SearchDC->getRedeclContext()))
18316 F.erase();
18317 }
18318 F.done();
18319 }
18320
18321 // C++11 [namespace.memdef]p3:
18322 // If the name in a friend declaration is neither qualified nor
18323 // a template-id and the declaration is a function or an
18324 // elaborated-type-specifier, the lookup to determine whether
18325 // the entity has been previously declared shall not consider
18326 // any scopes outside the innermost enclosing namespace.
18327 //
18328 // MSVC doesn't implement the above rule for types, so a friend tag
18329 // declaration may be a redeclaration of a type declared in an enclosing
18330 // scope. They do implement this rule for friend functions.
18331 //
18332 // Does it matter that this should be by scope instead of by
18333 // semantic context?
18334 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18335 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18336 LookupResult::Filter F = Previous.makeFilter();
18337 bool FriendSawTagOutsideEnclosingNamespace = false;
18338 while (F.hasNext()) {
18339 NamedDecl *ND = F.next();
18340 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18341 if (DC->isFileContext() &&
18342 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18343 if (getLangOpts().MSVCCompat)
18344 FriendSawTagOutsideEnclosingNamespace = true;
18345 else
18346 F.erase();
18347 }
18348 }
18349 F.done();
18350
18351 // Diagnose this MSVC extension in the easy case where lookup would have
18352 // unambiguously found something outside the enclosing namespace.
18353 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18354 NamedDecl *ND = Previous.getFoundDecl();
18355 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18356 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18357 }
18358 }
18359
18360 // Note: there used to be some attempt at recovery here.
18361 if (Previous.isAmbiguous())
18362 return true;
18363
18364 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18365 // FIXME: This makes sure that we ignore the contexts associated
18366 // with C structs, unions, and enums when looking for a matching
18367 // tag declaration or definition. See the similar lookup tweak
18368 // in Sema::LookupName; is there a better way to deal with this?
18369 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18370 SearchDC = SearchDC->getParent();
18371 } else if (getLangOpts().CPlusPlus) {
18372 // Inside ObjCContainer want to keep it as a lexical decl context but go
18373 // past it (most often to TranslationUnit) to find the semantic decl
18374 // context.
18375 while (isa<ObjCContainerDecl>(Val: SearchDC))
18376 SearchDC = SearchDC->getParent();
18377 }
18378 } else if (getLangOpts().CPlusPlus) {
18379 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18380 // TagDecl the same way as we skip it for named TagDecl.
18381 while (isa<ObjCContainerDecl>(Val: SearchDC))
18382 SearchDC = SearchDC->getParent();
18383 }
18384
18385 if (Previous.isSingleResult() &&
18386 Previous.getFoundDecl()->isTemplateParameter()) {
18387 // Maybe we will complain about the shadowed template parameter.
18388 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18389 // Just pretend that we didn't see the previous declaration.
18390 Previous.clear();
18391 }
18392
18393 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18394 DC->Equals(DC: getStdNamespace())) {
18395 if (Name->isStr(Str: "bad_alloc")) {
18396 // This is a declaration of or a reference to "std::bad_alloc".
18397 isStdBadAlloc = true;
18398
18399 // If std::bad_alloc has been implicitly declared (but made invisible to
18400 // name lookup), fill in this implicit declaration as the previous
18401 // declaration, so that the declarations get chained appropriately.
18402 if (Previous.empty() && StdBadAlloc)
18403 Previous.addDecl(D: getStdBadAlloc());
18404 } else if (Name->isStr(Str: "align_val_t")) {
18405 isStdAlignValT = true;
18406 if (Previous.empty() && StdAlignValT)
18407 Previous.addDecl(D: getStdAlignValT());
18408 }
18409 }
18410
18411 // If we didn't find a previous declaration, and this is a reference
18412 // (or friend reference), move to the correct scope. In C++, we
18413 // also need to do a redeclaration lookup there, just in case
18414 // there's a shadow friend decl.
18415 if (Name && Previous.empty() &&
18416 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18417 IsTemplateParamOrArg)) {
18418 if (Invalid) goto CreateNewDecl;
18419 assert(SS.isEmpty());
18420
18421 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18422 // C++ [basic.scope.pdecl]p5:
18423 // -- for an elaborated-type-specifier of the form
18424 //
18425 // class-key identifier
18426 //
18427 // if the elaborated-type-specifier is used in the
18428 // decl-specifier-seq or parameter-declaration-clause of a
18429 // function defined in namespace scope, the identifier is
18430 // declared as a class-name in the namespace that contains
18431 // the declaration; otherwise, except as a friend
18432 // declaration, the identifier is declared in the smallest
18433 // non-class, non-function-prototype scope that contains the
18434 // declaration.
18435 //
18436 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18437 // C structs and unions.
18438 //
18439 // It is an error in C++ to declare (rather than define) an enum
18440 // type, including via an elaborated type specifier. We'll
18441 // diagnose that later; for now, declare the enum in the same
18442 // scope as we would have picked for any other tag type.
18443 //
18444 // GNU C also supports this behavior as part of its incomplete
18445 // enum types extension, while GNU C++ does not.
18446 //
18447 // Find the context where we'll be declaring the tag.
18448 // FIXME: We would like to maintain the current DeclContext as the
18449 // lexical context,
18450 SearchDC = getTagInjectionContext(DC: SearchDC);
18451
18452 // Find the scope where we'll be declaring the tag.
18453 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18454 } else {
18455 assert(TUK == TagUseKind::Friend);
18456 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18457
18458 // C++ [namespace.memdef]p3:
18459 // If a friend declaration in a non-local class first declares a
18460 // class or function, the friend class or function is a member of
18461 // the innermost enclosing namespace.
18462 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18463 : SearchDC->getEnclosingNamespaceContext();
18464 }
18465
18466 // In C++, we need to do a redeclaration lookup to properly
18467 // diagnose some problems.
18468 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18469 // hidden declaration so that we don't get ambiguity errors when using a
18470 // type declared by an elaborated-type-specifier. In C that is not correct
18471 // and we should instead merge compatible types found by lookup.
18472 if (getLangOpts().CPlusPlus) {
18473 // FIXME: This can perform qualified lookups into function contexts,
18474 // which are meaningless.
18475 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18476 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18477 } else {
18478 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18479 LookupName(R&: Previous, S);
18480 }
18481 }
18482
18483 // If we have a known previous declaration to use, then use it.
18484 if (Previous.empty() && SkipBody && SkipBody->Previous)
18485 Previous.addDecl(D: SkipBody->Previous);
18486
18487 if (!Previous.empty()) {
18488 NamedDecl *PrevDecl = Previous.getFoundDecl();
18489 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18490
18491 // It's okay to have a tag decl in the same scope as a typedef
18492 // which hides a tag decl in the same scope. Finding this
18493 // with a redeclaration lookup can only actually happen in C++.
18494 //
18495 // This is also okay for elaborated-type-specifiers, which is
18496 // technically forbidden by the current standard but which is
18497 // okay according to the likely resolution of an open issue;
18498 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18499 if (getLangOpts().CPlusPlus) {
18500 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18501 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18502 if (Tag->getDeclName() == Name &&
18503 Tag->getDeclContext()->getRedeclContext()
18504 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18505 PrevDecl = Tag;
18506 Previous.clear();
18507 Previous.addDecl(D: Tag);
18508 Previous.resolveKind();
18509 }
18510 }
18511 }
18512 }
18513
18514 // If this is a redeclaration of a using shadow declaration, it must
18515 // declare a tag in the same context. In MSVC mode, we allow a
18516 // redefinition if either context is within the other.
18517 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18518 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18519 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18520 TUK != TagUseKind::Friend &&
18521 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18522 !(OldTag && isAcceptableTagRedeclContext(
18523 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18524 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18525 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18526 DiagID: diag::note_using_decl_target);
18527 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18528 << 0;
18529 // Recover by ignoring the old declaration.
18530 Previous.clear();
18531 goto CreateNewDecl;
18532 }
18533 }
18534
18535 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18536 // If this is a use of a previous tag, or if the tag is already declared
18537 // in the same scope (so that the definition/declaration completes or
18538 // rementions the tag), reuse the decl.
18539 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18540 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18541 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18542
18543 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18544 RD && RD->isInjectedClassName()) {
18545 // If lookup found the injected class name, the previous declaration
18546 // is the class being injected into.
18547 Previous.clear();
18548 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(Val: RD->getDeclContext());
18549 Previous.addDecl(D: PrevDecl);
18550 Previous.resolveKind();
18551 IsInjectedClassName = true;
18552 }
18553
18554 // Make sure that this wasn't declared as an enum and now used as a
18555 // struct or something similar.
18556 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18557 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18558 Name)) {
18559 bool SafeToContinue =
18560 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18561 Kind != TagTypeKind::Enum);
18562 if (SafeToContinue)
18563 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18564 << Name
18565 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18566 Code: PrevTagDecl->getKindName());
18567 else
18568 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18569 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18570
18571 if (SafeToContinue)
18572 Kind = PrevTagDecl->getTagKind();
18573 else {
18574 // Recover by making this an anonymous redefinition.
18575 Name = nullptr;
18576 Previous.clear();
18577 Invalid = true;
18578 }
18579 }
18580
18581 if (Kind == TagTypeKind::Enum &&
18582 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18583 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18584 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18585 return PrevTagDecl;
18586
18587 QualType EnumUnderlyingTy;
18588 if (TypeSourceInfo *TI =
18589 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18590 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18591 else if (const Type *T =
18592 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18593 EnumUnderlyingTy = QualType(T, 0);
18594
18595 // All conflicts with previous declarations are recovered by
18596 // returning the previous declaration, unless this is a definition,
18597 // in which case we want the caller to bail out.
18598 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18599 IsScoped: ScopedEnum, EnumUnderlyingTy,
18600 IsFixed, Prev: PrevEnum))
18601 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18602 }
18603
18604 // C++11 [class.mem]p1:
18605 // A member shall not be declared twice in the member-specification,
18606 // except that a nested class or member class template can be declared
18607 // and then later defined.
18608 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18609 S->isDeclScope(D: PrevDecl)) {
18610 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18611 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18612 }
18613
18614 // C++ [class.local]p3:
18615 // A class nested within a local class is a local class. A member of
18616 // a local class X shall be declared only in the definition of X or,
18617 // if the member is a nested class, in the nearest enclosing block
18618 // scope of X.
18619 if (TUK == TagUseKind::Definition && SS.isValid()) {
18620 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18621 while (const auto *ParentClass =
18622 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18623 OutermostClass = ParentClass;
18624
18625 if (OutermostClass->isLocalClass() &&
18626 !S->isDeclScope(D: OutermostClass)) {
18627 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18628 << Name << OutermostClass;
18629 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18630 << OutermostClass;
18631 }
18632 }
18633 }
18634
18635 if (!Invalid) {
18636 // If this is a use, just return the declaration we found, unless
18637 // we have attributes.
18638 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18639 if (!Attrs.empty()) {
18640 // FIXME: Diagnose these attributes. For now, we create a new
18641 // declaration to hold them.
18642 } else if (TUK == TagUseKind::Reference &&
18643 (PrevTagDecl->getFriendObjectKind() ==
18644 Decl::FOK_Undeclared ||
18645 PrevDecl->getOwningModule() != getCurrentModule()) &&
18646 SS.isEmpty()) {
18647 // This declaration is a reference to an existing entity, but
18648 // has different visibility from that entity: it either makes
18649 // a friend visible or it makes a type visible in a new module.
18650 // In either case, create a new declaration. We only do this if
18651 // the declaration would have meant the same thing if no prior
18652 // declaration were found, that is, if it was found in the same
18653 // scope where we would have injected a declaration.
18654 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18655 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18656 return PrevTagDecl;
18657 // This is in the injected scope, create a new declaration in
18658 // that scope.
18659 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18660 } else {
18661 return PrevTagDecl;
18662 }
18663 }
18664
18665 // Diagnose attempts to redefine a tag.
18666 if (TUK == TagUseKind::Definition) {
18667 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18668 // If the type is currently being defined, complain
18669 // about a nested redefinition.
18670 if (Def->isBeingDefined()) {
18671 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18672 Diag(Loc: PrevTagDecl->getLocation(),
18673 DiagID: diag::note_previous_definition);
18674 Name = nullptr;
18675 Previous.clear();
18676 Invalid = true;
18677 } else {
18678 // If we're defining a specialization and the previous
18679 // definition is from an implicit instantiation, don't emit an
18680 // error here; we'll catch this in the general case below.
18681 bool IsExplicitSpecializationAfterInstantiation = false;
18682 if (isMemberSpecialization) {
18683 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18684 IsExplicitSpecializationAfterInstantiation =
18685 RD->getTemplateSpecializationKind() !=
18686 TSK_ExplicitSpecialization;
18687 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18688 IsExplicitSpecializationAfterInstantiation =
18689 ED->getTemplateSpecializationKind() !=
18690 TSK_ExplicitSpecialization;
18691 }
18692
18693 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18694 // do not keep more that one definition around (merge them).
18695 // However, ensure the decl passes the structural compatibility
18696 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18697 NamedDecl *Hidden = nullptr;
18698 bool HiddenDefVisible = false;
18699 if (SkipBody &&
18700 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18701 getLangOpts().C23)) {
18702 // There is a definition of this tag, but it is not visible.
18703 // We explicitly make use of C++'s one definition rule here,
18704 // and assume that this definition is identical to the hidden
18705 // one we already have. Make the existing definition visible
18706 // and use it in place of this one.
18707 if (!getLangOpts().CPlusPlus) {
18708 // Postpone making the old definition visible until after we
18709 // complete parsing the new one and do the structural
18710 // comparison.
18711 SkipBody->CheckSameAsPrevious = true;
18712 SkipBody->New = createTagFromNewDecl();
18713 SkipBody->Previous = Def;
18714
18715 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18716 return Def;
18717 }
18718
18719 SkipBody->ShouldSkip = true;
18720 SkipBody->Previous = Def;
18721 if (!HiddenDefVisible && Hidden)
18722 makeMergedDefinitionVisible(ND: Hidden);
18723 // Carry on and handle it like a normal definition. We'll
18724 // skip starting the definition later.
18725
18726 } else if (!IsExplicitSpecializationAfterInstantiation) {
18727 // A redeclaration in function prototype scope in C isn't
18728 // visible elsewhere, so merely issue a warning.
18729 if (!getLangOpts().CPlusPlus &&
18730 S->containedInPrototypeScope())
18731 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18732 << Name;
18733 else
18734 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18735 notePreviousDefinition(Old: Def,
18736 New: NameLoc.isValid() ? NameLoc : KWLoc);
18737 // If this is a redefinition, recover by making this
18738 // struct be anonymous, which will make any later
18739 // references get the previous definition.
18740 Name = nullptr;
18741 Previous.clear();
18742 Invalid = true;
18743 }
18744 }
18745 }
18746
18747 // Okay, this is definition of a previously declared or referenced
18748 // tag. We're going to create a new Decl for it.
18749 }
18750
18751 // Okay, we're going to make a redeclaration. If this is some kind
18752 // of reference, make sure we build the redeclaration in the same DC
18753 // as the original, and ignore the current access specifier.
18754 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18755 IsInjectedClassName) {
18756 SearchDC = PrevTagDecl->getDeclContext();
18757 AS = AS_none;
18758 }
18759 }
18760 // If we get here we have (another) forward declaration or we
18761 // have a definition. Just create a new decl.
18762
18763 } else {
18764 // If we get here, this is a definition of a new tag type in a nested
18765 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18766 // new decl/type. We set PrevDecl to NULL so that the entities
18767 // have distinct types.
18768 Previous.clear();
18769 }
18770 // If we get here, we're going to create a new Decl. If PrevDecl
18771 // is non-NULL, it's a definition of the tag declared by
18772 // PrevDecl. If it's NULL, we have a new definition.
18773
18774 // Otherwise, PrevDecl is not a tag, but was found with tag
18775 // lookup. This is only actually possible in C++, where a few
18776 // things like templates still live in the tag namespace.
18777 } else {
18778 // Use a better diagnostic if an elaborated-type-specifier
18779 // found the wrong kind of type on the first
18780 // (non-redeclaration) lookup.
18781 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18782 !Previous.isForRedeclaration()) {
18783 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18784 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18785 << PrevDecl << NTK << Kind;
18786 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18787 Invalid = true;
18788
18789 // Otherwise, only diagnose if the declaration is in scope.
18790 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18791 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18792 // do nothing
18793
18794 // Diagnose implicit declarations introduced by elaborated types.
18795 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18796 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18797 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18798 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18799 Invalid = true;
18800
18801 // Otherwise it's a declaration. Call out a particularly common
18802 // case here.
18803 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18804 unsigned Kind = 0;
18805 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18806 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18807 << Name << Kind << TND->getUnderlyingType();
18808 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18809 Invalid = true;
18810
18811 // Otherwise, diagnose.
18812 } else {
18813 // The tag name clashes with something else in the target scope,
18814 // issue an error and recover by making this tag be anonymous.
18815 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18816 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18817 Name = nullptr;
18818 Invalid = true;
18819 }
18820
18821 // The existing declaration isn't relevant to us; we're in a
18822 // new scope, so clear out the previous declaration.
18823 Previous.clear();
18824 }
18825 }
18826
18827CreateNewDecl:
18828
18829 TagDecl *PrevDecl = nullptr;
18830 if (Previous.isSingleResult())
18831 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18832
18833 // If there is an identifier, use the location of the identifier as the
18834 // location of the decl, otherwise use the location of the struct/union
18835 // keyword.
18836 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18837
18838 // Otherwise, create a new declaration. If there is a previous
18839 // declaration of the same entity, the two will be linked via
18840 // PrevDecl.
18841 TagDecl *New;
18842
18843 if (Kind == TagTypeKind::Enum) {
18844 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18845 // enum X { A, B, C } D; D should chain to X.
18846 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18847 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18848 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18849
18850 EnumDecl *ED = cast<EnumDecl>(Val: New);
18851 ED->setEnumKeyRange(SourceRange(
18852 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18853
18854 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18855 StdAlignValT = cast<EnumDecl>(Val: New);
18856
18857 // If this is an undefined enum, warn.
18858 if (TUK != TagUseKind::Definition && !Invalid) {
18859 TagDecl *Def;
18860 if (IsFixed && ED->isFixed()) {
18861 // C++0x: 7.2p2: opaque-enum-declaration.
18862 // Conflicts are diagnosed above. Do nothing.
18863 } else if (PrevDecl &&
18864 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18865 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18866 << New;
18867 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18868 } else {
18869 unsigned DiagID = diag::ext_forward_ref_enum;
18870 if (getLangOpts().MSVCCompat)
18871 DiagID = diag::ext_ms_forward_ref_enum;
18872 else if (getLangOpts().CPlusPlus)
18873 DiagID = diag::err_forward_ref_enum;
18874 Diag(Loc, DiagID);
18875 }
18876 }
18877
18878 if (EnumUnderlying) {
18879 EnumDecl *ED = cast<EnumDecl>(Val: New);
18880 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18881 ED->setIntegerTypeSourceInfo(TI);
18882 else
18883 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18884 QualType EnumTy = ED->getIntegerType();
18885 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18886 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18887 : EnumTy);
18888 assert(ED->isComplete() && "enum with type should be complete");
18889 }
18890 } else {
18891 // struct/union/class
18892
18893 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18894 // struct X { int A; } D; D should chain to X.
18895 if (getLangOpts().CPlusPlus) {
18896 // FIXME: Look for a way to use RecordDecl for simple structs.
18897 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18898 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18899
18900 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18901 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18902 } else
18903 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18904 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18905 }
18906
18907 // Only C23 and later allow defining new types in 'offsetof()'.
18908 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18909 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18910 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18911 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18912
18913 // C++11 [dcl.type]p3:
18914 // A type-specifier-seq shall not define a class or enumeration [...].
18915 if (!Invalid && getLangOpts().CPlusPlus &&
18916 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18917 TUK == TagUseKind::Definition) {
18918 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18919 << Context.getCanonicalTagType(TD: New);
18920 Invalid = true;
18921 }
18922
18923 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18924 DC->getDeclKind() == Decl::Enum) {
18925 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18926 << Context.getCanonicalTagType(TD: New);
18927 Invalid = true;
18928 }
18929
18930 // Maybe add qualifier info.
18931 if (SS.isNotEmpty()) {
18932 if (SS.isSet()) {
18933 // If this is either a declaration or a definition, check the
18934 // nested-name-specifier against the current context.
18935 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18936 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18937 /*TemplateId=*/nullptr,
18938 IsMemberSpecialization: isMemberSpecialization))
18939 Invalid = true;
18940
18941 New->setQualifierInfo(SS.getWithLocInContext(Context));
18942 if (TemplateParameterLists.size() > 0) {
18943 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18944 }
18945 }
18946 else
18947 Invalid = true;
18948 }
18949
18950 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18951 // Add alignment attributes if necessary; these attributes are checked when
18952 // the ASTContext lays out the structure.
18953 //
18954 // It is important for implementing the correct semantics that this
18955 // happen here (in ActOnTag). The #pragma pack stack is
18956 // maintained as a result of parser callbacks which can occur at
18957 // many points during the parsing of a struct declaration (because
18958 // the #pragma tokens are effectively skipped over during the
18959 // parsing of the struct).
18960 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18961 if (LangOpts.HLSL)
18962 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18963 AddAlignmentAttributesForRecord(RD);
18964 AddMsStructLayoutForRecord(RD);
18965 }
18966 }
18967
18968 if (ModulePrivateLoc.isValid()) {
18969 if (isMemberSpecialization)
18970 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18971 << 2
18972 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18973 // __module_private__ does not apply to local classes. However, we only
18974 // diagnose this as an error when the declaration specifiers are
18975 // freestanding. Here, we just ignore the __module_private__.
18976 else if (!SearchDC->isFunctionOrMethod())
18977 New->setModulePrivate();
18978 }
18979
18980 // If this is a specialization of a member class (of a class template),
18981 // check the specialization.
18982 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18983 Invalid = true;
18984
18985 // If we're declaring or defining a tag in function prototype scope in C,
18986 // note that this type can only be used within the function and add it to
18987 // the list of decls to inject into the function definition scope. However,
18988 // in C23 and later, while the type is only visible within the function, the
18989 // function can be called with a compatible type defined in the same TU, so
18990 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18991 if ((Name || Kind == TagTypeKind::Enum) &&
18992 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18993 if (getLangOpts().CPlusPlus) {
18994 // C++ [dcl.fct]p6:
18995 // Types shall not be defined in return or parameter types.
18996 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18997 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18998 << Name;
18999 Invalid = true;
19000 }
19001 if (TUK == TagUseKind::Declaration)
19002 Invalid = true;
19003 } else if (!PrevDecl) {
19004 // In C23 mode, if the declaration is complete, we do not want to
19005 // diagnose.
19006 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19007 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
19008 << Context.getCanonicalTagType(TD: New);
19009 }
19010 }
19011
19012 if (Invalid)
19013 New->setInvalidDecl();
19014
19015 // Set the lexical context. If the tag has a C++ scope specifier, the
19016 // lexical context will be different from the semantic context.
19017 New->setLexicalDeclContext(CurContext);
19018
19019 // Mark this as a friend decl if applicable.
19020 // In Microsoft mode, a friend declaration also acts as a forward
19021 // declaration so we always pass true to setObjectOfFriendDecl to make
19022 // the tag name visible.
19023 if (TUK == TagUseKind::Friend)
19024 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19025
19026 // Set the access specifier.
19027 if (!Invalid && SearchDC->isRecord())
19028 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
19029
19030 if (PrevDecl)
19031 CheckRedeclarationInModule(New, Old: PrevDecl);
19032
19033 if (TUK == TagUseKind::Definition) {
19034 if (!SkipBody || !SkipBody->ShouldSkip) {
19035 New->startDefinition();
19036 } else {
19037 New->setCompleteDefinition();
19038 New->demoteThisDefinitionToDeclaration();
19039 }
19040 }
19041
19042 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
19043 AddPragmaAttributes(S, D: New);
19044
19045 // If this has an identifier, add it to the scope stack.
19046 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19047 // We might be replacing an existing declaration in the lookup tables;
19048 // if so, borrow its access specifier.
19049 if (PrevDecl)
19050 New->setAccess(PrevDecl->getAccess());
19051
19052 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19053 DC->makeDeclVisibleInContext(D: New);
19054 if (Name) // can be null along some error paths
19055 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19056 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
19057 } else if (Name) {
19058 S = getNonFieldDeclScope(S);
19059 PushOnScopeChains(D: New, S, AddToContext: true);
19060 } else {
19061 CurContext->addDecl(D: New);
19062 }
19063
19064 // If this is the C FILE type, notify the AST context.
19065 if (IdentifierInfo *II = New->getIdentifier())
19066 if (!New->isInvalidDecl() &&
19067 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19068 II->isStr(Str: "FILE"))
19069 Context.setFILEDecl(New);
19070
19071 if (PrevDecl)
19072 mergeDeclAttributes(New, Old: PrevDecl);
19073
19074 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19075 inferGslOwnerPointerAttribute(Record: CXXRD);
19076 inferNullableClassAttribute(CRD: CXXRD);
19077 }
19078
19079 // If there's a #pragma GCC visibility in scope, set the visibility of this
19080 // record.
19081 AddPushedVisibilityAttribute(RD: New);
19082
19083 // If this is not a definition, process API notes for it now.
19084 if (TUK != TagUseKind::Definition)
19085 ProcessAPINotes(D: New);
19086
19087 if (isMemberSpecialization && !New->isInvalidDecl())
19088 CompleteMemberSpecialization(Member: New, Previous);
19089
19090 OwnedDecl = true;
19091 // In C++, don't return an invalid declaration. We can't recover well from
19092 // the cases where we make the type anonymous.
19093 if (Invalid && getLangOpts().CPlusPlus) {
19094 if (New->isBeingDefined())
19095 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19096 RD->completeDefinition();
19097 return true;
19098 } else if (SkipBody && SkipBody->ShouldSkip) {
19099 return SkipBody->Previous;
19100 } else {
19101 return New;
19102 }
19103}
19104
19105void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19106 AdjustDeclIfTemplate(Decl&: TagD);
19107 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19108
19109 // Enter the tag context.
19110 PushDeclContext(S, DC: Tag);
19111
19112 ActOnDocumentableDecl(D: TagD);
19113
19114 // If there's a #pragma GCC visibility in scope, set the visibility of this
19115 // record.
19116 AddPushedVisibilityAttribute(RD: Tag);
19117}
19118
19119bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19120 SkipBodyInfo &SkipBody) {
19121 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19122 return false;
19123
19124 // Make the previous decl visible.
19125 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19126 CleanupMergedEnum(S, New: SkipBody.New);
19127 return true;
19128}
19129
19130void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19131 SourceLocation FinalLoc,
19132 bool IsFinalSpelledSealed,
19133 bool IsAbstract,
19134 SourceLocation LBraceLoc) {
19135 AdjustDeclIfTemplate(Decl&: TagD);
19136 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19137
19138 FieldCollector->StartClass();
19139
19140 if (!Record->getIdentifier())
19141 return;
19142
19143 if (IsAbstract)
19144 Record->markAbstract();
19145
19146 if (FinalLoc.isValid()) {
19147 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19148 S: IsFinalSpelledSealed
19149 ? FinalAttr::Keyword_sealed
19150 : FinalAttr::Keyword_final));
19151 }
19152
19153 // C++ [class]p2:
19154 // [...] The class-name is also inserted into the scope of the
19155 // class itself; this is known as the injected-class-name. For
19156 // purposes of access checking, the injected-class-name is treated
19157 // as if it were a public member name.
19158 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19159 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19160 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19161 InjectedClassName->setImplicit();
19162 InjectedClassName->setAccess(AS_public);
19163 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19164 InjectedClassName->setDescribedClassTemplate(Template);
19165
19166 PushOnScopeChains(D: InjectedClassName, S);
19167 assert(InjectedClassName->isInjectedClassName() &&
19168 "Broken injected-class-name");
19169}
19170
19171void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19172 SourceRange BraceRange) {
19173 AdjustDeclIfTemplate(Decl&: TagD);
19174 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19175 Tag->setBraceRange(BraceRange);
19176
19177 // Make sure we "complete" the definition even it is invalid.
19178 if (Tag->isBeingDefined()) {
19179 assert(Tag->isInvalidDecl() && "We should already have completed it");
19180 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19181 RD->completeDefinition();
19182 }
19183
19184 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19185 FieldCollector->FinishClass();
19186 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19187 auto *Def = RD->getDefinition();
19188 assert(Def && "The record is expected to have a completed definition");
19189 unsigned NumInitMethods = 0;
19190 for (auto *Method : Def->methods()) {
19191 if (!Method->getIdentifier())
19192 continue;
19193 if (Method->getName() == "__init")
19194 NumInitMethods++;
19195 }
19196 if (NumInitMethods > 1 || !Def->hasInitMethod())
19197 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19198 }
19199
19200 // If we're defining a dynamic class in a module interface unit, we always
19201 // need to produce the vtable for it, even if the vtable is not used in the
19202 // current TU.
19203 //
19204 // The case where the current class is not dynamic is handled in
19205 // MarkVTableUsed.
19206 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19207 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19208 }
19209
19210 // Exit this scope of this tag's definition.
19211 PopDeclContext();
19212
19213 if (getCurLexicalContext()->isObjCContainer() &&
19214 Tag->getDeclContext()->isFileContext())
19215 Tag->setTopLevelDeclInObjCContainer();
19216
19217 // Notify the consumer that we've defined a tag.
19218 if (!Tag->isInvalidDecl())
19219 Consumer.HandleTagDeclDefinition(D: Tag);
19220
19221 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19222 // from XLs and instead matches the XL #pragma pack(1) behavior.
19223 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19224 AlignPackStack.hasValue()) {
19225 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19226 // Only diagnose #pragma align(packed).
19227 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19228 return;
19229 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19230 if (!RD)
19231 return;
19232 // Only warn if there is at least 1 bitfield member.
19233 if (llvm::any_of(Range: RD->fields(),
19234 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19235 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19236 }
19237}
19238
19239void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19240 AdjustDeclIfTemplate(Decl&: TagD);
19241 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19242 Tag->setInvalidDecl();
19243
19244 // Make sure we "complete" the definition even it is invalid.
19245 if (Tag->isBeingDefined()) {
19246 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19247 RD->completeDefinition();
19248 }
19249
19250 // We're undoing ActOnTagStartDefinition here, not
19251 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19252 // the FieldCollector.
19253
19254 PopDeclContext();
19255}
19256
19257// Note that FieldName may be null for anonymous bitfields.
19258ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19259 const IdentifierInfo *FieldName,
19260 QualType FieldTy, bool IsMsStruct,
19261 Expr *BitWidth) {
19262 assert(BitWidth);
19263 if (BitWidth->containsErrors())
19264 return ExprError();
19265
19266 // C99 6.7.2.1p4 - verify the field type.
19267 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19268 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19269 // Handle incomplete and sizeless types with a specific error.
19270 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19271 DiagID: diag::err_field_incomplete_or_sizeless))
19272 return ExprError();
19273 if (FieldName)
19274 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19275 << FieldName << FieldTy << BitWidth->getSourceRange();
19276 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19277 << FieldTy << BitWidth->getSourceRange();
19278 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19279 return ExprError();
19280
19281 // If the bit-width is type- or value-dependent, don't try to check
19282 // it now.
19283 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19284 return BitWidth;
19285
19286 llvm::APSInt Value;
19287 ExprResult ICE =
19288 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19289 if (ICE.isInvalid())
19290 return ICE;
19291 BitWidth = ICE.get();
19292
19293 // Zero-width bitfield is ok for anonymous field.
19294 if (Value == 0 && FieldName)
19295 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19296 << FieldName << BitWidth->getSourceRange();
19297
19298 if (Value.isSigned() && Value.isNegative()) {
19299 if (FieldName)
19300 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19301 << FieldName << toString(I: Value, Radix: 10);
19302 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19303 << toString(I: Value, Radix: 10);
19304 }
19305
19306 // The size of the bit-field must not exceed our maximum permitted object
19307 // size.
19308 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19309 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19310 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19311 }
19312
19313 if (!FieldTy->isDependentType()) {
19314 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19315 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19316 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19317
19318 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19319 // ABI.
19320 bool CStdConstraintViolation =
19321 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19322 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19323 if (CStdConstraintViolation || MSBitfieldViolation) {
19324 unsigned DiagWidth =
19325 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19326 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19327 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19328 << !CStdConstraintViolation << DiagWidth;
19329 }
19330
19331 // Warn on types where the user might conceivably expect to get all
19332 // specified bits as value bits: that's all integral types other than
19333 // 'bool'.
19334 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19335 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19336 << FieldName << Value << (unsigned)TypeWidth;
19337 }
19338 }
19339
19340 if (isa<ConstantExpr>(Val: BitWidth))
19341 return BitWidth;
19342 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19343}
19344
19345Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19346 Declarator &D, Expr *BitfieldWidth) {
19347 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19348 D, BitfieldWidth,
19349 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19350 return Res;
19351}
19352
19353FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19354 SourceLocation DeclStart,
19355 Declarator &D, Expr *BitWidth,
19356 InClassInitStyle InitStyle,
19357 AccessSpecifier AS) {
19358 if (D.isDecompositionDeclarator()) {
19359 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19360 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19361 << Decomp.getSourceRange();
19362 return nullptr;
19363 }
19364
19365 const IdentifierInfo *II = D.getIdentifier();
19366 SourceLocation Loc = DeclStart;
19367 if (II) Loc = D.getIdentifierLoc();
19368
19369 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19370 QualType T = TInfo->getType();
19371 if (getLangOpts().CPlusPlus) {
19372 CheckExtraCXXDefaultArguments(D);
19373
19374 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19375 UPPC: UPPC_DataMemberType)) {
19376 D.setInvalidType();
19377 T = Context.IntTy;
19378 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19379 }
19380 }
19381
19382 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19383
19384 if (D.getDeclSpec().isInlineSpecified())
19385 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19386 << getLangOpts().CPlusPlus17;
19387 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19388 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19389 DiagID: diag::err_invalid_thread)
19390 << DeclSpec::getSpecifierName(S: TSCS);
19391
19392 // Check to see if this name was declared as a member previously
19393 NamedDecl *PrevDecl = nullptr;
19394 LookupResult Previous(*this, II, Loc, LookupMemberName,
19395 RedeclarationKind::ForVisibleRedeclaration);
19396 LookupName(R&: Previous, S);
19397 switch (Previous.getResultKind()) {
19398 case LookupResultKind::Found:
19399 case LookupResultKind::FoundUnresolvedValue:
19400 PrevDecl = Previous.getAsSingle<NamedDecl>();
19401 break;
19402
19403 case LookupResultKind::FoundOverloaded:
19404 PrevDecl = Previous.getRepresentativeDecl();
19405 break;
19406
19407 case LookupResultKind::NotFound:
19408 case LookupResultKind::NotFoundInCurrentInstantiation:
19409 case LookupResultKind::Ambiguous:
19410 break;
19411 }
19412 Previous.suppressDiagnostics();
19413
19414 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19415 // Maybe we will complain about the shadowed template parameter.
19416 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19417 // Just pretend that we didn't see the previous declaration.
19418 PrevDecl = nullptr;
19419 }
19420
19421 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19422 PrevDecl = nullptr;
19423
19424 bool Mutable
19425 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19426 SourceLocation TSSL = D.getBeginLoc();
19427 FieldDecl *NewFD
19428 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19429 TSSL, AS, PrevDecl, D: &D);
19430
19431 if (NewFD->isInvalidDecl())
19432 Record->setInvalidDecl();
19433
19434 if (D.getDeclSpec().isModulePrivateSpecified())
19435 NewFD->setModulePrivate();
19436
19437 if (NewFD->isInvalidDecl() && PrevDecl) {
19438 // Don't introduce NewFD into scope; there's already something
19439 // with the same name in the same scope.
19440 } else if (II) {
19441 PushOnScopeChains(D: NewFD, S);
19442 } else
19443 Record->addDecl(D: NewFD);
19444
19445 return NewFD;
19446}
19447
19448FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19449 TypeSourceInfo *TInfo,
19450 RecordDecl *Record, SourceLocation Loc,
19451 bool Mutable, Expr *BitWidth,
19452 InClassInitStyle InitStyle,
19453 SourceLocation TSSL,
19454 AccessSpecifier AS, NamedDecl *PrevDecl,
19455 Declarator *D) {
19456 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19457 bool InvalidDecl = false;
19458 if (D) InvalidDecl = D->isInvalidType();
19459
19460 // If we receive a broken type, recover by assuming 'int' and
19461 // marking this declaration as invalid.
19462 if (T.isNull() || T->containsErrors()) {
19463 InvalidDecl = true;
19464 T = Context.IntTy;
19465 }
19466
19467 QualType EltTy = Context.getBaseElementType(QT: T);
19468 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19469 bool isIncomplete =
19470 LangOpts.HLSL // HLSL allows sizeless builtin types
19471 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19472 : RequireCompleteSizedType(Loc, T: EltTy,
19473 DiagID: diag::err_field_incomplete_or_sizeless);
19474 if (isIncomplete) {
19475 // Fields of incomplete type force their record to be invalid.
19476 Record->setInvalidDecl();
19477 InvalidDecl = true;
19478 } else {
19479 NamedDecl *Def;
19480 EltTy->isIncompleteType(Def: &Def);
19481 if (Def && Def->isInvalidDecl()) {
19482 Record->setInvalidDecl();
19483 InvalidDecl = true;
19484 }
19485 }
19486 }
19487
19488 // TR 18037 does not allow fields to be declared with address space
19489 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19490 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19491 Diag(Loc, DiagID: diag::err_field_with_address_space);
19492 Record->setInvalidDecl();
19493 InvalidDecl = true;
19494 }
19495
19496 if (LangOpts.OpenCL) {
19497 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19498 // used as structure or union field: image, sampler, event or block types.
19499 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19500 T->isBlockPointerType()) {
19501 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19502 Record->setInvalidDecl();
19503 InvalidDecl = true;
19504 }
19505 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19506 // is enabled.
19507 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19508 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19509 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19510 InvalidDecl = true;
19511 }
19512 }
19513
19514 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19515 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19516 T.hasQualifiers()) {
19517 InvalidDecl = true;
19518 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19519 }
19520
19521 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19522 // than a variably modified type.
19523 if (!InvalidDecl && T->isVariablyModifiedType()) {
19524 if (!tryToFixVariablyModifiedVarType(
19525 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19526 InvalidDecl = true;
19527 }
19528
19529 // Fields can not have abstract class types
19530 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19531 DiagID: diag::err_abstract_type_in_decl,
19532 Args: AbstractFieldType))
19533 InvalidDecl = true;
19534
19535 if (InvalidDecl)
19536 BitWidth = nullptr;
19537 // If this is declared as a bit-field, check the bit-field.
19538 if (BitWidth) {
19539 BitWidth =
19540 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19541 if (!BitWidth) {
19542 InvalidDecl = true;
19543 BitWidth = nullptr;
19544 }
19545 }
19546
19547 // Check that 'mutable' is consistent with the type of the declaration.
19548 if (!InvalidDecl && Mutable) {
19549 unsigned DiagID = 0;
19550 if (T->isReferenceType())
19551 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19552 : diag::err_mutable_reference;
19553 else if (T.isConstQualified())
19554 DiagID = diag::err_mutable_const;
19555
19556 if (DiagID) {
19557 SourceLocation ErrLoc = Loc;
19558 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19559 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19560 Diag(Loc: ErrLoc, DiagID);
19561 if (DiagID != diag::ext_mutable_reference) {
19562 Mutable = false;
19563 InvalidDecl = true;
19564 }
19565 }
19566 }
19567
19568 // C++11 [class.union]p8 (DR1460):
19569 // At most one variant member of a union may have a
19570 // brace-or-equal-initializer.
19571 if (InitStyle != ICIS_NoInit)
19572 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19573
19574 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19575 BW: BitWidth, Mutable, InitStyle);
19576 if (InvalidDecl)
19577 NewFD->setInvalidDecl();
19578
19579 if (!InvalidDecl)
19580 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19581
19582 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19583 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19584 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19585 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19586 NewFD->setInvalidDecl();
19587 }
19588
19589 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19590 if (Record->isUnion()) {
19591 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19592 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19593
19594 // C++ [class.union]p1: An object of a class with a non-trivial
19595 // constructor, a non-trivial copy constructor, a non-trivial
19596 // destructor, or a non-trivial copy assignment operator
19597 // cannot be a member of a union, nor can an array of such
19598 // objects.
19599 if (CheckNontrivialField(FD: NewFD))
19600 NewFD->setInvalidDecl();
19601 }
19602
19603 // C++ [class.union]p1: If a union contains a member of reference type,
19604 // the program is ill-formed, except when compiling with MSVC extensions
19605 // enabled.
19606 if (EltTy->isReferenceType()) {
19607 const bool HaveMSExt =
19608 getLangOpts().MicrosoftExt &&
19609 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19610
19611 Diag(Loc: NewFD->getLocation(),
19612 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19613 : diag::err_union_member_of_reference_type)
19614 << NewFD->getDeclName() << EltTy;
19615 if (!HaveMSExt)
19616 NewFD->setInvalidDecl();
19617 }
19618 }
19619 }
19620
19621 // FIXME: We need to pass in the attributes given an AST
19622 // representation, not a parser representation.
19623 if (D) {
19624 // FIXME: The current scope is almost... but not entirely... correct here.
19625 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19626
19627 if (NewFD->hasAttrs())
19628 CheckAlignasUnderalignment(D: NewFD);
19629 }
19630
19631 // In auto-retain/release, infer strong retension for fields of
19632 // retainable type.
19633 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19634 NewFD->setInvalidDecl();
19635
19636 if (T.isObjCGCWeak())
19637 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19638
19639 // PPC MMA non-pointer types are not allowed as field types.
19640 if (Context.getTargetInfo().getTriple().isPPC64() &&
19641 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19642 NewFD->setInvalidDecl();
19643
19644 NewFD->setAccess(AS);
19645 return NewFD;
19646}
19647
19648bool Sema::CheckNontrivialField(FieldDecl *FD) {
19649 assert(FD);
19650 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19651
19652 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19653 return false;
19654
19655 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19656 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19657 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19658 // We check for copy constructors before constructors
19659 // because otherwise we'll never get complaints about
19660 // copy constructors.
19661
19662 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19663 // We're required to check for any non-trivial constructors. Since the
19664 // implicit default constructor is suppressed if there are any
19665 // user-declared constructors, we just need to check that there is a
19666 // trivial default constructor and a trivial copy constructor. (We don't
19667 // worry about move constructors here, since this is a C++98 check.)
19668 if (RDecl->hasNonTrivialCopyConstructor())
19669 member = CXXSpecialMemberKind::CopyConstructor;
19670 else if (!RDecl->hasTrivialDefaultConstructor())
19671 member = CXXSpecialMemberKind::DefaultConstructor;
19672 else if (RDecl->hasNonTrivialCopyAssignment())
19673 member = CXXSpecialMemberKind::CopyAssignment;
19674 else if (RDecl->hasNonTrivialDestructor())
19675 member = CXXSpecialMemberKind::Destructor;
19676
19677 if (member != CXXSpecialMemberKind::Invalid) {
19678 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19679 RDecl->hasObjectMember()) {
19680 // Objective-C++ ARC: it is an error to have a non-trivial field of
19681 // a union. However, system headers in Objective-C programs
19682 // occasionally have Objective-C lifetime objects within unions,
19683 // and rather than cause the program to fail, we make those
19684 // members unavailable.
19685 SourceLocation Loc = FD->getLocation();
19686 if (getSourceManager().isInSystemHeader(Loc)) {
19687 if (!FD->hasAttr<UnavailableAttr>())
19688 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19689 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19690 return false;
19691 }
19692 }
19693
19694 Diag(Loc: FD->getLocation(),
19695 DiagID: getLangOpts().CPlusPlus11
19696 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19697 : diag::err_illegal_union_or_anon_struct_member)
19698 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19699 DiagnoseNontrivial(Record: RDecl, CSM: member);
19700 return !getLangOpts().CPlusPlus11;
19701 }
19702 }
19703
19704 return false;
19705}
19706
19707void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19708 SmallVectorImpl<Decl *> &AllIvarDecls) {
19709 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19710 return;
19711
19712 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19713 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19714
19715 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19716 return;
19717 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19718 if (!ID) {
19719 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19720 if (!CD->IsClassExtension())
19721 return;
19722 }
19723 // No need to add this to end of @implementation.
19724 else
19725 return;
19726 }
19727 // All conditions are met. Add a new bitfield to the tail end of ivars.
19728 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19729 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19730 Expr *BitWidth =
19731 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19732
19733 Ivar = ObjCIvarDecl::Create(
19734 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19735 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19736 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19737 AllIvarDecls.push_back(Elt: Ivar);
19738}
19739
19740/// [class.dtor]p4:
19741/// At the end of the definition of a class, overload resolution is
19742/// performed among the prospective destructors declared in that class with
19743/// an empty argument list to select the destructor for the class, also
19744/// known as the selected destructor.
19745///
19746/// We do the overload resolution here, then mark the selected constructor in the AST.
19747/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19748static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19749 if (!Record->hasUserDeclaredDestructor()) {
19750 return;
19751 }
19752
19753 SourceLocation Loc = Record->getLocation();
19754 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19755
19756 for (auto *Decl : Record->decls()) {
19757 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19758 if (DD->isInvalidDecl())
19759 continue;
19760 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19761 CandidateSet&: OCS);
19762 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19763 }
19764 }
19765
19766 if (OCS.empty()) {
19767 return;
19768 }
19769 OverloadCandidateSet::iterator Best;
19770 unsigned Msg = 0;
19771 OverloadCandidateDisplayKind DisplayKind;
19772
19773 switch (OCS.BestViableFunction(S, Loc, Best)) {
19774 case OR_Success:
19775 case OR_Deleted:
19776 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19777 break;
19778
19779 case OR_Ambiguous:
19780 Msg = diag::err_ambiguous_destructor;
19781 DisplayKind = OCD_AmbiguousCandidates;
19782 break;
19783
19784 case OR_No_Viable_Function:
19785 Msg = diag::err_no_viable_destructor;
19786 DisplayKind = OCD_AllCandidates;
19787 break;
19788 }
19789
19790 if (Msg) {
19791 // OpenCL have got their own thing going with destructors. It's slightly broken,
19792 // but we allow it.
19793 if (!S.LangOpts.OpenCL) {
19794 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19795 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19796 Record->setInvalidDecl();
19797 }
19798 // It's a bit hacky: At this point we've raised an error but we want the
19799 // rest of the compiler to continue somehow working. However almost
19800 // everything we'll try to do with the class will depend on there being a
19801 // destructor. So let's pretend the first one is selected and hope for the
19802 // best.
19803 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19804 }
19805}
19806
19807/// [class.mem.special]p5
19808/// Two special member functions are of the same kind if:
19809/// - they are both default constructors,
19810/// - they are both copy or move constructors with the same first parameter
19811/// type, or
19812/// - they are both copy or move assignment operators with the same first
19813/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19814static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19815 CXXMethodDecl *M1,
19816 CXXMethodDecl *M2,
19817 CXXSpecialMemberKind CSM) {
19818 // We don't want to compare templates to non-templates: See
19819 // https://github.com/llvm/llvm-project/issues/59206
19820 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19821 return bool(M1->getDescribedFunctionTemplate()) ==
19822 bool(M2->getDescribedFunctionTemplate());
19823 // FIXME: better resolve CWG
19824 // https://cplusplus.github.io/CWG/issues/2787.html
19825 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19826 T2: M2->getNonObjectParameter(I: 0)->getType()))
19827 return false;
19828 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19829 T2: M2->getFunctionObjectParameterReferenceType()))
19830 return false;
19831
19832 return true;
19833}
19834
19835/// [class.mem.special]p6:
19836/// An eligible special member function is a special member function for which:
19837/// - the function is not deleted,
19838/// - the associated constraints, if any, are satisfied, and
19839/// - no special member function of the same kind whose associated constraints
19840/// [CWG2595], if any, are satisfied is more constrained.
19841static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19842 ArrayRef<CXXMethodDecl *> Methods,
19843 CXXSpecialMemberKind CSM) {
19844 SmallVector<bool, 4> SatisfactionStatus;
19845
19846 for (CXXMethodDecl *Method : Methods) {
19847 if (!Method->getTrailingRequiresClause())
19848 SatisfactionStatus.push_back(Elt: true);
19849 else {
19850 ConstraintSatisfaction Satisfaction;
19851 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19852 SatisfactionStatus.push_back(Elt: false);
19853 else
19854 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19855 }
19856 }
19857
19858 for (size_t i = 0; i < Methods.size(); i++) {
19859 if (!SatisfactionStatus[i])
19860 continue;
19861 CXXMethodDecl *Method = Methods[i];
19862 CXXMethodDecl *OrigMethod = Method;
19863 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19864 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19865
19866 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19867 bool AnotherMethodIsMoreConstrained = false;
19868 for (size_t j = 0; j < Methods.size(); j++) {
19869 if (i == j || !SatisfactionStatus[j])
19870 continue;
19871 CXXMethodDecl *OtherMethod = Methods[j];
19872 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19873 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19874
19875 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19876 CSM))
19877 continue;
19878
19879 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19880 if (!Other)
19881 continue;
19882 if (!Orig) {
19883 AnotherMethodIsMoreConstrained = true;
19884 break;
19885 }
19886 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19887 Result&: AnotherMethodIsMoreConstrained)) {
19888 // There was an error with the constraints comparison. Exit the loop
19889 // and don't consider this function eligible.
19890 AnotherMethodIsMoreConstrained = true;
19891 }
19892 if (AnotherMethodIsMoreConstrained)
19893 break;
19894 }
19895 // FIXME: Do not consider deleted methods as eligible after implementing
19896 // DR1734 and DR1496.
19897 if (!AnotherMethodIsMoreConstrained) {
19898 Method->setIneligibleOrNotSelected(false);
19899 Record->addedEligibleSpecialMemberFunction(MD: Method,
19900 SMKind: 1 << llvm::to_underlying(E: CSM));
19901 }
19902 }
19903}
19904
19905static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19906 CXXRecordDecl *Record) {
19907 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19908 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19909 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19910 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19911 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19912
19913 for (auto *Decl : Record->decls()) {
19914 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19915 if (!MD) {
19916 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19917 if (FTD)
19918 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19919 }
19920 if (!MD)
19921 continue;
19922 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19923 if (CD->isInvalidDecl())
19924 continue;
19925 if (CD->isDefaultConstructor())
19926 DefaultConstructors.push_back(Elt: MD);
19927 else if (CD->isCopyConstructor())
19928 CopyConstructors.push_back(Elt: MD);
19929 else if (CD->isMoveConstructor())
19930 MoveConstructors.push_back(Elt: MD);
19931 } else if (MD->isCopyAssignmentOperator()) {
19932 CopyAssignmentOperators.push_back(Elt: MD);
19933 } else if (MD->isMoveAssignmentOperator()) {
19934 MoveAssignmentOperators.push_back(Elt: MD);
19935 }
19936 }
19937
19938 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19939 CSM: CXXSpecialMemberKind::DefaultConstructor);
19940 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19941 CSM: CXXSpecialMemberKind::CopyConstructor);
19942 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19943 CSM: CXXSpecialMemberKind::MoveConstructor);
19944 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19945 CSM: CXXSpecialMemberKind::CopyAssignment);
19946 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19947 CSM: CXXSpecialMemberKind::MoveAssignment);
19948}
19949
19950bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19951 // Check to see if a FieldDecl is a pointer to a function.
19952 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19953 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19954 if (!FD) {
19955 // Check whether this is a forward declaration that was inserted by
19956 // Clang. This happens when a non-forward declared / defined type is
19957 // used, e.g.:
19958 //
19959 // struct foo {
19960 // struct bar *(*f)();
19961 // struct bar *(*g)();
19962 // };
19963 //
19964 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19965 // incomplete definition.
19966 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19967 return !TD->isCompleteDefinition();
19968 return false;
19969 }
19970 QualType FieldType = FD->getType().getDesugaredType(Context);
19971 if (isa<PointerType>(Val: FieldType)) {
19972 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19973 return PointeeType.getDesugaredType(Context)->isFunctionType();
19974 }
19975 // If a member is a struct entirely of function pointers, that counts too.
19976 if (const auto *Record = FieldType->getAsRecordDecl();
19977 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19978 return true;
19979 return false;
19980 };
19981
19982 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19983}
19984
19985void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19986 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19987 SourceLocation RBrac,
19988 const ParsedAttributesView &Attrs) {
19989 assert(EnclosingDecl && "missing record or interface decl");
19990
19991 // If this is an Objective-C @implementation or category and we have
19992 // new fields here we should reset the layout of the interface since
19993 // it will now change.
19994 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19995 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19996 switch (DC->getKind()) {
19997 default: break;
19998 case Decl::ObjCCategory:
19999 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
20000 break;
20001 case Decl::ObjCImplementation:
20002 Context.
20003 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
20004 break;
20005 }
20006 }
20007
20008 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
20009 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
20010
20011 // Start counting up the number of named members; make sure to include
20012 // members of anonymous structs and unions in the total.
20013 unsigned NumNamedMembers = 0;
20014 if (Record) {
20015 for (const auto *I : Record->decls()) {
20016 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
20017 if (IFD->getDeclName())
20018 ++NumNamedMembers;
20019 }
20020 }
20021
20022 // Verify that all the fields are okay.
20023 SmallVector<FieldDecl*, 32> RecFields;
20024 const FieldDecl *PreviousField = nullptr;
20025 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20026 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
20027 FieldDecl *FD = cast<FieldDecl>(Val: *i);
20028
20029 // Get the type for the field.
20030 const Type *FDTy = FD->getType().getTypePtr();
20031
20032 if (!FD->isAnonymousStructOrUnion()) {
20033 // Remember all fields written by the user.
20034 RecFields.push_back(Elt: FD);
20035 }
20036
20037 // If the field is already invalid for some reason, don't emit more
20038 // diagnostics about it.
20039 if (FD->isInvalidDecl()) {
20040 EnclosingDecl->setInvalidDecl();
20041 continue;
20042 }
20043
20044 // C99 6.7.2.1p2:
20045 // A structure or union shall not contain a member with
20046 // incomplete or function type (hence, a structure shall not
20047 // contain an instance of itself, but may contain a pointer to
20048 // an instance of itself), except that the last member of a
20049 // structure with more than one named member may have incomplete
20050 // array type; such a structure (and any union containing,
20051 // possibly recursively, a member that is such a structure)
20052 // shall not be a member of a structure or an element of an
20053 // array.
20054 bool IsLastField = (i + 1 == Fields.end());
20055 if (FDTy->isFunctionType()) {
20056 // Field declared as a function.
20057 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
20058 << FD->getDeclName();
20059 FD->setInvalidDecl();
20060 EnclosingDecl->setInvalidDecl();
20061 continue;
20062 } else if (FDTy->isIncompleteArrayType() &&
20063 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20064 if (Record) {
20065 // Flexible array member.
20066 // Microsoft and g++ is more permissive regarding flexible array.
20067 // It will accept flexible array in union and also
20068 // as the sole element of a struct/class.
20069 unsigned DiagID = 0;
20070 if (!Record->isUnion() && !IsLastField) {
20071 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20072 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20073 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20074 FD->setInvalidDecl();
20075 EnclosingDecl->setInvalidDecl();
20076 continue;
20077 } else if (Record->isUnion())
20078 DiagID = getLangOpts().MicrosoftExt
20079 ? diag::ext_flexible_array_union_ms
20080 : diag::ext_flexible_array_union_gnu;
20081 else if (NumNamedMembers < 1)
20082 DiagID = getLangOpts().MicrosoftExt
20083 ? diag::ext_flexible_array_empty_aggregate_ms
20084 : diag::ext_flexible_array_empty_aggregate_gnu;
20085
20086 if (DiagID)
20087 Diag(Loc: FD->getLocation(), DiagID)
20088 << FD->getDeclName() << Record->getTagKind();
20089 // While the layout of types that contain virtual bases is not specified
20090 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20091 // virtual bases after the derived members. This would make a flexible
20092 // array member declared at the end of an object not adjacent to the end
20093 // of the type.
20094 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20095 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20096 << FD->getDeclName() << Record->getTagKind();
20097 if (!getLangOpts().C99)
20098 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20099 << FD->getDeclName() << Record->getTagKind();
20100
20101 // If the element type has a non-trivial destructor, we would not
20102 // implicitly destroy the elements, so disallow it for now.
20103 //
20104 // FIXME: GCC allows this. We should probably either implicitly delete
20105 // the destructor of the containing class, or just allow this.
20106 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20107 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20108 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20109 << FD->getDeclName() << FD->getType();
20110 FD->setInvalidDecl();
20111 EnclosingDecl->setInvalidDecl();
20112 continue;
20113 }
20114 // Okay, we have a legal flexible array member at the end of the struct.
20115 Record->setHasFlexibleArrayMember(true);
20116 } else {
20117 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20118 // unless they are followed by another ivar. That check is done
20119 // elsewhere, after synthesized ivars are known.
20120 }
20121 } else if (!FDTy->isDependentType() &&
20122 (LangOpts.HLSL // HLSL allows sizeless builtin types
20123 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20124 DiagID: diag::err_incomplete_type)
20125 : RequireCompleteSizedType(
20126 Loc: FD->getLocation(), T: FD->getType(),
20127 DiagID: diag::err_field_incomplete_or_sizeless))) {
20128 // Incomplete type
20129 FD->setInvalidDecl();
20130 EnclosingDecl->setInvalidDecl();
20131 continue;
20132 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20133 if (Record && RD->hasFlexibleArrayMember()) {
20134 // A type which contains a flexible array member is considered to be a
20135 // flexible array member.
20136 Record->setHasFlexibleArrayMember(true);
20137 if (!Record->isUnion()) {
20138 // If this is a struct/class and this is not the last element, reject
20139 // it. Note that GCC supports variable sized arrays in the middle of
20140 // structures.
20141 if (!IsLastField)
20142 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20143 << FD->getDeclName() << FD->getType();
20144 else {
20145 // We support flexible arrays at the end of structs in
20146 // other structs as an extension.
20147 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20148 << FD->getDeclName();
20149 }
20150 }
20151 }
20152 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20153 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20154 DiagID: diag::err_abstract_type_in_decl,
20155 Args: AbstractIvarType)) {
20156 // Ivars can not have abstract class types
20157 FD->setInvalidDecl();
20158 }
20159 if (Record && RD->hasObjectMember())
20160 Record->setHasObjectMember(true);
20161 if (Record && RD->hasVolatileMember())
20162 Record->setHasVolatileMember(true);
20163 } else if (FDTy->isObjCObjectType()) {
20164 /// A field cannot be an Objective-c object
20165 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20166 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20167 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20168 FD->setType(T);
20169 } else if (Record && Record->isUnion() &&
20170 FD->getType().hasNonTrivialObjCLifetime() &&
20171 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20172 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20173 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20174 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20175 // For backward compatibility, fields of C unions declared in system
20176 // headers that have non-trivial ObjC ownership qualifications are marked
20177 // as unavailable unless the qualifier is explicit and __strong. This can
20178 // break ABI compatibility between programs compiled with ARC and MRR, but
20179 // is a better option than rejecting programs using those unions under
20180 // ARC.
20181 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20182 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20183 Range: FD->getLocation()));
20184 } else if (getLangOpts().ObjC &&
20185 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20186 !Record->hasObjectMember()) {
20187 if (FD->getType()->isObjCObjectPointerType() ||
20188 FD->getType().isObjCGCStrong())
20189 Record->setHasObjectMember(true);
20190 else if (Context.getAsArrayType(T: FD->getType())) {
20191 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20192 if (const auto *RD = BaseType->getAsRecordDecl();
20193 RD && RD->hasObjectMember())
20194 Record->setHasObjectMember(true);
20195 else if (BaseType->isObjCObjectPointerType() ||
20196 BaseType.isObjCGCStrong())
20197 Record->setHasObjectMember(true);
20198 }
20199 }
20200
20201 if (Record && !getLangOpts().CPlusPlus &&
20202 !shouldIgnoreForRecordTriviality(FD)) {
20203 QualType FT = FD->getType();
20204 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20205 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20206 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20207 Record->isUnion())
20208 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20209 }
20210 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20211 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20212 Record->setNonTrivialToPrimitiveCopy(true);
20213 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20214 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20215 }
20216 if (FD->hasAttr<ExplicitInitAttr>())
20217 Record->setHasUninitializedExplicitInitFields(true);
20218 if (FT.isDestructedType()) {
20219 Record->setNonTrivialToPrimitiveDestroy(true);
20220 Record->setParamDestroyedInCallee(true);
20221 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20222 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20223 }
20224
20225 if (const auto *RD = FT->getAsRecordDecl()) {
20226 if (RD->getArgPassingRestrictions() ==
20227 RecordArgPassingKind::CanNeverPassInRegs)
20228 Record->setArgPassingRestrictions(
20229 RecordArgPassingKind::CanNeverPassInRegs);
20230 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20231 Record->setArgPassingRestrictions(
20232 RecordArgPassingKind::CanNeverPassInRegs);
20233 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20234 Q && Q.isAddressDiscriminated()) {
20235 Record->setArgPassingRestrictions(
20236 RecordArgPassingKind::CanNeverPassInRegs);
20237 Record->setNonTrivialToPrimitiveCopy(true);
20238 }
20239 }
20240
20241 if (Record && FD->getType().isVolatileQualified())
20242 Record->setHasVolatileMember(true);
20243 bool ReportMSBitfieldStoragePacking =
20244 Record && PreviousField &&
20245 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20246 Loc: Record->getLocation());
20247 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20248 return FD->isBitField() && !FD->getType()->isDependentType();
20249 };
20250
20251 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20252 IsNonDependentBitField(PreviousField)) {
20253 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20254 CharUnits PreviousFieldStorageSize =
20255 Context.getTypeSizeInChars(T: PreviousField->getType());
20256 if (FDStorageSize != PreviousFieldStorageSize) {
20257 Diag(Loc: FD->getLocation(),
20258 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20259 << FD << FD->getType() << FDStorageSize.getQuantity()
20260 << PreviousFieldStorageSize.getQuantity();
20261 Diag(Loc: PreviousField->getLocation(),
20262 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20263 << PreviousField << PreviousField->getType();
20264 }
20265 }
20266 // Keep track of the number of named members.
20267 if (FD->getIdentifier())
20268 ++NumNamedMembers;
20269 }
20270
20271 // Okay, we successfully defined 'Record'.
20272 if (Record) {
20273 bool Completed = false;
20274 if (S) {
20275 Scope *Parent = S->getParent();
20276 if (Parent && Parent->isTypeAliasScope() &&
20277 Parent->isTemplateParamScope())
20278 Record->setInvalidDecl();
20279 }
20280
20281 if (CXXRecord) {
20282 if (!CXXRecord->isInvalidDecl()) {
20283 // Set access bits correctly on the directly-declared conversions.
20284 for (CXXRecordDecl::conversion_iterator
20285 I = CXXRecord->conversion_begin(),
20286 E = CXXRecord->conversion_end(); I != E; ++I)
20287 I.setAccess((*I)->getAccess());
20288 }
20289
20290 // Add any implicitly-declared members to this class.
20291 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20292
20293 if (!CXXRecord->isDependentType()) {
20294 if (!CXXRecord->isInvalidDecl()) {
20295 // If we have virtual base classes, we may end up finding multiple
20296 // final overriders for a given virtual function. Check for this
20297 // problem now.
20298 if (CXXRecord->getNumVBases()) {
20299 CXXFinalOverriderMap FinalOverriders;
20300 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20301
20302 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20303 MEnd = FinalOverriders.end();
20304 M != MEnd; ++M) {
20305 for (OverridingMethods::iterator SO = M->second.begin(),
20306 SOEnd = M->second.end();
20307 SO != SOEnd; ++SO) {
20308 assert(SO->second.size() > 0 &&
20309 "Virtual function without overriding functions?");
20310 if (SO->second.size() == 1)
20311 continue;
20312
20313 // C++ [class.virtual]p2:
20314 // In a derived class, if a virtual member function of a base
20315 // class subobject has more than one final overrider the
20316 // program is ill-formed.
20317 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20318 << (const NamedDecl *)M->first << Record;
20319 Diag(Loc: M->first->getLocation(),
20320 DiagID: diag::note_overridden_virtual_function);
20321 for (OverridingMethods::overriding_iterator
20322 OM = SO->second.begin(),
20323 OMEnd = SO->second.end();
20324 OM != OMEnd; ++OM)
20325 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20326 << (const NamedDecl *)M->first << OM->Method->getParent();
20327
20328 Record->setInvalidDecl();
20329 }
20330 }
20331 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20332 Completed = true;
20333 }
20334 }
20335 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20336 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20337 }
20338 }
20339
20340 if (!Completed)
20341 Record->completeDefinition();
20342
20343 // Handle attributes before checking the layout.
20344 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20345
20346 // Maybe randomize the record's decls. We automatically randomize a record
20347 // of function pointers, unless it has the "no_randomize_layout" attribute.
20348 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20349 !Record->isRandomized() && !Record->isUnion() &&
20350 (Record->hasAttr<RandomizeLayoutAttr>() ||
20351 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20352 EntirelyFunctionPointers(Record)))) {
20353 SmallVector<Decl *, 32> NewDeclOrdering;
20354 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20355 FinalOrdering&: NewDeclOrdering))
20356 Record->reorderDecls(Decls: NewDeclOrdering);
20357 }
20358
20359 // We may have deferred checking for a deleted destructor. Check now.
20360 if (CXXRecord) {
20361 auto *Dtor = CXXRecord->getDestructor();
20362 if (Dtor && Dtor->isImplicit() &&
20363 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20364 CXXRecord->setImplicitDestructorIsDeleted();
20365 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20366 }
20367 }
20368
20369 if (Record->hasAttrs()) {
20370 CheckAlignasUnderalignment(D: Record);
20371
20372 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20373 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20374 Range: IA->getRange(), BestCase: IA->getBestCase(),
20375 SemanticSpelling: IA->getInheritanceModel());
20376 }
20377
20378 // Check if the structure/union declaration is a type that can have zero
20379 // size in C. For C this is a language extension, for C++ it may cause
20380 // compatibility problems.
20381 bool CheckForZeroSize;
20382 if (!getLangOpts().CPlusPlus) {
20383 CheckForZeroSize = true;
20384 } else {
20385 // For C++ filter out types that cannot be referenced in C code.
20386 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20387 CheckForZeroSize =
20388 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20389 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20390 CXXRecord->isCLike();
20391 }
20392 if (CheckForZeroSize) {
20393 bool ZeroSize = true;
20394 bool IsEmpty = true;
20395 unsigned NonBitFields = 0;
20396 for (RecordDecl::field_iterator I = Record->field_begin(),
20397 E = Record->field_end();
20398 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20399 IsEmpty = false;
20400 if (I->isUnnamedBitField()) {
20401 if (!I->isZeroLengthBitField())
20402 ZeroSize = false;
20403 } else {
20404 ++NonBitFields;
20405 QualType FieldType = I->getType();
20406 if (FieldType->isIncompleteType() ||
20407 !Context.getTypeSizeInChars(T: FieldType).isZero())
20408 ZeroSize = false;
20409 }
20410 }
20411
20412 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20413 // allowed in C++, but warn if its declaration is inside
20414 // extern "C" block.
20415 if (ZeroSize) {
20416 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20417 diag::warn_zero_size_struct_union_in_extern_c :
20418 diag::warn_zero_size_struct_union_compat)
20419 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20420 }
20421
20422 // Structs without named members are extension in C (C99 6.7.2.1p7),
20423 // but are accepted by GCC. In C2y, this became implementation-defined
20424 // (C2y 6.7.3.2p10).
20425 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20426 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20427 : diag::ext_no_named_members_in_struct_union)
20428 << Record->isUnion();
20429 }
20430 }
20431 } else {
20432 ObjCIvarDecl **ClsFields =
20433 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20434 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20435 ID->setEndOfDefinitionLoc(RBrac);
20436 // Add ivar's to class's DeclContext.
20437 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20438 ClsFields[i]->setLexicalDeclContext(ID);
20439 ID->addDecl(D: ClsFields[i]);
20440 }
20441 // Must enforce the rule that ivars in the base classes may not be
20442 // duplicates.
20443 if (ID->getSuperClass())
20444 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20445 } else if (ObjCImplementationDecl *IMPDecl =
20446 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20447 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20448 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20449 // Ivar declared in @implementation never belongs to the implementation.
20450 // Only it is in implementation's lexical context.
20451 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20452 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20453 Loc: RBrac);
20454 IMPDecl->setIvarLBraceLoc(LBrac);
20455 IMPDecl->setIvarRBraceLoc(RBrac);
20456 } else if (ObjCCategoryDecl *CDecl =
20457 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20458 // case of ivars in class extension; all other cases have been
20459 // reported as errors elsewhere.
20460 // FIXME. Class extension does not have a LocEnd field.
20461 // CDecl->setLocEnd(RBrac);
20462 // Add ivar's to class extension's DeclContext.
20463 // Diagnose redeclaration of private ivars.
20464 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20465 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20466 if (IDecl) {
20467 if (const ObjCIvarDecl *ClsIvar =
20468 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20469 Diag(Loc: ClsFields[i]->getLocation(),
20470 DiagID: diag::err_duplicate_ivar_declaration);
20471 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20472 continue;
20473 }
20474 for (const auto *Ext : IDecl->known_extensions()) {
20475 if (const ObjCIvarDecl *ClsExtIvar
20476 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20477 Diag(Loc: ClsFields[i]->getLocation(),
20478 DiagID: diag::err_duplicate_ivar_declaration);
20479 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20480 continue;
20481 }
20482 }
20483 }
20484 ClsFields[i]->setLexicalDeclContext(CDecl);
20485 CDecl->addDecl(D: ClsFields[i]);
20486 }
20487 CDecl->setIvarLBraceLoc(LBrac);
20488 CDecl->setIvarRBraceLoc(RBrac);
20489 }
20490 }
20491 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20492 ProcessAPINotes(D: Record);
20493}
20494
20495// Given an integral type, return the next larger integral type
20496// (or a NULL type of no such type exists).
20497static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20498 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20499 // enum checking below.
20500 assert((T->isIntegralType(Context) ||
20501 T->isEnumeralType()) && "Integral type required!");
20502 const unsigned NumTypes = 4;
20503 QualType SignedIntegralTypes[NumTypes] = {
20504 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20505 };
20506 QualType UnsignedIntegralTypes[NumTypes] = {
20507 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20508 Context.UnsignedLongLongTy
20509 };
20510
20511 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20512 // bits but a 64-bit standard type can still represent its incremented
20513 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20514 // bit-precise type either.
20515 unsigned BitWidth = Context.getIntWidth(T);
20516 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20517 : UnsignedIntegralTypes;
20518 for (unsigned I = 0; I != NumTypes; ++I)
20519 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20520 return Types[I];
20521
20522 return QualType();
20523}
20524
20525EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20526 EnumConstantDecl *LastEnumConst,
20527 SourceLocation IdLoc,
20528 IdentifierInfo *Id,
20529 Expr *Val) {
20530 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20531 llvm::APSInt EnumVal(IntWidth);
20532 QualType EltTy;
20533
20534 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20535 Val = nullptr;
20536
20537 if (Val)
20538 Val = DefaultLvalueConversion(E: Val).get();
20539
20540 if (Val) {
20541 if (Enum->isDependentType() || Val->isTypeDependent() ||
20542 Val->containsErrors())
20543 EltTy = Context.DependentTy;
20544 else {
20545 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20546 // underlying type, but do allow it in all other contexts.
20547 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20548 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20549 // constant-expression in the enumerator-definition shall be a converted
20550 // constant expression of the underlying type.
20551 EltTy = Enum->getIntegerType();
20552 ExprResult Converted = CheckConvertedConstantExpression(
20553 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20554 if (Converted.isInvalid())
20555 Val = nullptr;
20556 else
20557 Val = Converted.get();
20558 } else if (!Val->isValueDependent() &&
20559 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20560 CanFold: AllowFoldKind::Allow)
20561 .get())) {
20562 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20563 } else {
20564 if (Enum->isComplete()) {
20565 EltTy = Enum->getIntegerType();
20566
20567 // In Obj-C and Microsoft mode, require the enumeration value to be
20568 // representable in the underlying type of the enumeration. In C++11,
20569 // we perform a non-narrowing conversion as part of converted constant
20570 // expression checking.
20571 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20572 if (Context.getTargetInfo()
20573 .getTriple()
20574 .isWindowsMSVCEnvironment()) {
20575 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20576 } else {
20577 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20578 }
20579 }
20580
20581 // Cast to the underlying type.
20582 Val = ImpCastExprToType(E: Val, Type: EltTy,
20583 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20584 : CK_IntegralCast)
20585 .get();
20586 } else if (getLangOpts().CPlusPlus) {
20587 // C++11 [dcl.enum]p5:
20588 // If the underlying type is not fixed, the type of each enumerator
20589 // is the type of its initializing value:
20590 // - If an initializer is specified for an enumerator, the
20591 // initializing value has the same type as the expression.
20592 EltTy = Val->getType();
20593 } else {
20594 // C99 6.7.2.2p2:
20595 // The expression that defines the value of an enumeration constant
20596 // shall be an integer constant expression that has a value
20597 // representable as an int.
20598
20599 // Complain if the value is not representable in an int.
20600 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20601 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20602 ? diag::warn_c17_compat_enum_value_not_int
20603 : diag::ext_c23_enum_value_not_int)
20604 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20605 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20606 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20607 // Force the type of the expression to 'int'.
20608 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20609 }
20610 EltTy = Val->getType();
20611 }
20612 }
20613 }
20614 }
20615
20616 if (!Val) {
20617 if (Enum->isDependentType())
20618 EltTy = Context.DependentTy;
20619 else if (!LastEnumConst) {
20620 // C++0x [dcl.enum]p5:
20621 // If the underlying type is not fixed, the type of each enumerator
20622 // is the type of its initializing value:
20623 // - If no initializer is specified for the first enumerator, the
20624 // initializing value has an unspecified integral type.
20625 //
20626 // GCC uses 'int' for its unspecified integral type, as does
20627 // C99 6.7.2.2p3.
20628 if (Enum->isFixed()) {
20629 EltTy = Enum->getIntegerType();
20630 }
20631 else {
20632 EltTy = Context.IntTy;
20633 }
20634 } else {
20635 // Assign the last value + 1.
20636 EnumVal = LastEnumConst->getInitVal();
20637 ++EnumVal;
20638 EltTy = LastEnumConst->getType();
20639
20640 // Check for overflow on increment.
20641 if (EnumVal < LastEnumConst->getInitVal()) {
20642 // C++0x [dcl.enum]p5:
20643 // If the underlying type is not fixed, the type of each enumerator
20644 // is the type of its initializing value:
20645 //
20646 // - Otherwise the type of the initializing value is the same as
20647 // the type of the initializing value of the preceding enumerator
20648 // unless the incremented value is not representable in that type,
20649 // in which case the type is an unspecified integral type
20650 // sufficient to contain the incremented value. If no such type
20651 // exists, the program is ill-formed.
20652 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20653 if (T.isNull() || Enum->isFixed()) {
20654 // There is no integral type larger enough to represent this
20655 // value. Complain, then allow the value to wrap around.
20656 EnumVal = LastEnumConst->getInitVal();
20657 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20658 ++EnumVal;
20659 if (Enum->isFixed())
20660 // When the underlying type is fixed, this is ill-formed.
20661 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20662 << toString(I: EnumVal, Radix: 10)
20663 << EltTy;
20664 else
20665 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20666 << toString(I: EnumVal, Radix: 10);
20667 } else {
20668 EltTy = T;
20669 }
20670
20671 // Retrieve the last enumerator's value, extent that type to the
20672 // type that is supposed to be large enough to represent the incremented
20673 // value, then increment.
20674 EnumVal = LastEnumConst->getInitVal();
20675 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20676 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20677 ++EnumVal;
20678
20679 // If we're not in C++, diagnose the overflow of enumerator values,
20680 // which in C99 means that the enumerator value is not representable in
20681 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20682 // are representable in some larger integral type and we allow it in
20683 // older language modes as an extension.
20684 // Exclude fixed enumerators since they are diagnosed with an error for
20685 // this case.
20686 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20687 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20688 ? diag::warn_c17_compat_enum_value_not_int
20689 : diag::ext_c23_enum_value_not_int)
20690 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20691 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20692 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20693 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20694 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20695 : diag::ext_c23_enum_value_not_int)
20696 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20697 }
20698 }
20699 }
20700
20701 if (!EltTy->isDependentType()) {
20702 // Make the enumerator value match the signedness and size of the
20703 // enumerator's type.
20704 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20705 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20706 }
20707
20708 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20709 E: Val, V: EnumVal);
20710}
20711
20712SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20713 SourceLocation IILoc) {
20714 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20715 !getLangOpts().CPlusPlus)
20716 return SkipBodyInfo();
20717
20718 // We have an anonymous enum definition. Look up the first enumerator to
20719 // determine if we should merge the definition with an existing one and
20720 // skip the body.
20721 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20722 Redecl: forRedeclarationInCurContext());
20723 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20724 if (!PrevECD)
20725 return SkipBodyInfo();
20726
20727 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20728 NamedDecl *Hidden;
20729 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20730 SkipBodyInfo Skip;
20731 Skip.Previous = Hidden;
20732 return Skip;
20733 }
20734
20735 return SkipBodyInfo();
20736}
20737
20738Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20739 SourceLocation IdLoc, IdentifierInfo *Id,
20740 const ParsedAttributesView &Attrs,
20741 SourceLocation EqualLoc, Expr *Val,
20742 SkipBodyInfo *SkipBody) {
20743 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20744 EnumConstantDecl *LastEnumConst =
20745 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20746
20747 // The scope passed in may not be a decl scope. Zip up the scope tree until
20748 // we find one that is.
20749 S = getNonFieldDeclScope(S);
20750
20751 // Verify that there isn't already something declared with this name in this
20752 // scope.
20753 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20754 RedeclarationKind::ForVisibleRedeclaration);
20755 LookupName(R, S);
20756 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20757
20758 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20759 // Maybe we will complain about the shadowed template parameter.
20760 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20761 // Just pretend that we didn't see the previous declaration.
20762 PrevDecl = nullptr;
20763 }
20764
20765 // C++ [class.mem]p15:
20766 // If T is the name of a class, then each of the following shall have a name
20767 // different from T:
20768 // - every enumerator of every member of class T that is an unscoped
20769 // enumerated type
20770 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20771 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20772 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20773 return nullptr;
20774
20775 EnumConstantDecl *New =
20776 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20777 if (!New)
20778 return nullptr;
20779
20780 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20781 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20782 // Check for other kinds of shadowing not already handled.
20783 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20784 }
20785
20786 // When in C++, we may get a TagDecl with the same name; in this case the
20787 // enum constant will 'hide' the tag.
20788 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20789 "Received TagDecl when not in C++!");
20790 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20791 if (isa<EnumConstantDecl>(Val: PrevDecl))
20792 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20793 else
20794 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20795 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20796 return nullptr;
20797 }
20798 }
20799
20800 // Process attributes.
20801 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20802 AddPragmaAttributes(S, D: New);
20803 ProcessAPINotes(D: New);
20804
20805 // Register this decl in the current scope stack.
20806 New->setAccess(TheEnumDecl->getAccess());
20807 PushOnScopeChains(D: New, S);
20808
20809 ActOnDocumentableDecl(D: New);
20810
20811 return New;
20812}
20813
20814// Returns true when the enum initial expression does not trigger the
20815// duplicate enum warning. A few common cases are exempted as follows:
20816// Element2 = Element1
20817// Element2 = Element1 + 1
20818// Element2 = Element1 - 1
20819// Where Element2 and Element1 are from the same enum.
20820static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20821 Expr *InitExpr = ECD->getInitExpr();
20822 if (!InitExpr)
20823 return true;
20824 InitExpr = InitExpr->IgnoreImpCasts();
20825
20826 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20827 if (!BO->isAdditiveOp())
20828 return true;
20829 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20830 if (!IL)
20831 return true;
20832 if (IL->getValue() != 1)
20833 return true;
20834
20835 InitExpr = BO->getLHS();
20836 }
20837
20838 // This checks if the elements are from the same enum.
20839 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20840 if (!DRE)
20841 return true;
20842
20843 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20844 if (!EnumConstant)
20845 return true;
20846
20847 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20848 Enum)
20849 return true;
20850
20851 return false;
20852}
20853
20854// Emits a warning when an element is implicitly set a value that
20855// a previous element has already been set to.
20856static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20857 EnumDecl *Enum, QualType EnumType) {
20858 // Avoid anonymous enums
20859 if (!Enum->getIdentifier())
20860 return;
20861
20862 // Only check for small enums.
20863 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20864 return;
20865
20866 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20867 return;
20868
20869 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20870 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20871
20872 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20873
20874 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20875 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20876
20877 // Use int64_t as a key to avoid needing special handling for map keys.
20878 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20879 llvm::APSInt Val = D->getInitVal();
20880 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20881 };
20882
20883 DuplicatesVector DupVector;
20884 ValueToVectorMap EnumMap;
20885
20886 // Populate the EnumMap with all values represented by enum constants without
20887 // an initializer.
20888 for (auto *Element : Elements) {
20889 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20890
20891 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20892 // this constant. Skip this enum since it may be ill-formed.
20893 if (!ECD) {
20894 return;
20895 }
20896
20897 // Constants with initializers are handled in the next loop.
20898 if (ECD->getInitExpr())
20899 continue;
20900
20901 // Duplicate values are handled in the next loop.
20902 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20903 }
20904
20905 if (EnumMap.size() == 0)
20906 return;
20907
20908 // Create vectors for any values that has duplicates.
20909 for (auto *Element : Elements) {
20910 // The last loop returned if any constant was null.
20911 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20912 if (!ValidDuplicateEnum(ECD, Enum))
20913 continue;
20914
20915 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20916 if (Iter == EnumMap.end())
20917 continue;
20918
20919 DeclOrVector& Entry = Iter->second;
20920 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20921 // Ensure constants are different.
20922 if (D == ECD)
20923 continue;
20924
20925 // Create new vector and push values onto it.
20926 auto Vec = std::make_unique<ECDVector>();
20927 Vec->push_back(Elt: D);
20928 Vec->push_back(Elt: ECD);
20929
20930 // Update entry to point to the duplicates vector.
20931 Entry = Vec.get();
20932
20933 // Store the vector somewhere we can consult later for quick emission of
20934 // diagnostics.
20935 DupVector.emplace_back(Args: std::move(Vec));
20936 continue;
20937 }
20938
20939 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20940 // Make sure constants are not added more than once.
20941 if (*Vec->begin() == ECD)
20942 continue;
20943
20944 Vec->push_back(Elt: ECD);
20945 }
20946
20947 // Emit diagnostics.
20948 for (const auto &Vec : DupVector) {
20949 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20950
20951 // Emit warning for one enum constant.
20952 auto *FirstECD = Vec->front();
20953 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20954 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20955 << FirstECD->getSourceRange();
20956
20957 // Emit one note for each of the remaining enum constants with
20958 // the same value.
20959 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20960 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20961 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20962 << ECD->getSourceRange();
20963 }
20964}
20965
20966bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20967 bool AllowMask) const {
20968 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20969 assert(ED->isCompleteDefinition() && "expected enum definition");
20970
20971 auto R = FlagBitsCache.try_emplace(Key: ED);
20972 llvm::APInt &FlagBits = R.first->second;
20973
20974 if (R.second) {
20975 for (auto *E : ED->enumerators()) {
20976 const auto &EVal = E->getInitVal();
20977 // Only single-bit enumerators introduce new flag values.
20978 if (EVal.isPowerOf2())
20979 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20980 }
20981 }
20982
20983 // A value is in a flag enum if either its bits are a subset of the enum's
20984 // flag bits (the first condition) or we are allowing masks and the same is
20985 // true of its complement (the second condition). When masks are allowed, we
20986 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20987 //
20988 // While it's true that any value could be used as a mask, the assumption is
20989 // that a mask will have all of the insignificant bits set. Anything else is
20990 // likely a logic error.
20991 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20992 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20993}
20994
20995// Emits a warning when a suspicious comparison operator is used along side
20996// binary operators in enum initializers.
20997static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20998 const EnumDecl *Enum) {
20999 bool HasBitwiseOp = false;
21000 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21001
21002 // Iterate over all the enum values, gather suspisious comparison ops and
21003 // whether any enum initialisers contain a binary operator.
21004 for (const auto *ECD : Enum->enumerators()) {
21005 const Expr *InitExpr = ECD->getInitExpr();
21006 if (!InitExpr)
21007 continue;
21008
21009 const Expr *E = InitExpr->IgnoreParenImpCasts();
21010
21011 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
21012 BinaryOperatorKind Op = BinOp->getOpcode();
21013
21014 // Check for bitwise ops (<<, >>, &, |)
21015 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21016 HasBitwiseOp = true;
21017 } else if (Op == BO_LT || Op == BO_GT) {
21018 // Check for the typo pattern (Comparison < or >)
21019 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21020 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
21021 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21022 if (IntLiteral->getValue() == 1)
21023 SuspiciousCompares.push_back(Elt: BinOp);
21024 }
21025 }
21026 }
21027 }
21028
21029 // If we found a bitwise op and some sus compares, iterate over the compares
21030 // and warn.
21031 if (HasBitwiseOp) {
21032 for (const auto *BinOp : SuspiciousCompares) {
21033 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21034 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
21035 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
21036 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21037
21038 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
21039 << BinOp->getOpcodeStr() << SuggestedOp;
21040
21041 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
21042 << SuggestedOp
21043 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
21044 }
21045 }
21046}
21047
21048void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
21049 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21050 const ParsedAttributesView &Attrs) {
21051 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
21052 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
21053
21054 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
21055 ProcessAPINotes(D: Enum);
21056
21057 if (Enum->isDependentType()) {
21058 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21059 EnumConstantDecl *ECD =
21060 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
21061 if (!ECD) continue;
21062
21063 ECD->setType(EnumType);
21064 }
21065
21066 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
21067 return;
21068 }
21069
21070 // Verify that all the values are okay, compute the size of the values, and
21071 // reverse the list.
21072 unsigned NumNegativeBits = 0;
21073 unsigned NumPositiveBits = 0;
21074 bool MembersRepresentableByInt =
21075 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21076
21077 // Figure out the type that should be used for this enum.
21078 QualType BestType;
21079 unsigned BestWidth;
21080
21081 // C++0x N3000 [conv.prom]p3:
21082 // An rvalue of an unscoped enumeration type whose underlying
21083 // type is not fixed can be converted to an rvalue of the first
21084 // of the following types that can represent all the values of
21085 // the enumeration: int, unsigned int, long int, unsigned long
21086 // int, long long int, or unsigned long long int.
21087 // C99 6.4.4.3p2:
21088 // An identifier declared as an enumeration constant has type int.
21089 // The C99 rule is modified by C23.
21090 QualType BestPromotionType;
21091
21092 bool Packed = Enum->hasAttr<PackedAttr>();
21093 // -fshort-enums is the equivalent to specifying the packed attribute on all
21094 // enum definitions.
21095 if (LangOpts.ShortEnums)
21096 Packed = true;
21097
21098 // If the enum already has a type because it is fixed or dictated by the
21099 // target, promote that type instead of analyzing the enumerators.
21100 if (Enum->isComplete()) {
21101 BestType = Enum->getIntegerType();
21102 if (Context.isPromotableIntegerType(T: BestType))
21103 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21104 else
21105 BestPromotionType = BestType;
21106
21107 BestWidth = Context.getIntWidth(T: BestType);
21108 } else {
21109 bool EnumTooLarge = Context.computeBestEnumTypes(
21110 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21111 BestWidth = Context.getIntWidth(T: BestType);
21112 if (EnumTooLarge)
21113 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21114 }
21115
21116 // Loop over all of the enumerator constants, changing their types to match
21117 // the type of the enum if needed.
21118 for (auto *D : Elements) {
21119 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21120 if (!ECD) continue; // Already issued a diagnostic.
21121
21122 // C99 says the enumerators have int type, but we allow, as an
21123 // extension, the enumerators to be larger than int size. If each
21124 // enumerator value fits in an int, type it as an int, otherwise type it the
21125 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21126 // that X has type 'int', not 'unsigned'.
21127
21128 // Determine whether the value fits into an int.
21129 llvm::APSInt InitVal = ECD->getInitVal();
21130
21131 // If it fits into an integer type, force it. Otherwise force it to match
21132 // the enum decl type.
21133 QualType NewTy;
21134 unsigned NewWidth;
21135 bool NewSign;
21136 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21137 MembersRepresentableByInt) {
21138 // C23 6.7.3.3.3p15:
21139 // The enumeration member type for an enumerated type without fixed
21140 // underlying type upon completion is:
21141 // - int if all the values of the enumeration are representable as an
21142 // int; or,
21143 // - the enumerated type
21144 NewTy = Context.IntTy;
21145 NewWidth = Context.getTargetInfo().getIntWidth();
21146 NewSign = true;
21147 } else if (ECD->getType() == BestType) {
21148 // Already the right type!
21149 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21150 // C++ [dcl.enum]p4: Following the closing brace of an
21151 // enum-specifier, each enumerator has the type of its
21152 // enumeration.
21153 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21154 // with fixed underlying type is the enumerated type.
21155 ECD->setType(EnumType);
21156 continue;
21157 } else {
21158 NewTy = BestType;
21159 NewWidth = BestWidth;
21160 NewSign = BestType->isSignedIntegerOrEnumerationType();
21161 }
21162
21163 // Adjust the APSInt value.
21164 InitVal = InitVal.extOrTrunc(width: NewWidth);
21165 InitVal.setIsSigned(NewSign);
21166 ECD->setInitVal(C: Context, V: InitVal);
21167
21168 // Adjust the Expr initializer and type.
21169 if (ECD->getInitExpr() &&
21170 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21171 ECD->setInitExpr(ImplicitCastExpr::Create(
21172 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21173 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21174 if (getLangOpts().CPlusPlus ||
21175 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21176 // C++ [dcl.enum]p4: Following the closing brace of an
21177 // enum-specifier, each enumerator has the type of its
21178 // enumeration.
21179 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21180 // with fixed underlying type is the enumerated type.
21181 ECD->setType(EnumType);
21182 else
21183 ECD->setType(NewTy);
21184 }
21185
21186 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21187 NumPositiveBits, NumNegativeBits);
21188
21189 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21190 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21191
21192 if (Enum->isClosedFlag()) {
21193 for (Decl *D : Elements) {
21194 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21195 if (!ECD) continue; // Already issued a diagnostic.
21196
21197 llvm::APSInt InitVal = ECD->getInitVal();
21198 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21199 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21200 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21201 << ECD << Enum;
21202 }
21203 }
21204
21205 // Now that the enum type is defined, ensure it's not been underaligned.
21206 if (Enum->hasAttrs())
21207 CheckAlignasUnderalignment(D: Enum);
21208}
21209
21210Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21211 SourceLocation EndLoc) {
21212
21213 FileScopeAsmDecl *New =
21214 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21215 CurContext->addDecl(D: New);
21216 return New;
21217}
21218
21219TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21220 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21221 CurContext->addDecl(D: New);
21222 PushDeclContext(S, DC: New);
21223 PushFunctionScope();
21224 PushCompoundScope(IsStmtExpr: false);
21225 return New;
21226}
21227
21228void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21229 if (Statement)
21230 D->setStmt(Statement);
21231 PopCompoundScope();
21232 PopFunctionScopeInfo();
21233 PopDeclContext();
21234}
21235
21236void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21237 IdentifierInfo* AliasName,
21238 SourceLocation PragmaLoc,
21239 SourceLocation NameLoc,
21240 SourceLocation AliasNameLoc) {
21241 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21242 NameKind: LookupOrdinaryName);
21243 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21244 AttributeCommonInfo::Form::Pragma());
21245 AsmLabelAttr *Attr =
21246 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21247
21248 // If a declaration that:
21249 // 1) declares a function or a variable
21250 // 2) has external linkage
21251 // already exists, add a label attribute to it.
21252 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21253 if (isDeclExternC(D: PrevDecl))
21254 PrevDecl->addAttr(A: Attr);
21255 else
21256 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21257 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21258 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21259 } else
21260 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21261}
21262
21263void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21264 SourceLocation PragmaLoc,
21265 SourceLocation NameLoc) {
21266 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21267
21268 if (PrevDecl) {
21269 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21270 } else {
21271 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21272 }
21273}
21274
21275void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21276 IdentifierInfo* AliasName,
21277 SourceLocation PragmaLoc,
21278 SourceLocation NameLoc,
21279 SourceLocation AliasNameLoc) {
21280 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21281 NameKind: LookupOrdinaryName);
21282 WeakInfo W = WeakInfo(Name, NameLoc);
21283
21284 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21285 if (!PrevDecl->hasAttr<AliasAttr>())
21286 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21287 DeclApplyPragmaWeak(S: TUScope, ND, W);
21288 } else {
21289 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21290 }
21291}
21292
21293Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21294 bool Final) {
21295 assert(FD && "Expected non-null FunctionDecl");
21296
21297 // Templates are emitted when they're instantiated.
21298 if (FD->isDependentContext())
21299 return FunctionEmissionStatus::TemplateDiscarded;
21300
21301 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21302 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21303 FD->hasAttr<SYCLExternalAttr>()))
21304 return FunctionEmissionStatus::Emitted;
21305
21306 // Check whether this function is an externally visible definition.
21307 auto IsEmittedForExternalSymbol = [this, FD]() {
21308 // We have to check the GVA linkage of the function's *definition* -- if we
21309 // only have a declaration, we don't know whether or not the function will
21310 // be emitted, because (say) the definition could include "inline".
21311 const FunctionDecl *Def = FD->getDefinition();
21312
21313 // We can't compute linkage when we skip function bodies.
21314 return Def && !Def->hasSkippedBody() &&
21315 !isDiscardableGVALinkage(
21316 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21317 };
21318
21319 if (LangOpts.OpenMPIsTargetDevice) {
21320 // In OpenMP device mode we will not emit host only functions, or functions
21321 // we don't need due to their linkage.
21322 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21323 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21324 // DevTy may be changed later by
21325 // #pragma omp declare target to(*) device_type(*).
21326 // Therefore DevTy having no value does not imply host. The emission status
21327 // will be checked again at the end of compilation unit with Final = true.
21328 if (DevTy)
21329 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21330 return FunctionEmissionStatus::OMPDiscarded;
21331 // If we have an explicit value for the device type, or we are in a target
21332 // declare context, we need to emit all extern and used symbols.
21333 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21334 if (IsEmittedForExternalSymbol())
21335 return FunctionEmissionStatus::Emitted;
21336 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21337 // we'll omit it.
21338 if (Final)
21339 return FunctionEmissionStatus::OMPDiscarded;
21340 } else if (LangOpts.OpenMP > 45) {
21341 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21342 // function. In 5.0, no_host was introduced which might cause a function to
21343 // be omitted.
21344 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21345 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21346 if (DevTy)
21347 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21348 return FunctionEmissionStatus::OMPDiscarded;
21349 }
21350
21351 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21352 return FunctionEmissionStatus::Emitted;
21353
21354 if (LangOpts.CUDA) {
21355 // When compiling for device, host functions are never emitted. Similarly,
21356 // when compiling for host, device and global functions are never emitted.
21357 // (Technically, we do emit a host-side stub for global functions, but this
21358 // doesn't count for our purposes here.)
21359 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21360 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21361 return FunctionEmissionStatus::CUDADiscarded;
21362 if (!LangOpts.CUDAIsDevice &&
21363 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21364 return FunctionEmissionStatus::CUDADiscarded;
21365
21366 if (IsEmittedForExternalSymbol())
21367 return FunctionEmissionStatus::Emitted;
21368 }
21369
21370 // Otherwise, the function is known-emitted if it's in our set of
21371 // known-emitted functions.
21372 return FunctionEmissionStatus::Unknown;
21373}
21374
21375bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21376 // Host-side references to a __global__ function refer to the stub, so the
21377 // function itself is never emitted and therefore should not be marked.
21378 // If we have host fn calls kernel fn calls host+device, the HD function
21379 // does not get instantiated on the host. We model this by omitting at the
21380 // call to the kernel from the callgraph. This ensures that, when compiling
21381 // for host, only HD functions actually called from the host get marked as
21382 // known-emitted.
21383 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21384 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21385}
21386
21387bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21388 bool &Visible) {
21389 Visible = hasVisibleDefinition(D, Suggested);
21390 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21391 // for declaratins which is attached to named modules.
21392 // We only did this if the current module is named module as we have better
21393 // diagnostics for declarations in global module and named modules.
21394 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21395 D->isInNamedModule())
21396 return false;
21397 // The redefinition of D in the **current** TU is allowed if D is invisible or
21398 // D is defined in the global module of other module units.
21399 return D->isInAnotherModuleUnit() || !Visible;
21400}
21401