1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NonTrivialTypeVisitor.h"
28#include "clang/AST/Randstruct.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/DiagnosticComment.h"
33#include "clang/Basic/HLSLRuntime.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/CXXFieldCollector.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/DelayedDiagnostic.h"
44#include "clang/Sema/Initialization.h"
45#include "clang/Sema/Lookup.h"
46#include "clang/Sema/ParsedTemplate.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/SemaARM.h"
50#include "clang/Sema/SemaCUDA.h"
51#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaInternal.h"
53#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaOpenACC.h"
55#include "clang/Sema/SemaOpenMP.h"
56#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaRISCV.h"
58#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaSwift.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/Template.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallString.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/ADT/StringRef.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/TargetParser/Triple.h"
71#include <algorithm>
72#include <cstring>
73#include <optional>
74#include <unordered_map>
75
76using namespace clang;
77using namespace sema;
78
79Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
80 if (OwnedType) {
81 Decl *Group[2] = { OwnedType, Ptr };
82 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
83 }
84
85 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
86}
87
88namespace {
89
90class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
91 public:
92 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
93 bool AllowTemplates = false,
94 bool AllowNonTemplates = true)
95 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
96 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
97 WantExpressionKeywords = false;
98 WantCXXNamedCasts = false;
99 WantRemainingKeywords = false;
100 }
101
102 bool ValidateCandidate(const TypoCorrection &candidate) override {
103 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
104 if (!AllowInvalidDecl && ND->isInvalidDecl())
105 return false;
106
107 if (getAsTypeTemplateDecl(D: ND))
108 return AllowTemplates;
109
110 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
111 if (!IsType)
112 return false;
113
114 if (AllowNonTemplates)
115 return true;
116
117 // An injected-class-name of a class template (specialization) is valid
118 // as a template or as a non-template.
119 if (AllowTemplates) {
120 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
121 if (!RD || !RD->isInjectedClassName())
122 return false;
123 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
124 return RD->getDescribedClassTemplate() ||
125 isa<ClassTemplateSpecializationDecl>(Val: RD);
126 }
127
128 return false;
129 }
130
131 return !WantClassName && candidate.isKeyword();
132 }
133
134 std::unique_ptr<CorrectionCandidateCallback> clone() override {
135 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
136 }
137
138 private:
139 bool AllowInvalidDecl;
140 bool WantClassName;
141 bool AllowTemplates;
142 bool AllowNonTemplates;
143};
144
145} // end anonymous namespace
146
147void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
148 TypeDecl *TD, SourceLocation NameLoc) {
149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
150 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
151 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
152 FoundRD->isInjectedClassName() &&
153 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
154 Diag(Loc: NameLoc,
155 DiagID: DCK == DiagCtorKind::Typename
156 ? diag::ext_out_of_line_qualified_id_type_names_constructor
157 : diag::err_out_of_line_qualified_id_type_names_constructor)
158 << TD->getIdentifier() << /*Type=*/1
159 << 0 /*if any keyword was present, it was 'typename'*/;
160 }
161
162 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
163 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
164}
165
166namespace {
167enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171};
172} // end anonymous namespace
173
174/// Tries to perform unqualified lookup of the type decls in bases for
175/// dependent class.
176/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177/// type decl, \a FoundType if only type decls are found.
178static UnqualifiedTypeNameLookupResult
179lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
189 if (BaseRD) {
190 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
191 Val: Base.getType().getCanonicalType())) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
204 if (const ClassTemplatePartialSpecializationDecl *PS =
205 CTD->findPartialSpecialization(T: Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
213 if (!isa<TypeDecl>(Val: ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232}
233
234static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(Val: DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
255 // allowed. We'll fully resolve the lookup during template instantiation.
256 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
257
258 ASTContext &Context = S.Context;
259 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
260 QualType T =
261 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
269 DepTL.setElaboratedKeywordLoc(SourceLocation());
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
272}
273
274ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275 Scope *S, CXXScopeSpec *SS, bool isClassName,
276 bool HasTrailingDot, ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 ImplicitTypenameContext AllowImplicitTypename,
281 IdentifierInfo **CorrectedII) {
282 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
283 // FIXME: Consider allowing this outside C++1z mode as an extension.
284 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
285 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
286 !HasTrailingDot;
287
288 // Determine where we will perform name lookup.
289 DeclContext *LookupCtx = nullptr;
290 if (ObjectTypePtr) {
291 QualType ObjectType = ObjectTypePtr.get();
292 if (ObjectType->isRecordType())
293 LookupCtx = computeDeclContext(T: ObjectType);
294 } else if (SS && SS->isNotEmpty()) {
295 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
296
297 if (!LookupCtx) {
298 if (isDependentScopeSpecifier(SS: *SS)) {
299 // C++ [temp.res]p3:
300 // A qualified-id that refers to a type and in which the
301 // nested-name-specifier depends on a template-parameter (14.6.2)
302 // shall be prefixed by the keyword typename to indicate that the
303 // qualified-id denotes a type, forming an
304 // elaborated-type-specifier (7.1.5.3).
305 //
306 // We therefore do not perform any name lookup if the result would
307 // refer to a member of an unknown specialization.
308 // In C++2a, in several contexts a 'typename' is not required. Also
309 // allow this as an extension.
310 if (IsImplicitTypename) {
311 if (AllowImplicitTypename == ImplicitTypenameContext::No)
312 return nullptr;
313 SourceLocation QualifiedLoc = SS->getRange().getBegin();
314 // FIXME: Defer the diagnostic after we build the type and use it.
315 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
316 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
317 NNS: SS->getScopeRep(), Name: &II);
318 if (!getLangOpts().CPlusPlus20)
319 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
320 }
321
322 // We know from the grammar that this name refers to a type,
323 // so build a dependent node to describe the type.
324 if (WantNontrivialTypeSourceInfo)
325 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
326 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
327 .get();
328
329 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
330 QualType T = CheckTypenameType(
331 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
332 : ElaboratedTypeKeyword::None,
333 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
334 return ParsedType::make(P: T);
335 }
336
337 return nullptr;
338 }
339
340 if (!LookupCtx->isDependentContext() &&
341 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
342 return nullptr;
343 }
344
345 // In the case where we know that the identifier is a class name, we know that
346 // it is a type declaration (struct, class, union or enum) so we can use tag
347 // name lookup.
348 //
349 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
350 // the component name of the type-name or simple-template-id is type-only.
351 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
352 LookupResult Result(*this, &II, NameLoc, Kind);
353 if (LookupCtx) {
354 // Perform "qualified" name lookup into the declaration context we
355 // computed, which is either the type of the base of a member access
356 // expression or the declaration context associated with a prior
357 // nested-name-specifier.
358 LookupQualifiedName(R&: Result, LookupCtx);
359
360 if (ObjectTypePtr && Result.empty()) {
361 // C++ [basic.lookup.classref]p3:
362 // If the unqualified-id is ~type-name, the type-name is looked up
363 // in the context of the entire postfix-expression. If the type T of
364 // the object expression is of a class type C, the type-name is also
365 // looked up in the scope of class C. At least one of the lookups shall
366 // find a name that refers to (possibly cv-qualified) T.
367 LookupName(R&: Result, S);
368 }
369 } else {
370 // Perform unqualified name lookup.
371 LookupName(R&: Result, S);
372
373 // For unqualified lookup in a class template in MSVC mode, look into
374 // dependent base classes where the primary class template is known.
375 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
376 if (ParsedType TypeInBase =
377 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
378 return TypeInBase;
379 }
380 }
381
382 NamedDecl *IIDecl = nullptr;
383 UsingShadowDecl *FoundUsingShadow = nullptr;
384 switch (Result.getResultKind()) {
385 case LookupResultKind::NotFound:
386 if (CorrectedII) {
387 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
388 AllowDeducedTemplate);
389 TypoCorrection Correction =
390 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
391 Mode: CorrectTypoKind::ErrorRecovery);
392 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
393 TemplateTy Template;
394 bool MemberOfUnknownSpecialization;
395 UnqualifiedId TemplateName;
396 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
397 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
398 CXXScopeSpec NewSS, *NewSSPtr = SS;
399 if (SS && NNS) {
400 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
401 NewSSPtr = &NewSS;
402 }
403 if (Correction && (NNS || NewII != &II) &&
404 // Ignore a correction to a template type as the to-be-corrected
405 // identifier is not a template (typo correction for template names
406 // is handled elsewhere).
407 !(getLangOpts().CPlusPlus && NewSSPtr &&
408 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
409 Template, MemberOfUnknownSpecialization))) {
410 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
411 isClassName, HasTrailingDot, ObjectTypePtr,
412 IsCtorOrDtorName,
413 WantNontrivialTypeSourceInfo,
414 IsClassTemplateDeductionContext);
415 if (Ty) {
416 diagnoseTypo(Correction,
417 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
418 << Result.getLookupName() << isClassName);
419 if (SS && NNS)
420 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
421 *CorrectedII = NewII;
422 return Ty;
423 }
424 }
425 }
426 Result.suppressDiagnostics();
427 return nullptr;
428 case LookupResultKind::NotFoundInCurrentInstantiation:
429 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
430 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
431 NNS: SS->getScopeRep(), Name: &II);
432 TypeLocBuilder TLB;
433 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
434 TL.setElaboratedKeywordLoc(SourceLocation());
435 TL.setQualifierLoc(SS->getWithLocInContext(Context));
436 TL.setNameLoc(NameLoc);
437 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
438 }
439 [[fallthrough]];
440 case LookupResultKind::FoundOverloaded:
441 case LookupResultKind::FoundUnresolvedValue:
442 Result.suppressDiagnostics();
443 return nullptr;
444
445 case LookupResultKind::Ambiguous:
446 // Recover from type-hiding ambiguities by hiding the type. We'll
447 // do the lookup again when looking for an object, and we can
448 // diagnose the error then. If we don't do this, then the error
449 // about hiding the type will be immediately followed by an error
450 // that only makes sense if the identifier was treated like a type.
451 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
452 Result.suppressDiagnostics();
453 return nullptr;
454 }
455
456 // Look to see if we have a type anywhere in the list of results.
457 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
458 Res != ResEnd; ++Res) {
459 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
460 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
461 Val: RealRes) ||
462 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
463 if (!IIDecl ||
464 // Make the selection of the recovery decl deterministic.
465 RealRes->getLocation() < IIDecl->getLocation()) {
466 IIDecl = RealRes;
467 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
468 }
469 }
470 }
471
472 if (!IIDecl) {
473 // None of the entities we found is a type, so there is no way
474 // to even assume that the result is a type. In this case, don't
475 // complain about the ambiguity. The parser will either try to
476 // perform this lookup again (e.g., as an object name), which
477 // will produce the ambiguity, or will complain that it expected
478 // a type name.
479 Result.suppressDiagnostics();
480 return nullptr;
481 }
482
483 // We found a type within the ambiguous lookup; diagnose the
484 // ambiguity and then return that type. This might be the right
485 // answer, or it might not be, but it suppresses any attempt to
486 // perform the name lookup again.
487 break;
488
489 case LookupResultKind::Found:
490 IIDecl = Result.getFoundDecl();
491 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
492 break;
493 }
494
495 assert(IIDecl && "Didn't find decl");
496
497 TypeLocBuilder TLB;
498 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
499 checkTypeDeclType(LookupCtx,
500 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
501 : DiagCtorKind::None,
502 TD, NameLoc);
503 QualType T;
504 if (FoundUsingShadow) {
505 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
506 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
507 D: FoundUsingShadow);
508 if (!WantNontrivialTypeSourceInfo)
509 return ParsedType::make(P: T);
510 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
511 QualifierLoc: SS ? SS->getWithLocInContext(Context)
512 : NestedNameSpecifierLoc(),
513 NameLoc);
514 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
515 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
516 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
517 /*OwnsTag=*/false);
518 if (!WantNontrivialTypeSourceInfo)
519 return ParsedType::make(P: T);
520 auto TL = TLB.push<TagTypeLoc>(T);
521 TL.setElaboratedKeywordLoc(SourceLocation());
522 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
523 : NestedNameSpecifierLoc());
524 TL.setNameLoc(NameLoc);
525 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
526 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
527 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
528 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
529 if (!WantNontrivialTypeSourceInfo)
530 return ParsedType::make(P: T);
531 TLB.push<TypedefTypeLoc>(T).set(
532 /*ElaboratedKeywordLoc=*/SourceLocation(),
533 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
534 NameLoc);
535 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
536 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
537 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
538 D: UD);
539 if (!WantNontrivialTypeSourceInfo)
540 return ParsedType::make(P: T);
541 TLB.push<UnresolvedUsingTypeLoc>(T).set(
542 /*ElaboratedKeywordLoc=*/SourceLocation(),
543 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
544 NameLoc);
545 } else {
546 T = Context.getTypeDeclType(Decl: TD);
547 if (!WantNontrivialTypeSourceInfo)
548 return ParsedType::make(P: T);
549 if (isa<ObjCTypeParamType>(Val: T))
550 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
551 else
552 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
553 }
554 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
555 }
556 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
557 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
558 if (!HasTrailingDot) {
559 // FIXME: Support UsingType for this case.
560 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
561 if (!WantNontrivialTypeSourceInfo)
562 return ParsedType::make(P: T);
563 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
564 TL.setNameLoc(NameLoc);
565 // FIXME: Pass in this source location.
566 TL.setNameEndLoc(NameLoc);
567 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
568 }
569 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
570 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
571 // Recover with 'int'
572 return ParsedType::make(P: Context.IntTy);
573 } else if (AllowDeducedTemplate) {
574 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
575 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
576 // FIXME: Support UsingType here.
577 TemplateName Template = Context.getQualifiedTemplateName(
578 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
579 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
580 QualType T = Context.getDeducedTemplateSpecializationType(
581 Keyword: ElaboratedTypeKeyword::None, Template, DeducedType: QualType(), IsDependent: false);
582 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
583 TL.setElaboratedKeywordLoc(SourceLocation());
584 TL.setNameLoc(NameLoc);
585 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
586 : NestedNameSpecifierLoc());
587 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
588 }
589 }
590
591 // As it's not plausibly a type, suppress diagnostics.
592 Result.suppressDiagnostics();
593 return nullptr;
594}
595
596// Builds a fake NNS for the given decl context.
597static NestedNameSpecifier
598synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
599 for (;; DC = DC->getLookupParent()) {
600 DC = DC->getPrimaryContext();
601 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
602 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
603 return NestedNameSpecifier(Context, ND, std::nullopt);
604 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
605 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
606 if (isa<TranslationUnitDecl>(Val: DC))
607 return NestedNameSpecifier::getGlobal();
608 }
609 llvm_unreachable("something isn't in TU scope?");
610}
611
612/// Find the parent class with dependent bases of the innermost enclosing method
613/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
614/// up allowing unqualified dependent type names at class-level, which MSVC
615/// correctly rejects.
616static const CXXRecordDecl *
617findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
618 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
619 DC = DC->getPrimaryContext();
620 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
621 if (MD->getParent()->hasAnyDependentBases())
622 return MD->getParent();
623 }
624 return nullptr;
625}
626
627ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
628 SourceLocation NameLoc,
629 bool IsTemplateTypeArg) {
630 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
631
632 NestedNameSpecifier NNS = std::nullopt;
633 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
634 // If we weren't able to parse a default template argument, delay lookup
635 // until instantiation time by making a non-dependent DependentTypeName. We
636 // pretend we saw a NestedNameSpecifier referring to the current scope, and
637 // lookup is retried.
638 // FIXME: This hurts our diagnostic quality, since we get errors like "no
639 // type named 'Foo' in 'current_namespace'" when the user didn't write any
640 // name specifiers.
641 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
642 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
643 } else if (const CXXRecordDecl *RD =
644 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
645 // Build a DependentNameType that will perform lookup into RD at
646 // instantiation time.
647 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
648
649 // Diagnose that this identifier was undeclared, and retry the lookup during
650 // template instantiation.
651 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
652 << RD;
653 } else {
654 // This is not a situation that we should recover from.
655 return ParsedType();
656 }
657
658 QualType T =
659 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
660
661 // Build type location information. We synthesized the qualifier, so we have
662 // to build a fake NestedNameSpecifierLoc.
663 NestedNameSpecifierLocBuilder NNSLocBuilder;
664 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
665 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
666
667 TypeLocBuilder Builder;
668 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
669 DepTL.setNameLoc(NameLoc);
670 DepTL.setElaboratedKeywordLoc(SourceLocation());
671 DepTL.setQualifierLoc(QualifierLoc);
672 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
673}
674
675DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
676 // Do a tag name lookup in this scope.
677 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
678 LookupName(R, S, AllowBuiltinCreation: false);
679 R.suppressDiagnostics();
680 if (R.getResultKind() == LookupResultKind::Found)
681 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
682 switch (TD->getTagKind()) {
683 case TagTypeKind::Struct:
684 return DeclSpec::TST_struct;
685 case TagTypeKind::Interface:
686 return DeclSpec::TST_interface;
687 case TagTypeKind::Union:
688 return DeclSpec::TST_union;
689 case TagTypeKind::Class:
690 return DeclSpec::TST_class;
691 case TagTypeKind::Enum:
692 return DeclSpec::TST_enum;
693 }
694 }
695
696 return DeclSpec::TST_unspecified;
697}
698
699bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
700 if (!CurContext->isRecord())
701 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
702
703 switch (SS->getScopeRep().getKind()) {
704 case NestedNameSpecifier::Kind::MicrosoftSuper:
705 return true;
706 case NestedNameSpecifier::Kind::Type: {
707 QualType T(SS->getScopeRep().getAsType(), 0);
708 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
709 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
710 return true;
711 [[fallthrough]];
712 }
713 default:
714 return S->isFunctionPrototypeScope();
715 }
716}
717
718void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
719 SourceLocation IILoc,
720 Scope *S,
721 CXXScopeSpec *SS,
722 ParsedType &SuggestedType,
723 bool IsTemplateName) {
724 // Don't report typename errors for editor placeholders.
725 if (II->isEditorPlaceholder())
726 return;
727 // We don't have anything to suggest (yet).
728 SuggestedType = nullptr;
729
730 // There may have been a typo in the name of the type. Look up typo
731 // results, in case we have something that we can suggest.
732 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
733 /*AllowTemplates=*/IsTemplateName,
734 /*AllowNonTemplates=*/!IsTemplateName);
735 if (TypoCorrection Corrected =
736 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
737 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
738 // FIXME: Support error recovery for the template-name case.
739 bool CanRecover = !IsTemplateName;
740 if (Corrected.isKeyword()) {
741 // We corrected to a keyword.
742 diagnoseTypo(Correction: Corrected,
743 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
744 : diag::err_unknown_typename_suggest)
745 << II);
746 II = Corrected.getCorrectionAsIdentifierInfo();
747 } else {
748 // We found a similarly-named type or interface; suggest that.
749 if (!SS || !SS->isSet()) {
750 diagnoseTypo(Correction: Corrected,
751 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
752 : diag::err_unknown_typename_suggest)
753 << II, ErrorRecovery: CanRecover);
754 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
755 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
756 bool DroppedSpecifier =
757 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
758 diagnoseTypo(Correction: Corrected,
759 TypoDiag: PDiag(DiagID: IsTemplateName
760 ? diag::err_no_member_template_suggest
761 : diag::err_unknown_nested_typename_suggest)
762 << II << DC << DroppedSpecifier << SS->getRange(),
763 ErrorRecovery: CanRecover);
764 } else {
765 llvm_unreachable("could not have corrected a typo here");
766 }
767
768 if (!CanRecover)
769 return;
770
771 CXXScopeSpec tmpSS;
772 if (Corrected.getCorrectionSpecifier())
773 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
774 R: SourceRange(IILoc));
775 // FIXME: Support class template argument deduction here.
776 SuggestedType =
777 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
778 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
779 /*IsCtorOrDtorName=*/false,
780 /*WantNontrivialTypeSourceInfo=*/true);
781 }
782 return;
783 }
784
785 if (getLangOpts().CPlusPlus && !IsTemplateName) {
786 // See if II is a class template that the user forgot to pass arguments to.
787 UnqualifiedId Name;
788 Name.setIdentifier(Id: II, IdLoc: IILoc);
789 CXXScopeSpec EmptySS;
790 TemplateTy TemplateResult;
791 bool MemberOfUnknownSpecialization;
792 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
793 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
794 MemberOfUnknownSpecialization) == TNK_Type_template) {
795 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
796 return;
797 }
798 }
799
800 // FIXME: Should we move the logic that tries to recover from a missing tag
801 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
802
803 if (!SS || (!SS->isSet() && !SS->isInvalid()))
804 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
805 : diag::err_unknown_typename)
806 << II;
807 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
808 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
809 : diag::err_typename_nested_not_found)
810 << II << DC << SS->getRange();
811 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
812 SuggestedType =
813 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
814 } else if (isDependentScopeSpecifier(SS: *SS)) {
815 unsigned DiagID = diag::err_typename_missing;
816 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
817 DiagID = diag::ext_typename_missing;
818
819 SuggestedType =
820 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
821
822 Diag(Loc: SS->getRange().getBegin(), DiagID)
823 << GetTypeFromParser(Ty: SuggestedType)
824 << SourceRange(SS->getRange().getBegin(), IILoc)
825 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
826 } else {
827 assert(SS && SS->isInvalid() &&
828 "Invalid scope specifier has already been diagnosed");
829 }
830}
831
832/// Determine whether the given result set contains either a type name
833/// or
834static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
835 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
836 NextToken.is(K: tok::less);
837
838 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
839 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
840 return true;
841
842 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
843 return true;
844 }
845
846 return false;
847}
848
849static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
850 Scope *S, CXXScopeSpec &SS,
851 IdentifierInfo *&Name,
852 SourceLocation NameLoc) {
853 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
854 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
855 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
856 StringRef FixItTagName;
857 switch (Tag->getTagKind()) {
858 case TagTypeKind::Class:
859 FixItTagName = "class ";
860 break;
861
862 case TagTypeKind::Enum:
863 FixItTagName = "enum ";
864 break;
865
866 case TagTypeKind::Struct:
867 FixItTagName = "struct ";
868 break;
869
870 case TagTypeKind::Interface:
871 FixItTagName = "__interface ";
872 break;
873
874 case TagTypeKind::Union:
875 FixItTagName = "union ";
876 break;
877 }
878
879 StringRef TagName = FixItTagName.drop_back();
880 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
881 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
882 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
883
884 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
885 I != IEnd; ++I)
886 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
887 << Name << TagName;
888
889 // Replace lookup results with just the tag decl.
890 Result.clear(Kind: Sema::LookupTagName);
891 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
892 return true;
893 }
894
895 return false;
896}
897
898Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
899 IdentifierInfo *&Name,
900 SourceLocation NameLoc,
901 const Token &NextToken,
902 CorrectionCandidateCallback *CCC) {
903 DeclarationNameInfo NameInfo(Name, NameLoc);
904 ObjCMethodDecl *CurMethod = getCurMethodDecl();
905
906 assert(NextToken.isNot(tok::coloncolon) &&
907 "parse nested name specifiers before calling ClassifyName");
908 if (getLangOpts().CPlusPlus && SS.isSet() &&
909 isCurrentClassName(II: *Name, S, SS: &SS)) {
910 // Per [class.qual]p2, this names the constructors of SS, not the
911 // injected-class-name. We don't have a classification for that.
912 // There's not much point caching this result, since the parser
913 // will reject it later.
914 return NameClassification::Unknown();
915 }
916
917 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
918 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
919 /*AllowBuiltinCreation=*/!CurMethod);
920
921 if (SS.isInvalid())
922 return NameClassification::Error();
923
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927 if (ParsedType TypeInBase =
928 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
929 return TypeInBase;
930 }
931
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
937 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
938 if (Ivar.isInvalid())
939 return NameClassification::Error();
940 if (Ivar.isUsable())
941 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
942
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
944 if (Result.empty())
945 LookupBuiltin(R&: Result);
946 }
947
948 bool SecondTry = false;
949 bool IsFilteredTemplateName = false;
950
951Corrected:
952 switch (Result.getResultKind()) {
953 case LookupResultKind::NotFound:
954 // If an unqualified-id is followed by a '(', then we have a function
955 // call.
956 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
957 // In C++, this is an ADL-only call.
958 // FIXME: Reference?
959 if (getLangOpts().CPlusPlus)
960 return NameClassification::UndeclaredNonType();
961
962 // C90 6.3.2.2:
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
968 //
969 // extern int identifier ();
970 //
971 // appeared.
972 //
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
975 // be supported.
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
978 return NameClassification::NonType(D);
979 }
980 }
981
982 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
985 //
986 // FIXME: Find a way to still do typo correction in this case.
987 TemplateName Template =
988 Context.getAssumedTemplateName(Name: NameInfo.getName());
989 return NameClassification::UndeclaredTemplate(Name: Template);
990 }
991
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus && !SecondTry &&
996 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
997 break;
998 }
999
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry && CCC) {
1003 SecondTry = true;
1004 if (TypoCorrection Corrected =
1005 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1006 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1007 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008 unsigned QualifiedDiag = diag::err_no_member_suggest;
1009
1010 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1013 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1014 UnqualifiedDiag = diag::err_no_template_suggest;
1015 QualifiedDiag = diag::err_no_member_template_suggest;
1016 } else if (UnderlyingFirstDecl &&
1017 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1018 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1019 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1020 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022 }
1023
1024 if (SS.isEmpty()) {
1025 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1028 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029 Name->getName() == CorrectedStr;
1030 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1031 << Name << computeDeclContext(SS, EnteringContext: false)
1032 << DroppedSpecifier << SS.getRange());
1033 }
1034
1035 // Update the name, so that the caller has the new name.
1036 Name = Corrected.getCorrectionAsIdentifierInfo();
1037
1038 // Typo correction corrected to a keyword.
1039 if (Corrected.isKeyword())
1040 return Name;
1041
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1044 Result.clear();
1045 Result.setLookupName(Corrected.getCorrection());
1046 if (FirstDecl)
1047 Result.addDecl(D: FirstDecl);
1048
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054 DeclResult R =
1055 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1056 if (R.isInvalid())
1057 return NameClassification::Error();
1058 if (R.isUsable())
1059 return NameClassification::NonType(D: Ivar);
1060 }
1061
1062 goto Corrected;
1063 }
1064 }
1065
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result.suppressDiagnostics();
1068 return NameClassification::Unknown();
1069
1070 case LookupResultKind::NotFoundInCurrentInstantiation: {
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1074
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1080 //
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1084 // keyword here.
1085 return NameClassification::DependentNonType();
1086 }
1087
1088 case LookupResultKind::Found:
1089 case LookupResultKind::FoundOverloaded:
1090 case LookupResultKind::FoundUnresolvedValue:
1091 break;
1092
1093 case LookupResultKind::Ambiguous:
1094 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1095 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1104 // ambiguous.
1105 //
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1108 FilterAcceptableTemplateNames(R&: Result);
1109 if (!Result.isAmbiguous()) {
1110 IsFilteredTemplateName = true;
1111 break;
1112 }
1113 }
1114
1115 // Diagnose the ambiguity and return an error.
1116 return NameClassification::Error();
1117 }
1118
1119 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1120 (IsFilteredTemplateName ||
1121 hasAnyAcceptableTemplateNames(
1122 R&: Result, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1125 getLangOpts().CPlusPlus20))) {
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName)
1137 FilterAcceptableTemplateNames(R&: Result);
1138
1139 bool IsFunctionTemplate;
1140 bool IsVarTemplate;
1141 TemplateName Template;
1142 if (Result.end() - Result.begin() > 1) {
1143 IsFunctionTemplate = true;
1144 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1145 End: Result.end());
1146 } else if (!Result.empty()) {
1147 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1148 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1151 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1152
1153 UsingShadowDecl *FoundUsingShadow =
1154 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1155 assert(!FoundUsingShadow ||
1156 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1157 Template = Context.getQualifiedTemplateName(
1158 Qualifier: SS.getScopeRep(),
1159 /*TemplateKeyword=*/false,
1160 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1161 } else {
1162 // All results were non-template functions. This is a function template
1163 // name.
1164 IsFunctionTemplate = true;
1165 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1166 }
1167
1168 if (IsFunctionTemplate) {
1169 // Function templates always go through overload resolution, at which
1170 // point we'll perform the various checks (e.g., accessibility) we need
1171 // to based on which function we selected.
1172 Result.suppressDiagnostics();
1173
1174 return NameClassification::FunctionTemplate(Name: Template);
1175 }
1176
1177 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1178 : NameClassification::TypeTemplate(Name: Template);
1179 }
1180
1181 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1182 QualType T;
1183 TypeLocBuilder TLB;
1184 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1185 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1186 D: USD);
1187 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1188 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1189 } else {
1190 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1191 Decl: Type);
1192 if (isa<TagType>(Val: T)) {
1193 auto TTL = TLB.push<TagTypeLoc>(T);
1194 TTL.setElaboratedKeywordLoc(SourceLocation());
1195 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1196 TTL.setNameLoc(NameLoc);
1197 } else if (isa<TypedefType>(Val: T)) {
1198 TLB.push<TypedefTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1201 } else if (isa<UnresolvedUsingType>(Val: T)) {
1202 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1203 /*ElaboratedKeywordLoc=*/SourceLocation(),
1204 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1205 } else {
1206 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1207 }
1208 }
1209 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1210 };
1211
1212 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1213 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1214 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1215 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1216 return BuildTypeFor(Type, *Result.begin());
1217 }
1218
1219 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1220 if (!Class) {
1221 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1222 if (ObjCCompatibleAliasDecl *Alias =
1223 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1224 Class = Alias->getClassInterface();
1225 }
1226
1227 if (Class) {
1228 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1229
1230 if (NextToken.is(K: tok::period)) {
1231 // Interface. <something> is parsed as a property reference expression.
1232 // Just return "unknown" as a fall-through for now.
1233 Result.suppressDiagnostics();
1234 return NameClassification::Unknown();
1235 }
1236
1237 QualType T = Context.getObjCInterfaceType(Decl: Class);
1238 return ParsedType::make(P: T);
1239 }
1240
1241 if (isa<ConceptDecl>(Val: FirstDecl)) {
1242 // We want to preserve the UsingShadowDecl for concepts.
1243 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1244 return NameClassification::Concept(Name: TemplateName(USD));
1245 return NameClassification::Concept(
1246 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1247 }
1248
1249 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1250 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1251 return NameClassification::Error();
1252 }
1253
1254 // We can have a type template here if we're classifying a template argument.
1255 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1256 !isa<VarTemplateDecl>(Val: FirstDecl))
1257 return NameClassification::TypeTemplate(
1258 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1259
1260 // Check for a tag type hidden by a non-type decl in a few cases where it
1261 // seems likely a type is wanted instead of the non-type that was found.
1262 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1263 if ((NextToken.is(K: tok::identifier) ||
1264 (NextIsOp &&
1265 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1266 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1267 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1268 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1269 return BuildTypeFor(Type, *Result.begin());
1270 }
1271
1272 // If we already know which single declaration is referenced, just annotate
1273 // that declaration directly. Defer resolving even non-overloaded class
1274 // member accesses, as we need to defer certain access checks until we know
1275 // the context.
1276 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1277 if (Result.isSingleResult() && !ADL &&
1278 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1279 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1280
1281 // Otherwise, this is an overload set that we will need to resolve later.
1282 Result.suppressDiagnostics();
1283 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1284 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1285 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1286 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1287}
1288
1289ExprResult
1290Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1291 SourceLocation NameLoc) {
1292 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1293 CXXScopeSpec SS;
1294 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1295 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1296}
1297
1298ExprResult
1299Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1300 IdentifierInfo *Name,
1301 SourceLocation NameLoc,
1302 bool IsAddressOfOperand) {
1303 DeclarationNameInfo NameInfo(Name, NameLoc);
1304 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1305 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1306 /*TemplateArgs=*/nullptr);
1307}
1308
1309ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1310 NamedDecl *Found,
1311 SourceLocation NameLoc,
1312 const Token &NextToken) {
1313 if (getCurMethodDecl() && SS.isEmpty())
1314 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1315 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1316
1317 // Reconstruct the lookup result.
1318 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1319 Result.addDecl(D: Found);
1320 Result.resolveKind();
1321
1322 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1323 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1324}
1325
1326ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1327 // For an implicit class member access, transform the result into a member
1328 // access expression if necessary.
1329 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1330 if ((*ULE->decls_begin())->isCXXClassMember()) {
1331 CXXScopeSpec SS;
1332 SS.Adopt(Other: ULE->getQualifierLoc());
1333
1334 // Reconstruct the lookup result.
1335 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1336 LookupOrdinaryName);
1337 Result.setNamingClass(ULE->getNamingClass());
1338 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1339 Result.addDecl(D: *I, AS: I.getAccess());
1340 Result.resolveKind();
1341 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1342 TemplateArgs: nullptr, S);
1343 }
1344
1345 // Otherwise, this is already in the form we needed, and no further checks
1346 // are necessary.
1347 return ULE;
1348}
1349
1350Sema::TemplateNameKindForDiagnostics
1351Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1352 auto *TD = Name.getAsTemplateDecl();
1353 if (!TD)
1354 return TemplateNameKindForDiagnostics::DependentTemplate;
1355 if (isa<ClassTemplateDecl>(Val: TD))
1356 return TemplateNameKindForDiagnostics::ClassTemplate;
1357 if (isa<FunctionTemplateDecl>(Val: TD))
1358 return TemplateNameKindForDiagnostics::FunctionTemplate;
1359 if (isa<VarTemplateDecl>(Val: TD))
1360 return TemplateNameKindForDiagnostics::VarTemplate;
1361 if (isa<TypeAliasTemplateDecl>(Val: TD))
1362 return TemplateNameKindForDiagnostics::AliasTemplate;
1363 if (isa<TemplateTemplateParmDecl>(Val: TD))
1364 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1365 if (isa<ConceptDecl>(Val: TD))
1366 return TemplateNameKindForDiagnostics::Concept;
1367 return TemplateNameKindForDiagnostics::DependentTemplate;
1368}
1369
1370void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1371 assert(DC->getLexicalParent() == CurContext &&
1372 "The next DeclContext should be lexically contained in the current one.");
1373 CurContext = DC;
1374 S->setEntity(DC);
1375}
1376
1377void Sema::PopDeclContext() {
1378 assert(CurContext && "DeclContext imbalance!");
1379
1380 CurContext = CurContext->getLexicalParent();
1381 assert(CurContext && "Popped translation unit!");
1382}
1383
1384Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1385 Decl *D) {
1386 // Unlike PushDeclContext, the context to which we return is not necessarily
1387 // the containing DC of TD, because the new context will be some pre-existing
1388 // TagDecl definition instead of a fresh one.
1389 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1390 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1391 assert(CurContext && "skipping definition of undefined tag");
1392 // Start lookups from the parent of the current context; we don't want to look
1393 // into the pre-existing complete definition.
1394 S->setEntity(CurContext->getLookupParent());
1395 return Result;
1396}
1397
1398void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1399 CurContext = static_cast<decltype(CurContext)>(Context);
1400}
1401
1402void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1403 // C++0x [basic.lookup.unqual]p13:
1404 // A name used in the definition of a static data member of class
1405 // X (after the qualified-id of the static member) is looked up as
1406 // if the name was used in a member function of X.
1407 // C++0x [basic.lookup.unqual]p14:
1408 // If a variable member of a namespace is defined outside of the
1409 // scope of its namespace then any name used in the definition of
1410 // the variable member (after the declarator-id) is looked up as
1411 // if the definition of the variable member occurred in its
1412 // namespace.
1413 // Both of these imply that we should push a scope whose context
1414 // is the semantic context of the declaration. We can't use
1415 // PushDeclContext here because that context is not necessarily
1416 // lexically contained in the current context. Fortunately,
1417 // the containing scope should have the appropriate information.
1418
1419 assert(!S->getEntity() && "scope already has entity");
1420
1421#ifndef NDEBUG
1422 Scope *Ancestor = S->getParent();
1423 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1424 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1425#endif
1426
1427 CurContext = DC;
1428 S->setEntity(DC);
1429
1430 if (S->getParent()->isTemplateParamScope()) {
1431 // Also set the corresponding entities for all immediately-enclosing
1432 // template parameter scopes.
1433 EnterTemplatedContext(S: S->getParent(), DC);
1434 }
1435}
1436
1437void Sema::ExitDeclaratorContext(Scope *S) {
1438 assert(S->getEntity() == CurContext && "Context imbalance!");
1439
1440 // Switch back to the lexical context. The safety of this is
1441 // enforced by an assert in EnterDeclaratorContext.
1442 Scope *Ancestor = S->getParent();
1443 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1444 CurContext = Ancestor->getEntity();
1445
1446 // We don't need to do anything with the scope, which is going to
1447 // disappear.
1448}
1449
1450void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1451 assert(S->isTemplateParamScope() &&
1452 "expected to be initializing a template parameter scope");
1453
1454 // C++20 [temp.local]p7:
1455 // In the definition of a member of a class template that appears outside
1456 // of the class template definition, the name of a member of the class
1457 // template hides the name of a template-parameter of any enclosing class
1458 // templates (but not a template-parameter of the member if the member is a
1459 // class or function template).
1460 // C++20 [temp.local]p9:
1461 // In the definition of a class template or in the definition of a member
1462 // of such a template that appears outside of the template definition, for
1463 // each non-dependent base class (13.8.2.1), if the name of the base class
1464 // or the name of a member of the base class is the same as the name of a
1465 // template-parameter, the base class name or member name hides the
1466 // template-parameter name (6.4.10).
1467 //
1468 // This means that a template parameter scope should be searched immediately
1469 // after searching the DeclContext for which it is a template parameter
1470 // scope. For example, for
1471 // template<typename T> template<typename U> template<typename V>
1472 // void N::A<T>::B<U>::f(...)
1473 // we search V then B<U> (and base classes) then U then A<T> (and base
1474 // classes) then T then N then ::.
1475 unsigned ScopeDepth = getTemplateDepth(S);
1476 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1477 DeclContext *SearchDCAfterScope = DC;
1478 for (; DC; DC = DC->getLookupParent()) {
1479 if (const TemplateParameterList *TPL =
1480 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1481 unsigned DCDepth = TPL->getDepth() + 1;
1482 if (DCDepth > ScopeDepth)
1483 continue;
1484 if (ScopeDepth == DCDepth)
1485 SearchDCAfterScope = DC = DC->getLookupParent();
1486 break;
1487 }
1488 }
1489 S->setLookupEntity(SearchDCAfterScope);
1490 }
1491}
1492
1493void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1494 // We assume that the caller has already called
1495 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1496 FunctionDecl *FD = D->getAsFunction();
1497 if (!FD)
1498 return;
1499
1500 // Same implementation as PushDeclContext, but enters the context
1501 // from the lexical parent, rather than the top-level class.
1502 assert(CurContext == FD->getLexicalParent() &&
1503 "The next DeclContext should be lexically contained in the current one.");
1504 CurContext = FD;
1505 S->setEntity(CurContext);
1506
1507 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1508 ParmVarDecl *Param = FD->getParamDecl(i: P);
1509 // If the parameter has an identifier, then add it to the scope
1510 if (Param->getIdentifier()) {
1511 S->AddDecl(D: Param);
1512 IdResolver.AddDecl(D: Param);
1513 }
1514 }
1515}
1516
1517void Sema::ActOnExitFunctionContext() {
1518 // Same implementation as PopDeclContext, but returns to the lexical parent,
1519 // rather than the top-level class.
1520 assert(CurContext && "DeclContext imbalance!");
1521 CurContext = CurContext->getLexicalParent();
1522 assert(CurContext && "Popped translation unit!");
1523}
1524
1525/// Determine whether overloading is allowed for a new function
1526/// declaration considering prior declarations of the same name.
1527///
1528/// This routine determines whether overloading is possible, not
1529/// whether a new declaration actually overloads a previous one.
1530/// It will return true in C++ (where overloads are always permitted)
1531/// or, as a C extension, when either the new declaration or a
1532/// previous one is declared with the 'overloadable' attribute.
1533static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1534 ASTContext &Context,
1535 const FunctionDecl *New) {
1536 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1537 return true;
1538
1539 // Multiversion function declarations are not overloads in the
1540 // usual sense of that term, but lookup will report that an
1541 // overload set was found if more than one multiversion function
1542 // declaration is present for the same name. It is therefore
1543 // inadequate to assume that some prior declaration(s) had
1544 // the overloadable attribute; checking is required. Since one
1545 // declaration is permitted to omit the attribute, it is necessary
1546 // to check at least two; hence the 'any_of' check below. Note that
1547 // the overloadable attribute is implicitly added to declarations
1548 // that were required to have it but did not.
1549 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1550 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1551 return ND->hasAttr<OverloadableAttr>();
1552 });
1553 } else if (Previous.getResultKind() == LookupResultKind::Found)
1554 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1555
1556 return false;
1557}
1558
1559void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1560 // Move up the scope chain until we find the nearest enclosing
1561 // non-transparent context. The declaration will be introduced into this
1562 // scope.
1563 while (S->getEntity() && S->getEntity()->isTransparentContext())
1564 S = S->getParent();
1565
1566 // Add scoped declarations into their context, so that they can be
1567 // found later. Declarations without a context won't be inserted
1568 // into any context.
1569 if (AddToContext)
1570 CurContext->addDecl(D);
1571
1572 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1573 // are function-local declarations.
1574 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1575 return;
1576
1577 // Template instantiations should also not be pushed into scope.
1578 if (isa<FunctionDecl>(Val: D) &&
1579 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1580 return;
1581
1582 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1583 S->AddDecl(D);
1584 return;
1585 }
1586 // If this replaces anything in the current scope,
1587 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1588 IEnd = IdResolver.end();
1589 for (; I != IEnd; ++I) {
1590 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1591 S->RemoveDecl(D: *I);
1592 IdResolver.RemoveDecl(D: *I);
1593
1594 // Should only need to replace one decl.
1595 break;
1596 }
1597 }
1598
1599 S->AddDecl(D);
1600
1601 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1602 // Implicitly-generated labels may end up getting generated in an order that
1603 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1604 // the label at the appropriate place in the identifier chain.
1605 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1606 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1607 if (IDC == CurContext) {
1608 if (!S->isDeclScope(D: *I))
1609 continue;
1610 } else if (IDC->Encloses(DC: CurContext))
1611 break;
1612 }
1613
1614 IdResolver.InsertDeclAfter(Pos: I, D);
1615 } else {
1616 IdResolver.AddDecl(D);
1617 }
1618 warnOnReservedIdentifier(D);
1619}
1620
1621bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1622 bool AllowInlineNamespace) const {
1623 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1624}
1625
1626Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1627 DeclContext *TargetDC = DC->getPrimaryContext();
1628 do {
1629 if (DeclContext *ScopeDC = S->getEntity())
1630 if (ScopeDC->getPrimaryContext() == TargetDC)
1631 return S;
1632 } while ((S = S->getParent()));
1633
1634 return nullptr;
1635}
1636
1637static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1638 DeclContext*,
1639 ASTContext&);
1640
1641void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1642 bool ConsiderLinkage,
1643 bool AllowInlineNamespace) {
1644 LookupResult::Filter F = R.makeFilter();
1645 while (F.hasNext()) {
1646 NamedDecl *D = F.next();
1647
1648 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1649 continue;
1650
1651 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1652 continue;
1653
1654 F.erase();
1655 }
1656
1657 F.done();
1658}
1659
1660static bool isImplicitInstantiation(NamedDecl *D) {
1661 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1662 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1664 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1665 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1666 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1667
1668 return false;
1669}
1670
1671bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1672 // [module.interface]p7:
1673 // A declaration is attached to a module as follows:
1674 // - If the declaration is a non-dependent friend declaration that nominates a
1675 // function with a declarator-id that is a qualified-id or template-id or that
1676 // nominates a class other than with an elaborated-type-specifier with neither
1677 // a nested-name-specifier nor a simple-template-id, it is attached to the
1678 // module to which the friend is attached ([basic.link]).
1679 if (New->getFriendObjectKind() &&
1680 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1681 New->setLocalOwningModule(Old->getOwningModule());
1682 makeMergedDefinitionVisible(ND: New);
1683 return false;
1684 }
1685
1686 // Although we have questions for the module ownership of implicit
1687 // instantiations, it should be sure that we shouldn't diagnose the
1688 // redeclaration of incorrect module ownership for different implicit
1689 // instantiations in different modules. We will diagnose the redeclaration of
1690 // incorrect module ownership for the template itself.
1691 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1692 return false;
1693
1694 Module *NewM = New->getOwningModule();
1695 Module *OldM = Old->getOwningModule();
1696
1697 if (NewM && NewM->isPrivateModule())
1698 NewM = NewM->Parent;
1699 if (OldM && OldM->isPrivateModule())
1700 OldM = OldM->Parent;
1701
1702 if (NewM == OldM)
1703 return false;
1704
1705 if (NewM && OldM) {
1706 // A module implementation unit has visibility of the decls in its
1707 // implicitly imported interface.
1708 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1709 return false;
1710
1711 // Partitions are part of the module, but a partition could import another
1712 // module, so verify that the PMIs agree.
1713 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1714 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1715 return false;
1716 }
1717
1718 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1719 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1720 if (NewIsModuleInterface || OldIsModuleInterface) {
1721 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1722 // if a declaration of D [...] appears in the purview of a module, all
1723 // other such declarations shall appear in the purview of the same module
1724 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1725 << New
1726 << NewIsModuleInterface
1727 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1728 << OldIsModuleInterface
1729 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1730 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1731 New->setInvalidDecl();
1732 return true;
1733 }
1734
1735 return false;
1736}
1737
1738bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1739 // [module.interface]p1:
1740 // An export-declaration shall inhabit a namespace scope.
1741 //
1742 // So it is meaningless to talk about redeclaration which is not at namespace
1743 // scope.
1744 if (!New->getLexicalDeclContext()
1745 ->getNonTransparentContext()
1746 ->isFileContext() ||
1747 !Old->getLexicalDeclContext()
1748 ->getNonTransparentContext()
1749 ->isFileContext())
1750 return false;
1751
1752 bool IsNewExported = New->isInExportDeclContext();
1753 bool IsOldExported = Old->isInExportDeclContext();
1754
1755 // It should be irrevelant if both of them are not exported.
1756 if (!IsNewExported && !IsOldExported)
1757 return false;
1758
1759 if (IsOldExported)
1760 return false;
1761
1762 // If the Old declaration are not attached to named modules
1763 // and the New declaration are attached to global module.
1764 // It should be fine to allow the export since it doesn't change
1765 // the linkage of declarations. See
1766 // https://github.com/llvm/llvm-project/issues/98583 for details.
1767 if (!Old->isInNamedModule() && New->getOwningModule() &&
1768 New->getOwningModule()->isImplicitGlobalModule())
1769 return false;
1770
1771 assert(IsNewExported);
1772
1773 auto Lk = Old->getFormalLinkage();
1774 int S = 0;
1775 if (Lk == Linkage::Internal)
1776 S = 1;
1777 else if (Lk == Linkage::Module)
1778 S = 2;
1779 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1780 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1781 return true;
1782}
1783
1784bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1785 if (CheckRedeclarationModuleOwnership(New, Old))
1786 return true;
1787
1788 if (CheckRedeclarationExported(New, Old))
1789 return true;
1790
1791 return false;
1792}
1793
1794bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1795 const NamedDecl *Old) const {
1796 assert(getASTContext().isSameEntity(New, Old) &&
1797 "New and Old are not the same definition, we should diagnostic it "
1798 "immediately instead of checking it.");
1799 assert(const_cast<Sema *>(this)->isReachable(New) &&
1800 const_cast<Sema *>(this)->isReachable(Old) &&
1801 "We shouldn't see unreachable definitions here.");
1802
1803 Module *NewM = New->getOwningModule();
1804 Module *OldM = Old->getOwningModule();
1805
1806 // We only checks for named modules here. The header like modules is skipped.
1807 // FIXME: This is not right if we import the header like modules in the module
1808 // purview.
1809 //
1810 // For example, assuming "header.h" provides definition for `D`.
1811 // ```C++
1812 // //--- M.cppm
1813 // export module M;
1814 // import "header.h"; // or #include "header.h" but import it by clang modules
1815 // actually.
1816 //
1817 // //--- Use.cpp
1818 // import M;
1819 // import "header.h"; // or uses clang modules.
1820 // ```
1821 //
1822 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1823 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1824 // reject it. But the current implementation couldn't detect the case since we
1825 // don't record the information about the importee modules.
1826 //
1827 // But this might not be painful in practice. Since the design of C++20 Named
1828 // Modules suggests us to use headers in global module fragment instead of
1829 // module purview.
1830 if (NewM && NewM->isHeaderLikeModule())
1831 NewM = nullptr;
1832 if (OldM && OldM->isHeaderLikeModule())
1833 OldM = nullptr;
1834
1835 if (!NewM && !OldM)
1836 return true;
1837
1838 // [basic.def.odr]p14.3
1839 // Each such definition shall not be attached to a named module
1840 // ([module.unit]).
1841 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1842 return true;
1843
1844 // Then New and Old lives in the same TU if their share one same module unit.
1845 if (NewM)
1846 NewM = NewM->getTopLevelModule();
1847 if (OldM)
1848 OldM = OldM->getTopLevelModule();
1849 return OldM == NewM;
1850}
1851
1852static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1853 if (D->getDeclContext()->isFileContext())
1854 return false;
1855
1856 return isa<UsingShadowDecl>(Val: D) ||
1857 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1858 isa<UnresolvedUsingValueDecl>(Val: D);
1859}
1860
1861/// Removes using shadow declarations not at class scope from the lookup
1862/// results.
1863static void RemoveUsingDecls(LookupResult &R) {
1864 LookupResult::Filter F = R.makeFilter();
1865 while (F.hasNext())
1866 if (isUsingDeclNotAtClassScope(D: F.next()))
1867 F.erase();
1868
1869 F.done();
1870}
1871
1872/// Check for this common pattern:
1873/// @code
1874/// class S {
1875/// S(const S&); // DO NOT IMPLEMENT
1876/// void operator=(const S&); // DO NOT IMPLEMENT
1877/// };
1878/// @endcode
1879static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1880 // FIXME: Should check for private access too but access is set after we get
1881 // the decl here.
1882 if (D->doesThisDeclarationHaveABody())
1883 return false;
1884
1885 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1886 return CD->isCopyConstructor();
1887 return D->isCopyAssignmentOperator();
1888}
1889
1890bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1891 const DeclContext *DC = D->getDeclContext();
1892 while (!DC->isTranslationUnit()) {
1893 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1894 if (!RD->hasNameForLinkage())
1895 return true;
1896 }
1897 DC = DC->getParent();
1898 }
1899
1900 return !D->isExternallyVisible();
1901}
1902
1903// FIXME: This needs to be refactored; some other isInMainFile users want
1904// these semantics.
1905static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1906 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1907 return false;
1908 return S.SourceMgr.isInMainFile(Loc);
1909}
1910
1911bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1912 assert(D);
1913
1914 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1915 return false;
1916
1917 // Ignore all entities declared within templates, and out-of-line definitions
1918 // of members of class templates.
1919 if (D->getDeclContext()->isDependentContext() ||
1920 D->getLexicalDeclContext()->isDependentContext())
1921 return false;
1922
1923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1924 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1925 return false;
1926 // A non-out-of-line declaration of a member specialization was implicitly
1927 // instantiated; it's the out-of-line declaration that we're interested in.
1928 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1929 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1930 return false;
1931
1932 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1933 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1934 return false;
1935 } else {
1936 // 'static inline' functions are defined in headers; don't warn.
1937 if (FD->isInlined() && !isMainFileLoc(S: *this, Loc: FD->getLocation()))
1938 return false;
1939 }
1940
1941 if (FD->doesThisDeclarationHaveABody() &&
1942 Context.DeclMustBeEmitted(D: FD))
1943 return false;
1944 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1945 // Constants and utility variables are defined in headers with internal
1946 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1947 // like "inline".)
1948 if (!isMainFileLoc(S: *this, Loc: VD->getLocation()))
1949 return false;
1950
1951 if (Context.DeclMustBeEmitted(D: VD))
1952 return false;
1953
1954 if (VD->isStaticDataMember() &&
1955 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1956 return false;
1957 if (VD->isStaticDataMember() &&
1958 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1959 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1960 return false;
1961
1962 if (VD->isInline() && !isMainFileLoc(S: *this, Loc: VD->getLocation()))
1963 return false;
1964 } else {
1965 return false;
1966 }
1967
1968 // Only warn for unused decls internal to the translation unit.
1969 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1970 // for inline functions defined in the main source file, for instance.
1971 return mightHaveNonExternalLinkage(D);
1972}
1973
1974void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1975 if (!D)
1976 return;
1977
1978 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1979 const FunctionDecl *First = FD->getFirstDecl();
1980 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1981 return; // First should already be in the vector.
1982 }
1983
1984 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1985 const VarDecl *First = VD->getFirstDecl();
1986 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1987 return; // First should already be in the vector.
1988 }
1989
1990 if (ShouldWarnIfUnusedFileScopedDecl(D))
1991 UnusedFileScopedDecls.push_back(LocalValue: D);
1992}
1993
1994static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1995 const NamedDecl *D) {
1996 if (D->isInvalidDecl())
1997 return false;
1998
1999 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2000 // For a decomposition declaration, warn if none of the bindings are
2001 // referenced, instead of if the variable itself is referenced (which
2002 // it is, by the bindings' expressions).
2003 bool IsAllIgnored = true;
2004 for (const auto *BD : DD->bindings()) {
2005 if (BD->isReferenced())
2006 return false;
2007 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2008 BD->hasAttr<UnusedAttr>());
2009 }
2010 if (IsAllIgnored)
2011 return false;
2012 } else if (!D->getDeclName()) {
2013 return false;
2014 } else if (D->isReferenced() || D->isUsed()) {
2015 return false;
2016 }
2017
2018 if (D->isPlaceholderVar(LangOpts))
2019 return false;
2020
2021 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2022 D->hasAttr<CleanupAttr>())
2023 return false;
2024
2025 if (isa<LabelDecl>(Val: D))
2026 return true;
2027
2028 // Except for labels, we only care about unused decls that are local to
2029 // functions.
2030 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2031 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2032 // For dependent types, the diagnostic is deferred.
2033 WithinFunction =
2034 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2035 if (!WithinFunction)
2036 return false;
2037
2038 if (isa<TypedefNameDecl>(Val: D))
2039 return true;
2040
2041 // White-list anything that isn't a local variable.
2042 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2043 return false;
2044
2045 // Types of valid local variables should be complete, so this should succeed.
2046 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2047
2048 const Expr *Init = VD->getInit();
2049 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2050 Init = Cleanups->getSubExpr();
2051
2052 const auto *Ty = VD->getType().getTypePtr();
2053
2054 // Only look at the outermost level of typedef.
2055 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2056 // Allow anything marked with __attribute__((unused)).
2057 if (TT->getDecl()->hasAttr<UnusedAttr>())
2058 return false;
2059 }
2060
2061 // Warn for reference variables whose initializtion performs lifetime
2062 // extension.
2063 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2064 MTE && MTE->getExtendingDecl()) {
2065 Ty = VD->getType().getNonReferenceType().getTypePtr();
2066 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2067 }
2068
2069 // If we failed to complete the type for some reason, or if the type is
2070 // dependent, don't diagnose the variable.
2071 if (Ty->isIncompleteType() || Ty->isDependentType())
2072 return false;
2073
2074 // Look at the element type to ensure that the warning behaviour is
2075 // consistent for both scalars and arrays.
2076 Ty = Ty->getBaseElementTypeUnsafe();
2077
2078 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2079 if (Tag->hasAttr<UnusedAttr>())
2080 return false;
2081
2082 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2083 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2084 return false;
2085
2086 if (Init) {
2087 const auto *Construct =
2088 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2089 if (Construct && !Construct->isElidable()) {
2090 const CXXConstructorDecl *CD = Construct->getConstructor();
2091 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2092 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2093 return false;
2094 }
2095
2096 // Suppress the warning if we don't know how this is constructed, and
2097 // it could possibly be non-trivial constructor.
2098 if (Init->isTypeDependent()) {
2099 for (const CXXConstructorDecl *Ctor : RD->ctors())
2100 if (!Ctor->isTrivial())
2101 return false;
2102 }
2103
2104 // Suppress the warning if the constructor is unresolved because
2105 // its arguments are dependent.
2106 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2107 return false;
2108 }
2109 }
2110 }
2111
2112 // TODO: __attribute__((unused)) templates?
2113 }
2114
2115 return true;
2116}
2117
2118static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2119 FixItHint &Hint) {
2120 if (isa<LabelDecl>(Val: D)) {
2121 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2122 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2123 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2124 if (AfterColon.isInvalid())
2125 return;
2126 Hint = FixItHint::CreateRemoval(
2127 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2128 }
2129}
2130
2131void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2132 DiagnoseUnusedNestedTypedefs(
2133 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2134}
2135
2136void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2137 DiagReceiverTy DiagReceiver) {
2138 if (D->isDependentType())
2139 return;
2140
2141 for (auto *TmpD : D->decls()) {
2142 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2143 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2144 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2145 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2146 }
2147}
2148
2149void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2150 DiagnoseUnusedDecl(
2151 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2152}
2153
2154void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2155 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2156 return;
2157
2158 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2159 // typedefs can be referenced later on, so the diagnostics are emitted
2160 // at end-of-translation-unit.
2161 UnusedLocalTypedefNameCandidates.insert(X: TD);
2162 return;
2163 }
2164
2165 FixItHint Hint;
2166 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2167
2168 unsigned DiagID;
2169 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2170 DiagID = diag::warn_unused_exception_param;
2171 else if (isa<LabelDecl>(Val: D))
2172 DiagID = diag::warn_unused_label;
2173 else
2174 DiagID = diag::warn_unused_variable;
2175
2176 SourceLocation DiagLoc = D->getLocation();
2177 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2178}
2179
2180void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2181 DiagReceiverTy DiagReceiver) {
2182 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2183 // it's not really unused.
2184 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2185 return;
2186
2187 // In C++, `_` variables behave as if they were maybe_unused
2188 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2189 return;
2190
2191 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2192
2193 if (Ty->isReferenceType() || Ty->isDependentType())
2194 return;
2195
2196 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2197 if (Tag->hasAttr<UnusedAttr>())
2198 return;
2199 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2200 // mimic gcc's behavior.
2201 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2202 RD && !RD->hasAttr<WarnUnusedAttr>())
2203 return;
2204 }
2205
2206 // Don't warn about __block Objective-C pointer variables, as they might
2207 // be assigned in the block but not used elsewhere for the purpose of lifetime
2208 // extension.
2209 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2210 return;
2211
2212 // Don't warn about Objective-C pointer variables with precise lifetime
2213 // semantics; they can be used to ensure ARC releases the object at a known
2214 // time, which may mean assignment but no other references.
2215 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2216 return;
2217
2218 auto iter = RefsMinusAssignments.find(Val: VD);
2219 if (iter == RefsMinusAssignments.end())
2220 return;
2221
2222 assert(iter->getSecond() >= 0 &&
2223 "Found a negative number of references to a VarDecl");
2224 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2225 // Assume the given VarDecl is "used" if its ref count stored in
2226 // `RefMinusAssignments` is positive, with one exception.
2227 //
2228 // For a C++ variable whose decl (with initializer) entirely consist the
2229 // condition expression of a if/while/for construct,
2230 // Clang creates a DeclRefExpr for the condition expression rather than a
2231 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2232 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2233 // used in the body of the if/while/for construct.
2234 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2235 if (!UnusedCXXCondDecl)
2236 return;
2237 }
2238
2239 unsigned DiagID = isa<ParmVarDecl>(Val: VD) ? diag::warn_unused_but_set_parameter
2240 : diag::warn_unused_but_set_variable;
2241 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2242}
2243
2244static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2245 Sema::DiagReceiverTy DiagReceiver) {
2246 // Verify that we have no forward references left. If so, there was a goto
2247 // or address of a label taken, but no definition of it. Label fwd
2248 // definitions are indicated with a null substmt which is also not a resolved
2249 // MS inline assembly label name.
2250 bool Diagnose = false;
2251 if (L->isMSAsmLabel())
2252 Diagnose = !L->isResolvedMSAsmLabel();
2253 else
2254 Diagnose = L->getStmt() == nullptr;
2255 if (Diagnose)
2256 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2257 << L);
2258}
2259
2260void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2261 S->applyNRVO();
2262
2263 if (S->decl_empty()) return;
2264 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2265 "Scope shouldn't contain decls!");
2266
2267 /// We visit the decls in non-deterministic order, but we want diagnostics
2268 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2269 /// and sort the diagnostics before emitting them, after we visited all decls.
2270 struct LocAndDiag {
2271 SourceLocation Loc;
2272 std::optional<SourceLocation> PreviousDeclLoc;
2273 PartialDiagnostic PD;
2274 };
2275 SmallVector<LocAndDiag, 16> DeclDiags;
2276 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2277 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2278 };
2279 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2280 SourceLocation PreviousDeclLoc,
2281 PartialDiagnostic PD) {
2282 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2283 };
2284
2285 for (auto *TmpD : S->decls()) {
2286 assert(TmpD && "This decl didn't get pushed??");
2287
2288 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2289 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2290
2291 // Diagnose unused variables in this scope.
2292 if (!S->hasUnrecoverableErrorOccurred()) {
2293 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2294 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2295 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2296 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2297 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2298 RefsMinusAssignments.erase(Val: VD);
2299 }
2300 }
2301
2302 if (!D->getDeclName()) continue;
2303
2304 // If this was a forward reference to a label, verify it was defined.
2305 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2306 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2307
2308 // Partial translation units that are created in incremental processing must
2309 // not clean up the IdResolver because PTUs should take into account the
2310 // declarations that came from previous PTUs.
2311 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2312 getLangOpts().CPlusPlus)
2313 IdResolver.RemoveDecl(D);
2314
2315 // Warn on it if we are shadowing a declaration.
2316 auto ShadowI = ShadowingDecls.find(Val: D);
2317 if (ShadowI != ShadowingDecls.end()) {
2318 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2319 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2320 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2321 << D << FD << FD->getParent());
2322 }
2323 ShadowingDecls.erase(I: ShadowI);
2324 }
2325 }
2326
2327 llvm::sort(C&: DeclDiags,
2328 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2329 // The particular order for diagnostics is not important, as long
2330 // as the order is deterministic. Using the raw location is going
2331 // to generally be in source order unless there are macro
2332 // expansions involved.
2333 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2334 });
2335 for (const LocAndDiag &D : DeclDiags) {
2336 Diag(Loc: D.Loc, PD: D.PD);
2337 if (D.PreviousDeclLoc)
2338 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2339 }
2340}
2341
2342Scope *Sema::getNonFieldDeclScope(Scope *S) {
2343 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2344 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2345 (S->isClassScope() && !getLangOpts().CPlusPlus))
2346 S = S->getParent();
2347 return S;
2348}
2349
2350static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2351 ASTContext::GetBuiltinTypeError Error) {
2352 switch (Error) {
2353 case ASTContext::GE_None:
2354 return "";
2355 case ASTContext::GE_Missing_type:
2356 return BuiltinInfo.getHeaderName(ID);
2357 case ASTContext::GE_Missing_stdio:
2358 return "stdio.h";
2359 case ASTContext::GE_Missing_setjmp:
2360 return "setjmp.h";
2361 case ASTContext::GE_Missing_ucontext:
2362 return "ucontext.h";
2363 }
2364 llvm_unreachable("unhandled error kind");
2365}
2366
2367FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2368 unsigned ID, SourceLocation Loc) {
2369 DeclContext *Parent = Context.getTranslationUnitDecl();
2370
2371 if (getLangOpts().CPlusPlus) {
2372 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2373 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2374 CLinkageDecl->setImplicit();
2375 Parent->addDecl(D: CLinkageDecl);
2376 Parent = CLinkageDecl;
2377 }
2378
2379 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2380 if (Context.BuiltinInfo.isImmediate(ID)) {
2381 assert(getLangOpts().CPlusPlus20 &&
2382 "consteval builtins should only be available in C++20 mode");
2383 ConstexprKind = ConstexprSpecKind::Consteval;
2384 }
2385
2386 FunctionDecl *New = FunctionDecl::Create(
2387 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2388 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2389 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2390 New->setImplicit();
2391 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2392
2393 // Create Decl objects for each parameter, adding them to the
2394 // FunctionDecl.
2395 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2396 SmallVector<ParmVarDecl *, 16> Params;
2397 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2398 ParmVarDecl *parm = ParmVarDecl::Create(
2399 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2400 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2401 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2402 Params.push_back(Elt: parm);
2403 }
2404 New->setParams(Params);
2405 }
2406
2407 AddKnownFunctionAttributes(FD: New);
2408 return New;
2409}
2410
2411NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2412 Scope *S, bool ForRedeclaration,
2413 SourceLocation Loc) {
2414 LookupNecessaryTypesForBuiltin(S, ID);
2415
2416 ASTContext::GetBuiltinTypeError Error;
2417 QualType R = Context.GetBuiltinType(ID, Error);
2418 if (Error) {
2419 if (!ForRedeclaration)
2420 return nullptr;
2421
2422 // If we have a builtin without an associated type we should not emit a
2423 // warning when we were not able to find a type for it.
2424 if (Error == ASTContext::GE_Missing_type ||
2425 Context.BuiltinInfo.allowTypeMismatch(ID))
2426 return nullptr;
2427
2428 // If we could not find a type for setjmp it is because the jmp_buf type was
2429 // not defined prior to the setjmp declaration.
2430 if (Error == ASTContext::GE_Missing_setjmp) {
2431 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2432 << Context.BuiltinInfo.getName(ID);
2433 return nullptr;
2434 }
2435
2436 // Generally, we emit a warning that the declaration requires the
2437 // appropriate header.
2438 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2439 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2440 << Context.BuiltinInfo.getName(ID);
2441 return nullptr;
2442 }
2443
2444 if (!ForRedeclaration &&
2445 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2446 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2447 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2448 : diag::ext_implicit_lib_function_decl)
2449 << Context.BuiltinInfo.getName(ID) << R;
2450 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2451 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2452 << Header << Context.BuiltinInfo.getName(ID);
2453 }
2454
2455 if (R.isNull())
2456 return nullptr;
2457
2458 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2459 RegisterLocallyScopedExternCDecl(ND: New, S);
2460
2461 // TUScope is the translation-unit scope to insert this function into.
2462 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2463 // relate Scopes to DeclContexts, and probably eliminate CurContext
2464 // entirely, but we're not there yet.
2465 DeclContext *SavedContext = CurContext;
2466 CurContext = New->getDeclContext();
2467 PushOnScopeChains(D: New, S: TUScope);
2468 CurContext = SavedContext;
2469 return New;
2470}
2471
2472/// Typedef declarations don't have linkage, but they still denote the same
2473/// entity if their types are the same.
2474/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2475/// isSameEntity.
2476static void
2477filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2478 LookupResult &Previous) {
2479 // This is only interesting when modules are enabled.
2480 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2481 return;
2482
2483 // Empty sets are uninteresting.
2484 if (Previous.empty())
2485 return;
2486
2487 LookupResult::Filter Filter = Previous.makeFilter();
2488 while (Filter.hasNext()) {
2489 NamedDecl *Old = Filter.next();
2490
2491 // Non-hidden declarations are never ignored.
2492 if (S.isVisible(D: Old))
2493 continue;
2494
2495 // Declarations of the same entity are not ignored, even if they have
2496 // different linkages.
2497 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2498 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2499 T2: Decl->getUnderlyingType()))
2500 continue;
2501
2502 // If both declarations give a tag declaration a typedef name for linkage
2503 // purposes, then they declare the same entity.
2504 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2505 Decl->getAnonDeclWithTypedefName())
2506 continue;
2507 }
2508
2509 Filter.erase();
2510 }
2511
2512 Filter.done();
2513}
2514
2515bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2516 QualType OldType;
2517 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2518 OldType = OldTypedef->getUnderlyingType();
2519 else
2520 OldType = Context.getTypeDeclType(Decl: Old);
2521 QualType NewType = New->getUnderlyingType();
2522
2523 if (NewType->isVariablyModifiedType()) {
2524 // Must not redefine a typedef with a variably-modified type.
2525 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2526 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2527 << Kind << NewType;
2528 if (Old->getLocation().isValid())
2529 notePreviousDefinition(Old, New: New->getLocation());
2530 New->setInvalidDecl();
2531 return true;
2532 }
2533
2534 if (OldType != NewType &&
2535 !OldType->isDependentType() &&
2536 !NewType->isDependentType() &&
2537 !Context.hasSameType(T1: OldType, T2: NewType)) {
2538 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2539 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2540 << Kind << NewType << OldType;
2541 if (Old->getLocation().isValid())
2542 notePreviousDefinition(Old, New: New->getLocation());
2543 New->setInvalidDecl();
2544 return true;
2545 }
2546 return false;
2547}
2548
2549void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2550 LookupResult &OldDecls) {
2551 // If the new decl is known invalid already, don't bother doing any
2552 // merging checks.
2553 if (New->isInvalidDecl()) return;
2554
2555 // Allow multiple definitions for ObjC built-in typedefs.
2556 // FIXME: Verify the underlying types are equivalent!
2557 if (getLangOpts().ObjC) {
2558 const IdentifierInfo *TypeID = New->getIdentifier();
2559 switch (TypeID->getLength()) {
2560 default: break;
2561 case 2:
2562 {
2563 if (!TypeID->isStr(Str: "id"))
2564 break;
2565 QualType T = New->getUnderlyingType();
2566 if (!T->isPointerType())
2567 break;
2568 if (!T->isVoidPointerType()) {
2569 QualType PT = T->castAs<PointerType>()->getPointeeType();
2570 if (!PT->isStructureType())
2571 break;
2572 }
2573 Context.setObjCIdRedefinitionType(T);
2574 // Install the built-in type for 'id', ignoring the current definition.
2575 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2576 modedTy: Context.getObjCIdType());
2577 return;
2578 }
2579 case 5:
2580 if (!TypeID->isStr(Str: "Class"))
2581 break;
2582 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2583 // Install the built-in type for 'Class', ignoring the current definition.
2584 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2585 modedTy: Context.getObjCClassType());
2586 return;
2587 case 3:
2588 if (!TypeID->isStr(Str: "SEL"))
2589 break;
2590 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2591 // Install the built-in type for 'SEL', ignoring the current definition.
2592 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2593 modedTy: Context.getObjCSelType());
2594 return;
2595 }
2596 // Fall through - the typedef name was not a builtin type.
2597 }
2598
2599 // Verify the old decl was also a type.
2600 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2601 if (!Old) {
2602 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2603 << New->getDeclName();
2604
2605 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2606 if (OldD->getLocation().isValid())
2607 notePreviousDefinition(Old: OldD, New: New->getLocation());
2608
2609 return New->setInvalidDecl();
2610 }
2611
2612 // If the old declaration is invalid, just give up here.
2613 if (Old->isInvalidDecl())
2614 return New->setInvalidDecl();
2615
2616 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2617 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2618 auto *NewTag = New->getAnonDeclWithTypedefName();
2619 NamedDecl *Hidden = nullptr;
2620 if (OldTag && NewTag &&
2621 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2622 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2623 // There is a definition of this tag, but it is not visible. Use it
2624 // instead of our tag.
2625 if (OldTD->isModed())
2626 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2627 modedTy: OldTD->getUnderlyingType());
2628 else
2629 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2630
2631 // Make the old tag definition visible.
2632 makeMergedDefinitionVisible(ND: Hidden);
2633
2634 CleanupMergedEnum(S, New: NewTag);
2635 }
2636 }
2637
2638 // If the typedef types are not identical, reject them in all languages and
2639 // with any extensions enabled.
2640 if (isIncompatibleTypedef(Old, New))
2641 return;
2642
2643 // The types match. Link up the redeclaration chain and merge attributes if
2644 // the old declaration was a typedef.
2645 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2646 New->setPreviousDecl(Typedef);
2647 mergeDeclAttributes(New, Old);
2648 }
2649
2650 if (getLangOpts().MicrosoftExt)
2651 return;
2652
2653 if (getLangOpts().CPlusPlus) {
2654 // C++ [dcl.typedef]p2:
2655 // In a given non-class scope, a typedef specifier can be used to
2656 // redefine the name of any type declared in that scope to refer
2657 // to the type to which it already refers.
2658 if (!isa<CXXRecordDecl>(Val: CurContext))
2659 return;
2660
2661 // C++0x [dcl.typedef]p4:
2662 // In a given class scope, a typedef specifier can be used to redefine
2663 // any class-name declared in that scope that is not also a typedef-name
2664 // to refer to the type to which it already refers.
2665 //
2666 // This wording came in via DR424, which was a correction to the
2667 // wording in DR56, which accidentally banned code like:
2668 //
2669 // struct S {
2670 // typedef struct A { } A;
2671 // };
2672 //
2673 // in the C++03 standard. We implement the C++0x semantics, which
2674 // allow the above but disallow
2675 //
2676 // struct S {
2677 // typedef int I;
2678 // typedef int I;
2679 // };
2680 //
2681 // since that was the intent of DR56.
2682 if (!isa<TypedefNameDecl>(Val: Old))
2683 return;
2684
2685 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2686 << New->getDeclName();
2687 notePreviousDefinition(Old, New: New->getLocation());
2688 return New->setInvalidDecl();
2689 }
2690
2691 // Modules always permit redefinition of typedefs, as does C11.
2692 if (getLangOpts().Modules || getLangOpts().C11)
2693 return;
2694
2695 // If we have a redefinition of a typedef in C, emit a warning. This warning
2696 // is normally mapped to an error, but can be controlled with
2697 // -Wtypedef-redefinition. If either the original or the redefinition is
2698 // in a system header, don't emit this for compatibility with GCC.
2699 if (getDiagnostics().getSuppressSystemWarnings() &&
2700 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2701 (Old->isImplicit() ||
2702 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2703 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2704 return;
2705
2706 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2707 << New->getDeclName();
2708 notePreviousDefinition(Old, New: New->getLocation());
2709}
2710
2711void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2712 // If this was an unscoped enumeration, yank all of its enumerators
2713 // out of the scope.
2714 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2715 Scope *EnumScope = getNonFieldDeclScope(S);
2716 for (auto *ECD : ED->enumerators()) {
2717 assert(EnumScope->isDeclScope(ECD));
2718 EnumScope->RemoveDecl(D: ECD);
2719 IdResolver.RemoveDecl(D: ECD);
2720 }
2721 }
2722}
2723
2724/// DeclhasAttr - returns true if decl Declaration already has the target
2725/// attribute.
2726static bool DeclHasAttr(const Decl *D, const Attr *A) {
2727 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2728 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2729 for (const auto *i : D->attrs())
2730 if (i->getKind() == A->getKind()) {
2731 if (Ann) {
2732 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2733 return true;
2734 continue;
2735 }
2736 // FIXME: Don't hardcode this check
2737 if (OA && isa<OwnershipAttr>(Val: i))
2738 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2739 return true;
2740 }
2741
2742 return false;
2743}
2744
2745static bool isAttributeTargetADefinition(Decl *D) {
2746 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2747 return VD->isThisDeclarationADefinition();
2748 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2749 return TD->isCompleteDefinition() || TD->isBeingDefined();
2750 return true;
2751}
2752
2753/// Merge alignment attributes from \p Old to \p New, taking into account the
2754/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2755///
2756/// \return \c true if any attributes were added to \p New.
2757static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2758 // Look for alignas attributes on Old, and pick out whichever attribute
2759 // specifies the strictest alignment requirement.
2760 AlignedAttr *OldAlignasAttr = nullptr;
2761 AlignedAttr *OldStrictestAlignAttr = nullptr;
2762 unsigned OldAlign = 0;
2763 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2764 // FIXME: We have no way of representing inherited dependent alignments
2765 // in a case like:
2766 // template<int A, int B> struct alignas(A) X;
2767 // template<int A, int B> struct alignas(B) X {};
2768 // For now, we just ignore any alignas attributes which are not on the
2769 // definition in such a case.
2770 if (I->isAlignmentDependent())
2771 return false;
2772
2773 if (I->isAlignas())
2774 OldAlignasAttr = I;
2775
2776 unsigned Align = I->getAlignment(Ctx&: S.Context);
2777 if (Align > OldAlign) {
2778 OldAlign = Align;
2779 OldStrictestAlignAttr = I;
2780 }
2781 }
2782
2783 // Look for alignas attributes on New.
2784 AlignedAttr *NewAlignasAttr = nullptr;
2785 unsigned NewAlign = 0;
2786 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2787 if (I->isAlignmentDependent())
2788 return false;
2789
2790 if (I->isAlignas())
2791 NewAlignasAttr = I;
2792
2793 unsigned Align = I->getAlignment(Ctx&: S.Context);
2794 if (Align > NewAlign)
2795 NewAlign = Align;
2796 }
2797
2798 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2799 // Both declarations have 'alignas' attributes. We require them to match.
2800 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2801 // fall short. (If two declarations both have alignas, they must both match
2802 // every definition, and so must match each other if there is a definition.)
2803
2804 // If either declaration only contains 'alignas(0)' specifiers, then it
2805 // specifies the natural alignment for the type.
2806 if (OldAlign == 0 || NewAlign == 0) {
2807 QualType Ty;
2808 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2809 Ty = VD->getType();
2810 else
2811 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2812
2813 if (OldAlign == 0)
2814 OldAlign = S.Context.getTypeAlign(T: Ty);
2815 if (NewAlign == 0)
2816 NewAlign = S.Context.getTypeAlign(T: Ty);
2817 }
2818
2819 if (OldAlign != NewAlign) {
2820 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2821 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2822 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2823 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2824 }
2825 }
2826
2827 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2828 // C++11 [dcl.align]p6:
2829 // if any declaration of an entity has an alignment-specifier,
2830 // every defining declaration of that entity shall specify an
2831 // equivalent alignment.
2832 // C11 6.7.5/7:
2833 // If the definition of an object does not have an alignment
2834 // specifier, any other declaration of that object shall also
2835 // have no alignment specifier.
2836 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2837 << OldAlignasAttr;
2838 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2839 << OldAlignasAttr;
2840 }
2841
2842 bool AnyAdded = false;
2843
2844 // Ensure we have an attribute representing the strictest alignment.
2845 if (OldAlign > NewAlign) {
2846 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2847 Clone->setInherited(true);
2848 New->addAttr(A: Clone);
2849 AnyAdded = true;
2850 }
2851
2852 // Ensure we have an alignas attribute if the old declaration had one.
2853 if (OldAlignasAttr && !NewAlignasAttr &&
2854 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2855 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2856 Clone->setInherited(true);
2857 New->addAttr(A: Clone);
2858 AnyAdded = true;
2859 }
2860
2861 return AnyAdded;
2862}
2863
2864#define WANT_DECL_MERGE_LOGIC
2865#include "clang/Sema/AttrParsedAttrImpl.inc"
2866#undef WANT_DECL_MERGE_LOGIC
2867
2868static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2869 const InheritableAttr *Attr,
2870 AvailabilityMergeKind AMK) {
2871 // Diagnose any mutual exclusions between the attribute that we want to add
2872 // and attributes that already exist on the declaration.
2873 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2874 return false;
2875
2876 // This function copies an attribute Attr from a previous declaration to the
2877 // new declaration D if the new declaration doesn't itself have that attribute
2878 // yet or if that attribute allows duplicates.
2879 // If you're adding a new attribute that requires logic different from
2880 // "use explicit attribute on decl if present, else use attribute from
2881 // previous decl", for example if the attribute needs to be consistent
2882 // between redeclarations, you need to call a custom merge function here.
2883 InheritableAttr *NewAttr = nullptr;
2884 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr))
2885 NewAttr = S.mergeAvailabilityAttr(
2886 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2887 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2888 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2889 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment());
2890 else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2891 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2892 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2893 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2894 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2895 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2896 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2897 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2898 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2899 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2900 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2901 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2902 FirstArg: FA->getFirstArg());
2903 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2904 NewAttr = S.mergeFormatMatchesAttr(
2905 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2906 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2907 NewAttr = S.mergeModularFormatAttr(
2908 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2909 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2910 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2911 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2912 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2913 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2914 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2915 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2916 Model: IA->getInheritanceModel());
2917 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2918 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2919 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2920 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2921 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2922 isa<CUDAGlobalAttr>(Val: Attr))) {
2923 // CUDA target attributes are part of function signature for
2924 // overloading purposes and must not be merged.
2925 return false;
2926 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2927 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2928 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2929 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2930 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2931 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2932 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2933 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2934 else if (isa<AlignedAttr>(Val: Attr))
2935 // AlignedAttrs are handled separately, because we need to handle all
2936 // such attributes on a declaration at the same time.
2937 NewAttr = nullptr;
2938 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2939 (AMK == AvailabilityMergeKind::Override ||
2940 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2941 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2942 NewAttr = nullptr;
2943 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2944 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2945 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2946 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2947 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2948 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2949 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2950 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2951 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2952 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2953 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2954 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2955 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2956 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2957 Z: NT->getZ());
2958 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
2959 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
2960 Preferred: WS->getPreferred(),
2961 SpelledArgsCount: WS->getSpelledArgsCount());
2962 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
2963 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
2964 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
2965 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
2966 else if (isa<SuppressAttr>(Val: Attr))
2967 // Do nothing. Each redeclaration should be suppressed separately.
2968 NewAttr = nullptr;
2969 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
2970 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
2971 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
2972 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
2973
2974 if (NewAttr) {
2975 NewAttr->setInherited(true);
2976 D->addAttr(A: NewAttr);
2977 if (isa<MSInheritanceAttr>(Val: NewAttr))
2978 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
2979 return true;
2980 }
2981
2982 return false;
2983}
2984
2985static const NamedDecl *getDefinition(const Decl *D) {
2986 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
2987 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2988 return Def;
2989 return nullptr;
2990 }
2991 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2992 const VarDecl *Def = VD->getDefinition();
2993 if (Def)
2994 return Def;
2995 return VD->getActingDefinition();
2996 }
2997 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2998 const FunctionDecl *Def = nullptr;
2999 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3000 return Def;
3001 }
3002 return nullptr;
3003}
3004
3005static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3006 for (const auto *Attribute : D->attrs())
3007 if (Attribute->getKind() == Kind)
3008 return true;
3009 return false;
3010}
3011
3012/// checkNewAttributesAfterDef - If we already have a definition, check that
3013/// there are no new attributes in this declaration.
3014static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3015 if (!New->hasAttrs())
3016 return;
3017
3018 const NamedDecl *Def = getDefinition(D: Old);
3019 if (!Def || Def == New)
3020 return;
3021
3022 AttrVec &NewAttributes = New->getAttrs();
3023 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3024 Attr *NewAttribute = NewAttributes[I];
3025
3026 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3028 SkipBodyInfo SkipBody;
3029 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3030
3031 // If we're skipping this definition, drop the "alias" attribute.
3032 if (SkipBody.ShouldSkip) {
3033 NewAttributes.erase(CI: NewAttributes.begin() + I);
3034 --E;
3035 continue;
3036 }
3037 } else {
3038 VarDecl *VD = cast<VarDecl>(Val: New);
3039 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3040 VarDecl::TentativeDefinition
3041 ? diag::err_alias_after_tentative
3042 : diag::err_redefinition;
3043 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3044 if (Diag == diag::err_redefinition)
3045 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3046 else
3047 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3048 VD->setInvalidDecl();
3049 }
3050 ++I;
3051 continue;
3052 }
3053
3054 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3055 // Tentative definitions are only interesting for the alias check above.
3056 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3057 ++I;
3058 continue;
3059 }
3060 }
3061
3062 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3063 ++I;
3064 continue; // regular attr merging will take care of validating this.
3065 }
3066
3067 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3068 // C's _Noreturn is allowed to be added to a function after it is defined.
3069 ++I;
3070 continue;
3071 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3072 // msvc will allow a subsequent definition to add an uuid to a class
3073 ++I;
3074 continue;
3075 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3076 Val: NewAttribute) &&
3077 NewAttribute->isStandardAttributeSyntax()) {
3078 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3079 // deprecated attribute can later be re-declared with the attribute and
3080 // vice-versa.
3081 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3082 // maybe_unused attribute can later be redeclared with the attribute and
3083 // vice versa.
3084 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3085 // nodiscard attribute can later be redeclared with the attribute and
3086 // vice-versa.
3087 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3088 ++I;
3089 continue;
3090 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3091 if (AA->isAlignas()) {
3092 // C++11 [dcl.align]p6:
3093 // if any declaration of an entity has an alignment-specifier,
3094 // every defining declaration of that entity shall specify an
3095 // equivalent alignment.
3096 // C11 6.7.5/7:
3097 // If the definition of an object does not have an alignment
3098 // specifier, any other declaration of that object shall also
3099 // have no alignment specifier.
3100 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3101 << AA;
3102 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3103 << AA;
3104 NewAttributes.erase(CI: NewAttributes.begin() + I);
3105 --E;
3106 continue;
3107 }
3108 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3109 // If there is a C definition followed by a redeclaration with this
3110 // attribute then there are two different definitions. In C++, prefer the
3111 // standard diagnostics.
3112 if (!S.getLangOpts().CPlusPlus) {
3113 S.Diag(Loc: NewAttribute->getLocation(),
3114 DiagID: diag::err_loader_uninitialized_redeclaration);
3115 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3116 NewAttributes.erase(CI: NewAttributes.begin() + I);
3117 --E;
3118 continue;
3119 }
3120 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3121 cast<VarDecl>(Val: New)->isInline() &&
3122 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3123 // Don't warn about applying selectany to implicitly inline variables.
3124 // Older compilers and language modes would require the use of selectany
3125 // to make such variables inline, and it would have no effect if we
3126 // honored it.
3127 ++I;
3128 continue;
3129 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3130 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3131 // declarations after definitions.
3132 ++I;
3133 continue;
3134 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3135 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3136 // error since the definition will have already been created without
3137 // the semantic effects of the attribute having been applied.
3138 S.Diag(Loc: NewAttribute->getLocation(),
3139 DiagID: diag::err_sycl_entry_point_after_definition)
3140 << NewAttribute;
3141 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3142 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3143 ++I;
3144 continue;
3145 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3146 // SYCLExternalAttr may be added after a definition.
3147 ++I;
3148 continue;
3149 }
3150
3151 S.Diag(Loc: NewAttribute->getLocation(),
3152 DiagID: diag::warn_attribute_precede_definition);
3153 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3154 NewAttributes.erase(CI: NewAttributes.begin() + I);
3155 --E;
3156 }
3157}
3158
3159static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3160 const ConstInitAttr *CIAttr,
3161 bool AttrBeforeInit) {
3162 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3163
3164 // Figure out a good way to write this specifier on the old declaration.
3165 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3166 // enough of the attribute list spelling information to extract that without
3167 // heroics.
3168 std::string SuitableSpelling;
3169 if (S.getLangOpts().CPlusPlus20)
3170 SuitableSpelling = std::string(
3171 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3172 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3173 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3174 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3175 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3176 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3177 tok::r_square, tok::r_square}));
3178 if (SuitableSpelling.empty())
3179 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3180 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3181 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3182 tok::r_paren, tok::r_paren}));
3183 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3184 SuitableSpelling = "constinit";
3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3186 SuitableSpelling = "[[clang::require_constant_initialization]]";
3187 if (SuitableSpelling.empty())
3188 SuitableSpelling = "__attribute__((require_constant_initialization))";
3189 SuitableSpelling += " ";
3190
3191 if (AttrBeforeInit) {
3192 // extern constinit int a;
3193 // int a = 0; // error (missing 'constinit'), accepted as extension
3194 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3195 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3196 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3197 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3198 } else {
3199 // int a = 0;
3200 // constinit extern int a; // error (missing 'constinit')
3201 S.Diag(Loc: CIAttr->getLocation(),
3202 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3203 : diag::warn_require_const_init_added_too_late)
3204 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3205 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3206 << CIAttr->isConstinit()
3207 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3208 }
3209}
3210
3211void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3212 AvailabilityMergeKind AMK) {
3213 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3214 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3215 NewAttr->setInherited(true);
3216 New->addAttr(A: NewAttr);
3217 }
3218 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3219 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3220 NewAttr->setInherited(true);
3221 New->addAttr(A: NewAttr);
3222 }
3223
3224 if (!Old->hasAttrs() && !New->hasAttrs())
3225 return;
3226
3227 // [dcl.constinit]p1:
3228 // If the [constinit] specifier is applied to any declaration of a
3229 // variable, it shall be applied to the initializing declaration.
3230 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3231 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3232 if (bool(OldConstInit) != bool(NewConstInit)) {
3233 const auto *OldVD = cast<VarDecl>(Val: Old);
3234 auto *NewVD = cast<VarDecl>(Val: New);
3235
3236 // Find the initializing declaration. Note that we might not have linked
3237 // the new declaration into the redeclaration chain yet.
3238 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3239 if (!InitDecl &&
3240 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3241 InitDecl = NewVD;
3242
3243 if (InitDecl == NewVD) {
3244 // This is the initializing declaration. If it would inherit 'constinit',
3245 // that's ill-formed. (Note that we do not apply this to the attribute
3246 // form).
3247 if (OldConstInit && OldConstInit->isConstinit())
3248 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3249 /*AttrBeforeInit=*/true);
3250 } else if (NewConstInit) {
3251 // This is the first time we've been told that this declaration should
3252 // have a constant initializer. If we already saw the initializing
3253 // declaration, this is too late.
3254 if (InitDecl && InitDecl != NewVD) {
3255 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3256 /*AttrBeforeInit=*/false);
3257 NewVD->dropAttr<ConstInitAttr>();
3258 }
3259 }
3260 }
3261
3262 // Attributes declared post-definition are currently ignored.
3263 checkNewAttributesAfterDef(S&: *this, New, Old);
3264
3265 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3266 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3267 if (!OldA->isEquivalent(Other: NewA)) {
3268 // This redeclaration changes __asm__ label.
3269 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3270 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3271 }
3272 } else if (Old->isUsed()) {
3273 // This redeclaration adds an __asm__ label to a declaration that has
3274 // already been ODR-used.
3275 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3276 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3277 }
3278 }
3279
3280 // Re-declaration cannot add abi_tag's.
3281 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3282 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3283 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3284 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3285 Diag(Loc: NewAbiTagAttr->getLocation(),
3286 DiagID: diag::err_new_abi_tag_on_redeclaration)
3287 << NewTag;
3288 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3289 }
3290 }
3291 } else {
3292 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3293 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3294 }
3295 }
3296
3297 // This redeclaration adds a section attribute.
3298 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3299 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3300 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3301 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3302 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3303 }
3304 }
3305 }
3306
3307 // Redeclaration adds code-seg attribute.
3308 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3309 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3310 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3311 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3312 << 0 /*codeseg*/;
3313 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3314 }
3315
3316 if (!Old->hasAttrs())
3317 return;
3318
3319 bool foundAny = New->hasAttrs();
3320
3321 // Ensure that any moving of objects within the allocated map is done before
3322 // we process them.
3323 if (!foundAny) New->setAttrs(AttrVec());
3324
3325 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3326 // Ignore deprecated/unavailable/availability attributes if requested.
3327 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3328 if (isa<DeprecatedAttr>(Val: I) ||
3329 isa<UnavailableAttr>(Val: I) ||
3330 isa<AvailabilityAttr>(Val: I)) {
3331 switch (AMK) {
3332 case AvailabilityMergeKind::None:
3333 continue;
3334
3335 case AvailabilityMergeKind::Redeclaration:
3336 case AvailabilityMergeKind::Override:
3337 case AvailabilityMergeKind::ProtocolImplementation:
3338 case AvailabilityMergeKind::OptionalProtocolImplementation:
3339 LocalAMK = AMK;
3340 break;
3341 }
3342 }
3343
3344 // Already handled.
3345 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3346 continue;
3347
3348 if (isa<InferredNoReturnAttr>(Val: I)) {
3349 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3350 FD &&
3351 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3352 continue; // Don't propagate inferred noreturn attributes to explicit
3353 }
3354
3355 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3356 foundAny = true;
3357 }
3358
3359 if (mergeAlignedAttrs(S&: *this, New, Old))
3360 foundAny = true;
3361
3362 if (!foundAny) New->dropAttrs();
3363}
3364
3365void Sema::CheckAttributesOnDeducedType(Decl *D) {
3366 for (const Attr *A : D->attrs())
3367 checkAttrIsTypeDependent(D, A);
3368}
3369
3370// Returns the number of added attributes.
3371template <class T>
3372static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3373 Sema &S) {
3374 unsigned found = 0;
3375 for (const auto *I : From->specific_attrs<T>()) {
3376 if (!DeclHasAttr(To, I)) {
3377 T *newAttr = cast<T>(I->clone(S.Context));
3378 newAttr->setInherited(true);
3379 To->addAttr(A: newAttr);
3380 ++found;
3381 }
3382 }
3383 return found;
3384}
3385
3386template <class F>
3387static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3388 F &&propagator) {
3389 if (!From->hasAttrs()) {
3390 return;
3391 }
3392
3393 bool foundAny = To->hasAttrs();
3394
3395 // Ensure that any moving of objects within the allocated map is
3396 // done before we process them.
3397 if (!foundAny)
3398 To->setAttrs(AttrVec());
3399
3400 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3401
3402 if (!foundAny)
3403 To->dropAttrs();
3404}
3405
3406/// mergeParamDeclAttributes - Copy attributes from the old parameter
3407/// to the new one.
3408static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3409 const ParmVarDecl *oldDecl,
3410 Sema &S) {
3411 // C++11 [dcl.attr.depend]p2:
3412 // The first declaration of a function shall specify the
3413 // carries_dependency attribute for its declarator-id if any declaration
3414 // of the function specifies the carries_dependency attribute.
3415 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3416 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3417 S.Diag(Loc: CDA->getLocation(),
3418 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3419 // Find the first declaration of the parameter.
3420 // FIXME: Should we build redeclaration chains for function parameters?
3421 const FunctionDecl *FirstFD =
3422 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3423 const ParmVarDecl *FirstVD =
3424 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3425 S.Diag(Loc: FirstVD->getLocation(),
3426 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3427 }
3428
3429 propagateAttributes(
3430 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3431 unsigned found = 0;
3432 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3433 // Propagate the lifetimebound attribute from parameters to the
3434 // most recent declaration. Note that this doesn't include the implicit
3435 // 'this' parameter, as the attribute is applied to the function type in
3436 // that case.
3437 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3438 return found;
3439 });
3440}
3441
3442static bool EquivalentArrayTypes(QualType Old, QualType New,
3443 const ASTContext &Ctx) {
3444
3445 auto NoSizeInfo = [&Ctx](QualType Ty) {
3446 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3447 return true;
3448 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3449 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3450 return false;
3451 };
3452
3453 // `type[]` is equivalent to `type *` and `type[*]`.
3454 if (NoSizeInfo(Old) && NoSizeInfo(New))
3455 return true;
3456
3457 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3458 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3459 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3460 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3461 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3462 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3463 return false;
3464 return true;
3465 }
3466
3467 // Only compare size, ignore Size modifiers and CVR.
3468 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3469 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3470 Ctx.getAsConstantArrayType(T: New)->getSize();
3471 }
3472
3473 // Don't try to compare dependent sized array
3474 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3475 return true;
3476 }
3477
3478 return Old == New;
3479}
3480
3481static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3482 const ParmVarDecl *OldParam,
3483 Sema &S) {
3484 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3485 if (auto Newnullability = NewParam->getType()->getNullability()) {
3486 if (*Oldnullability != *Newnullability) {
3487 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3488 << DiagNullabilityKind(
3489 *Newnullability,
3490 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3491 != 0))
3492 << DiagNullabilityKind(
3493 *Oldnullability,
3494 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3495 != 0));
3496 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3497 }
3498 } else {
3499 QualType NewT = NewParam->getType();
3500 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3501 NewParam->setType(NewT);
3502 }
3503 }
3504 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3505 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3506 if (OldParamDT && NewParamDT &&
3507 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3508 QualType OldParamOT = OldParamDT->getOriginalType();
3509 QualType NewParamOT = NewParamDT->getOriginalType();
3510 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3511 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3512 << NewParam << NewParamOT;
3513 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3514 << OldParamOT;
3515 }
3516 }
3517}
3518
3519namespace {
3520
3521/// Used in MergeFunctionDecl to keep track of function parameters in
3522/// C.
3523struct GNUCompatibleParamWarning {
3524 ParmVarDecl *OldParm;
3525 ParmVarDecl *NewParm;
3526 QualType PromotedType;
3527};
3528
3529} // end anonymous namespace
3530
3531// Determine whether the previous declaration was a definition, implicit
3532// declaration, or a declaration.
3533template <typename T>
3534static std::pair<diag::kind, SourceLocation>
3535getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3536 diag::kind PrevDiag;
3537 SourceLocation OldLocation = Old->getLocation();
3538 if (Old->isThisDeclarationADefinition())
3539 PrevDiag = diag::note_previous_definition;
3540 else if (Old->isImplicit()) {
3541 PrevDiag = diag::note_previous_implicit_declaration;
3542 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3543 if (FD->getBuiltinID())
3544 PrevDiag = diag::note_previous_builtin_declaration;
3545 }
3546 if (OldLocation.isInvalid())
3547 OldLocation = New->getLocation();
3548 } else
3549 PrevDiag = diag::note_previous_declaration;
3550 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3551}
3552
3553/// canRedefineFunction - checks if a function can be redefined. Currently,
3554/// only extern inline functions can be redefined, and even then only in
3555/// GNU89 mode.
3556static bool canRedefineFunction(const FunctionDecl *FD,
3557 const LangOptions& LangOpts) {
3558 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3559 !LangOpts.CPlusPlus &&
3560 FD->isInlineSpecified() &&
3561 FD->getStorageClass() == SC_Extern);
3562}
3563
3564const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3565 const AttributedType *AT = T->getAs<AttributedType>();
3566 while (AT && !AT->isCallingConv())
3567 AT = AT->getModifiedType()->getAs<AttributedType>();
3568 return AT;
3569}
3570
3571template <typename T>
3572static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3573 const DeclContext *DC = Old->getDeclContext();
3574 if (DC->isRecord())
3575 return false;
3576
3577 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3578 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3579 return true;
3580 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3581 return true;
3582 return false;
3583}
3584
3585template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3586static bool isExternC(VarTemplateDecl *) { return false; }
3587static bool isExternC(FunctionTemplateDecl *) { return false; }
3588
3589/// Check whether a redeclaration of an entity introduced by a
3590/// using-declaration is valid, given that we know it's not an overload
3591/// (nor a hidden tag declaration).
3592template<typename ExpectedDecl>
3593static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3594 ExpectedDecl *New) {
3595 // C++11 [basic.scope.declarative]p4:
3596 // Given a set of declarations in a single declarative region, each of
3597 // which specifies the same unqualified name,
3598 // -- they shall all refer to the same entity, or all refer to functions
3599 // and function templates; or
3600 // -- exactly one declaration shall declare a class name or enumeration
3601 // name that is not a typedef name and the other declarations shall all
3602 // refer to the same variable or enumerator, or all refer to functions
3603 // and function templates; in this case the class name or enumeration
3604 // name is hidden (3.3.10).
3605
3606 // C++11 [namespace.udecl]p14:
3607 // If a function declaration in namespace scope or block scope has the
3608 // same name and the same parameter-type-list as a function introduced
3609 // by a using-declaration, and the declarations do not declare the same
3610 // function, the program is ill-formed.
3611
3612 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3613 if (Old &&
3614 !Old->getDeclContext()->getRedeclContext()->Equals(
3615 New->getDeclContext()->getRedeclContext()) &&
3616 !(isExternC(Old) && isExternC(New)))
3617 Old = nullptr;
3618
3619 if (!Old) {
3620 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3621 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3622 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3623 return true;
3624 }
3625 return false;
3626}
3627
3628static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3629 const FunctionDecl *B) {
3630 assert(A->getNumParams() == B->getNumParams());
3631
3632 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3633 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3634 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3635 if (AttrA == AttrB)
3636 return true;
3637 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3638 AttrA->isDynamic() == AttrB->isDynamic();
3639 };
3640
3641 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3642}
3643
3644/// If necessary, adjust the semantic declaration context for a qualified
3645/// declaration to name the correct inline namespace within the qualifier.
3646static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3647 DeclaratorDecl *OldD) {
3648 // The only case where we need to update the DeclContext is when
3649 // redeclaration lookup for a qualified name finds a declaration
3650 // in an inline namespace within the context named by the qualifier:
3651 //
3652 // inline namespace N { int f(); }
3653 // int ::f(); // Sema DC needs adjusting from :: to N::.
3654 //
3655 // For unqualified declarations, the semantic context *can* change
3656 // along the redeclaration chain (for local extern declarations,
3657 // extern "C" declarations, and friend declarations in particular).
3658 if (!NewD->getQualifier())
3659 return;
3660
3661 // NewD is probably already in the right context.
3662 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3663 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3664 if (NamedDC->Equals(DC: SemaDC))
3665 return;
3666
3667 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3668 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3669 "unexpected context for redeclaration");
3670
3671 auto *LexDC = NewD->getLexicalDeclContext();
3672 auto FixSemaDC = [=](NamedDecl *D) {
3673 if (!D)
3674 return;
3675 D->setDeclContext(SemaDC);
3676 D->setLexicalDeclContext(LexDC);
3677 };
3678
3679 FixSemaDC(NewD);
3680 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3681 FixSemaDC(FD->getDescribedFunctionTemplate());
3682 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3683 FixSemaDC(VD->getDescribedVarTemplate());
3684}
3685
3686bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3687 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3688 // Verify the old decl was also a function.
3689 FunctionDecl *Old = OldD->getAsFunction();
3690 if (!Old) {
3691 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3692 // We don't need to check the using friend pattern from other module unit
3693 // since we should have diagnosed such cases in its unit already.
3694 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3695 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3696 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3697 DiagID: diag::note_using_decl_target);
3698 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3699 << 0;
3700 return true;
3701 }
3702
3703 // Check whether the two declarations might declare the same function or
3704 // function template.
3705 if (FunctionTemplateDecl *NewTemplate =
3706 New->getDescribedFunctionTemplate()) {
3707 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3708 New: NewTemplate))
3709 return true;
3710 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3711 ->getAsFunction();
3712 } else {
3713 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3714 return true;
3715 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3716 }
3717 } else {
3718 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3719 << New->getDeclName();
3720 notePreviousDefinition(Old: OldD, New: New->getLocation());
3721 return true;
3722 }
3723 }
3724
3725 // If the old declaration was found in an inline namespace and the new
3726 // declaration was qualified, update the DeclContext to match.
3727 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3728
3729 // If the old declaration is invalid, just give up here.
3730 if (Old->isInvalidDecl())
3731 return true;
3732
3733 // Disallow redeclaration of some builtins.
3734 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3735 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3736 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3737 << Old << Old->getType();
3738 return true;
3739 }
3740
3741 diag::kind PrevDiag;
3742 SourceLocation OldLocation;
3743 std::tie(args&: PrevDiag, args&: OldLocation) =
3744 getNoteDiagForInvalidRedeclaration(Old, New);
3745
3746 // Don't complain about this if we're in GNU89 mode and the old function
3747 // is an extern inline function.
3748 // Don't complain about specializations. They are not supposed to have
3749 // storage classes.
3750 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3751 New->getStorageClass() == SC_Static &&
3752 Old->hasExternalFormalLinkage() &&
3753 !New->getTemplateSpecializationInfo() &&
3754 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3755 if (getLangOpts().MicrosoftExt) {
3756 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3757 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3758 } else {
3759 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3760 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3761 return true;
3762 }
3763 }
3764
3765 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3766 if (!Old->hasAttr<InternalLinkageAttr>()) {
3767 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3768 << ILA;
3769 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3770 New->dropAttr<InternalLinkageAttr>();
3771 }
3772
3773 if (auto *EA = New->getAttr<ErrorAttr>()) {
3774 if (!Old->hasAttr<ErrorAttr>()) {
3775 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3776 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3777 New->dropAttr<ErrorAttr>();
3778 }
3779 }
3780
3781 if (CheckRedeclarationInModule(New, Old))
3782 return true;
3783
3784 if (!getLangOpts().CPlusPlus) {
3785 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3786 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3787 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3788 << New << OldOvl;
3789
3790 // Try our best to find a decl that actually has the overloadable
3791 // attribute for the note. In most cases (e.g. programs with only one
3792 // broken declaration/definition), this won't matter.
3793 //
3794 // FIXME: We could do this if we juggled some extra state in
3795 // OverloadableAttr, rather than just removing it.
3796 const Decl *DiagOld = Old;
3797 if (OldOvl) {
3798 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3799 const auto *A = D->getAttr<OverloadableAttr>();
3800 return A && !A->isImplicit();
3801 });
3802 // If we've implicitly added *all* of the overloadable attrs to this
3803 // chain, emitting a "previous redecl" note is pointless.
3804 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3805 }
3806
3807 if (DiagOld)
3808 Diag(Loc: DiagOld->getLocation(),
3809 DiagID: diag::note_attribute_overloadable_prev_overload)
3810 << OldOvl;
3811
3812 if (OldOvl)
3813 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3814 else
3815 New->dropAttr<OverloadableAttr>();
3816 }
3817 }
3818
3819 // It is not permitted to redeclare an SME function with different SME
3820 // attributes.
3821 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3822 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3823 << New->getType() << Old->getType();
3824 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3825 return true;
3826 }
3827
3828 // If a function is first declared with a calling convention, but is later
3829 // declared or defined without one, all following decls assume the calling
3830 // convention of the first.
3831 //
3832 // It's OK if a function is first declared without a calling convention,
3833 // but is later declared or defined with the default calling convention.
3834 //
3835 // To test if either decl has an explicit calling convention, we look for
3836 // AttributedType sugar nodes on the type as written. If they are missing or
3837 // were canonicalized away, we assume the calling convention was implicit.
3838 //
3839 // Note also that we DO NOT return at this point, because we still have
3840 // other tests to run.
3841 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3842 QualType NewQType = Context.getCanonicalType(T: New->getType());
3843 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3844 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3845 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3846 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3847 bool RequiresAdjustment = false;
3848
3849 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3850 FunctionDecl *First = Old->getFirstDecl();
3851 const FunctionType *FT =
3852 First->getType().getCanonicalType()->castAs<FunctionType>();
3853 FunctionType::ExtInfo FI = FT->getExtInfo();
3854 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3855 if (!NewCCExplicit) {
3856 // Inherit the CC from the previous declaration if it was specified
3857 // there but not here.
3858 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3859 RequiresAdjustment = true;
3860 } else if (Old->getBuiltinID()) {
3861 // Builtin attribute isn't propagated to the new one yet at this point,
3862 // so we check if the old one is a builtin.
3863
3864 // Calling Conventions on a Builtin aren't really useful and setting a
3865 // default calling convention and cdecl'ing some builtin redeclarations is
3866 // common, so warn and ignore the calling convention on the redeclaration.
3867 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3868 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3869 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3870 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3871 RequiresAdjustment = true;
3872 } else {
3873 // Calling conventions aren't compatible, so complain.
3874 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3875 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3876 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3877 << !FirstCCExplicit
3878 << (!FirstCCExplicit ? "" :
3879 FunctionType::getNameForCallConv(CC: FI.getCC()));
3880
3881 // Put the note on the first decl, since it is the one that matters.
3882 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3883 return true;
3884 }
3885 }
3886
3887 // FIXME: diagnose the other way around?
3888 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3889 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3890 RequiresAdjustment = true;
3891 }
3892
3893 // If the declaration is marked with cfi_unchecked_callee but the definition
3894 // isn't, the definition is also cfi_unchecked_callee.
3895 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3896 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3897 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3898 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3899
3900 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3901 EPI2.CFIUncheckedCallee = true;
3902 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3903 Args: FPT2->getParamTypes(), EPI: EPI2);
3904 NewType = cast<FunctionType>(Val&: NewQType);
3905 New->setType(NewQType);
3906 }
3907 }
3908 }
3909
3910 // Merge regparm attribute.
3911 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3912 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3913 if (NewTypeInfo.getHasRegParm()) {
3914 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3915 << NewType->getRegParmType()
3916 << OldType->getRegParmType();
3917 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3918 return true;
3919 }
3920
3921 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3922 RequiresAdjustment = true;
3923 }
3924
3925 // Merge ns_returns_retained attribute.
3926 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3927 if (NewTypeInfo.getProducesResult()) {
3928 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3929 << "'ns_returns_retained'";
3930 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3931 return true;
3932 }
3933
3934 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3935 RequiresAdjustment = true;
3936 }
3937
3938 if (OldTypeInfo.getNoCallerSavedRegs() !=
3939 NewTypeInfo.getNoCallerSavedRegs()) {
3940 if (NewTypeInfo.getNoCallerSavedRegs()) {
3941 AnyX86NoCallerSavedRegistersAttr *Attr =
3942 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3943 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3944 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3945 return true;
3946 }
3947
3948 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3949 RequiresAdjustment = true;
3950 }
3951
3952 if (RequiresAdjustment) {
3953 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3954 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3955 New->setType(QualType(AdjustedType, 0));
3956 NewQType = Context.getCanonicalType(T: New->getType());
3957 }
3958
3959 // If this redeclaration makes the function inline, we may need to add it to
3960 // UndefinedButUsed.
3961 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3962 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
3963 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3964 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
3965 y: SourceLocation()));
3966
3967 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3968 // about it.
3969 if (New->hasAttr<GNUInlineAttr>() &&
3970 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3971 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
3972 }
3973
3974 // If pass_object_size params don't match up perfectly, this isn't a valid
3975 // redeclaration.
3976 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3977 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3978 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
3979 << New->getDeclName();
3980 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3981 return true;
3982 }
3983
3984 QualType OldQTypeForComparison = OldQType;
3985 if (Context.hasAnyFunctionEffects()) {
3986 const auto OldFX = Old->getFunctionEffects();
3987 const auto NewFX = New->getFunctionEffects();
3988 if (OldFX != NewFX) {
3989 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3990 for (const auto &Diff : Diffs) {
3991 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
3992 Diag(Loc: New->getLocation(),
3993 DiagID: diag::warn_mismatched_func_effect_redeclaration)
3994 << Diff.effectName();
3995 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3996 }
3997 }
3998 // Following a warning, we could skip merging effects from the previous
3999 // declaration, but that would trigger an additional "conflicting types"
4000 // error.
4001 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4002 FunctionEffectSet::Conflicts MergeErrs;
4003 FunctionEffectSet MergedFX =
4004 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4005 if (!MergeErrs.empty())
4006 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4007 OldLoc: Old->getLocation());
4008
4009 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4010 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4011 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4012 Args: NewFPT->getParamTypes(), EPI);
4013
4014 New->setType(ModQT);
4015 NewQType = New->getType();
4016
4017 // Revise OldQTForComparison to include the merged effects,
4018 // so as not to fail due to differences later.
4019 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4020 EPI = OldFPT->getExtProtoInfo();
4021 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4022 OldQTypeForComparison = Context.getFunctionType(
4023 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4024 }
4025 if (OldFX.empty()) {
4026 // A redeclaration may add the attribute to a previously seen function
4027 // body which needs to be verified.
4028 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4029 }
4030 }
4031 }
4032 }
4033
4034 if (getLangOpts().CPlusPlus) {
4035 OldQType = Context.getCanonicalType(T: Old->getType());
4036 NewQType = Context.getCanonicalType(T: New->getType());
4037
4038 // Go back to the type source info to compare the declared return types,
4039 // per C++1y [dcl.type.auto]p13:
4040 // Redeclarations or specializations of a function or function template
4041 // with a declared return type that uses a placeholder type shall also
4042 // use that placeholder, not a deduced type.
4043 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4044 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4045 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4046 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4047 OldT: OldDeclaredReturnType)) {
4048 QualType ResQT;
4049 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4050 OldDeclaredReturnType->isObjCObjectPointerType())
4051 // FIXME: This does the wrong thing for a deduced return type.
4052 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4053 if (ResQT.isNull()) {
4054 if (New->isCXXClassMember() && New->isOutOfLine())
4055 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4056 << New << New->getReturnTypeSourceRange();
4057 else if (Old->isExternC() && New->isExternC() &&
4058 !Old->hasAttr<OverloadableAttr>() &&
4059 !New->hasAttr<OverloadableAttr>())
4060 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4061 else
4062 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4063 << New->getReturnTypeSourceRange();
4064 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4065 << Old->getReturnTypeSourceRange();
4066 return true;
4067 }
4068 else
4069 NewQType = ResQT;
4070 }
4071
4072 QualType OldReturnType = OldType->getReturnType();
4073 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4074 if (OldReturnType != NewReturnType) {
4075 // If this function has a deduced return type and has already been
4076 // defined, copy the deduced value from the old declaration.
4077 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4078 if (OldAT && OldAT->isDeduced()) {
4079 QualType DT = OldAT->getDeducedType();
4080 if (DT.isNull()) {
4081 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4082 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4083 } else {
4084 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4085 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4086 }
4087 }
4088 }
4089
4090 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4091 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4092 if (OldMethod && NewMethod) {
4093 // Preserve triviality.
4094 NewMethod->setTrivial(OldMethod->isTrivial());
4095
4096 // MSVC allows explicit template specialization at class scope:
4097 // 2 CXXMethodDecls referring to the same function will be injected.
4098 // We don't want a redeclaration error.
4099 bool IsClassScopeExplicitSpecialization =
4100 OldMethod->isFunctionTemplateSpecialization() &&
4101 NewMethod->isFunctionTemplateSpecialization();
4102 bool isFriend = NewMethod->getFriendObjectKind();
4103
4104 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4105 !IsClassScopeExplicitSpecialization) {
4106 // -- Member function declarations with the same name and the
4107 // same parameter types cannot be overloaded if any of them
4108 // is a static member function declaration.
4109 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4110 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4111 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4112 return true;
4113 }
4114
4115 // C++ [class.mem]p1:
4116 // [...] A member shall not be declared twice in the
4117 // member-specification, except that a nested class or member
4118 // class template can be declared and then later defined.
4119 if (!inTemplateInstantiation()) {
4120 unsigned NewDiag;
4121 if (isa<CXXConstructorDecl>(Val: OldMethod))
4122 NewDiag = diag::err_constructor_redeclared;
4123 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4124 NewDiag = diag::err_destructor_redeclared;
4125 else if (isa<CXXConversionDecl>(Val: NewMethod))
4126 NewDiag = diag::err_conv_function_redeclared;
4127 else
4128 NewDiag = diag::err_member_redeclared;
4129
4130 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4131 } else {
4132 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4133 << New << New->getType();
4134 }
4135 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4136 return true;
4137
4138 // Complain if this is an explicit declaration of a special
4139 // member that was initially declared implicitly.
4140 //
4141 // As an exception, it's okay to befriend such methods in order
4142 // to permit the implicit constructor/destructor/operator calls.
4143 } else if (OldMethod->isImplicit()) {
4144 if (isFriend) {
4145 NewMethod->setImplicit();
4146 } else {
4147 Diag(Loc: NewMethod->getLocation(),
4148 DiagID: diag::err_definition_of_implicitly_declared_member)
4149 << New << getSpecialMember(MD: OldMethod);
4150 return true;
4151 }
4152 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4153 Diag(Loc: NewMethod->getLocation(),
4154 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4155 << getSpecialMember(MD: OldMethod);
4156 return true;
4157 }
4158 }
4159
4160 // C++1z [over.load]p2
4161 // Certain function declarations cannot be overloaded:
4162 // -- Function declarations that differ only in the return type,
4163 // the exception specification, or both cannot be overloaded.
4164
4165 // Check the exception specifications match. This may recompute the type of
4166 // both Old and New if it resolved exception specifications, so grab the
4167 // types again after this. Because this updates the type, we do this before
4168 // any of the other checks below, which may update the "de facto" NewQType
4169 // but do not necessarily update the type of New.
4170 if (CheckEquivalentExceptionSpec(Old, New))
4171 return true;
4172
4173 // C++11 [dcl.attr.noreturn]p1:
4174 // The first declaration of a function shall specify the noreturn
4175 // attribute if any declaration of that function specifies the noreturn
4176 // attribute.
4177 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4178 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4179 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4180 << NRA;
4181 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4182 }
4183
4184 // C++11 [dcl.attr.depend]p2:
4185 // The first declaration of a function shall specify the
4186 // carries_dependency attribute for its declarator-id if any declaration
4187 // of the function specifies the carries_dependency attribute.
4188 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4189 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4190 Diag(Loc: CDA->getLocation(),
4191 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4192 Diag(Loc: Old->getFirstDecl()->getLocation(),
4193 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4194 }
4195
4196 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4197 // When a function is declared with SYCL_EXTERNAL, that macro must be
4198 // used on the first declaration of that function in the translation unit.
4199 // Redeclarations of the function in the same translation unit may
4200 // optionally use SYCL_EXTERNAL, but this is not required.
4201 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4202 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4203 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4204 << SEA;
4205 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4206 }
4207
4208 // (C++98 8.3.5p3):
4209 // All declarations for a function shall agree exactly in both the
4210 // return type and the parameter-type-list.
4211 // We also want to respect all the extended bits except noreturn.
4212
4213 // noreturn should now match unless the old type info didn't have it.
4214 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4215 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4216 const FunctionType *OldTypeForComparison
4217 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4218 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4219 assert(OldQTypeForComparison.isCanonical());
4220 }
4221
4222 if (haveIncompatibleLanguageLinkages(Old, New)) {
4223 // As a special case, retain the language linkage from previous
4224 // declarations of a friend function as an extension.
4225 //
4226 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4227 // and is useful because there's otherwise no way to specify language
4228 // linkage within class scope.
4229 //
4230 // Check cautiously as the friend object kind isn't yet complete.
4231 if (New->getFriendObjectKind() != Decl::FOK_None) {
4232 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4233 Diag(Loc: OldLocation, DiagID: PrevDiag);
4234 } else {
4235 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4236 Diag(Loc: OldLocation, DiagID: PrevDiag);
4237 return true;
4238 }
4239 }
4240
4241 // HLSL check parameters for matching ABI specifications.
4242 if (getLangOpts().HLSL) {
4243 if (HLSL().CheckCompatibleParameterABI(New, Old))
4244 return true;
4245
4246 // If no errors are generated when checking parameter ABIs we can check if
4247 // the two declarations have the same type ignoring the ABIs and if so,
4248 // the declarations can be merged. This case for merging is only valid in
4249 // HLSL because there are no valid cases of merging mismatched parameter
4250 // ABIs except the HLSL implicit in and explicit in.
4251 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4252 U: NewQType))
4253 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4254 // Fall through for conflicting redeclarations and redefinitions.
4255 }
4256
4257 // If the function types are compatible, merge the declarations. Ignore the
4258 // exception specifier because it was already checked above in
4259 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4260 // about incompatible types under -fms-compatibility.
4261 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4262 U: NewQType))
4263 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4264
4265 // If the types are imprecise (due to dependent constructs in friends or
4266 // local extern declarations), it's OK if they differ. We'll check again
4267 // during instantiation.
4268 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4269 return false;
4270
4271 // Fall through for conflicting redeclarations and redefinitions.
4272 }
4273
4274 // C: Function types need to be compatible, not identical. This handles
4275 // duplicate function decls like "void f(int); void f(enum X);" properly.
4276 if (!getLangOpts().CPlusPlus) {
4277 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4278 // type is specified by a function definition that contains a (possibly
4279 // empty) identifier list, both shall agree in the number of parameters
4280 // and the type of each parameter shall be compatible with the type that
4281 // results from the application of default argument promotions to the
4282 // type of the corresponding identifier. ...
4283 // This cannot be handled by ASTContext::typesAreCompatible() because that
4284 // doesn't know whether the function type is for a definition or not when
4285 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4286 // we need to cover here is that the number of arguments agree as the
4287 // default argument promotion rules were already checked by
4288 // ASTContext::typesAreCompatible().
4289 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4290 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4291 if (Old->hasInheritedPrototype())
4292 Old = Old->getCanonicalDecl();
4293 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4294 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4295 return true;
4296 }
4297
4298 // If we are merging two functions where only one of them has a prototype,
4299 // we may have enough information to decide to issue a diagnostic that the
4300 // function without a prototype will change behavior in C23. This handles
4301 // cases like:
4302 // void i(); void i(int j);
4303 // void i(int j); void i();
4304 // void i(); void i(int j) {}
4305 // See ActOnFinishFunctionBody() for other cases of the behavior change
4306 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4307 // type without a prototype.
4308 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4309 !New->isImplicit() && !Old->isImplicit()) {
4310 const FunctionDecl *WithProto, *WithoutProto;
4311 if (New->hasWrittenPrototype()) {
4312 WithProto = New;
4313 WithoutProto = Old;
4314 } else {
4315 WithProto = Old;
4316 WithoutProto = New;
4317 }
4318
4319 if (WithProto->getNumParams() != 0) {
4320 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4321 // The one without the prototype will be changing behavior in C23, so
4322 // warn about that one so long as it's a user-visible declaration.
4323 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4324 if (WithoutProto == New)
4325 IsWithoutProtoADef = NewDeclIsDefn;
4326 else
4327 IsWithProtoADef = NewDeclIsDefn;
4328 Diag(Loc: WithoutProto->getLocation(),
4329 DiagID: diag::warn_non_prototype_changes_behavior)
4330 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4331 << (WithoutProto == Old) << IsWithProtoADef;
4332
4333 // The reason the one without the prototype will be changing behavior
4334 // is because of the one with the prototype, so note that so long as
4335 // it's a user-visible declaration. There is one exception to this:
4336 // when the new declaration is a definition without a prototype, the
4337 // old declaration with a prototype is not the cause of the issue,
4338 // and that does not need to be noted because the one with a
4339 // prototype will not change behavior in C23.
4340 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4341 !IsWithoutProtoADef)
4342 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4343 }
4344 }
4345 }
4346
4347 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4348 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4349 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4350 const FunctionProtoType *OldProto = nullptr;
4351 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4352 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4353 // The old declaration provided a function prototype, but the
4354 // new declaration does not. Merge in the prototype.
4355 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4356 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4357 Args: OldProto->getParamTypes(),
4358 EPI: OldProto->getExtProtoInfo());
4359 New->setType(NewQType);
4360 New->setHasInheritedPrototype();
4361
4362 // Synthesize parameters with the same types.
4363 SmallVector<ParmVarDecl *, 16> Params;
4364 for (const auto &ParamType : OldProto->param_types()) {
4365 ParmVarDecl *Param = ParmVarDecl::Create(
4366 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4367 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4368 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4369 Param->setImplicit();
4370 Params.push_back(Elt: Param);
4371 }
4372
4373 New->setParams(Params);
4374 }
4375
4376 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4377 }
4378 }
4379
4380 // Check if the function types are compatible when pointer size address
4381 // spaces are ignored.
4382 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4383 return false;
4384
4385 // GNU C permits a K&R definition to follow a prototype declaration
4386 // if the declared types of the parameters in the K&R definition
4387 // match the types in the prototype declaration, even when the
4388 // promoted types of the parameters from the K&R definition differ
4389 // from the types in the prototype. GCC then keeps the types from
4390 // the prototype.
4391 //
4392 // If a variadic prototype is followed by a non-variadic K&R definition,
4393 // the K&R definition becomes variadic. This is sort of an edge case, but
4394 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4395 // C99 6.9.1p8.
4396 if (!getLangOpts().CPlusPlus &&
4397 Old->hasPrototype() && !New->hasPrototype() &&
4398 New->getType()->getAs<FunctionProtoType>() &&
4399 Old->getNumParams() == New->getNumParams()) {
4400 SmallVector<QualType, 16> ArgTypes;
4401 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4402 const FunctionProtoType *OldProto
4403 = Old->getType()->getAs<FunctionProtoType>();
4404 const FunctionProtoType *NewProto
4405 = New->getType()->getAs<FunctionProtoType>();
4406
4407 // Determine whether this is the GNU C extension.
4408 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4409 NewProto->getReturnType());
4410 bool LooseCompatible = !MergedReturn.isNull();
4411 for (unsigned Idx = 0, End = Old->getNumParams();
4412 LooseCompatible && Idx != End; ++Idx) {
4413 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4414 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4415 if (Context.typesAreCompatible(T1: OldParm->getType(),
4416 T2: NewProto->getParamType(i: Idx))) {
4417 ArgTypes.push_back(Elt: NewParm->getType());
4418 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4419 T2: NewParm->getType(),
4420 /*CompareUnqualified=*/true)) {
4421 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4422 .PromotedType: NewProto->getParamType(i: Idx) };
4423 Warnings.push_back(Elt: Warn);
4424 ArgTypes.push_back(Elt: NewParm->getType());
4425 } else
4426 LooseCompatible = false;
4427 }
4428
4429 if (LooseCompatible) {
4430 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4431 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4432 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4433 << Warnings[Warn].PromotedType
4434 << Warnings[Warn].OldParm->getType();
4435 if (Warnings[Warn].OldParm->getLocation().isValid())
4436 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4437 DiagID: diag::note_previous_declaration);
4438 }
4439
4440 if (MergeTypeWithOld)
4441 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4442 EPI: OldProto->getExtProtoInfo()));
4443 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4444 }
4445
4446 // Fall through to diagnose conflicting types.
4447 }
4448
4449 // A function that has already been declared has been redeclared or
4450 // defined with a different type; show an appropriate diagnostic.
4451
4452 // If the previous declaration was an implicitly-generated builtin
4453 // declaration, then at the very least we should use a specialized note.
4454 unsigned BuiltinID;
4455 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4456 // If it's actually a library-defined builtin function like 'malloc'
4457 // or 'printf', just warn about the incompatible redeclaration.
4458 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4459 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4460 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4461 << Old << Old->getType();
4462 return false;
4463 }
4464
4465 PrevDiag = diag::note_previous_builtin_declaration;
4466 }
4467
4468 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4469 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4470 return true;
4471}
4472
4473bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4474 Scope *S, bool MergeTypeWithOld) {
4475 // Merge the attributes
4476 mergeDeclAttributes(New, Old);
4477
4478 // Merge "pure" flag.
4479 if (Old->isPureVirtual())
4480 New->setIsPureVirtual();
4481
4482 // Merge "used" flag.
4483 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4484 New->setIsUsed();
4485
4486 // Merge attributes from the parameters. These can mismatch with K&R
4487 // declarations.
4488 if (New->getNumParams() == Old->getNumParams())
4489 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4490 ParmVarDecl *NewParam = New->getParamDecl(i);
4491 ParmVarDecl *OldParam = Old->getParamDecl(i);
4492 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4493 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4494 }
4495
4496 if (getLangOpts().CPlusPlus)
4497 return MergeCXXFunctionDecl(New, Old, S);
4498
4499 // Merge the function types so the we get the composite types for the return
4500 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4501 // was visible.
4502 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4503 if (!Merged.isNull() && MergeTypeWithOld)
4504 New->setType(Merged);
4505
4506 return false;
4507}
4508
4509void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4510 ObjCMethodDecl *oldMethod) {
4511 // Merge the attributes, including deprecated/unavailable
4512 AvailabilityMergeKind MergeKind =
4513 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4514 ? (oldMethod->isOptional()
4515 ? AvailabilityMergeKind::OptionalProtocolImplementation
4516 : AvailabilityMergeKind::ProtocolImplementation)
4517 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4518 ? AvailabilityMergeKind::Redeclaration
4519 : AvailabilityMergeKind::Override;
4520
4521 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4522
4523 // Merge attributes from the parameters.
4524 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4525 oe = oldMethod->param_end();
4526 for (ObjCMethodDecl::param_iterator
4527 ni = newMethod->param_begin(), ne = newMethod->param_end();
4528 ni != ne && oi != oe; ++ni, ++oi)
4529 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4530
4531 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4532}
4533
4534static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4535 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4536
4537 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4538 ? diag::err_redefinition_different_type
4539 : diag::err_redeclaration_different_type)
4540 << New->getDeclName() << New->getType() << Old->getType();
4541
4542 diag::kind PrevDiag;
4543 SourceLocation OldLocation;
4544 std::tie(args&: PrevDiag, args&: OldLocation)
4545 = getNoteDiagForInvalidRedeclaration(Old, New);
4546 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4547 New->setInvalidDecl();
4548}
4549
4550void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4551 bool MergeTypeWithOld) {
4552 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4553 return;
4554
4555 QualType MergedT;
4556 if (getLangOpts().CPlusPlus) {
4557 if (New->getType()->isUndeducedType()) {
4558 // We don't know what the new type is until the initializer is attached.
4559 return;
4560 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4561 // These could still be something that needs exception specs checked.
4562 return MergeVarDeclExceptionSpecs(New, Old);
4563 }
4564 // C++ [basic.link]p10:
4565 // [...] the types specified by all declarations referring to a given
4566 // object or function shall be identical, except that declarations for an
4567 // array object can specify array types that differ by the presence or
4568 // absence of a major array bound (8.3.4).
4569 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4570 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4571 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4572
4573 // We are merging a variable declaration New into Old. If it has an array
4574 // bound, and that bound differs from Old's bound, we should diagnose the
4575 // mismatch.
4576 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4577 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4578 PrevVD = PrevVD->getPreviousDecl()) {
4579 QualType PrevVDTy = PrevVD->getType();
4580 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4581 continue;
4582
4583 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4584 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4585 }
4586 }
4587
4588 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4589 if (Context.hasSameType(T1: OldArray->getElementType(),
4590 T2: NewArray->getElementType()))
4591 MergedT = New->getType();
4592 }
4593 // FIXME: Check visibility. New is hidden but has a complete type. If New
4594 // has no array bound, it should not inherit one from Old, if Old is not
4595 // visible.
4596 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4597 if (Context.hasSameType(T1: OldArray->getElementType(),
4598 T2: NewArray->getElementType()))
4599 MergedT = Old->getType();
4600 }
4601 }
4602 else if (New->getType()->isObjCObjectPointerType() &&
4603 Old->getType()->isObjCObjectPointerType()) {
4604 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4605 Old->getType());
4606 }
4607 } else {
4608 // C 6.2.7p2:
4609 // All declarations that refer to the same object or function shall have
4610 // compatible type.
4611 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4612 }
4613 if (MergedT.isNull()) {
4614 // It's OK if we couldn't merge types if either type is dependent, for a
4615 // block-scope variable. In other cases (static data members of class
4616 // templates, variable templates, ...), we require the types to be
4617 // equivalent.
4618 // FIXME: The C++ standard doesn't say anything about this.
4619 if ((New->getType()->isDependentType() ||
4620 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4621 // If the old type was dependent, we can't merge with it, so the new type
4622 // becomes dependent for now. We'll reproduce the original type when we
4623 // instantiate the TypeSourceInfo for the variable.
4624 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4625 New->setType(Context.DependentTy);
4626 return;
4627 }
4628 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4629 }
4630
4631 // Don't actually update the type on the new declaration if the old
4632 // declaration was an extern declaration in a different scope.
4633 if (MergeTypeWithOld)
4634 New->setType(MergedT);
4635}
4636
4637static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4638 LookupResult &Previous) {
4639 // C11 6.2.7p4:
4640 // For an identifier with internal or external linkage declared
4641 // in a scope in which a prior declaration of that identifier is
4642 // visible, if the prior declaration specifies internal or
4643 // external linkage, the type of the identifier at the later
4644 // declaration becomes the composite type.
4645 //
4646 // If the variable isn't visible, we do not merge with its type.
4647 if (Previous.isShadowed())
4648 return false;
4649
4650 if (S.getLangOpts().CPlusPlus) {
4651 // C++11 [dcl.array]p3:
4652 // If there is a preceding declaration of the entity in the same
4653 // scope in which the bound was specified, an omitted array bound
4654 // is taken to be the same as in that earlier declaration.
4655 return NewVD->isPreviousDeclInSameBlockScope() ||
4656 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4657 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4658 } else {
4659 // If the old declaration was function-local, don't merge with its
4660 // type unless we're in the same function.
4661 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4662 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4663 }
4664}
4665
4666void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4667 // If the new decl is already invalid, don't do any other checking.
4668 if (New->isInvalidDecl())
4669 return;
4670
4671 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4672 return;
4673
4674 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4675
4676 // Verify the old decl was also a variable or variable template.
4677 VarDecl *Old = nullptr;
4678 VarTemplateDecl *OldTemplate = nullptr;
4679 if (Previous.isSingleResult()) {
4680 if (NewTemplate) {
4681 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4682 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4683
4684 if (auto *Shadow =
4685 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4686 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4687 return New->setInvalidDecl();
4688 } else {
4689 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4690
4691 if (auto *Shadow =
4692 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4693 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4694 return New->setInvalidDecl();
4695 }
4696 }
4697 if (!Old) {
4698 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4699 << New->getDeclName();
4700 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4701 New: New->getLocation());
4702 return New->setInvalidDecl();
4703 }
4704
4705 // If the old declaration was found in an inline namespace and the new
4706 // declaration was qualified, update the DeclContext to match.
4707 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4708
4709 // Ensure the template parameters are compatible.
4710 if (NewTemplate &&
4711 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4712 Old: OldTemplate->getTemplateParameters(),
4713 /*Complain=*/true, Kind: TPL_TemplateMatch))
4714 return New->setInvalidDecl();
4715
4716 // C++ [class.mem]p1:
4717 // A member shall not be declared twice in the member-specification [...]
4718 //
4719 // Here, we need only consider static data members.
4720 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4721 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4722 << New->getIdentifier();
4723 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4724 New->setInvalidDecl();
4725 }
4726
4727 mergeDeclAttributes(New, Old);
4728 // Warn if an already-defined variable is made a weak_import in a subsequent
4729 // declaration
4730 if (New->hasAttr<WeakImportAttr>())
4731 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4732 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4733 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4734 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4735 // Remove weak_import attribute on new declaration.
4736 New->dropAttr<WeakImportAttr>();
4737 break;
4738 }
4739 }
4740
4741 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4742 if (!Old->hasAttr<InternalLinkageAttr>()) {
4743 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4744 << ILA;
4745 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4746 New->dropAttr<InternalLinkageAttr>();
4747 }
4748
4749 // Merge the types.
4750 VarDecl *MostRecent = Old->getMostRecentDecl();
4751 if (MostRecent != Old) {
4752 MergeVarDeclTypes(New, Old: MostRecent,
4753 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4754 if (New->isInvalidDecl())
4755 return;
4756 }
4757
4758 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4759 if (New->isInvalidDecl())
4760 return;
4761
4762 diag::kind PrevDiag;
4763 SourceLocation OldLocation;
4764 std::tie(args&: PrevDiag, args&: OldLocation) =
4765 getNoteDiagForInvalidRedeclaration(Old, New);
4766
4767 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4768 if (New->getStorageClass() == SC_Static &&
4769 !New->isStaticDataMember() &&
4770 Old->hasExternalFormalLinkage()) {
4771 if (getLangOpts().MicrosoftExt) {
4772 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4773 << New->getDeclName();
4774 Diag(Loc: OldLocation, DiagID: PrevDiag);
4775 } else {
4776 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4777 << New->getDeclName();
4778 Diag(Loc: OldLocation, DiagID: PrevDiag);
4779 return New->setInvalidDecl();
4780 }
4781 }
4782 // C99 6.2.2p4:
4783 // For an identifier declared with the storage-class specifier
4784 // extern in a scope in which a prior declaration of that
4785 // identifier is visible,23) if the prior declaration specifies
4786 // internal or external linkage, the linkage of the identifier at
4787 // the later declaration is the same as the linkage specified at
4788 // the prior declaration. If no prior declaration is visible, or
4789 // if the prior declaration specifies no linkage, then the
4790 // identifier has external linkage.
4791 if (New->hasExternalStorage() && Old->hasLinkage())
4792 /* Okay */;
4793 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4794 !New->isStaticDataMember() &&
4795 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4796 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4797 Diag(Loc: OldLocation, DiagID: PrevDiag);
4798 return New->setInvalidDecl();
4799 }
4800
4801 // Check if extern is followed by non-extern and vice-versa.
4802 if (New->hasExternalStorage() &&
4803 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4804 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4805 Diag(Loc: OldLocation, DiagID: PrevDiag);
4806 return New->setInvalidDecl();
4807 }
4808 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4809 !New->hasExternalStorage()) {
4810 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4811 Diag(Loc: OldLocation, DiagID: PrevDiag);
4812 return New->setInvalidDecl();
4813 }
4814
4815 if (CheckRedeclarationInModule(New, Old))
4816 return;
4817
4818 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4819
4820 // FIXME: The test for external storage here seems wrong? We still
4821 // need to check for mismatches.
4822 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4823 // Don't complain about out-of-line definitions of static members.
4824 !(Old->getLexicalDeclContext()->isRecord() &&
4825 !New->getLexicalDeclContext()->isRecord())) {
4826 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4827 Diag(Loc: OldLocation, DiagID: PrevDiag);
4828 return New->setInvalidDecl();
4829 }
4830
4831 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4832 if (VarDecl *Def = Old->getDefinition()) {
4833 // C++1z [dcl.fcn.spec]p4:
4834 // If the definition of a variable appears in a translation unit before
4835 // its first declaration as inline, the program is ill-formed.
4836 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4837 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4838 }
4839 }
4840
4841 // If this redeclaration makes the variable inline, we may need to add it to
4842 // UndefinedButUsed.
4843 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4844 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4845 !Old->isInAnotherModuleUnit())
4846 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4847 y: SourceLocation()));
4848
4849 if (New->getTLSKind() != Old->getTLSKind()) {
4850 if (!Old->getTLSKind()) {
4851 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4852 Diag(Loc: OldLocation, DiagID: PrevDiag);
4853 } else if (!New->getTLSKind()) {
4854 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4855 Diag(Loc: OldLocation, DiagID: PrevDiag);
4856 } else {
4857 // Do not allow redeclaration to change the variable between requiring
4858 // static and dynamic initialization.
4859 // FIXME: GCC allows this, but uses the TLS keyword on the first
4860 // declaration to determine the kind. Do we need to be compatible here?
4861 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4862 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4863 Diag(Loc: OldLocation, DiagID: PrevDiag);
4864 }
4865 }
4866
4867 // C++ doesn't have tentative definitions, so go right ahead and check here.
4868 if (getLangOpts().CPlusPlus) {
4869 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4870 Old->getCanonicalDecl()->isConstexpr()) {
4871 // This definition won't be a definition any more once it's been merged.
4872 Diag(Loc: New->getLocation(),
4873 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4874 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4875 VarDecl *Def = Old->getDefinition();
4876 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4877 return;
4878 }
4879 } else {
4880 // C++ may not have a tentative definition rule, but it has a different
4881 // rule about what constitutes a definition in the first place. See
4882 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4883 // contains the extern specifier and doesn't have an initializer, it's fine
4884 // in C++.
4885 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4886 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4887 << New;
4888 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4889 }
4890 }
4891
4892 if (haveIncompatibleLanguageLinkages(Old, New)) {
4893 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4894 Diag(Loc: OldLocation, DiagID: PrevDiag);
4895 New->setInvalidDecl();
4896 return;
4897 }
4898
4899 // Merge "used" flag.
4900 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4901 New->setIsUsed();
4902
4903 // Keep a chain of previous declarations.
4904 New->setPreviousDecl(Old);
4905 if (NewTemplate)
4906 NewTemplate->setPreviousDecl(OldTemplate);
4907
4908 // Inherit access appropriately.
4909 New->setAccess(Old->getAccess());
4910 if (NewTemplate)
4911 NewTemplate->setAccess(New->getAccess());
4912
4913 if (Old->isInline())
4914 New->setImplicitlyInline();
4915}
4916
4917void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4918 SourceManager &SrcMgr = getSourceManager();
4919 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4920 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4921 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4922 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4923 auto &HSI = PP.getHeaderSearchInfo();
4924 StringRef HdrFilename =
4925 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4926
4927 auto noteFromModuleOrInclude = [&](Module *Mod,
4928 SourceLocation IncLoc) -> bool {
4929 // Redefinition errors with modules are common with non modular mapped
4930 // headers, example: a non-modular header H in module A that also gets
4931 // included directly in a TU. Pointing twice to the same header/definition
4932 // is confusing, try to get better diagnostics when modules is on.
4933 if (IncLoc.isValid()) {
4934 if (Mod) {
4935 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4936 << HdrFilename.str() << Mod->getFullModuleName();
4937 if (!Mod->DefinitionLoc.isInvalid())
4938 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4939 << Mod->getFullModuleName();
4940 } else {
4941 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4942 << HdrFilename.str();
4943 }
4944 return true;
4945 }
4946
4947 return false;
4948 };
4949
4950 // Is it the same file and same offset? Provide more information on why
4951 // this leads to a redefinition error.
4952 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4953 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4954 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4955 bool EmittedDiag =
4956 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4957 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4958
4959 // If the header has no guards, emit a note suggesting one.
4960 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
4961 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
4962
4963 if (EmittedDiag)
4964 return;
4965 }
4966
4967 // Redefinition coming from different files or couldn't do better above.
4968 if (Old->getLocation().isValid())
4969 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
4970}
4971
4972bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4973 if (!hasVisibleDefinition(D: Old) &&
4974 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4975 isa<VarTemplateSpecializationDecl>(Val: New) ||
4976 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4977 New->getDeclContext()->isDependentContext() ||
4978 New->hasAttr<SelectAnyAttr>())) {
4979 // The previous definition is hidden, and multiple definitions are
4980 // permitted (in separate TUs). Demote this to a declaration.
4981 New->demoteThisDefinitionToDeclaration();
4982
4983 // Make the canonical definition visible.
4984 if (auto *OldTD = Old->getDescribedVarTemplate())
4985 makeMergedDefinitionVisible(ND: OldTD);
4986 makeMergedDefinitionVisible(ND: Old);
4987 return false;
4988 } else {
4989 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
4990 notePreviousDefinition(Old, New: New->getLocation());
4991 New->setInvalidDecl();
4992 return true;
4993 }
4994}
4995
4996Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4997 DeclSpec &DS,
4998 const ParsedAttributesView &DeclAttrs,
4999 RecordDecl *&AnonRecord) {
5000 return ParsedFreeStandingDeclSpec(
5001 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5002}
5003
5004// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5005// disambiguate entities defined in different scopes.
5006// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5007// compatibility.
5008// We will pick our mangling number depending on which version of MSVC is being
5009// targeted.
5010static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5011 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5012 ? S->getMSCurManglingNumber()
5013 : S->getMSLastManglingNumber();
5014}
5015
5016void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5017 if (!Context.getLangOpts().CPlusPlus)
5018 return;
5019
5020 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5021 // If this tag is the direct child of a class, number it if
5022 // it is anonymous.
5023 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5024 return;
5025 MangleNumberingContext &MCtx =
5026 Context.getManglingNumberContext(DC: Tag->getParent());
5027 Context.setManglingNumber(
5028 ND: Tag, Number: MCtx.getManglingNumber(
5029 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5030 return;
5031 }
5032
5033 // If this tag isn't a direct child of a class, number it if it is local.
5034 MangleNumberingContext *MCtx;
5035 Decl *ManglingContextDecl;
5036 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5037 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5038 if (MCtx) {
5039 Context.setManglingNumber(
5040 ND: Tag, Number: MCtx->getManglingNumber(
5041 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5042 }
5043}
5044
5045namespace {
5046struct NonCLikeKind {
5047 enum {
5048 None,
5049 BaseClass,
5050 DefaultMemberInit,
5051 Lambda,
5052 Friend,
5053 OtherMember,
5054 Invalid,
5055 } Kind = None;
5056 SourceRange Range;
5057
5058 explicit operator bool() { return Kind != None; }
5059};
5060}
5061
5062/// Determine whether a class is C-like, according to the rules of C++
5063/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5064static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5065 if (RD->isInvalidDecl())
5066 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5067
5068 // C++ [dcl.typedef]p9: [P1766R1]
5069 // An unnamed class with a typedef name for linkage purposes shall not
5070 //
5071 // -- have any base classes
5072 if (RD->getNumBases())
5073 return {.Kind: NonCLikeKind::BaseClass,
5074 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5075 RD->bases_end()[-1].getEndLoc())};
5076 bool Invalid = false;
5077 for (Decl *D : RD->decls()) {
5078 // Don't complain about things we already diagnosed.
5079 if (D->isInvalidDecl()) {
5080 Invalid = true;
5081 continue;
5082 }
5083
5084 // -- have any [...] default member initializers
5085 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5086 if (FD->hasInClassInitializer()) {
5087 auto *Init = FD->getInClassInitializer();
5088 return {.Kind: NonCLikeKind::DefaultMemberInit,
5089 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5090 }
5091 continue;
5092 }
5093
5094 // FIXME: We don't allow friend declarations. This violates the wording of
5095 // P1766, but not the intent.
5096 if (isa<FriendDecl>(Val: D))
5097 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5098
5099 // -- declare any members other than non-static data members, member
5100 // enumerations, or member classes,
5101 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5102 isa<EnumDecl>(Val: D))
5103 continue;
5104 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5105 if (!MemberRD) {
5106 if (D->isImplicit())
5107 continue;
5108 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5109 }
5110
5111 // -- contain a lambda-expression,
5112 if (MemberRD->isLambda())
5113 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5114
5115 // and all member classes shall also satisfy these requirements
5116 // (recursively).
5117 if (MemberRD->isThisDeclarationADefinition()) {
5118 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5119 return Kind;
5120 }
5121 }
5122
5123 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5124}
5125
5126void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5127 TypedefNameDecl *NewTD) {
5128 if (TagFromDeclSpec->isInvalidDecl())
5129 return;
5130
5131 // Do nothing if the tag already has a name for linkage purposes.
5132 if (TagFromDeclSpec->hasNameForLinkage())
5133 return;
5134
5135 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5136 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5137
5138 // The type must match the tag exactly; no qualifiers allowed.
5139 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5140 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5141 if (getLangOpts().CPlusPlus)
5142 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5143 return;
5144 }
5145
5146 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5147 // An unnamed class with a typedef name for linkage purposes shall [be
5148 // C-like].
5149 //
5150 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5151 // shouldn't happen, but there are constructs that the language rule doesn't
5152 // disallow for which we can't reasonably avoid computing linkage early.
5153 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5154 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5155 : NonCLikeKind();
5156 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5157 if (NonCLike || ChangesLinkage) {
5158 if (NonCLike.Kind == NonCLikeKind::Invalid)
5159 return;
5160
5161 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5162 if (ChangesLinkage) {
5163 // If the linkage changes, we can't accept this as an extension.
5164 if (NonCLike.Kind == NonCLikeKind::None)
5165 DiagID = diag::err_typedef_changes_linkage;
5166 else
5167 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5168 }
5169
5170 SourceLocation FixitLoc =
5171 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5172 llvm::SmallString<40> TextToInsert;
5173 TextToInsert += ' ';
5174 TextToInsert += NewTD->getIdentifier()->getName();
5175
5176 Diag(Loc: FixitLoc, DiagID)
5177 << isa<TypeAliasDecl>(Val: NewTD)
5178 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5179 if (NonCLike.Kind != NonCLikeKind::None) {
5180 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5181 << NonCLike.Kind - 1 << NonCLike.Range;
5182 }
5183 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5184 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5185
5186 if (ChangesLinkage)
5187 return;
5188 }
5189
5190 // Otherwise, set this as the anon-decl typedef for the tag.
5191 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5192
5193 // Now that we have a name for the tag, process API notes again.
5194 ProcessAPINotes(D: TagFromDeclSpec);
5195}
5196
5197static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5198 DeclSpec::TST T = DS.getTypeSpecType();
5199 switch (T) {
5200 case DeclSpec::TST_class:
5201 return 0;
5202 case DeclSpec::TST_struct:
5203 return 1;
5204 case DeclSpec::TST_interface:
5205 return 2;
5206 case DeclSpec::TST_union:
5207 return 3;
5208 case DeclSpec::TST_enum:
5209 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5210 if (ED->isScopedUsingClassTag())
5211 return 5;
5212 if (ED->isScoped())
5213 return 6;
5214 }
5215 return 4;
5216 default:
5217 llvm_unreachable("unexpected type specifier");
5218 }
5219}
5220
5221Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5222 DeclSpec &DS,
5223 const ParsedAttributesView &DeclAttrs,
5224 MultiTemplateParamsArg TemplateParams,
5225 bool IsExplicitInstantiation,
5226 RecordDecl *&AnonRecord,
5227 SourceLocation EllipsisLoc) {
5228 Decl *TagD = nullptr;
5229 TagDecl *Tag = nullptr;
5230 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5231 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5232 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5233 DS.getTypeSpecType() == DeclSpec::TST_union ||
5234 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5235 TagD = DS.getRepAsDecl();
5236
5237 if (!TagD) // We probably had an error
5238 return nullptr;
5239
5240 // Note that the above type specs guarantee that the
5241 // type rep is a Decl, whereas in many of the others
5242 // it's a Type.
5243 if (isa<TagDecl>(Val: TagD))
5244 Tag = cast<TagDecl>(Val: TagD);
5245 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5246 Tag = CTD->getTemplatedDecl();
5247 }
5248
5249 if (Tag) {
5250 handleTagNumbering(Tag, TagScope: S);
5251 Tag->setFreeStanding();
5252 if (Tag->isInvalidDecl())
5253 return Tag;
5254 }
5255
5256 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5257 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5258 // or incomplete types shall not be restrict-qualified."
5259 if (TypeQuals & DeclSpec::TQ_restrict)
5260 Diag(Loc: DS.getRestrictSpecLoc(),
5261 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5262 << DS.getSourceRange();
5263 }
5264
5265 if (DS.isInlineSpecified())
5266 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5267 << getLangOpts().CPlusPlus17;
5268
5269 if (DS.hasConstexprSpecifier()) {
5270 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5271 // and definitions of functions and variables.
5272 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5273 // the declaration of a function or function template
5274 if (Tag)
5275 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5276 << GetDiagnosticTypeSpecifierID(DS)
5277 << static_cast<int>(DS.getConstexprSpecifier());
5278 else if (getLangOpts().C23)
5279 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5280 else
5281 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5282 << static_cast<int>(DS.getConstexprSpecifier());
5283 // Don't emit warnings after this error.
5284 return TagD;
5285 }
5286
5287 DiagnoseFunctionSpecifiers(DS);
5288
5289 if (DS.isFriendSpecified()) {
5290 // If we're dealing with a decl but not a TagDecl, assume that
5291 // whatever routines created it handled the friendship aspect.
5292 if (TagD && !Tag)
5293 return nullptr;
5294 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5295 }
5296
5297 assert(EllipsisLoc.isInvalid() &&
5298 "Friend ellipsis but not friend-specified?");
5299
5300 // Track whether this decl-specifier declares anything.
5301 bool DeclaresAnything = true;
5302
5303 // Handle anonymous struct definitions.
5304 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5305 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5306 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5307 if (getLangOpts().CPlusPlus ||
5308 Record->getDeclContext()->isRecord()) {
5309 // If CurContext is a DeclContext that can contain statements,
5310 // RecursiveASTVisitor won't visit the decls that
5311 // BuildAnonymousStructOrUnion() will put into CurContext.
5312 // Also store them here so that they can be part of the
5313 // DeclStmt that gets created in this case.
5314 // FIXME: Also return the IndirectFieldDecls created by
5315 // BuildAnonymousStructOr union, for the same reason?
5316 if (CurContext->isFunctionOrMethod())
5317 AnonRecord = Record;
5318 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5319 Policy: Context.getPrintingPolicy());
5320 }
5321
5322 DeclaresAnything = false;
5323 }
5324 }
5325
5326 // C11 6.7.2.1p2:
5327 // A struct-declaration that does not declare an anonymous structure or
5328 // anonymous union shall contain a struct-declarator-list.
5329 //
5330 // This rule also existed in C89 and C99; the grammar for struct-declaration
5331 // did not permit a struct-declaration without a struct-declarator-list.
5332 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5333 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5334 // Check for Microsoft C extension: anonymous struct/union member.
5335 // Handle 2 kinds of anonymous struct/union:
5336 // struct STRUCT;
5337 // union UNION;
5338 // and
5339 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5340 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5341 if ((Tag && Tag->getDeclName()) ||
5342 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5343 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5344 : DS.getRepAsType().get()->getAsRecordDecl();
5345 if (Record && getLangOpts().MSAnonymousStructs) {
5346 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5347 << Record->isUnion() << DS.getSourceRange();
5348 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5349 }
5350
5351 DeclaresAnything = false;
5352 }
5353 }
5354
5355 // Skip all the checks below if we have a type error.
5356 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5357 (TagD && TagD->isInvalidDecl()))
5358 return TagD;
5359
5360 if (getLangOpts().CPlusPlus &&
5361 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5362 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5363 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5364 !Enum->isInvalidDecl())
5365 DeclaresAnything = false;
5366
5367 if (!DS.isMissingDeclaratorOk()) {
5368 // Customize diagnostic for a typedef missing a name.
5369 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5370 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5371 << DS.getSourceRange();
5372 else
5373 DeclaresAnything = false;
5374 }
5375
5376 if (DS.isModulePrivateSpecified() &&
5377 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5378 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5379 << Tag->getTagKind()
5380 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5381
5382 ActOnDocumentableDecl(D: TagD);
5383
5384 // C 6.7/2:
5385 // A declaration [...] shall declare at least a declarator [...], a tag,
5386 // or the members of an enumeration.
5387 // C++ [dcl.dcl]p3:
5388 // [If there are no declarators], and except for the declaration of an
5389 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5390 // names into the program, or shall redeclare a name introduced by a
5391 // previous declaration.
5392 if (!DeclaresAnything) {
5393 // In C, we allow this as a (popular) extension / bug. Don't bother
5394 // producing further diagnostics for redundant qualifiers after this.
5395 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5396 ? diag::err_no_declarators
5397 : diag::ext_no_declarators)
5398 << DS.getSourceRange();
5399 return TagD;
5400 }
5401
5402 // C++ [dcl.stc]p1:
5403 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5404 // init-declarator-list of the declaration shall not be empty.
5405 // C++ [dcl.fct.spec]p1:
5406 // If a cv-qualifier appears in a decl-specifier-seq, the
5407 // init-declarator-list of the declaration shall not be empty.
5408 //
5409 // Spurious qualifiers here appear to be valid in C.
5410 unsigned DiagID = diag::warn_standalone_specifier;
5411 if (getLangOpts().CPlusPlus)
5412 DiagID = diag::ext_standalone_specifier;
5413
5414 // Note that a linkage-specification sets a storage class, but
5415 // 'extern "C" struct foo;' is actually valid and not theoretically
5416 // useless.
5417 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5418 if (SCS == DeclSpec::SCS_mutable)
5419 // Since mutable is not a viable storage class specifier in C, there is
5420 // no reason to treat it as an extension. Instead, diagnose as an error.
5421 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5422 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5423 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5424 << DeclSpec::getSpecifierName(S: SCS);
5425 }
5426
5427 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5428 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5429 << DeclSpec::getSpecifierName(S: TSCS);
5430 if (DS.getTypeQualifiers()) {
5431 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5432 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5433 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5434 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5435 // Restrict is covered above.
5436 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5437 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5438 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5439 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5440 }
5441
5442 // Warn about ignored type attributes, for example:
5443 // __attribute__((aligned)) struct A;
5444 // Attributes should be placed after tag to apply to type declaration.
5445 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5446 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5447 if (TypeSpecType == DeclSpec::TST_class ||
5448 TypeSpecType == DeclSpec::TST_struct ||
5449 TypeSpecType == DeclSpec::TST_interface ||
5450 TypeSpecType == DeclSpec::TST_union ||
5451 TypeSpecType == DeclSpec::TST_enum) {
5452
5453 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5454 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5455 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5456 DiagnosticId = diag::warn_attribute_ignored;
5457 else if (AL.isRegularKeywordAttribute())
5458 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5459 else
5460 DiagnosticId = diag::warn_declspec_attribute_ignored;
5461 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5462 << AL << GetDiagnosticTypeSpecifierID(DS);
5463 };
5464
5465 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5466 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5467 }
5468 }
5469
5470 return TagD;
5471}
5472
5473/// We are trying to inject an anonymous member into the given scope;
5474/// check if there's an existing declaration that can't be overloaded.
5475///
5476/// \return true if this is a forbidden redeclaration
5477static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5478 DeclContext *Owner,
5479 DeclarationName Name,
5480 SourceLocation NameLoc, bool IsUnion,
5481 StorageClass SC) {
5482 LookupResult R(SemaRef, Name, NameLoc,
5483 Owner->isRecord() ? Sema::LookupMemberName
5484 : Sema::LookupOrdinaryName,
5485 RedeclarationKind::ForVisibleRedeclaration);
5486 if (!SemaRef.LookupName(R, S)) return false;
5487
5488 // Pick a representative declaration.
5489 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5490 assert(PrevDecl && "Expected a non-null Decl");
5491
5492 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5493 return false;
5494
5495 if (SC == StorageClass::SC_None &&
5496 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5497 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5498 if (!Owner->isRecord())
5499 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5500 return false;
5501 }
5502
5503 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5504 << IsUnion << Name;
5505 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5506
5507 return true;
5508}
5509
5510void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5511 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5512 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5513}
5514
5515void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5516 if (!getLangOpts().CPlusPlus)
5517 return;
5518
5519 // This function can be parsed before we have validated the
5520 // structure as an anonymous struct
5521 if (Record->isAnonymousStructOrUnion())
5522 return;
5523
5524 const NamedDecl *First = 0;
5525 for (const Decl *D : Record->decls()) {
5526 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5527 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5528 continue;
5529 if (!First)
5530 First = ND;
5531 else
5532 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5533 }
5534}
5535
5536/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5537/// anonymous struct or union AnonRecord into the owning context Owner
5538/// and scope S. This routine will be invoked just after we realize
5539/// that an unnamed union or struct is actually an anonymous union or
5540/// struct, e.g.,
5541///
5542/// @code
5543/// union {
5544/// int i;
5545/// float f;
5546/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5547/// // f into the surrounding scope.x
5548/// @endcode
5549///
5550/// This routine is recursive, injecting the names of nested anonymous
5551/// structs/unions into the owning context and scope as well.
5552static bool
5553InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5554 RecordDecl *AnonRecord, AccessSpecifier AS,
5555 StorageClass SC,
5556 SmallVectorImpl<NamedDecl *> &Chaining) {
5557 bool Invalid = false;
5558
5559 // Look every FieldDecl and IndirectFieldDecl with a name.
5560 for (auto *D : AnonRecord->decls()) {
5561 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5562 cast<NamedDecl>(Val: D)->getDeclName()) {
5563 ValueDecl *VD = cast<ValueDecl>(Val: D);
5564 // C++ [class.union]p2:
5565 // The names of the members of an anonymous union shall be
5566 // distinct from the names of any other entity in the
5567 // scope in which the anonymous union is declared.
5568
5569 bool FieldInvalid = CheckAnonMemberRedeclaration(
5570 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5571 IsUnion: AnonRecord->isUnion(), SC);
5572 if (FieldInvalid)
5573 Invalid = true;
5574
5575 // Inject the IndirectFieldDecl even if invalid, because later
5576 // diagnostics may depend on it being present, see findDefaultInitializer.
5577
5578 // C++ [class.union]p2:
5579 // For the purpose of name lookup, after the anonymous union
5580 // definition, the members of the anonymous union are
5581 // considered to have been defined in the scope in which the
5582 // anonymous union is declared.
5583 unsigned OldChainingSize = Chaining.size();
5584 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5585 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5586 else
5587 Chaining.push_back(Elt: VD);
5588
5589 assert(Chaining.size() >= 2);
5590 NamedDecl **NamedChain =
5591 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5592 for (unsigned i = 0; i < Chaining.size(); i++)
5593 NamedChain[i] = Chaining[i];
5594
5595 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5596 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5597 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5598
5599 for (const auto *Attr : VD->attrs())
5600 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5601
5602 IndirectField->setAccess(AS);
5603 IndirectField->setImplicit();
5604 IndirectField->setInvalidDecl(FieldInvalid);
5605 SemaRef.PushOnScopeChains(D: IndirectField, S);
5606
5607 // That includes picking up the appropriate access specifier.
5608 if (AS != AS_none)
5609 IndirectField->setAccess(AS);
5610
5611 Chaining.resize(N: OldChainingSize);
5612 }
5613 }
5614
5615 return Invalid;
5616}
5617
5618/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5619/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5620/// illegal input values are mapped to SC_None.
5621static StorageClass
5622StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5623 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5624 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5625 "Parser allowed 'typedef' as storage class VarDecl.");
5626 switch (StorageClassSpec) {
5627 case DeclSpec::SCS_unspecified: return SC_None;
5628 case DeclSpec::SCS_extern:
5629 if (DS.isExternInLinkageSpec())
5630 return SC_None;
5631 return SC_Extern;
5632 case DeclSpec::SCS_static: return SC_Static;
5633 case DeclSpec::SCS_auto: return SC_Auto;
5634 case DeclSpec::SCS_register: return SC_Register;
5635 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5636 // Illegal SCSs map to None: error reporting is up to the caller.
5637 case DeclSpec::SCS_mutable: // Fall through.
5638 case DeclSpec::SCS_typedef: return SC_None;
5639 }
5640 llvm_unreachable("unknown storage class specifier");
5641}
5642
5643static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5644 assert(Record->hasInClassInitializer());
5645
5646 for (const auto *I : Record->decls()) {
5647 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5648 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5649 FD = IFD->getAnonField();
5650 if (FD && FD->hasInClassInitializer())
5651 return FD->getLocation();
5652 }
5653
5654 llvm_unreachable("couldn't find in-class initializer");
5655}
5656
5657static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5658 SourceLocation DefaultInitLoc) {
5659 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5660 return;
5661
5662 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5663 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5664}
5665
5666static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5667 CXXRecordDecl *AnonUnion) {
5668 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5669 return;
5670
5671 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5672}
5673
5674Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5675 AccessSpecifier AS,
5676 RecordDecl *Record,
5677 const PrintingPolicy &Policy) {
5678 DeclContext *Owner = Record->getDeclContext();
5679
5680 // Diagnose whether this anonymous struct/union is an extension.
5681 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5682 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5683 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5684 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5685 else if (!Record->isUnion() && !getLangOpts().C11)
5686 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5687
5688 // C and C++ require different kinds of checks for anonymous
5689 // structs/unions.
5690 bool Invalid = false;
5691 if (getLangOpts().CPlusPlus) {
5692 const char *PrevSpec = nullptr;
5693 if (Record->isUnion()) {
5694 // C++ [class.union]p6:
5695 // C++17 [class.union.anon]p2:
5696 // Anonymous unions declared in a named namespace or in the
5697 // global namespace shall be declared static.
5698 unsigned DiagID;
5699 DeclContext *OwnerScope = Owner->getRedeclContext();
5700 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5701 (OwnerScope->isTranslationUnit() ||
5702 (OwnerScope->isNamespace() &&
5703 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5704 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5705 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5706
5707 // Recover by adding 'static'.
5708 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5709 PrevSpec, DiagID, Policy);
5710 }
5711 // C++ [class.union]p6:
5712 // A storage class is not allowed in a declaration of an
5713 // anonymous union in a class scope.
5714 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5715 isa<RecordDecl>(Val: Owner)) {
5716 Diag(Loc: DS.getStorageClassSpecLoc(),
5717 DiagID: diag::err_anonymous_union_with_storage_spec)
5718 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5719
5720 // Recover by removing the storage specifier.
5721 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5722 Loc: SourceLocation(),
5723 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5724 }
5725 }
5726
5727 // Ignore const/volatile/restrict qualifiers.
5728 if (DS.getTypeQualifiers()) {
5729 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5730 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5731 << Record->isUnion() << "const"
5732 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5733 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5734 Diag(Loc: DS.getVolatileSpecLoc(),
5735 DiagID: diag::ext_anonymous_struct_union_qualified)
5736 << Record->isUnion() << "volatile"
5737 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5738 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5739 Diag(Loc: DS.getRestrictSpecLoc(),
5740 DiagID: diag::ext_anonymous_struct_union_qualified)
5741 << Record->isUnion() << "restrict"
5742 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5743 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5744 Diag(Loc: DS.getAtomicSpecLoc(),
5745 DiagID: diag::ext_anonymous_struct_union_qualified)
5746 << Record->isUnion() << "_Atomic"
5747 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5748 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5749 Diag(Loc: DS.getUnalignedSpecLoc(),
5750 DiagID: diag::ext_anonymous_struct_union_qualified)
5751 << Record->isUnion() << "__unaligned"
5752 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5753
5754 DS.ClearTypeQualifiers();
5755 }
5756
5757 // C++ [class.union]p2:
5758 // The member-specification of an anonymous union shall only
5759 // define non-static data members. [Note: nested types and
5760 // functions cannot be declared within an anonymous union. ]
5761 for (auto *Mem : Record->decls()) {
5762 // Ignore invalid declarations; we already diagnosed them.
5763 if (Mem->isInvalidDecl())
5764 continue;
5765
5766 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5767 // C++ [class.union]p3:
5768 // An anonymous union shall not have private or protected
5769 // members (clause 11).
5770 assert(FD->getAccess() != AS_none);
5771 if (FD->getAccess() != AS_public) {
5772 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5773 << Record->isUnion() << (FD->getAccess() == AS_protected);
5774 Invalid = true;
5775 }
5776
5777 // C++ [class.union]p1
5778 // An object of a class with a non-trivial constructor, a non-trivial
5779 // copy constructor, a non-trivial destructor, or a non-trivial copy
5780 // assignment operator cannot be a member of a union, nor can an
5781 // array of such objects.
5782 if (CheckNontrivialField(FD))
5783 Invalid = true;
5784 } else if (Mem->isImplicit()) {
5785 // Any implicit members are fine.
5786 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5787 // This is a type that showed up in an
5788 // elaborated-type-specifier inside the anonymous struct or
5789 // union, but which actually declares a type outside of the
5790 // anonymous struct or union. It's okay.
5791 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5792 if (!MemRecord->isAnonymousStructOrUnion() &&
5793 MemRecord->getDeclName()) {
5794 // Visual C++ allows type definition in anonymous struct or union.
5795 if (getLangOpts().MicrosoftExt)
5796 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5797 << Record->isUnion();
5798 else {
5799 // This is a nested type declaration.
5800 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5801 << Record->isUnion();
5802 Invalid = true;
5803 }
5804 } else {
5805 // This is an anonymous type definition within another anonymous type.
5806 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5807 // not part of standard C++.
5808 Diag(Loc: MemRecord->getLocation(),
5809 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5810 << Record->isUnion();
5811 }
5812 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5813 // Any access specifier is fine.
5814 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5815 // In C++1z, static_assert declarations are also fine.
5816 } else {
5817 // We have something that isn't a non-static data
5818 // member. Complain about it.
5819 unsigned DK = diag::err_anonymous_record_bad_member;
5820 if (isa<TypeDecl>(Val: Mem))
5821 DK = diag::err_anonymous_record_with_type;
5822 else if (isa<FunctionDecl>(Val: Mem))
5823 DK = diag::err_anonymous_record_with_function;
5824 else if (isa<VarDecl>(Val: Mem))
5825 DK = diag::err_anonymous_record_with_static;
5826
5827 // Visual C++ allows type definition in anonymous struct or union.
5828 if (getLangOpts().MicrosoftExt &&
5829 DK == diag::err_anonymous_record_with_type)
5830 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5831 << Record->isUnion();
5832 else {
5833 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5834 Invalid = true;
5835 }
5836 }
5837 }
5838
5839 // C++11 [class.union]p8 (DR1460):
5840 // At most one variant member of a union may have a
5841 // brace-or-equal-initializer.
5842 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5843 Owner->isRecord())
5844 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5845 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5846 }
5847
5848 if (!Record->isUnion() && !Owner->isRecord()) {
5849 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5850 << getLangOpts().CPlusPlus;
5851 Invalid = true;
5852 }
5853
5854 // C++ [dcl.dcl]p3:
5855 // [If there are no declarators], and except for the declaration of an
5856 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5857 // names into the program
5858 // C++ [class.mem]p2:
5859 // each such member-declaration shall either declare at least one member
5860 // name of the class or declare at least one unnamed bit-field
5861 //
5862 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5863 if (getLangOpts().CPlusPlus && Record->field_empty())
5864 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5865
5866 // Mock up a declarator.
5867 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5868 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5869 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5870 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5871
5872 // Create a declaration for this anonymous struct/union.
5873 NamedDecl *Anon = nullptr;
5874 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5875 Anon = FieldDecl::Create(
5876 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5877 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5878 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5879 /*InitStyle=*/ICIS_NoInit);
5880 Anon->setAccess(AS);
5881 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5882
5883 if (getLangOpts().CPlusPlus)
5884 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5885 } else {
5886 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5887 if (SCSpec == DeclSpec::SCS_mutable) {
5888 // mutable can only appear on non-static class members, so it's always
5889 // an error here
5890 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5891 Invalid = true;
5892 SC = SC_None;
5893 }
5894
5895 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5896 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5897 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5898 if (Invalid)
5899 Anon->setInvalidDecl();
5900
5901 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5902
5903 // Default-initialize the implicit variable. This initialization will be
5904 // trivial in almost all cases, except if a union member has an in-class
5905 // initializer:
5906 // union { int n = 0; };
5907 ActOnUninitializedDecl(dcl: Anon);
5908 }
5909 Anon->setImplicit();
5910
5911 // Mark this as an anonymous struct/union type.
5912 Record->setAnonymousStructOrUnion(true);
5913
5914 // Add the anonymous struct/union object to the current
5915 // context. We'll be referencing this object when we refer to one of
5916 // its members.
5917 Owner->addDecl(D: Anon);
5918
5919 // Inject the members of the anonymous struct/union into the owning
5920 // context and into the identifier resolver chain for name lookup
5921 // purposes.
5922 SmallVector<NamedDecl*, 2> Chain;
5923 Chain.push_back(Elt: Anon);
5924
5925 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5926 Chaining&: Chain))
5927 Invalid = true;
5928
5929 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5930 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5931 MangleNumberingContext *MCtx;
5932 Decl *ManglingContextDecl;
5933 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5934 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5935 if (MCtx) {
5936 Context.setManglingNumber(
5937 ND: NewVD, Number: MCtx->getManglingNumber(
5938 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5939 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5940 }
5941 }
5942 }
5943
5944 if (Invalid)
5945 Anon->setInvalidDecl();
5946
5947 return Anon;
5948}
5949
5950Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5951 RecordDecl *Record) {
5952 assert(Record && "expected a record!");
5953
5954 // Mock up a declarator.
5955 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5956 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5957 assert(TInfo && "couldn't build declarator info for anonymous struct");
5958
5959 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5960 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
5961
5962 // Create a declaration for this anonymous struct.
5963 NamedDecl *Anon =
5964 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
5965 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
5966 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5967 /*InitStyle=*/ICIS_NoInit);
5968 Anon->setImplicit();
5969
5970 // Add the anonymous struct object to the current context.
5971 CurContext->addDecl(D: Anon);
5972
5973 // Inject the members of the anonymous struct into the current
5974 // context and into the identifier resolver chain for name lookup
5975 // purposes.
5976 SmallVector<NamedDecl*, 2> Chain;
5977 Chain.push_back(Elt: Anon);
5978
5979 RecordDecl *RecordDef = Record->getDefinition();
5980 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
5981 DiagID: diag::err_field_incomplete_or_sizeless) ||
5982 InjectAnonymousStructOrUnionMembers(
5983 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
5984 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
5985 Anon->setInvalidDecl();
5986 ParentDecl->setInvalidDecl();
5987 }
5988
5989 return Anon;
5990}
5991
5992DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5993 return GetNameFromUnqualifiedId(Name: D.getName());
5994}
5995
5996DeclarationNameInfo
5997Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5998 DeclarationNameInfo NameInfo;
5999 NameInfo.setLoc(Name.StartLocation);
6000
6001 switch (Name.getKind()) {
6002
6003 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6004 case UnqualifiedIdKind::IK_Identifier:
6005 NameInfo.setName(Name.Identifier);
6006 return NameInfo;
6007
6008 case UnqualifiedIdKind::IK_DeductionGuideName: {
6009 // C++ [temp.deduct.guide]p3:
6010 // The simple-template-id shall name a class template specialization.
6011 // The template-name shall be the same identifier as the template-name
6012 // of the simple-template-id.
6013 // These together intend to imply that the template-name shall name a
6014 // class template.
6015 // FIXME: template<typename T> struct X {};
6016 // template<typename T> using Y = X<T>;
6017 // Y(int) -> Y<int>;
6018 // satisfies these rules but does not name a class template.
6019 TemplateName TN = Name.TemplateName.get().get();
6020 auto *Template = TN.getAsTemplateDecl();
6021 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6022 Diag(Loc: Name.StartLocation,
6023 DiagID: diag::err_deduction_guide_name_not_class_template)
6024 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6025 if (Template)
6026 NoteTemplateLocation(Decl: *Template);
6027 return DeclarationNameInfo();
6028 }
6029
6030 NameInfo.setName(
6031 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6032 return NameInfo;
6033 }
6034
6035 case UnqualifiedIdKind::IK_OperatorFunctionId:
6036 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6037 Op: Name.OperatorFunctionId.Operator));
6038 NameInfo.setCXXOperatorNameRange(SourceRange(
6039 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6040 return NameInfo;
6041
6042 case UnqualifiedIdKind::IK_LiteralOperatorId:
6043 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6044 II: Name.Identifier));
6045 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6046 return NameInfo;
6047
6048 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6049 TypeSourceInfo *TInfo;
6050 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6051 if (Ty.isNull())
6052 return DeclarationNameInfo();
6053 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6054 Ty: Context.getCanonicalType(T: Ty)));
6055 NameInfo.setNamedTypeInfo(TInfo);
6056 return NameInfo;
6057 }
6058
6059 case UnqualifiedIdKind::IK_ConstructorName: {
6060 TypeSourceInfo *TInfo;
6061 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6062 if (Ty.isNull())
6063 return DeclarationNameInfo();
6064 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6065 Ty: Context.getCanonicalType(T: Ty)));
6066 NameInfo.setNamedTypeInfo(TInfo);
6067 return NameInfo;
6068 }
6069
6070 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6071 // In well-formed code, we can only have a constructor
6072 // template-id that refers to the current context, so go there
6073 // to find the actual type being constructed.
6074 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6075 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6076 return DeclarationNameInfo();
6077
6078 // Determine the type of the class being constructed.
6079 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6080
6081 // FIXME: Check two things: that the template-id names the same type as
6082 // CurClassType, and that the template-id does not occur when the name
6083 // was qualified.
6084
6085 NameInfo.setName(
6086 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6087 // FIXME: should we retrieve TypeSourceInfo?
6088 NameInfo.setNamedTypeInfo(nullptr);
6089 return NameInfo;
6090 }
6091
6092 case UnqualifiedIdKind::IK_DestructorName: {
6093 TypeSourceInfo *TInfo;
6094 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6095 if (Ty.isNull())
6096 return DeclarationNameInfo();
6097 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6098 Ty: Context.getCanonicalType(T: Ty)));
6099 NameInfo.setNamedTypeInfo(TInfo);
6100 return NameInfo;
6101 }
6102
6103 case UnqualifiedIdKind::IK_TemplateId: {
6104 TemplateName TName = Name.TemplateId->Template.get();
6105 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6106 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6107 }
6108
6109 } // switch (Name.getKind())
6110
6111 llvm_unreachable("Unknown name kind");
6112}
6113
6114static QualType getCoreType(QualType Ty) {
6115 do {
6116 if (Ty->isPointerOrReferenceType())
6117 Ty = Ty->getPointeeType();
6118 else if (Ty->isArrayType())
6119 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6120 else
6121 return Ty.withoutLocalFastQualifiers();
6122 } while (true);
6123}
6124
6125/// hasSimilarParameters - Determine whether the C++ functions Declaration
6126/// and Definition have "nearly" matching parameters. This heuristic is
6127/// used to improve diagnostics in the case where an out-of-line function
6128/// definition doesn't match any declaration within the class or namespace.
6129/// Also sets Params to the list of indices to the parameters that differ
6130/// between the declaration and the definition. If hasSimilarParameters
6131/// returns true and Params is empty, then all of the parameters match.
6132static bool hasSimilarParameters(ASTContext &Context,
6133 FunctionDecl *Declaration,
6134 FunctionDecl *Definition,
6135 SmallVectorImpl<unsigned> &Params) {
6136 Params.clear();
6137 if (Declaration->param_size() != Definition->param_size())
6138 return false;
6139 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6140 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6141 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6142
6143 // The parameter types are identical
6144 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6145 continue;
6146
6147 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6148 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6149 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6150 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6151
6152 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6153 (DeclTyName && DeclTyName == DefTyName))
6154 Params.push_back(Elt: Idx);
6155 else // The two parameters aren't even close
6156 return false;
6157 }
6158
6159 return true;
6160}
6161
6162/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6163/// declarator needs to be rebuilt in the current instantiation.
6164/// Any bits of declarator which appear before the name are valid for
6165/// consideration here. That's specifically the type in the decl spec
6166/// and the base type in any member-pointer chunks.
6167static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6168 DeclarationName Name) {
6169 // The types we specifically need to rebuild are:
6170 // - typenames, typeofs, and decltypes
6171 // - types which will become injected class names
6172 // Of course, we also need to rebuild any type referencing such a
6173 // type. It's safest to just say "dependent", but we call out a
6174 // few cases here.
6175
6176 DeclSpec &DS = D.getMutableDeclSpec();
6177 switch (DS.getTypeSpecType()) {
6178 case DeclSpec::TST_typename:
6179 case DeclSpec::TST_typeofType:
6180 case DeclSpec::TST_typeof_unqualType:
6181#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6182#include "clang/Basic/TransformTypeTraits.def"
6183 case DeclSpec::TST_atomic: {
6184 // Grab the type from the parser.
6185 TypeSourceInfo *TSI = nullptr;
6186 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6187 if (T.isNull() || !T->isInstantiationDependentType()) break;
6188
6189 // Make sure there's a type source info. This isn't really much
6190 // of a waste; most dependent types should have type source info
6191 // attached already.
6192 if (!TSI)
6193 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6194
6195 // Rebuild the type in the current instantiation.
6196 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6197 if (!TSI) return true;
6198
6199 // Store the new type back in the decl spec.
6200 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6201 DS.UpdateTypeRep(Rep: LocType);
6202 break;
6203 }
6204
6205 case DeclSpec::TST_decltype:
6206 case DeclSpec::TST_typeof_unqualExpr:
6207 case DeclSpec::TST_typeofExpr: {
6208 Expr *E = DS.getRepAsExpr();
6209 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6210 if (Result.isInvalid()) return true;
6211 DS.UpdateExprRep(Rep: Result.get());
6212 break;
6213 }
6214
6215 default:
6216 // Nothing to do for these decl specs.
6217 break;
6218 }
6219
6220 // It doesn't matter what order we do this in.
6221 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6222 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6223
6224 // The only type information in the declarator which can come
6225 // before the declaration name is the base type of a member
6226 // pointer.
6227 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6228 continue;
6229
6230 // Rebuild the scope specifier in-place.
6231 CXXScopeSpec &SS = Chunk.Mem.Scope();
6232 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6233 return true;
6234 }
6235
6236 return false;
6237}
6238
6239/// Returns true if the declaration is declared in a system header or from a
6240/// system macro.
6241static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6242 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6243 SM.isInSystemMacro(loc: D->getLocation());
6244}
6245
6246void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6247 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6248 // of system decl.
6249 if (D->getPreviousDecl() || D->isImplicit())
6250 return;
6251 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6252 if (Status != ReservedIdentifierStatus::NotReserved &&
6253 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6254 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6255 << D << static_cast<int>(Status);
6256 }
6257}
6258
6259Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6260 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6261
6262 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6263 // declaration only if the `bind_to_declaration` extension is set.
6264 SmallVector<FunctionDecl *, 4> Bases;
6265 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6266 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6267 TP: llvm::omp::TraitProperty::
6268 implementation_extension_bind_to_declaration))
6269 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6270 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6271
6272 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6273
6274 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6275 Dcl && Dcl->getDeclContext()->isFileContext())
6276 Dcl->setTopLevelDeclInObjCContainer();
6277
6278 if (!Bases.empty())
6279 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6280 Bases);
6281
6282 return Dcl;
6283}
6284
6285bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6286 DeclarationNameInfo NameInfo) {
6287 DeclarationName Name = NameInfo.getName();
6288
6289 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6290 while (Record && Record->isAnonymousStructOrUnion())
6291 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6292 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6293 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6294 return true;
6295 }
6296
6297 return false;
6298}
6299
6300bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6301 DeclarationName Name,
6302 SourceLocation Loc,
6303 TemplateIdAnnotation *TemplateId,
6304 bool IsMemberSpecialization) {
6305 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6306 "without nested-name-specifier");
6307 DeclContext *Cur = CurContext;
6308 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6309 Cur = Cur->getParent();
6310
6311 // If the user provided a superfluous scope specifier that refers back to the
6312 // class in which the entity is already declared, diagnose and ignore it.
6313 //
6314 // class X {
6315 // void X::f();
6316 // };
6317 //
6318 // Note, it was once ill-formed to give redundant qualification in all
6319 // contexts, but that rule was removed by DR482.
6320 if (Cur->Equals(DC)) {
6321 if (Cur->isRecord()) {
6322 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6323 : diag::err_member_extra_qualification)
6324 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6325 SS.clear();
6326 } else {
6327 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6328 }
6329 return false;
6330 }
6331
6332 // Check whether the qualifying scope encloses the scope of the original
6333 // declaration. For a template-id, we perform the checks in
6334 // CheckTemplateSpecializationScope.
6335 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6336 if (Cur->isRecord())
6337 Diag(Loc, DiagID: diag::err_member_qualification)
6338 << Name << SS.getRange();
6339 else if (isa<TranslationUnitDecl>(Val: DC))
6340 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6341 << Name << SS.getRange();
6342 else if (isa<FunctionDecl>(Val: Cur))
6343 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6344 << Name << SS.getRange();
6345 else if (isa<BlockDecl>(Val: Cur))
6346 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6347 << Name << SS.getRange();
6348 else if (isa<ExportDecl>(Val: Cur)) {
6349 if (!isa<NamespaceDecl>(Val: DC))
6350 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6351 << Name << SS.getRange();
6352 else
6353 // The cases that DC is not NamespaceDecl should be handled in
6354 // CheckRedeclarationExported.
6355 return false;
6356 } else
6357 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6358 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6359
6360 return true;
6361 }
6362
6363 if (Cur->isRecord()) {
6364 // Cannot qualify members within a class.
6365 Diag(Loc, DiagID: diag::err_member_qualification)
6366 << Name << SS.getRange();
6367 SS.clear();
6368
6369 // C++ constructors and destructors with incorrect scopes can break
6370 // our AST invariants by having the wrong underlying types. If
6371 // that's the case, then drop this declaration entirely.
6372 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6373 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6374 !Context.hasSameType(
6375 T1: Name.getCXXNameType(),
6376 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6377 return true;
6378
6379 return false;
6380 }
6381
6382 // C++23 [temp.names]p5:
6383 // The keyword template shall not appear immediately after a declarative
6384 // nested-name-specifier.
6385 //
6386 // First check the template-id (if any), and then check each component of the
6387 // nested-name-specifier in reverse order.
6388 //
6389 // FIXME: nested-name-specifiers in friend declarations are declarative,
6390 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6391 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6392 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6393 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6394
6395 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6396 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6397 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6398 SourceLocation TemplateKeywordLoc;
6399 switch (TL.getTypeLocClass()) {
6400 case TypeLoc::TemplateSpecialization: {
6401 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6402 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6403 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6404 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6405 << TST.getLocalSourceRange();
6406 break;
6407 }
6408 case TypeLoc::Decltype:
6409 case TypeLoc::PackIndexing: {
6410 const Type *T = TL.getTypePtr();
6411 // C++23 [expr.prim.id.qual]p2:
6412 // [...] A declarative nested-name-specifier shall not have a
6413 // computed-type-specifier.
6414 //
6415 // CWG2858 changed this from 'decltype-specifier' to
6416 // 'computed-type-specifier'.
6417 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6418 << T->isDecltypeType() << TL.getSourceRange();
6419 break;
6420 }
6421 case TypeLoc::DependentName:
6422 NextTL =
6423 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6424 break;
6425 default:
6426 break;
6427 }
6428 if (TemplateKeywordLoc.isValid())
6429 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6430 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6431 }
6432
6433 return false;
6434}
6435
6436NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6437 MultiTemplateParamsArg TemplateParamLists) {
6438 // TODO: consider using NameInfo for diagnostic.
6439 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6440 DeclarationName Name = NameInfo.getName();
6441
6442 // All of these full declarators require an identifier. If it doesn't have
6443 // one, the ParsedFreeStandingDeclSpec action should be used.
6444 if (D.isDecompositionDeclarator()) {
6445 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6446 } else if (!Name) {
6447 if (!D.isInvalidType()) // Reject this if we think it is valid.
6448 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6449 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6450 return nullptr;
6451 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6452 return nullptr;
6453
6454 DeclContext *DC = CurContext;
6455 if (D.getCXXScopeSpec().isInvalid())
6456 D.setInvalidType();
6457 else if (D.getCXXScopeSpec().isSet()) {
6458 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6459 UPPC: UPPC_DeclarationQualifier))
6460 return nullptr;
6461
6462 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6463 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6464 if (!DC || isa<EnumDecl>(Val: DC)) {
6465 // If we could not compute the declaration context, it's because the
6466 // declaration context is dependent but does not refer to a class,
6467 // class template, or class template partial specialization. Complain
6468 // and return early, to avoid the coming semantic disaster.
6469 Diag(Loc: D.getIdentifierLoc(),
6470 DiagID: diag::err_template_qualified_declarator_no_match)
6471 << D.getCXXScopeSpec().getScopeRep()
6472 << D.getCXXScopeSpec().getRange();
6473 return nullptr;
6474 }
6475 bool IsDependentContext = DC->isDependentContext();
6476
6477 if (!IsDependentContext &&
6478 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6479 return nullptr;
6480
6481 // If a class is incomplete, do not parse entities inside it.
6482 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6483 Diag(Loc: D.getIdentifierLoc(),
6484 DiagID: diag::err_member_def_undefined_record)
6485 << Name << DC << D.getCXXScopeSpec().getRange();
6486 return nullptr;
6487 }
6488 if (!D.getDeclSpec().isFriendSpecified()) {
6489 TemplateIdAnnotation *TemplateId =
6490 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6491 ? D.getName().TemplateId
6492 : nullptr;
6493 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6494 Loc: D.getIdentifierLoc(), TemplateId,
6495 /*IsMemberSpecialization=*/false)) {
6496 if (DC->isRecord())
6497 return nullptr;
6498
6499 D.setInvalidType();
6500 }
6501 }
6502
6503 // Check whether we need to rebuild the type of the given
6504 // declaration in the current instantiation.
6505 if (EnteringContext && IsDependentContext &&
6506 TemplateParamLists.size() != 0) {
6507 ContextRAII SavedContext(*this, DC);
6508 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6509 D.setInvalidType();
6510 }
6511 }
6512
6513 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6514 QualType R = TInfo->getType();
6515
6516 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6517 UPPC: UPPC_DeclarationType))
6518 D.setInvalidType();
6519
6520 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6521 forRedeclarationInCurContext());
6522
6523 // See if this is a redefinition of a variable in the same scope.
6524 if (!D.getCXXScopeSpec().isSet()) {
6525 bool IsLinkageLookup = false;
6526 bool CreateBuiltins = false;
6527
6528 // If the declaration we're planning to build will be a function
6529 // or object with linkage, then look for another declaration with
6530 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6531 //
6532 // If the declaration we're planning to build will be declared with
6533 // external linkage in the translation unit, create any builtin with
6534 // the same name.
6535 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6536 /* Do nothing*/;
6537 else if (CurContext->isFunctionOrMethod() &&
6538 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6539 R->isFunctionType())) {
6540 IsLinkageLookup = true;
6541 CreateBuiltins =
6542 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6543 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6544 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6545 CreateBuiltins = true;
6546
6547 if (IsLinkageLookup) {
6548 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6549 Previous.setRedeclarationKind(
6550 RedeclarationKind::ForExternalRedeclaration);
6551 }
6552
6553 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6554 } else { // Something like "int foo::x;"
6555 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6556
6557 // C++ [dcl.meaning]p1:
6558 // When the declarator-id is qualified, the declaration shall refer to a
6559 // previously declared member of the class or namespace to which the
6560 // qualifier refers (or, in the case of a namespace, of an element of the
6561 // inline namespace set of that namespace (7.3.1)) or to a specialization
6562 // thereof; [...]
6563 //
6564 // Note that we already checked the context above, and that we do not have
6565 // enough information to make sure that Previous contains the declaration
6566 // we want to match. For example, given:
6567 //
6568 // class X {
6569 // void f();
6570 // void f(float);
6571 // };
6572 //
6573 // void X::f(int) { } // ill-formed
6574 //
6575 // In this case, Previous will point to the overload set
6576 // containing the two f's declared in X, but neither of them
6577 // matches.
6578
6579 RemoveUsingDecls(R&: Previous);
6580 }
6581
6582 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6583 TPD && TPD->isTemplateParameter()) {
6584 // Older versions of clang allowed the names of function/variable templates
6585 // to shadow the names of their template parameters. For the compatibility
6586 // purposes we detect such cases and issue a default-to-error warning that
6587 // can be disabled with -Wno-strict-primary-template-shadow.
6588 if (!D.isInvalidType()) {
6589 bool AllowForCompatibility = false;
6590 if (Scope *DeclParent = S->getDeclParent();
6591 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6592 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6593 TemplateParamParent->isDeclScope(D: TPD);
6594 }
6595 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6596 SupportedForCompatibility: AllowForCompatibility);
6597 }
6598
6599 // Just pretend that we didn't see the previous declaration.
6600 Previous.clear();
6601 }
6602
6603 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6604 // Forget that the previous declaration is the injected-class-name.
6605 Previous.clear();
6606
6607 // In C++, the previous declaration we find might be a tag type
6608 // (class or enum). In this case, the new declaration will hide the
6609 // tag type. Note that this applies to functions, function templates, and
6610 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6611 if (Previous.isSingleTagDecl() &&
6612 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6613 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6614 Previous.clear();
6615
6616 // Check that there are no default arguments other than in the parameters
6617 // of a function declaration (C++ only).
6618 if (getLangOpts().CPlusPlus)
6619 CheckExtraCXXDefaultArguments(D);
6620
6621 /// Get the innermost enclosing declaration scope.
6622 S = S->getDeclParent();
6623
6624 NamedDecl *New;
6625
6626 bool AddToScope = true;
6627 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6628 if (TemplateParamLists.size()) {
6629 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6630 return nullptr;
6631 }
6632
6633 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6634 } else if (R->isFunctionType()) {
6635 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6636 TemplateParamLists,
6637 AddToScope);
6638 } else {
6639 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6640 AddToScope);
6641 }
6642
6643 if (!New)
6644 return nullptr;
6645
6646 warnOnCTypeHiddenInCPlusPlus(D: New);
6647
6648 // If this has an identifier and is not a function template specialization,
6649 // add it to the scope stack.
6650 if (New->getDeclName() && AddToScope)
6651 PushOnScopeChains(D: New, S);
6652
6653 if (OpenMP().isInOpenMPDeclareTargetContext())
6654 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6655
6656 return New;
6657}
6658
6659/// Helper method to turn variable array types into constant array
6660/// types in certain situations which would otherwise be errors (for
6661/// GCC compatibility).
6662static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6663 ASTContext &Context,
6664 bool &SizeIsNegative,
6665 llvm::APSInt &Oversized) {
6666 // This method tries to turn a variable array into a constant
6667 // array even when the size isn't an ICE. This is necessary
6668 // for compatibility with code that depends on gcc's buggy
6669 // constant expression folding, like struct {char x[(int)(char*)2];}
6670 SizeIsNegative = false;
6671 Oversized = 0;
6672
6673 if (T->isDependentType())
6674 return QualType();
6675
6676 QualifierCollector Qs;
6677 const Type *Ty = Qs.strip(type: T);
6678
6679 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6680 QualType Pointee = PTy->getPointeeType();
6681 QualType FixedType =
6682 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6683 Oversized);
6684 if (FixedType.isNull()) return FixedType;
6685 FixedType = Context.getPointerType(T: FixedType);
6686 return Qs.apply(Context, QT: FixedType);
6687 }
6688 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6689 QualType Inner = PTy->getInnerType();
6690 QualType FixedType =
6691 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6692 Oversized);
6693 if (FixedType.isNull()) return FixedType;
6694 FixedType = Context.getParenType(NamedType: FixedType);
6695 return Qs.apply(Context, QT: FixedType);
6696 }
6697
6698 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6699 if (!VLATy)
6700 return QualType();
6701
6702 QualType ElemTy = VLATy->getElementType();
6703 if (ElemTy->isVariablyModifiedType()) {
6704 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6705 SizeIsNegative, Oversized);
6706 if (ElemTy.isNull())
6707 return QualType();
6708 }
6709
6710 Expr::EvalResult Result;
6711 if (!VLATy->getSizeExpr() ||
6712 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6713 return QualType();
6714
6715 llvm::APSInt Res = Result.Val.getInt();
6716
6717 // Check whether the array size is negative.
6718 if (Res.isSigned() && Res.isNegative()) {
6719 SizeIsNegative = true;
6720 return QualType();
6721 }
6722
6723 // Check whether the array is too large to be addressed.
6724 unsigned ActiveSizeBits =
6725 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6726 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6727 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6728 : Res.getActiveBits();
6729 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6730 Oversized = Res;
6731 return QualType();
6732 }
6733
6734 QualType FoldedArrayType = Context.getConstantArrayType(
6735 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6736 return Qs.apply(Context, QT: FoldedArrayType);
6737}
6738
6739static void
6740FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6741 SrcTL = SrcTL.getUnqualifiedLoc();
6742 DstTL = DstTL.getUnqualifiedLoc();
6743 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6744 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6745 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6746 DstTL: DstPTL.getPointeeLoc());
6747 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6748 return;
6749 }
6750 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6751 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6752 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6753 DstTL: DstPTL.getInnerLoc());
6754 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6755 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6756 return;
6757 }
6758 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6759 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6760 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6761 TypeLoc DstElemTL = DstATL.getElementLoc();
6762 if (VariableArrayTypeLoc SrcElemATL =
6763 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6764 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6765 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6766 } else {
6767 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6768 }
6769 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6770 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6771 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6772}
6773
6774/// Helper method to turn variable array types into constant array
6775/// types in certain situations which would otherwise be errors (for
6776/// GCC compatibility).
6777static TypeSourceInfo*
6778TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6779 ASTContext &Context,
6780 bool &SizeIsNegative,
6781 llvm::APSInt &Oversized) {
6782 QualType FixedTy
6783 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6784 SizeIsNegative, Oversized);
6785 if (FixedTy.isNull())
6786 return nullptr;
6787 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6788 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6789 DstTL: FixedTInfo->getTypeLoc());
6790 return FixedTInfo;
6791}
6792
6793bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6794 QualType &T, SourceLocation Loc,
6795 unsigned FailedFoldDiagID) {
6796 bool SizeIsNegative;
6797 llvm::APSInt Oversized;
6798 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6799 TInfo, Context, SizeIsNegative, Oversized);
6800 if (FixedTInfo) {
6801 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6802 TInfo = FixedTInfo;
6803 T = FixedTInfo->getType();
6804 return true;
6805 }
6806
6807 if (SizeIsNegative)
6808 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6809 else if (Oversized.getBoolValue())
6810 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6811 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6812 /*UpperCase=*/false, /*InsertSeparators=*/true);
6813 else if (FailedFoldDiagID)
6814 Diag(Loc, DiagID: FailedFoldDiagID);
6815 return false;
6816}
6817
6818void
6819Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6820 if (!getLangOpts().CPlusPlus &&
6821 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6822 // Don't need to track declarations in the TU in C.
6823 return;
6824
6825 // Note that we have a locally-scoped external with this name.
6826 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6827}
6828
6829NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6830 // FIXME: We can have multiple results via __attribute__((overloadable)).
6831 auto Result = Context.getExternCContextDecl()->lookup(Name);
6832 return Result.empty() ? nullptr : *Result.begin();
6833}
6834
6835void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6836 // FIXME: We should probably indicate the identifier in question to avoid
6837 // confusion for constructs like "virtual int a(), b;"
6838 if (DS.isVirtualSpecified())
6839 Diag(Loc: DS.getVirtualSpecLoc(),
6840 DiagID: diag::err_virtual_non_function);
6841
6842 if (DS.hasExplicitSpecifier())
6843 Diag(Loc: DS.getExplicitSpecLoc(),
6844 DiagID: diag::err_explicit_non_function);
6845
6846 if (DS.isNoreturnSpecified())
6847 Diag(Loc: DS.getNoreturnSpecLoc(),
6848 DiagID: diag::err_noreturn_non_function);
6849}
6850
6851NamedDecl*
6852Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6853 TypeSourceInfo *TInfo, LookupResult &Previous) {
6854 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6855 if (D.getCXXScopeSpec().isSet()) {
6856 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6857 << D.getCXXScopeSpec().getRange();
6858 D.setInvalidType();
6859 // Pretend we didn't see the scope specifier.
6860 DC = CurContext;
6861 Previous.clear();
6862 }
6863
6864 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6865
6866 if (D.getDeclSpec().isInlineSpecified())
6867 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6868 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6869 ? diag::warn_ms_inline_non_function
6870 : diag::err_inline_non_function)
6871 << getLangOpts().CPlusPlus17;
6872 if (D.getDeclSpec().hasConstexprSpecifier())
6873 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6874 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6875
6876 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6877 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6878 Diag(Loc: D.getName().StartLocation,
6879 DiagID: diag::err_deduction_guide_invalid_specifier)
6880 << "typedef";
6881 else
6882 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6883 << D.getName().getSourceRange();
6884 return nullptr;
6885 }
6886
6887 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6888 if (!NewTD) return nullptr;
6889
6890 // Handle attributes prior to checking for duplicates in MergeVarDecl
6891 ProcessDeclAttributes(S, D: NewTD, PD: D);
6892
6893 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6894
6895 bool Redeclaration = D.isRedeclaration();
6896 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6897 D.setRedeclaration(Redeclaration);
6898 return ND;
6899}
6900
6901void
6902Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6903 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6904 // then it shall have block scope.
6905 // Note that variably modified types must be fixed before merging the decl so
6906 // that redeclarations will match.
6907 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6908 QualType T = TInfo->getType();
6909 if (T->isVariablyModifiedType()) {
6910 setFunctionHasBranchProtectedScope();
6911
6912 if (S->getFnParent() == nullptr) {
6913 bool SizeIsNegative;
6914 llvm::APSInt Oversized;
6915 TypeSourceInfo *FixedTInfo =
6916 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6917 SizeIsNegative,
6918 Oversized);
6919 if (FixedTInfo) {
6920 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6921 NewTD->setTypeSourceInfo(FixedTInfo);
6922 } else {
6923 if (SizeIsNegative)
6924 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6925 else if (T->isVariableArrayType())
6926 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6927 else if (Oversized.getBoolValue())
6928 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6929 << toString(I: Oversized, Radix: 10);
6930 else
6931 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6932 NewTD->setInvalidDecl();
6933 }
6934 }
6935 }
6936}
6937
6938NamedDecl*
6939Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6940 LookupResult &Previous, bool &Redeclaration) {
6941
6942 // Find the shadowed declaration before filtering for scope.
6943 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6944
6945 // Merge the decl with the existing one if appropriate. If the decl is
6946 // in an outer scope, it isn't the same thing.
6947 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6948 /*AllowInlineNamespace*/false);
6949 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6950 if (!Previous.empty()) {
6951 Redeclaration = true;
6952 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6953 } else {
6954 inferGslPointerAttribute(TD: NewTD);
6955 }
6956
6957 if (ShadowedDecl && !Redeclaration)
6958 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
6959
6960 // If this is the C FILE type, notify the AST context.
6961 if (IdentifierInfo *II = NewTD->getIdentifier())
6962 if (!NewTD->isInvalidDecl() &&
6963 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6964 switch (II->getNotableIdentifierID()) {
6965 case tok::NotableIdentifierKind::FILE:
6966 Context.setFILEDecl(NewTD);
6967 break;
6968 case tok::NotableIdentifierKind::jmp_buf:
6969 Context.setjmp_bufDecl(NewTD);
6970 break;
6971 case tok::NotableIdentifierKind::sigjmp_buf:
6972 Context.setsigjmp_bufDecl(NewTD);
6973 break;
6974 case tok::NotableIdentifierKind::ucontext_t:
6975 Context.setucontext_tDecl(NewTD);
6976 break;
6977 case tok::NotableIdentifierKind::float_t:
6978 case tok::NotableIdentifierKind::double_t:
6979 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
6980 break;
6981 default:
6982 break;
6983 }
6984 }
6985
6986 return NewTD;
6987}
6988
6989/// Determines whether the given declaration is an out-of-scope
6990/// previous declaration.
6991///
6992/// This routine should be invoked when name lookup has found a
6993/// previous declaration (PrevDecl) that is not in the scope where a
6994/// new declaration by the same name is being introduced. If the new
6995/// declaration occurs in a local scope, previous declarations with
6996/// linkage may still be considered previous declarations (C99
6997/// 6.2.2p4-5, C++ [basic.link]p6).
6998///
6999/// \param PrevDecl the previous declaration found by name
7000/// lookup
7001///
7002/// \param DC the context in which the new declaration is being
7003/// declared.
7004///
7005/// \returns true if PrevDecl is an out-of-scope previous declaration
7006/// for a new delcaration with the same name.
7007static bool
7008isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7009 ASTContext &Context) {
7010 if (!PrevDecl)
7011 return false;
7012
7013 if (!PrevDecl->hasLinkage())
7014 return false;
7015
7016 if (Context.getLangOpts().CPlusPlus) {
7017 // C++ [basic.link]p6:
7018 // If there is a visible declaration of an entity with linkage
7019 // having the same name and type, ignoring entities declared
7020 // outside the innermost enclosing namespace scope, the block
7021 // scope declaration declares that same entity and receives the
7022 // linkage of the previous declaration.
7023 DeclContext *OuterContext = DC->getRedeclContext();
7024 if (!OuterContext->isFunctionOrMethod())
7025 // This rule only applies to block-scope declarations.
7026 return false;
7027
7028 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7029 if (PrevOuterContext->isRecord())
7030 // We found a member function: ignore it.
7031 return false;
7032
7033 // Find the innermost enclosing namespace for the new and
7034 // previous declarations.
7035 OuterContext = OuterContext->getEnclosingNamespaceContext();
7036 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7037
7038 // The previous declaration is in a different namespace, so it
7039 // isn't the same function.
7040 if (!OuterContext->Equals(DC: PrevOuterContext))
7041 return false;
7042 }
7043
7044 return true;
7045}
7046
7047static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7048 CXXScopeSpec &SS = D.getCXXScopeSpec();
7049 if (!SS.isSet()) return;
7050 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7051}
7052
7053void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
7054 if (Decl->getType().hasAddressSpace())
7055 return;
7056 if (Decl->getType()->isDependentType())
7057 return;
7058 if (VarDecl *Var = dyn_cast<VarDecl>(Val: Decl)) {
7059 QualType Type = Var->getType();
7060 if (Type->isSamplerT() || Type->isVoidType())
7061 return;
7062 LangAS ImplAS = LangAS::opencl_private;
7063 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7064 // __opencl_c_program_scope_global_variables feature, the address space
7065 // for a variable at program scope or a static or extern variable inside
7066 // a function are inferred to be __global.
7067 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7068 Var->hasGlobalStorage())
7069 ImplAS = LangAS::opencl_global;
7070 // If the original type from a decayed type is an array type and that array
7071 // type has no address space yet, deduce it now.
7072 if (auto DT = dyn_cast<DecayedType>(Val&: Type)) {
7073 auto OrigTy = DT->getOriginalType();
7074 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7075 // Add the address space to the original array type and then propagate
7076 // that to the element type through `getAsArrayType`.
7077 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
7078 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
7079 // Re-generate the decayed type.
7080 Type = Context.getDecayedType(T: OrigTy);
7081 }
7082 }
7083 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
7084 // Apply any qualifiers (including address space) from the array type to
7085 // the element type. This implements C99 6.7.3p8: "If the specification of
7086 // an array type includes any type qualifiers, the element type is so
7087 // qualified, not the array type."
7088 if (Type->isArrayType())
7089 Type = QualType(Context.getAsArrayType(T: Type), 0);
7090 Decl->setType(Type);
7091 }
7092}
7093
7094static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7095 // 'weak' only applies to declarations with external linkage.
7096 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7097 if (!ND.isExternallyVisible()) {
7098 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7099 ND.dropAttr<WeakAttr>();
7100 }
7101 }
7102}
7103
7104static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7105 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7106 if (ND.isExternallyVisible()) {
7107 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7108 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7109 }
7110 }
7111}
7112
7113static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7114 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7115 if (VD->hasInit()) {
7116 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7117 assert(VD->isThisDeclarationADefinition() &&
7118 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7119 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7120 VD->dropAttr<AliasAttr>();
7121 }
7122 }
7123 }
7124}
7125
7126static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7127 // 'selectany' only applies to externally visible variable declarations.
7128 // It does not apply to functions.
7129 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7130 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7131 S.Diag(Loc: Attr->getLocation(),
7132 DiagID: diag::err_attribute_selectany_non_extern_data);
7133 ND.dropAttr<SelectAnyAttr>();
7134 }
7135 }
7136}
7137
7138static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7139 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7140 if (!ND.isExternallyVisible())
7141 S.Diag(Loc: Attr->getLocation(),
7142 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7143 }
7144}
7145
7146static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7147 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7148 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7149 bool IsAnonymousNS = false;
7150 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7151 if (VD) {
7152 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7153 while (NS && !IsAnonymousNS) {
7154 IsAnonymousNS = NS->isAnonymousNamespace();
7155 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7156 }
7157 }
7158 // dll attributes require external linkage. Static locals may have external
7159 // linkage but still cannot be explicitly imported or exported.
7160 // In Microsoft mode, a variable defined in anonymous namespace must have
7161 // external linkage in order to be exported.
7162 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7163 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7164 (!AnonNSInMicrosoftMode &&
7165 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7166 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7167 << &ND << Attr;
7168 ND.setInvalidDecl();
7169 }
7170 }
7171}
7172
7173static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7174 // Check the attributes on the function type and function params, if any.
7175 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7176 FD = FD->getMostRecentDecl();
7177 // Don't declare this variable in the second operand of the for-statement;
7178 // GCC miscompiles that by ending its lifetime before evaluating the
7179 // third operand. See gcc.gnu.org/PR86769.
7180 AttributedTypeLoc ATL;
7181 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7182 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7183 TL = ATL.getModifiedLoc()) {
7184 // The [[lifetimebound]] attribute can be applied to the implicit object
7185 // parameter of a non-static member function (other than a ctor or dtor)
7186 // by applying it to the function type.
7187 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7188 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7189 int NoImplicitObjectError = -1;
7190 if (!MD)
7191 NoImplicitObjectError = 0;
7192 else if (MD->isStatic())
7193 NoImplicitObjectError = 1;
7194 else if (MD->isExplicitObjectMemberFunction())
7195 NoImplicitObjectError = 2;
7196 if (NoImplicitObjectError != -1) {
7197 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7198 << NoImplicitObjectError << A->getRange();
7199 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7200 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7201 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7202 } else if (MD->getReturnType()->isVoidType()) {
7203 S.Diag(
7204 Loc: MD->getLocation(),
7205 DiagID: diag::
7206 err_lifetimebound_implicit_object_parameter_void_return_type);
7207 }
7208 }
7209 }
7210
7211 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7212 const ParmVarDecl *P = FD->getParamDecl(i: I);
7213
7214 // The [[lifetimebound]] attribute can be applied to a function parameter
7215 // only if the function returns a value.
7216 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7217 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7218 S.Diag(Loc: A->getLocation(),
7219 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7220 }
7221 }
7222 }
7223 }
7224}
7225
7226static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7227 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7228 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7229}
7230
7231static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7232 // Ensure that an auto decl is deduced otherwise the checks below might cache
7233 // the wrong linkage.
7234 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7235
7236 checkWeakAttr(S, ND);
7237 checkWeakRefAttr(S, ND);
7238 checkAliasAttr(S, ND);
7239 checkSelectAnyAttr(S, ND);
7240 checkHybridPatchableAttr(S, ND);
7241 checkInheritableAttr(S, ND);
7242 checkLifetimeBoundAttr(S, ND);
7243 checkModularFormatAttr(S, ND);
7244}
7245
7246static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7247 NamedDecl *NewDecl,
7248 bool IsSpecialization,
7249 bool IsDefinition) {
7250 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7251 return;
7252
7253 bool IsTemplate = false;
7254 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7255 OldDecl = OldTD->getTemplatedDecl();
7256 IsTemplate = true;
7257 if (!IsSpecialization)
7258 IsDefinition = false;
7259 }
7260 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7261 NewDecl = NewTD->getTemplatedDecl();
7262 IsTemplate = true;
7263 }
7264
7265 if (!OldDecl || !NewDecl)
7266 return;
7267
7268 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7269 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7270 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7271 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7272
7273 // dllimport and dllexport are inheritable attributes so we have to exclude
7274 // inherited attribute instances.
7275 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7276 (NewExportAttr && !NewExportAttr->isInherited());
7277
7278 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7279 // the only exception being explicit specializations.
7280 // Implicitly generated declarations are also excluded for now because there
7281 // is no other way to switch these to use dllimport or dllexport.
7282 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7283
7284 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7285 // Allow with a warning for free functions and global variables.
7286 bool JustWarn = false;
7287 if (!OldDecl->isCXXClassMember()) {
7288 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7289 if (VD && !VD->getDescribedVarTemplate())
7290 JustWarn = true;
7291 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7292 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7293 JustWarn = true;
7294 }
7295
7296 // We cannot change a declaration that's been used because IR has already
7297 // been emitted. Dllimported functions will still work though (modulo
7298 // address equality) as they can use the thunk.
7299 if (OldDecl->isUsed())
7300 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7301 JustWarn = false;
7302
7303 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7304 : diag::err_attribute_dll_redeclaration;
7305 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7306 << NewDecl
7307 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7308 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7309 if (!JustWarn) {
7310 NewDecl->setInvalidDecl();
7311 return;
7312 }
7313 }
7314
7315 // A redeclaration is not allowed to drop a dllimport attribute, the only
7316 // exceptions being inline function definitions (except for function
7317 // templates), local extern declarations, qualified friend declarations or
7318 // special MSVC extension: in the last case, the declaration is treated as if
7319 // it were marked dllexport.
7320 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7321 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7322 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7323 // Ignore static data because out-of-line definitions are diagnosed
7324 // separately.
7325 IsStaticDataMember = VD->isStaticDataMember();
7326 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7327 VarDecl::DeclarationOnly;
7328 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7329 IsInline = FD->isInlined();
7330 IsQualifiedFriend = FD->getQualifier() &&
7331 FD->getFriendObjectKind() == Decl::FOK_Declared;
7332 }
7333
7334 if (OldImportAttr && !HasNewAttr &&
7335 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7336 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7337 if (IsMicrosoftABI && IsDefinition) {
7338 if (IsSpecialization) {
7339 S.Diag(
7340 Loc: NewDecl->getLocation(),
7341 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7342 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7343 NewDecl->dropAttr<DLLImportAttr>();
7344 } else {
7345 S.Diag(Loc: NewDecl->getLocation(),
7346 DiagID: diag::warn_redeclaration_without_import_attribute)
7347 << NewDecl;
7348 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7349 NewDecl->dropAttr<DLLImportAttr>();
7350 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7351 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7352 }
7353 } else if (IsMicrosoftABI && IsSpecialization) {
7354 assert(!IsDefinition);
7355 // MSVC allows this. Keep the inherited attribute.
7356 } else {
7357 S.Diag(Loc: NewDecl->getLocation(),
7358 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7359 << NewDecl << OldImportAttr;
7360 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7361 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7362 OldDecl->dropAttr<DLLImportAttr>();
7363 NewDecl->dropAttr<DLLImportAttr>();
7364 }
7365 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7366 // In MinGW, seeing a function declared inline drops the dllimport
7367 // attribute.
7368 OldDecl->dropAttr<DLLImportAttr>();
7369 NewDecl->dropAttr<DLLImportAttr>();
7370 S.Diag(Loc: NewDecl->getLocation(),
7371 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7372 << NewDecl << OldImportAttr;
7373 }
7374
7375 // A specialization of a class template member function is processed here
7376 // since it's a redeclaration. If the parent class is dllexport, the
7377 // specialization inherits that attribute. This doesn't happen automatically
7378 // since the parent class isn't instantiated until later.
7379 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7380 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7381 !NewImportAttr && !NewExportAttr) {
7382 if (const DLLExportAttr *ParentExportAttr =
7383 MD->getParent()->getAttr<DLLExportAttr>()) {
7384 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7385 NewAttr->setInherited(true);
7386 NewDecl->addAttr(A: NewAttr);
7387 }
7388 }
7389 }
7390}
7391
7392/// Given that we are within the definition of the given function,
7393/// will that definition behave like C99's 'inline', where the
7394/// definition is discarded except for optimization purposes?
7395static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7396 // Try to avoid calling GetGVALinkageForFunction.
7397
7398 // All cases of this require the 'inline' keyword.
7399 if (!FD->isInlined()) return false;
7400
7401 // This is only possible in C++ with the gnu_inline attribute.
7402 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7403 return false;
7404
7405 // Okay, go ahead and call the relatively-more-expensive function.
7406 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7407}
7408
7409/// Determine whether a variable is extern "C" prior to attaching
7410/// an initializer. We can't just call isExternC() here, because that
7411/// will also compute and cache whether the declaration is externally
7412/// visible, which might change when we attach the initializer.
7413///
7414/// This can only be used if the declaration is known to not be a
7415/// redeclaration of an internal linkage declaration.
7416///
7417/// For instance:
7418///
7419/// auto x = []{};
7420///
7421/// Attaching the initializer here makes this declaration not externally
7422/// visible, because its type has internal linkage.
7423///
7424/// FIXME: This is a hack.
7425template<typename T>
7426static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7427 if (S.getLangOpts().CPlusPlus) {
7428 // In C++, the overloadable attribute negates the effects of extern "C".
7429 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7430 return false;
7431
7432 // So do CUDA's host/device attributes.
7433 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7434 D->template hasAttr<CUDAHostAttr>()))
7435 return false;
7436 }
7437 return D->isExternC();
7438}
7439
7440static bool shouldConsiderLinkage(const VarDecl *VD) {
7441 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7442 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7443 isa<OMPDeclareMapperDecl>(Val: DC))
7444 return VD->hasExternalStorage();
7445 if (DC->isFileContext())
7446 return true;
7447 if (DC->isRecord())
7448 return false;
7449 if (DC->getDeclKind() == Decl::HLSLBuffer)
7450 return false;
7451
7452 if (isa<RequiresExprBodyDecl>(Val: DC))
7453 return false;
7454 llvm_unreachable("Unexpected context");
7455}
7456
7457static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7458 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7459 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7460 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7461 return true;
7462 if (DC->isRecord())
7463 return false;
7464 llvm_unreachable("Unexpected context");
7465}
7466
7467static bool hasParsedAttr(Scope *S, const Declarator &PD,
7468 ParsedAttr::Kind Kind) {
7469 // Check decl attributes on the DeclSpec.
7470 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7471 return true;
7472
7473 // Walk the declarator structure, checking decl attributes that were in a type
7474 // position to the decl itself.
7475 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7476 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7477 return true;
7478 }
7479
7480 // Finally, check attributes on the decl itself.
7481 return PD.getAttributes().hasAttribute(K: Kind) ||
7482 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7483}
7484
7485bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7486 if (!DC->isFunctionOrMethod())
7487 return false;
7488
7489 // If this is a local extern function or variable declared within a function
7490 // template, don't add it into the enclosing namespace scope until it is
7491 // instantiated; it might have a dependent type right now.
7492 if (DC->isDependentContext())
7493 return true;
7494
7495 // C++11 [basic.link]p7:
7496 // When a block scope declaration of an entity with linkage is not found to
7497 // refer to some other declaration, then that entity is a member of the
7498 // innermost enclosing namespace.
7499 //
7500 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7501 // semantically-enclosing namespace, not a lexically-enclosing one.
7502 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7503 DC = DC->getParent();
7504 return true;
7505}
7506
7507/// Returns true if given declaration has external C language linkage.
7508static bool isDeclExternC(const Decl *D) {
7509 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7510 return FD->isExternC();
7511 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7512 return VD->isExternC();
7513
7514 llvm_unreachable("Unknown type of decl!");
7515}
7516
7517/// Returns true if there hasn't been any invalid type diagnosed.
7518static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7519 DeclContext *DC = NewVD->getDeclContext();
7520 QualType R = NewVD->getType();
7521
7522 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7523 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7524 // argument.
7525 if (R->isImageType() || R->isPipeType()) {
7526 Se.Diag(Loc: NewVD->getLocation(),
7527 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7528 << R;
7529 NewVD->setInvalidDecl();
7530 return false;
7531 }
7532
7533 // OpenCL v1.2 s6.9.r:
7534 // The event type cannot be used to declare a program scope variable.
7535 // OpenCL v2.0 s6.9.q:
7536 // The clk_event_t and reserve_id_t types cannot be declared in program
7537 // scope.
7538 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7539 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7540 Se.Diag(Loc: NewVD->getLocation(),
7541 DiagID: diag::err_invalid_type_for_program_scope_var)
7542 << R;
7543 NewVD->setInvalidDecl();
7544 return false;
7545 }
7546 }
7547
7548 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7549 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7550 LO: Se.getLangOpts())) {
7551 QualType NR = R.getCanonicalType();
7552 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7553 NR->isReferenceType()) {
7554 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7555 NR->isFunctionReferenceType()) {
7556 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7557 << NR->isReferenceType();
7558 NewVD->setInvalidDecl();
7559 return false;
7560 }
7561 NR = NR->getPointeeType();
7562 }
7563 }
7564
7565 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7566 LO: Se.getLangOpts())) {
7567 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7568 // half array type (unless the cl_khr_fp16 extension is enabled).
7569 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7570 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7571 NewVD->setInvalidDecl();
7572 return false;
7573 }
7574 }
7575
7576 // OpenCL v1.2 s6.9.r:
7577 // The event type cannot be used with the __local, __constant and __global
7578 // address space qualifiers.
7579 if (R->isEventT()) {
7580 if (R.getAddressSpace() != LangAS::opencl_private) {
7581 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7582 NewVD->setInvalidDecl();
7583 return false;
7584 }
7585 }
7586
7587 if (R->isSamplerT()) {
7588 // OpenCL v1.2 s6.9.b p4:
7589 // The sampler type cannot be used with the __local and __global address
7590 // space qualifiers.
7591 if (R.getAddressSpace() == LangAS::opencl_local ||
7592 R.getAddressSpace() == LangAS::opencl_global) {
7593 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7594 NewVD->setInvalidDecl();
7595 }
7596
7597 // OpenCL v1.2 s6.12.14.1:
7598 // A global sampler must be declared with either the constant address
7599 // space qualifier or with the const qualifier.
7600 if (DC->isTranslationUnit() &&
7601 !(R.getAddressSpace() == LangAS::opencl_constant ||
7602 R.isConstQualified())) {
7603 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7604 NewVD->setInvalidDecl();
7605 }
7606 if (NewVD->isInvalidDecl())
7607 return false;
7608 }
7609
7610 return true;
7611}
7612
7613template <typename AttrTy>
7614static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7615 const TypedefNameDecl *TND = TT->getDecl();
7616 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7617 AttrTy *Clone = Attribute->clone(S.Context);
7618 Clone->setInherited(true);
7619 D->addAttr(A: Clone);
7620 }
7621}
7622
7623// This function emits warning and a corresponding note based on the
7624// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7625// declarations of an annotated type must be const qualified.
7626static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7627 QualType VarType = VD->getType().getCanonicalType();
7628
7629 // Ignore local declarations (for now) and those with const qualification.
7630 // TODO: Local variables should not be allowed if their type declaration has
7631 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7632 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7633 return;
7634
7635 if (VarType->isArrayType()) {
7636 // Retrieve element type for array declarations.
7637 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7638 }
7639
7640 const RecordDecl *RD = VarType->getAsRecordDecl();
7641
7642 // Check if the record declaration is present and if it has any attributes.
7643 if (RD == nullptr)
7644 return;
7645
7646 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7647 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7648 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7649 return;
7650 }
7651}
7652
7653void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7654 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7655 "NewD is not a function or variable");
7656
7657 if (PendingExportedNames.empty())
7658 return;
7659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7660 if (getLangOpts().CPlusPlus && !FD->isExternC())
7661 return;
7662 }
7663 IdentifierInfo *IdentName = NewD->getIdentifier();
7664 if (IdentName == nullptr)
7665 return;
7666 auto PendingName = PendingExportedNames.find(Val: IdentName);
7667 if (PendingName != PendingExportedNames.end()) {
7668 auto &Label = PendingName->second;
7669 if (!Label.Used) {
7670 Label.Used = true;
7671 if (NewD->hasExternalFormalLinkage())
7672 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7673 else
7674 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7675 }
7676 }
7677}
7678
7679// Checks if VD is declared at global scope or with C language linkage.
7680static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7681 return Name.getAsIdentifierInfo() &&
7682 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7683 !VD->getDescribedVarTemplate() &&
7684 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7685 VD->isExternC());
7686}
7687
7688void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7689 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7690
7691 // Quickly return if the function does not have an `asm` attribute.
7692 if (E == nullptr)
7693 return;
7694
7695 // The parser guarantees this is a string.
7696 StringLiteral *SE = cast<StringLiteral>(Val: E);
7697 StringRef Label = SE->getString();
7698 QualType R = TInfo->getType();
7699 if (S->getFnParent() != nullptr) {
7700 switch (SC) {
7701 case SC_None:
7702 case SC_Auto:
7703 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7704 break;
7705 case SC_Register:
7706 // Local Named register
7707 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7708 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7709 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7710 break;
7711 case SC_Static:
7712 case SC_Extern:
7713 case SC_PrivateExtern:
7714 break;
7715 }
7716 } else if (SC == SC_Register) {
7717 // Global Named register
7718 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7719 const auto &TI = Context.getTargetInfo();
7720 bool HasSizeMismatch;
7721
7722 if (!TI.isValidGCCRegisterName(Name: Label))
7723 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7724 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7725 HasSizeMismatch))
7726 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7727 else if (HasSizeMismatch)
7728 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7729 }
7730
7731 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7732 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7733 DiagID: diag::err_asm_unsupported_register_type)
7734 << TInfo->getTypeLoc().getSourceRange();
7735 NewVD->setInvalidDecl(true);
7736 }
7737 }
7738}
7739
7740NamedDecl *Sema::ActOnVariableDeclarator(
7741 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7742 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7743 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7744 QualType R = TInfo->getType();
7745 DeclarationName Name = GetNameForDeclarator(D).getName();
7746
7747 IdentifierInfo *II = Name.getAsIdentifierInfo();
7748 bool IsPlaceholderVariable = false;
7749
7750 if (D.isDecompositionDeclarator()) {
7751 // Take the name of the first declarator as our name for diagnostic
7752 // purposes.
7753 auto &Decomp = D.getDecompositionDeclarator();
7754 if (!Decomp.bindings().empty()) {
7755 II = Decomp.bindings()[0].Name;
7756 Name = II;
7757 }
7758 } else if (!II) {
7759 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7760 return nullptr;
7761 }
7762
7763
7764 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7765 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7766 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7767 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7768
7769 IsPlaceholderVariable = true;
7770
7771 if (!Previous.empty()) {
7772 NamedDecl *PrevDecl = *Previous.begin();
7773 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7774 DC: DC->getRedeclContext());
7775 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7776 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7777 if (IsPlaceholderVariable)
7778 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7779 }
7780 }
7781 }
7782
7783 // dllimport globals without explicit storage class are treated as extern. We
7784 // have to change the storage class this early to get the right DeclContext.
7785 if (SC == SC_None && !DC->isRecord() &&
7786 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7787 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7788 SC = SC_Extern;
7789
7790 DeclContext *OriginalDC = DC;
7791 bool IsLocalExternDecl = SC == SC_Extern &&
7792 adjustContextForLocalExternDecl(DC);
7793
7794 if (SCSpec == DeclSpec::SCS_mutable) {
7795 // mutable can only appear on non-static class members, so it's always
7796 // an error here
7797 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7798 D.setInvalidType();
7799 SC = SC_None;
7800 }
7801
7802 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7803 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7804 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7805 // In C++11, the 'register' storage class specifier is deprecated.
7806 // Suppress the warning in system macros, it's used in macros in some
7807 // popular C system headers, such as in glibc's htonl() macro.
7808 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7809 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7810 : diag::warn_deprecated_register)
7811 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7812 }
7813
7814 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7815
7816 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7817 // C99 6.9p2: The storage-class specifiers auto and register shall not
7818 // appear in the declaration specifiers in an external declaration.
7819 // Global Register+Asm is a GNU extension we support.
7820 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7821 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7822 D.setInvalidType();
7823 }
7824 }
7825
7826 // If this variable has a VLA type and an initializer, try to
7827 // fold to a constant-sized type. This is otherwise invalid.
7828 if (D.hasInitializer() && R->isVariableArrayType())
7829 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7830 /*DiagID=*/FailedFoldDiagID: 0);
7831
7832 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7833 const AutoType *AT = TL.getTypePtr();
7834 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7835 }
7836
7837 bool IsMemberSpecialization = false;
7838 bool IsVariableTemplateSpecialization = false;
7839 bool IsPartialSpecialization = false;
7840 bool IsVariableTemplate = false;
7841 VarDecl *NewVD = nullptr;
7842 VarTemplateDecl *NewTemplate = nullptr;
7843 TemplateParameterList *TemplateParams = nullptr;
7844 if (!getLangOpts().CPlusPlus) {
7845 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7846 Id: II, T: R, TInfo, S: SC);
7847
7848 if (R->getContainedDeducedType())
7849 ParsingInitForAutoVars.insert(Ptr: NewVD);
7850
7851 if (D.isInvalidType())
7852 NewVD->setInvalidDecl();
7853
7854 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7855 NewVD->hasLocalStorage())
7856 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7857 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7858 } else {
7859 bool Invalid = false;
7860 // Match up the template parameter lists with the scope specifier, then
7861 // determine whether we have a template or a template specialization.
7862 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7863 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7864 SS: D.getCXXScopeSpec(),
7865 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7866 ? D.getName().TemplateId
7867 : nullptr,
7868 ParamLists: TemplateParamLists,
7869 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7870
7871 if (TemplateParams) {
7872 if (DC->isDependentContext()) {
7873 ContextRAII SavedContext(*this, DC);
7874 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7875 Invalid = true;
7876 }
7877
7878 if (!TemplateParams->size() &&
7879 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7880 // There is an extraneous 'template<>' for this variable. Complain
7881 // about it, but allow the declaration of the variable.
7882 Diag(Loc: TemplateParams->getTemplateLoc(),
7883 DiagID: diag::err_template_variable_noparams)
7884 << II
7885 << SourceRange(TemplateParams->getTemplateLoc(),
7886 TemplateParams->getRAngleLoc());
7887 TemplateParams = nullptr;
7888 } else {
7889 // Check that we can declare a template here.
7890 if (CheckTemplateDeclScope(S, TemplateParams))
7891 return nullptr;
7892
7893 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7894 // This is an explicit specialization or a partial specialization.
7895 IsVariableTemplateSpecialization = true;
7896 IsPartialSpecialization = TemplateParams->size() > 0;
7897 } else { // if (TemplateParams->size() > 0)
7898 // This is a template declaration.
7899 IsVariableTemplate = true;
7900
7901 // Only C++1y supports variable templates (N3651).
7902 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7903 }
7904 }
7905 } else {
7906 // Check that we can declare a member specialization here.
7907 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7908 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7909 return nullptr;
7910 assert((Invalid ||
7911 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7912 "should have a 'template<>' for this decl");
7913 }
7914
7915 bool IsExplicitSpecialization =
7916 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7917
7918 // C++ [temp.expl.spec]p2:
7919 // The declaration in an explicit-specialization shall not be an
7920 // export-declaration. An explicit specialization shall not use a
7921 // storage-class-specifier other than thread_local.
7922 //
7923 // We use the storage-class-specifier from DeclSpec because we may have
7924 // added implicit 'extern' for declarations with __declspec(dllimport)!
7925 if (SCSpec != DeclSpec::SCS_unspecified &&
7926 (IsExplicitSpecialization || IsMemberSpecialization)) {
7927 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7928 DiagID: diag::ext_explicit_specialization_storage_class)
7929 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7930 }
7931
7932 if (CurContext->isRecord()) {
7933 if (SC == SC_Static) {
7934 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7935 // Walk up the enclosing DeclContexts to check for any that are
7936 // incompatible with static data members.
7937 const DeclContext *FunctionOrMethod = nullptr;
7938 const CXXRecordDecl *AnonStruct = nullptr;
7939 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7940 if (Ctxt->isFunctionOrMethod()) {
7941 FunctionOrMethod = Ctxt;
7942 break;
7943 }
7944 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7945 if (ParentDecl && !ParentDecl->getDeclName()) {
7946 AnonStruct = ParentDecl;
7947 break;
7948 }
7949 }
7950 if (FunctionOrMethod) {
7951 // C++ [class.static.data]p5: A local class shall not have static
7952 // data members.
7953 Diag(Loc: D.getIdentifierLoc(),
7954 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7955 << Name << RD->getDeclName() << RD->getTagKind();
7956 } else if (AnonStruct) {
7957 // C++ [class.static.data]p4: Unnamed classes and classes contained
7958 // directly or indirectly within unnamed classes shall not contain
7959 // static data members.
7960 Diag(Loc: D.getIdentifierLoc(),
7961 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7962 << Name << AnonStruct->getTagKind();
7963 Invalid = true;
7964 } else if (RD->isUnion()) {
7965 // C++98 [class.union]p1: If a union contains a static data member,
7966 // the program is ill-formed. C++11 drops this restriction.
7967 DiagCompat(Loc: D.getIdentifierLoc(),
7968 CompatDiagId: diag_compat::static_data_member_in_union)
7969 << Name;
7970 }
7971 }
7972 } else if (IsVariableTemplate || IsPartialSpecialization) {
7973 // There is no such thing as a member field template.
7974 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7975 << II << TemplateParams->getSourceRange();
7976 // Recover by pretending this is a static data member template.
7977 SC = SC_Static;
7978 }
7979 } else if (DC->isRecord()) {
7980 // This is an out-of-line definition of a static data member.
7981 switch (SC) {
7982 case SC_None:
7983 break;
7984 case SC_Static:
7985 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7986 DiagID: diag::err_static_out_of_line)
7987 << FixItHint::CreateRemoval(
7988 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7989 break;
7990 case SC_Auto:
7991 case SC_Register:
7992 case SC_Extern:
7993 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7994 // to names of variables declared in a block or to function parameters.
7995 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7996 // of class members
7997
7998 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7999 DiagID: diag::err_storage_class_for_static_member)
8000 << FixItHint::CreateRemoval(
8001 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8002 break;
8003 case SC_PrivateExtern:
8004 llvm_unreachable("C storage class in c++!");
8005 }
8006 }
8007
8008 if (IsVariableTemplateSpecialization) {
8009 SourceLocation TemplateKWLoc =
8010 TemplateParamLists.size() > 0
8011 ? TemplateParamLists[0]->getTemplateLoc()
8012 : SourceLocation();
8013 DeclResult Res = ActOnVarTemplateSpecialization(
8014 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8015 IsPartialSpecialization);
8016 if (Res.isInvalid())
8017 return nullptr;
8018 NewVD = cast<VarDecl>(Val: Res.get());
8019 AddToScope = false;
8020 } else if (D.isDecompositionDeclarator()) {
8021 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8022 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
8023 Bindings);
8024 } else
8025 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8026 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8027
8028 // If this is supposed to be a variable template, create it as such.
8029 if (IsVariableTemplate) {
8030 NewTemplate =
8031 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8032 Params: TemplateParams, Decl: NewVD);
8033 NewVD->setDescribedVarTemplate(NewTemplate);
8034 }
8035
8036 // If this decl has an auto type in need of deduction, make a note of the
8037 // Decl so we can diagnose uses of it in its own initializer.
8038 if (R->getContainedDeducedType())
8039 ParsingInitForAutoVars.insert(Ptr: NewVD);
8040
8041 if (D.isInvalidType() || Invalid) {
8042 NewVD->setInvalidDecl();
8043 if (NewTemplate)
8044 NewTemplate->setInvalidDecl();
8045 }
8046
8047 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8048
8049 // If we have any template parameter lists that don't directly belong to
8050 // the variable (matching the scope specifier), store them.
8051 // An explicit variable template specialization does not own any template
8052 // parameter lists.
8053 unsigned VDTemplateParamLists =
8054 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8055 if (TemplateParamLists.size() > VDTemplateParamLists)
8056 NewVD->setTemplateParameterListsInfo(
8057 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8058 }
8059
8060 if (D.getDeclSpec().isInlineSpecified()) {
8061 if (!getLangOpts().CPlusPlus) {
8062 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8063 << 0;
8064 } else if (CurContext->isFunctionOrMethod()) {
8065 // 'inline' is not allowed on block scope variable declaration.
8066 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8067 DiagID: diag::err_inline_declaration_block_scope) << Name
8068 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8069 } else {
8070 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8071 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8072 : diag::compat_pre_cxx17_inline_variable);
8073 NewVD->setInlineSpecified();
8074 }
8075 }
8076
8077 // Set the lexical context. If the declarator has a C++ scope specifier, the
8078 // lexical context will be different from the semantic context.
8079 NewVD->setLexicalDeclContext(CurContext);
8080 if (NewTemplate)
8081 NewTemplate->setLexicalDeclContext(CurContext);
8082
8083 if (IsLocalExternDecl) {
8084 if (D.isDecompositionDeclarator())
8085 for (auto *B : Bindings)
8086 B->setLocalExternDecl();
8087 else
8088 NewVD->setLocalExternDecl();
8089 }
8090
8091 bool EmitTLSUnsupportedError = false;
8092 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8093 // C++11 [dcl.stc]p4:
8094 // When thread_local is applied to a variable of block scope the
8095 // storage-class-specifier static is implied if it does not appear
8096 // explicitly.
8097 // Core issue: 'static' is not implied if the variable is declared
8098 // 'extern'.
8099 if (NewVD->hasLocalStorage() &&
8100 (SCSpec != DeclSpec::SCS_unspecified ||
8101 TSCS != DeclSpec::TSCS_thread_local ||
8102 !DC->isFunctionOrMethod()))
8103 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8104 DiagID: diag::err_thread_non_global)
8105 << DeclSpec::getSpecifierName(S: TSCS);
8106 else if (!Context.getTargetInfo().isTLSSupported()) {
8107 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8108 // Postpone error emission until we've collected attributes required to
8109 // figure out whether it's a host or device variable and whether the
8110 // error should be ignored.
8111 EmitTLSUnsupportedError = true;
8112 // We still need to mark the variable as TLS so it shows up in AST with
8113 // proper storage class for other tools to use even if we're not going
8114 // to emit any code for it.
8115 NewVD->setTSCSpec(TSCS);
8116 } else
8117 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8118 DiagID: diag::err_thread_unsupported);
8119 } else
8120 NewVD->setTSCSpec(TSCS);
8121 }
8122
8123 switch (D.getDeclSpec().getConstexprSpecifier()) {
8124 case ConstexprSpecKind::Unspecified:
8125 break;
8126
8127 case ConstexprSpecKind::Consteval:
8128 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8129 DiagID: diag::err_constexpr_wrong_decl_kind)
8130 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8131 [[fallthrough]];
8132
8133 case ConstexprSpecKind::Constexpr:
8134 NewVD->setConstexpr(true);
8135 // C++1z [dcl.spec.constexpr]p1:
8136 // A static data member declared with the constexpr specifier is
8137 // implicitly an inline variable.
8138 if (NewVD->isStaticDataMember() &&
8139 (getLangOpts().CPlusPlus17 ||
8140 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8141 NewVD->setImplicitlyInline();
8142 break;
8143
8144 case ConstexprSpecKind::Constinit:
8145 if (!NewVD->hasGlobalStorage())
8146 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8147 DiagID: diag::err_constinit_local_variable);
8148 else
8149 NewVD->addAttr(
8150 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8151 S: ConstInitAttr::Keyword_constinit));
8152 break;
8153 }
8154
8155 // C99 6.7.4p3
8156 // An inline definition of a function with external linkage shall
8157 // not contain a definition of a modifiable object with static or
8158 // thread storage duration...
8159 // We only apply this when the function is required to be defined
8160 // elsewhere, i.e. when the function is not 'extern inline'. Note
8161 // that a local variable with thread storage duration still has to
8162 // be marked 'static'. Also note that it's possible to get these
8163 // semantics in C++ using __attribute__((gnu_inline)).
8164 if (SC == SC_Static && S->getFnParent() != nullptr &&
8165 !NewVD->getType().isConstQualified()) {
8166 FunctionDecl *CurFD = getCurFunctionDecl();
8167 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8168 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8169 DiagID: diag::warn_static_local_in_extern_inline);
8170 MaybeSuggestAddingStaticToDecl(D: CurFD);
8171 }
8172 }
8173
8174 if (D.getDeclSpec().isModulePrivateSpecified()) {
8175 if (IsVariableTemplateSpecialization)
8176 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8177 << (IsPartialSpecialization ? 1 : 0)
8178 << FixItHint::CreateRemoval(
8179 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8180 else if (IsMemberSpecialization)
8181 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8182 << 2
8183 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8184 else if (NewVD->hasLocalStorage())
8185 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8186 << 0 << NewVD
8187 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8188 << FixItHint::CreateRemoval(
8189 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8190 else {
8191 NewVD->setModulePrivate();
8192 if (NewTemplate)
8193 NewTemplate->setModulePrivate();
8194 for (auto *B : Bindings)
8195 B->setModulePrivate();
8196 }
8197 }
8198
8199 if (getLangOpts().OpenCL) {
8200 deduceOpenCLAddressSpace(Decl: NewVD);
8201
8202 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8203 if (TSC != TSCS_unspecified) {
8204 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8205 DiagID: diag::err_opencl_unknown_type_specifier)
8206 << getLangOpts().getOpenCLVersionString()
8207 << DeclSpec::getSpecifierName(S: TSC) << 1;
8208 NewVD->setInvalidDecl();
8209 }
8210 }
8211
8212 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8213 // address space if the table has local storage (semantic checks elsewhere
8214 // will produce an error anyway).
8215 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8216 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8217 !NewVD->hasLocalStorage()) {
8218 QualType Type = Context.getAddrSpaceQualType(
8219 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8220 NewVD->setType(Type);
8221 }
8222 }
8223
8224 if (Expr *E = D.getAsmLabel()) {
8225 // The parser guarantees this is a string.
8226 StringLiteral *SE = cast<StringLiteral>(Val: E);
8227 StringRef Label = SE->getString();
8228
8229 // Insert the asm attribute.
8230 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8231 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8232 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8233 ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier());
8234 if (I != ExtnameUndeclaredIdentifiers.end()) {
8235 if (isDeclExternC(D: NewVD)) {
8236 NewVD->addAttr(A: I->second);
8237 ExtnameUndeclaredIdentifiers.erase(I);
8238 } else
8239 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8240 << /*Variable*/ 1 << NewVD;
8241 }
8242 }
8243
8244 // Handle attributes prior to checking for duplicates in MergeVarDecl
8245 ProcessDeclAttributes(S, D: NewVD, PD: D);
8246
8247 if (getLangOpts().HLSL)
8248 HLSL().ActOnVariableDeclarator(VD: NewVD);
8249
8250 if (getLangOpts().OpenACC)
8251 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8252
8253 // FIXME: This is probably the wrong location to be doing this and we should
8254 // probably be doing this for more attributes (especially for function
8255 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8256 // the code to copy attributes would be generated by TableGen.
8257 if (R->isFunctionPointerType())
8258 if (const auto *TT = R->getAs<TypedefType>())
8259 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8260
8261 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8262 if (EmitTLSUnsupportedError &&
8263 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8264 (getLangOpts().OpenMPIsTargetDevice &&
8265 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8266 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8267 DiagID: diag::err_thread_unsupported);
8268
8269 if (EmitTLSUnsupportedError &&
8270 (LangOpts.SYCLIsDevice ||
8271 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8272 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8273 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8274 // storage [duration]."
8275 if (SC == SC_None && S->getFnParent() != nullptr &&
8276 (NewVD->hasAttr<CUDASharedAttr>() ||
8277 NewVD->hasAttr<CUDAConstantAttr>())) {
8278 NewVD->setStorageClass(SC_Static);
8279 }
8280 }
8281
8282 // Ensure that dllimport globals without explicit storage class are treated as
8283 // extern. The storage class is set above using parsed attributes. Now we can
8284 // check the VarDecl itself.
8285 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8286 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8287 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8288
8289 // In auto-retain/release, infer strong retension for variables of
8290 // retainable type.
8291 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8292 NewVD->setInvalidDecl();
8293
8294 // Check the ASM label here, as we need to know all other attributes of the
8295 // Decl first. Otherwise, we can't know if the asm label refers to the
8296 // host or device in a CUDA context. The device has other registers than
8297 // host and we must know where the function will be placed.
8298 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8299
8300 // Find the shadowed declaration before filtering for scope.
8301 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8302 ? getShadowedDeclaration(D: NewVD, R: Previous)
8303 : nullptr;
8304
8305 // Don't consider existing declarations that are in a different
8306 // scope and are out-of-semantic-context declarations (if the new
8307 // declaration has linkage).
8308 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8309 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8310 IsMemberSpecialization ||
8311 IsVariableTemplateSpecialization);
8312
8313 // Check whether the previous declaration is in the same block scope. This
8314 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8315 if (getLangOpts().CPlusPlus &&
8316 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8317 NewVD->setPreviousDeclInSameBlockScope(
8318 Previous.isSingleResult() && !Previous.isShadowed() &&
8319 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8320
8321 if (!getLangOpts().CPlusPlus) {
8322 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8323 } else {
8324 // If this is an explicit specialization of a static data member, check it.
8325 if (IsMemberSpecialization && !IsVariableTemplate &&
8326 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8327 CheckMemberSpecialization(Member: NewVD, Previous))
8328 NewVD->setInvalidDecl();
8329
8330 // Merge the decl with the existing one if appropriate.
8331 if (!Previous.empty()) {
8332 if (Previous.isSingleResult() &&
8333 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8334 D.getCXXScopeSpec().isSet()) {
8335 // The user tried to define a non-static data member
8336 // out-of-line (C++ [dcl.meaning]p1).
8337 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8338 << D.getCXXScopeSpec().getRange();
8339 Previous.clear();
8340 NewVD->setInvalidDecl();
8341 }
8342 } else if (D.getCXXScopeSpec().isSet() &&
8343 !IsVariableTemplateSpecialization) {
8344 // No previous declaration in the qualifying scope.
8345 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8346 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8347 << D.getCXXScopeSpec().getRange();
8348 NewVD->setInvalidDecl();
8349 }
8350
8351 if (!IsPlaceholderVariable)
8352 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8353
8354 // CheckVariableDeclaration will set NewVD as invalid if something is in
8355 // error like WebAssembly tables being declared as arrays with a non-zero
8356 // size, but then parsing continues and emits further errors on that line.
8357 // To avoid that we check here if it happened and return nullptr.
8358 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8359 return nullptr;
8360
8361 if (NewTemplate) {
8362 VarTemplateDecl *PrevVarTemplate =
8363 NewVD->getPreviousDecl()
8364 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8365 : nullptr;
8366
8367 // Check the template parameter list of this declaration, possibly
8368 // merging in the template parameter list from the previous variable
8369 // template declaration.
8370 if (CheckTemplateParameterList(
8371 NewParams: TemplateParams,
8372 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8373 : nullptr,
8374 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8375 DC->isDependentContext())
8376 ? TPC_ClassTemplateMember
8377 : TPC_Other))
8378 NewVD->setInvalidDecl();
8379
8380 // If we are providing an explicit specialization of a static variable
8381 // template, make a note of that.
8382 if (PrevVarTemplate &&
8383 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8384 PrevVarTemplate->setMemberSpecialization();
8385 }
8386 }
8387
8388 // Diagnose shadowed variables iff this isn't a redeclaration.
8389 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8390 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8391
8392 ProcessPragmaWeak(S, D: NewVD);
8393 ProcessPragmaExport(NewD: NewVD);
8394
8395 // If this is the first declaration of an extern C variable, update
8396 // the map of such variables.
8397 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8398 isIncompleteDeclExternC(S&: *this, D: NewVD))
8399 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8400
8401 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8402 MangleNumberingContext *MCtx;
8403 Decl *ManglingContextDecl;
8404 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8405 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8406 if (MCtx) {
8407 Context.setManglingNumber(
8408 ND: NewVD, Number: MCtx->getManglingNumber(
8409 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8410 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8411 }
8412 }
8413
8414 // Special handling of variable named 'main'.
8415 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8416 // C++ [basic.start.main]p3:
8417 // A program that declares
8418 // - a variable main at global scope, or
8419 // - an entity named main with C language linkage (in any namespace)
8420 // is ill-formed
8421 if (getLangOpts().CPlusPlus)
8422 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8423 << NewVD->isExternC();
8424
8425 // In C, and external-linkage variable named main results in undefined
8426 // behavior.
8427 else if (NewVD->hasExternalFormalLinkage())
8428 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8429 }
8430
8431 if (D.isRedeclaration() && !Previous.empty()) {
8432 NamedDecl *Prev = Previous.getRepresentativeDecl();
8433 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8434 IsDefinition: D.isFunctionDefinition());
8435 }
8436
8437 if (NewTemplate) {
8438 if (NewVD->isInvalidDecl())
8439 NewTemplate->setInvalidDecl();
8440 ActOnDocumentableDecl(D: NewTemplate);
8441 return NewTemplate;
8442 }
8443
8444 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8445 CompleteMemberSpecialization(Member: NewVD, Previous);
8446
8447 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8448
8449 return NewVD;
8450}
8451
8452/// Enum describing the %select options in diag::warn_decl_shadow.
8453enum ShadowedDeclKind {
8454 SDK_Local,
8455 SDK_Global,
8456 SDK_StaticMember,
8457 SDK_Field,
8458 SDK_Typedef,
8459 SDK_Using,
8460 SDK_StructuredBinding
8461};
8462
8463/// Determine what kind of declaration we're shadowing.
8464static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8465 const DeclContext *OldDC) {
8466 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8467 return SDK_Using;
8468 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8469 return SDK_Typedef;
8470 else if (isa<BindingDecl>(Val: ShadowedDecl))
8471 return SDK_StructuredBinding;
8472 else if (isa<RecordDecl>(Val: OldDC))
8473 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8474
8475 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8476}
8477
8478/// Return the location of the capture if the given lambda captures the given
8479/// variable \p VD, or an invalid source location otherwise.
8480static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8481 const ValueDecl *VD) {
8482 for (const Capture &Capture : LSI->Captures) {
8483 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8484 return Capture.getLocation();
8485 }
8486 return SourceLocation();
8487}
8488
8489static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8490 const LookupResult &R) {
8491 // Only diagnose if we're shadowing an unambiguous field or variable.
8492 if (R.getResultKind() != LookupResultKind::Found)
8493 return false;
8494
8495 // Return false if warning is ignored.
8496 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8497}
8498
8499NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8500 const LookupResult &R) {
8501 if (!shouldWarnIfShadowedDecl(Diags, R))
8502 return nullptr;
8503
8504 // Don't diagnose declarations at file scope.
8505 if (D->hasGlobalStorage() && !D->isStaticLocal())
8506 return nullptr;
8507
8508 NamedDecl *ShadowedDecl = R.getFoundDecl();
8509 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8510 : nullptr;
8511}
8512
8513NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8514 const LookupResult &R) {
8515 // Don't warn if typedef declaration is part of a class
8516 if (D->getDeclContext()->isRecord())
8517 return nullptr;
8518
8519 if (!shouldWarnIfShadowedDecl(Diags, R))
8520 return nullptr;
8521
8522 NamedDecl *ShadowedDecl = R.getFoundDecl();
8523 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8524}
8525
8526NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8527 const LookupResult &R) {
8528 if (!shouldWarnIfShadowedDecl(Diags, R))
8529 return nullptr;
8530
8531 NamedDecl *ShadowedDecl = R.getFoundDecl();
8532 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8533 : nullptr;
8534}
8535
8536void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8537 const LookupResult &R) {
8538 DeclContext *NewDC = D->getDeclContext();
8539
8540 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8541 if (const auto *MD =
8542 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8543 // Fields aren't shadowed in C++ static members or in member functions
8544 // with an explicit object parameter.
8545 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8546 return;
8547 }
8548 // Fields shadowed by constructor parameters are a special case. Usually
8549 // the constructor initializes the field with the parameter.
8550 if (isa<CXXConstructorDecl>(Val: NewDC))
8551 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8552 // Remember that this was shadowed so we can either warn about its
8553 // modification or its existence depending on warning settings.
8554 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8555 return;
8556 }
8557 }
8558
8559 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8560 if (shadowedVar->isExternC()) {
8561 // For shadowing external vars, make sure that we point to the global
8562 // declaration, not a locally scoped extern declaration.
8563 for (auto *I : shadowedVar->redecls())
8564 if (I->isFileVarDecl()) {
8565 ShadowedDecl = I;
8566 break;
8567 }
8568 }
8569
8570 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8571
8572 unsigned WarningDiag = diag::warn_decl_shadow;
8573 SourceLocation CaptureLoc;
8574 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8575 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8576 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8577 // Handle both VarDecl and BindingDecl in lambda contexts
8578 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8579 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8580 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8581 if (RD->getLambdaCaptureDefault() == LCD_None) {
8582 // Try to avoid warnings for lambdas with an explicit capture
8583 // list. Warn only when the lambda captures the shadowed decl
8584 // explicitly.
8585 CaptureLoc = getCaptureLocation(LSI, VD);
8586 if (CaptureLoc.isInvalid())
8587 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8588 } else {
8589 // Remember that this was shadowed so we can avoid the warning if
8590 // the shadowed decl isn't captured and the warning settings allow
8591 // it.
8592 cast<LambdaScopeInfo>(Val: getCurFunction())
8593 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8594 return;
8595 }
8596 }
8597 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8598 // If lambda can capture this, then emit default shadowing warning,
8599 // Otherwise it is not really a shadowing case since field is not
8600 // available in lambda's body.
8601 // At this point we don't know that lambda can capture this, so
8602 // remember that this was shadowed and delay until we know.
8603 cast<LambdaScopeInfo>(Val: getCurFunction())
8604 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8605 return;
8606 }
8607 }
8608 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8609 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8610 bool HasLocalStorage = false;
8611 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8612 HasLocalStorage = VD->hasLocalStorage();
8613 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8614 HasLocalStorage =
8615 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8616
8617 if (HasLocalStorage) {
8618 // A variable can't shadow a local variable or binding in an enclosing
8619 // scope, if they are separated by a non-capturing declaration
8620 // context.
8621 for (DeclContext *ParentDC = NewDC;
8622 ParentDC && !ParentDC->Equals(DC: OldDC);
8623 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8624 // Only block literals, captured statements, and lambda expressions
8625 // can capture; other scopes don't.
8626 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8627 !isLambdaCallOperator(DC: ParentDC))
8628 return;
8629 }
8630 }
8631 }
8632 }
8633 }
8634
8635 // Never warn about shadowing a placeholder variable.
8636 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8637 return;
8638
8639 // Only warn about certain kinds of shadowing for class members.
8640 if (NewDC) {
8641 // In particular, don't warn about shadowing non-class members.
8642 if (NewDC->isRecord() && !OldDC->isRecord())
8643 return;
8644
8645 // Skip shadowing check if we're in a class scope, dealing with an enum
8646 // constant in a different context.
8647 DeclContext *ReDC = NewDC->getRedeclContext();
8648 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8649 return;
8650
8651 // TODO: should we warn about static data members shadowing
8652 // static data members from base classes?
8653
8654 // TODO: don't diagnose for inaccessible shadowed members.
8655 // This is hard to do perfectly because we might friend the
8656 // shadowing context, but that's just a false negative.
8657 }
8658
8659 DeclarationName Name = R.getLookupName();
8660
8661 // Emit warning and note.
8662 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8663 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8664 if (!CaptureLoc.isInvalid())
8665 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8666 << Name << /*explicitly*/ 1;
8667 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8668}
8669
8670void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8671 for (const auto &Shadow : LSI->ShadowingDecls) {
8672 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8673 // Try to avoid the warning when the shadowed decl isn't captured.
8674 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8675 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8676 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8677 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8678 Diag(Loc: Shadow.VD->getLocation(),
8679 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8680 : diag::warn_decl_shadow)
8681 << Shadow.VD->getDeclName()
8682 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8683 if (CaptureLoc.isValid())
8684 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8685 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8686 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8687 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8688 Diag(Loc: Shadow.VD->getLocation(),
8689 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8690 : diag::warn_decl_shadow_uncaptured_local)
8691 << Shadow.VD->getDeclName()
8692 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8693 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8694 }
8695 }
8696}
8697
8698void Sema::CheckShadow(Scope *S, VarDecl *D) {
8699 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8700 return;
8701
8702 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8703 Sema::LookupOrdinaryName,
8704 RedeclarationKind::ForVisibleRedeclaration);
8705 LookupName(R, S);
8706 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8707 CheckShadow(D, ShadowedDecl, R);
8708}
8709
8710/// Check if 'E', which is an expression that is about to be modified, refers
8711/// to a constructor parameter that shadows a field.
8712void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8713 // Quickly ignore expressions that can't be shadowing ctor parameters.
8714 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8715 return;
8716 E = E->IgnoreParenImpCasts();
8717 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8718 if (!DRE)
8719 return;
8720 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8721 auto I = ShadowingDecls.find(Val: D);
8722 if (I == ShadowingDecls.end())
8723 return;
8724 const NamedDecl *ShadowedDecl = I->second;
8725 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8726 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8727 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8728 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8729
8730 // Avoid issuing multiple warnings about the same decl.
8731 ShadowingDecls.erase(I);
8732}
8733
8734/// Check for conflict between this global or extern "C" declaration and
8735/// previous global or extern "C" declarations. This is only used in C++.
8736template<typename T>
8737static bool checkGlobalOrExternCConflict(
8738 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8739 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8740 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8741
8742 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8743 // The common case: this global doesn't conflict with any extern "C"
8744 // declaration.
8745 return false;
8746 }
8747
8748 if (Prev) {
8749 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8750 // Both the old and new declarations have C language linkage. This is a
8751 // redeclaration.
8752 Previous.clear();
8753 Previous.addDecl(D: Prev);
8754 return true;
8755 }
8756
8757 // This is a global, non-extern "C" declaration, and there is a previous
8758 // non-global extern "C" declaration. Diagnose if this is a variable
8759 // declaration.
8760 if (!isa<VarDecl>(ND))
8761 return false;
8762 } else {
8763 // The declaration is extern "C". Check for any declaration in the
8764 // translation unit which might conflict.
8765 if (IsGlobal) {
8766 // We have already performed the lookup into the translation unit.
8767 IsGlobal = false;
8768 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8769 I != E; ++I) {
8770 if (isa<VarDecl>(Val: *I)) {
8771 Prev = *I;
8772 break;
8773 }
8774 }
8775 } else {
8776 DeclContext::lookup_result R =
8777 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8778 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8779 I != E; ++I) {
8780 if (isa<VarDecl>(Val: *I)) {
8781 Prev = *I;
8782 break;
8783 }
8784 // FIXME: If we have any other entity with this name in global scope,
8785 // the declaration is ill-formed, but that is a defect: it breaks the
8786 // 'stat' hack, for instance. Only variables can have mangled name
8787 // clashes with extern "C" declarations, so only they deserve a
8788 // diagnostic.
8789 }
8790 }
8791
8792 if (!Prev)
8793 return false;
8794 }
8795
8796 // Use the first declaration's location to ensure we point at something which
8797 // is lexically inside an extern "C" linkage-spec.
8798 assert(Prev && "should have found a previous declaration to diagnose");
8799 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8800 Prev = FD->getFirstDecl();
8801 else
8802 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8803
8804 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8805 << IsGlobal << ND;
8806 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8807 << IsGlobal;
8808 return false;
8809}
8810
8811/// Apply special rules for handling extern "C" declarations. Returns \c true
8812/// if we have found that this is a redeclaration of some prior entity.
8813///
8814/// Per C++ [dcl.link]p6:
8815/// Two declarations [for a function or variable] with C language linkage
8816/// with the same name that appear in different scopes refer to the same
8817/// [entity]. An entity with C language linkage shall not be declared with
8818/// the same name as an entity in global scope.
8819template<typename T>
8820static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8821 LookupResult &Previous) {
8822 if (!S.getLangOpts().CPlusPlus) {
8823 // In C, when declaring a global variable, look for a corresponding 'extern'
8824 // variable declared in function scope. We don't need this in C++, because
8825 // we find local extern decls in the surrounding file-scope DeclContext.
8826 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8827 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8828 Previous.clear();
8829 Previous.addDecl(D: Prev);
8830 return true;
8831 }
8832 }
8833 return false;
8834 }
8835
8836 // A declaration in the translation unit can conflict with an extern "C"
8837 // declaration.
8838 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8839 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8840
8841 // An extern "C" declaration can conflict with a declaration in the
8842 // translation unit or can be a redeclaration of an extern "C" declaration
8843 // in another scope.
8844 if (isIncompleteDeclExternC(S,ND))
8845 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8846
8847 // Neither global nor extern "C": nothing to do.
8848 return false;
8849}
8850
8851static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8852 QualType T) {
8853 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8854 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8855 // any of its members, even recursively, shall not have an atomic type, or a
8856 // variably modified type, or a type that is volatile or restrict qualified.
8857 if (CanonT->isVariablyModifiedType()) {
8858 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8859 return true;
8860 }
8861
8862 // Arrays are qualified by their element type, so get the base type (this
8863 // works on non-arrays as well).
8864 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8865
8866 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8867 CanonT.isRestrictQualified()) {
8868 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8869 return true;
8870 }
8871
8872 if (CanonT->isRecordType()) {
8873 const RecordDecl *RD = CanonT->getAsRecordDecl();
8874 if (!RD->isInvalidDecl() &&
8875 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8876 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8877 }))
8878 return true;
8879 }
8880
8881 return false;
8882}
8883
8884void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8885 // If the decl is already known invalid, don't check it.
8886 if (NewVD->isInvalidDecl())
8887 return;
8888
8889 QualType T = NewVD->getType();
8890
8891 // Defer checking an 'auto' type until its initializer is attached.
8892 if (T->isUndeducedType())
8893 return;
8894
8895 if (NewVD->hasAttrs())
8896 CheckAlignasUnderalignment(D: NewVD);
8897
8898 if (T->isObjCObjectType()) {
8899 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8900 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8901 T = Context.getObjCObjectPointerType(OIT: T);
8902 NewVD->setType(T);
8903 }
8904
8905 // Emit an error if an address space was applied to decl with local storage.
8906 // This includes arrays of objects with address space qualifiers, but not
8907 // automatic variables that point to other address spaces.
8908 // ISO/IEC TR 18037 S5.1.2
8909 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8910 T.getAddressSpace() != LangAS::Default) {
8911 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8912 NewVD->setInvalidDecl();
8913 return;
8914 }
8915
8916 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8917 // scope.
8918 if (getLangOpts().OpenCLVersion == 120 &&
8919 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8920 LO: getLangOpts()) &&
8921 NewVD->isStaticLocal()) {
8922 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8923 NewVD->setInvalidDecl();
8924 return;
8925 }
8926
8927 if (getLangOpts().OpenCL) {
8928 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8929 return;
8930
8931 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8932 if (NewVD->hasAttr<BlocksAttr>()) {
8933 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8934 return;
8935 }
8936
8937 if (T->isBlockPointerType()) {
8938 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8939 // can't use 'extern' storage class.
8940 if (!T.isConstQualified()) {
8941 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8942 << 0 /*const*/;
8943 NewVD->setInvalidDecl();
8944 return;
8945 }
8946 if (NewVD->hasExternalStorage()) {
8947 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8948 NewVD->setInvalidDecl();
8949 return;
8950 }
8951 }
8952
8953 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8954 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8955 NewVD->hasExternalStorage()) {
8956 if (!T->isSamplerT() && !T->isDependentType() &&
8957 !(T.getAddressSpace() == LangAS::opencl_constant ||
8958 (T.getAddressSpace() == LangAS::opencl_global &&
8959 getOpenCLOptions().areProgramScopeVariablesSupported(
8960 Opts: getLangOpts())))) {
8961 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8962 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8963 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8964 << Scope << "global or constant";
8965 else
8966 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8967 << Scope << "constant";
8968 NewVD->setInvalidDecl();
8969 return;
8970 }
8971 } else {
8972 if (T.getAddressSpace() == LangAS::opencl_global) {
8973 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8974 << 1 /*is any function*/ << "global";
8975 NewVD->setInvalidDecl();
8976 return;
8977 }
8978 // When this extension is enabled, 'local' variables are permitted in
8979 // non-kernel functions and within nested scopes of kernel functions,
8980 // bypassing standard OpenCL address space restrictions.
8981 bool AllowFunctionScopeLocalVariables =
8982 T.getAddressSpace() == LangAS::opencl_local &&
8983 getOpenCLOptions().isAvailableOption(
8984 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
8985 if (AllowFunctionScopeLocalVariables) {
8986 // Direct pass: No further diagnostics needed for this specific case.
8987 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
8988 T.getAddressSpace() == LangAS::opencl_local) {
8989 FunctionDecl *FD = getCurFunctionDecl();
8990 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8991 // in functions.
8992 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8993 if (T.getAddressSpace() == LangAS::opencl_constant)
8994 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8995 << 0 /*non-kernel only*/ << "constant";
8996 else
8997 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8998 << 0 /*non-kernel only*/ << "local";
8999 NewVD->setInvalidDecl();
9000 return;
9001 }
9002 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9003 // in the outermost scope of a kernel function.
9004 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9005 if (!getCurScope()->isFunctionScope()) {
9006 if (T.getAddressSpace() == LangAS::opencl_constant)
9007 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9008 << "constant";
9009 else
9010 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9011 << "local";
9012 NewVD->setInvalidDecl();
9013 return;
9014 }
9015 }
9016 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9017 // If we are parsing a template we didn't deduce an addr
9018 // space yet.
9019 T.getAddressSpace() != LangAS::Default) {
9020 // Do not allow other address spaces on automatic variable.
9021 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9022 NewVD->setInvalidDecl();
9023 return;
9024 }
9025 }
9026 }
9027
9028 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9029 && !NewVD->hasAttr<BlocksAttr>()) {
9030 if (getLangOpts().getGC() != LangOptions::NonGC)
9031 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9032 else {
9033 assert(!getLangOpts().ObjCAutoRefCount);
9034 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9035 }
9036 }
9037
9038 // WebAssembly tables must be static with a zero length and can't be
9039 // declared within functions.
9040 if (T->isWebAssemblyTableType()) {
9041 if (getCurScope()->getParent()) { // Parent is null at top-level
9042 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9043 NewVD->setInvalidDecl();
9044 return;
9045 }
9046 if (NewVD->getStorageClass() != SC_Static) {
9047 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9048 NewVD->setInvalidDecl();
9049 return;
9050 }
9051 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9052 if (!ATy || ATy->getZExtSize() != 0) {
9053 Diag(Loc: NewVD->getLocation(),
9054 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9055 NewVD->setInvalidDecl();
9056 return;
9057 }
9058 }
9059
9060 // zero sized static arrays are not allowed in HIP device functions
9061 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9062 if (FunctionDecl *FD = getCurFunctionDecl();
9063 FD &&
9064 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9065 if (const ConstantArrayType *ArrayT =
9066 getASTContext().getAsConstantArrayType(T);
9067 ArrayT && ArrayT->isZeroSize()) {
9068 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9069 }
9070 }
9071 }
9072
9073 bool isVM = T->isVariablyModifiedType();
9074 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9075 NewVD->hasAttr<BlocksAttr>())
9076 setFunctionHasBranchProtectedScope();
9077
9078 if ((isVM && NewVD->hasLinkage()) ||
9079 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9080 bool SizeIsNegative;
9081 llvm::APSInt Oversized;
9082 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9083 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9084 QualType FixedT;
9085 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9086 FixedT = FixedTInfo->getType();
9087 else if (FixedTInfo) {
9088 // Type and type-as-written are canonically different. We need to fix up
9089 // both types separately.
9090 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9091 Oversized);
9092 }
9093 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9094 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9095 // FIXME: This won't give the correct result for
9096 // int a[10][n];
9097 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9098
9099 if (NewVD->isFileVarDecl())
9100 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9101 << SizeRange;
9102 else if (NewVD->isStaticLocal())
9103 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9104 << SizeRange;
9105 else
9106 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9107 << SizeRange;
9108 NewVD->setInvalidDecl();
9109 return;
9110 }
9111
9112 if (!FixedTInfo) {
9113 if (NewVD->isFileVarDecl())
9114 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9115 else
9116 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9117 NewVD->setInvalidDecl();
9118 return;
9119 }
9120
9121 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9122 NewVD->setType(FixedT);
9123 NewVD->setTypeSourceInfo(FixedTInfo);
9124 }
9125
9126 if (T->isVoidType()) {
9127 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9128 // of objects and functions.
9129 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9130 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9131 << T;
9132 NewVD->setInvalidDecl();
9133 return;
9134 }
9135 }
9136
9137 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9138 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal);
9139 NewVD->setInvalidDecl();
9140 return;
9141 }
9142
9143 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9144 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9145 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9146 NewVD->setInvalidDecl();
9147 return;
9148 }
9149
9150 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9151 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm);
9152 NewVD->setInvalidDecl();
9153 return;
9154 }
9155
9156 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9157 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9158 NewVD->setInvalidDecl();
9159 return;
9160 }
9161
9162 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9163 !T->isDependentType() &&
9164 RequireLiteralType(Loc: NewVD->getLocation(), T,
9165 DiagID: diag::err_constexpr_var_non_literal)) {
9166 NewVD->setInvalidDecl();
9167 return;
9168 }
9169
9170 // PPC MMA non-pointer types are not allowed as non-local variable types.
9171 if (Context.getTargetInfo().getTriple().isPPC64() &&
9172 !NewVD->isLocalVarDecl() &&
9173 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9174 NewVD->setInvalidDecl();
9175 return;
9176 }
9177
9178 // Check that SVE types are only used in functions with SVE available.
9179 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9180 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9181 llvm::StringMap<bool> CallerFeatureMap;
9182 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9183 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9184 FeatureMap: CallerFeatureMap)) {
9185 NewVD->setInvalidDecl();
9186 return;
9187 }
9188 }
9189
9190 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9191 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9192 llvm::StringMap<bool> CallerFeatureMap;
9193 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9194 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9195 FeatureMap: CallerFeatureMap);
9196 }
9197}
9198
9199bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9200 CheckVariableDeclarationType(NewVD);
9201
9202 // If the decl is already known invalid, don't check it.
9203 if (NewVD->isInvalidDecl())
9204 return false;
9205
9206 // If we did not find anything by this name, look for a non-visible
9207 // extern "C" declaration with the same name.
9208 if (Previous.empty() &&
9209 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9210 Previous.setShadowed();
9211
9212 if (!Previous.empty()) {
9213 MergeVarDecl(New: NewVD, Previous);
9214 return true;
9215 }
9216 return false;
9217}
9218
9219bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9220 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9221
9222 // Look for methods in base classes that this method might override.
9223 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9224 /*DetectVirtual=*/false);
9225 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9226 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9227 DeclarationName Name = MD->getDeclName();
9228
9229 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9230 // We really want to find the base class destructor here.
9231 Name = Context.DeclarationNames.getCXXDestructorName(
9232 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9233 }
9234
9235 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9236 CXXMethodDecl *BaseMD =
9237 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9238 if (!BaseMD || !BaseMD->isVirtual() ||
9239 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9240 /*ConsiderCudaAttrs=*/true))
9241 continue;
9242 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9243 continue;
9244 if (Overridden.insert(Ptr: BaseMD).second) {
9245 MD->addOverriddenMethod(MD: BaseMD);
9246 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9247 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9248 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9249 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9250 }
9251
9252 // A method can only override one function from each base class. We
9253 // don't track indirectly overridden methods from bases of bases.
9254 return true;
9255 }
9256
9257 return false;
9258 };
9259
9260 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9261 return !Overridden.empty();
9262}
9263
9264namespace {
9265 // Struct for holding all of the extra arguments needed by
9266 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9267 struct ActOnFDArgs {
9268 Scope *S;
9269 Declarator &D;
9270 MultiTemplateParamsArg TemplateParamLists;
9271 bool AddToScope;
9272 };
9273} // end anonymous namespace
9274
9275namespace {
9276
9277// Callback to only accept typo corrections that have a non-zero edit distance.
9278// Also only accept corrections that have the same parent decl.
9279class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9280 public:
9281 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9282 CXXRecordDecl *Parent)
9283 : Context(Context), OriginalFD(TypoFD),
9284 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9285
9286 bool ValidateCandidate(const TypoCorrection &candidate) override {
9287 if (candidate.getEditDistance() == 0)
9288 return false;
9289
9290 SmallVector<unsigned, 1> MismatchedParams;
9291 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9292 CDeclEnd = candidate.end();
9293 CDecl != CDeclEnd; ++CDecl) {
9294 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9295
9296 if (FD && !FD->hasBody() &&
9297 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9298 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9299 CXXRecordDecl *Parent = MD->getParent();
9300 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9301 return true;
9302 } else if (!ExpectedParent) {
9303 return true;
9304 }
9305 }
9306 }
9307
9308 return false;
9309 }
9310
9311 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9312 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9313 }
9314
9315 private:
9316 ASTContext &Context;
9317 FunctionDecl *OriginalFD;
9318 CXXRecordDecl *ExpectedParent;
9319};
9320
9321} // end anonymous namespace
9322
9323void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9324 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9325}
9326
9327/// Generate diagnostics for an invalid function redeclaration.
9328///
9329/// This routine handles generating the diagnostic messages for an invalid
9330/// function redeclaration, including finding possible similar declarations
9331/// or performing typo correction if there are no previous declarations with
9332/// the same name.
9333///
9334/// Returns a NamedDecl iff typo correction was performed and substituting in
9335/// the new declaration name does not cause new errors.
9336static NamedDecl *DiagnoseInvalidRedeclaration(
9337 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9338 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9339 DeclarationName Name = NewFD->getDeclName();
9340 DeclContext *NewDC = NewFD->getDeclContext();
9341 SmallVector<unsigned, 1> MismatchedParams;
9342 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9343 TypoCorrection Correction;
9344 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9345 unsigned DiagMsg =
9346 IsLocalFriend ? diag::err_no_matching_local_friend :
9347 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9348 diag::err_member_decl_does_not_match;
9349 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9350 IsLocalFriend ? Sema::LookupLocalFriendName
9351 : Sema::LookupOrdinaryName,
9352 RedeclarationKind::ForVisibleRedeclaration);
9353
9354 NewFD->setInvalidDecl();
9355 if (IsLocalFriend)
9356 SemaRef.LookupName(R&: Prev, S);
9357 else
9358 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9359 assert(!Prev.isAmbiguous() &&
9360 "Cannot have an ambiguity in previous-declaration lookup");
9361 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9362 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9363 MD ? MD->getParent() : nullptr);
9364 if (!Prev.empty()) {
9365 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9366 Func != FuncEnd; ++Func) {
9367 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9368 if (FD &&
9369 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9370 // Add 1 to the index so that 0 can mean the mismatch didn't
9371 // involve a parameter
9372 unsigned ParamNum =
9373 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9374 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9375 }
9376 }
9377 // If the qualified name lookup yielded nothing, try typo correction
9378 } else if ((Correction = SemaRef.CorrectTypo(
9379 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9380 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9381 Mode: CorrectTypoKind::ErrorRecovery,
9382 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9383 // Set up everything for the call to ActOnFunctionDeclarator
9384 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9385 IdLoc: ExtraArgs.D.getIdentifierLoc());
9386 Previous.clear();
9387 Previous.setLookupName(Correction.getCorrection());
9388 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9389 CDeclEnd = Correction.end();
9390 CDecl != CDeclEnd; ++CDecl) {
9391 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9392 if (FD && !FD->hasBody() &&
9393 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9394 Previous.addDecl(D: FD);
9395 }
9396 }
9397 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9398
9399 NamedDecl *Result;
9400 // Retry building the function declaration with the new previous
9401 // declarations, and with errors suppressed.
9402 {
9403 // Trap errors.
9404 Sema::SFINAETrap Trap(SemaRef);
9405
9406 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9407 // pieces need to verify the typo-corrected C++ declaration and hopefully
9408 // eliminate the need for the parameter pack ExtraArgs.
9409 Result = SemaRef.ActOnFunctionDeclarator(
9410 S: ExtraArgs.S, D&: ExtraArgs.D,
9411 DC: Correction.getCorrectionDecl()->getDeclContext(),
9412 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9413 AddToScope&: ExtraArgs.AddToScope);
9414
9415 if (Trap.hasErrorOccurred())
9416 Result = nullptr;
9417 }
9418
9419 if (Result) {
9420 // Determine which correction we picked.
9421 Decl *Canonical = Result->getCanonicalDecl();
9422 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9423 I != E; ++I)
9424 if ((*I)->getCanonicalDecl() == Canonical)
9425 Correction.setCorrectionDecl(*I);
9426
9427 // Let Sema know about the correction.
9428 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9429 SemaRef.diagnoseTypo(
9430 Correction,
9431 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9432 ? diag::err_no_matching_local_friend_suggest
9433 : diag::err_member_decl_does_not_match_suggest)
9434 << Name << NewDC << IsDefinition);
9435 return Result;
9436 }
9437
9438 // Pretend the typo correction never occurred
9439 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9440 IdLoc: ExtraArgs.D.getIdentifierLoc());
9441 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9442 Previous.clear();
9443 Previous.setLookupName(Name);
9444 }
9445
9446 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9447 << Name << NewDC << IsDefinition << NewFD->getLocation();
9448
9449 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9450 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9451 CXXRecordDecl *RD = NewMD->getParent();
9452 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9453 << RD->getName() << RD->getLocation();
9454 }
9455
9456 bool NewFDisConst = NewMD && NewMD->isConst();
9457
9458 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9459 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9460 NearMatch != NearMatchEnd; ++NearMatch) {
9461 FunctionDecl *FD = NearMatch->first;
9462 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9463 bool FDisConst = MD && MD->isConst();
9464 bool IsMember = MD || !IsLocalFriend;
9465
9466 // FIXME: These notes are poorly worded for the local friend case.
9467 if (unsigned Idx = NearMatch->second) {
9468 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9469 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9470 if (Loc.isInvalid()) Loc = FD->getLocation();
9471 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9472 : diag::note_local_decl_close_param_match)
9473 << Idx << FDParam->getType()
9474 << NewFD->getParamDecl(i: Idx - 1)->getType();
9475 } else if (FDisConst != NewFDisConst) {
9476 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9477 DiagID: diag::note_member_def_close_const_match)
9478 << NewFDisConst << FD->getSourceRange().getEnd();
9479 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9480 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9481 Code: " const");
9482 else if (FTI.hasMethodTypeQualifiers() &&
9483 FTI.getConstQualifierLoc().isValid())
9484 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9485 } else {
9486 SemaRef.Diag(Loc: FD->getLocation(),
9487 DiagID: IsMember ? diag::note_member_def_close_match
9488 : diag::note_local_decl_close_match);
9489 }
9490 }
9491 return nullptr;
9492}
9493
9494static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9495 switch (D.getDeclSpec().getStorageClassSpec()) {
9496 default: llvm_unreachable("Unknown storage class!");
9497 case DeclSpec::SCS_auto:
9498 case DeclSpec::SCS_register:
9499 case DeclSpec::SCS_mutable:
9500 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9501 DiagID: diag::err_typecheck_sclass_func);
9502 D.getMutableDeclSpec().ClearStorageClassSpecs();
9503 D.setInvalidType();
9504 break;
9505 case DeclSpec::SCS_unspecified: break;
9506 case DeclSpec::SCS_extern:
9507 if (D.getDeclSpec().isExternInLinkageSpec())
9508 return SC_None;
9509 return SC_Extern;
9510 case DeclSpec::SCS_static: {
9511 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9512 // C99 6.7.1p5:
9513 // The declaration of an identifier for a function that has
9514 // block scope shall have no explicit storage-class specifier
9515 // other than extern
9516 // See also (C++ [dcl.stc]p4).
9517 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9518 DiagID: diag::err_static_block_func);
9519 break;
9520 } else
9521 return SC_Static;
9522 }
9523 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9524 }
9525
9526 // No explicit storage class has already been returned
9527 return SC_None;
9528}
9529
9530static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9531 DeclContext *DC, QualType &R,
9532 TypeSourceInfo *TInfo,
9533 StorageClass SC,
9534 bool &IsVirtualOkay) {
9535 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9536 DeclarationName Name = NameInfo.getName();
9537
9538 FunctionDecl *NewFD = nullptr;
9539 bool isInline = D.getDeclSpec().isInlineSpecified();
9540
9541 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9542 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9543 (SemaRef.getLangOpts().C23 &&
9544 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9545
9546 if (SemaRef.getLangOpts().C23)
9547 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9548 DiagID: diag::err_c23_constexpr_not_variable);
9549 else
9550 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9551 DiagID: diag::err_constexpr_wrong_decl_kind)
9552 << static_cast<int>(ConstexprKind);
9553 ConstexprKind = ConstexprSpecKind::Unspecified;
9554 D.getMutableDeclSpec().ClearConstexprSpec();
9555 }
9556
9557 if (!SemaRef.getLangOpts().CPlusPlus) {
9558 // Determine whether the function was written with a prototype. This is
9559 // true when:
9560 // - there is a prototype in the declarator, or
9561 // - the type R of the function is some kind of typedef or other non-
9562 // attributed reference to a type name (which eventually refers to a
9563 // function type). Note, we can't always look at the adjusted type to
9564 // check this case because attributes may cause a non-function
9565 // declarator to still have a function type. e.g.,
9566 // typedef void func(int a);
9567 // __attribute__((noreturn)) func other_func; // This has a prototype
9568 bool HasPrototype =
9569 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9570 (D.getDeclSpec().isTypeRep() &&
9571 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9572 ->isFunctionProtoType()) ||
9573 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9574 assert(
9575 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9576 "Strict prototypes are required");
9577
9578 NewFD = FunctionDecl::Create(
9579 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9580 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9581 ConstexprKind: ConstexprSpecKind::Unspecified,
9582 /*TrailingRequiresClause=*/{});
9583 if (D.isInvalidType())
9584 NewFD->setInvalidDecl();
9585
9586 return NewFD;
9587 }
9588
9589 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9590 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9591
9592 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9593
9594 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9595 // This is a C++ constructor declaration.
9596 assert(DC->isRecord() &&
9597 "Constructors can only be declared in a member context");
9598
9599 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9600 return CXXConstructorDecl::Create(
9601 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9602 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9603 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9604 Inherited: InheritedConstructor(), TrailingRequiresClause);
9605
9606 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9607 // This is a C++ destructor declaration.
9608 if (DC->isRecord()) {
9609 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9610 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9611 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9612 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9613 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9614 /*isImplicitlyDeclared=*/false, ConstexprKind,
9615 TrailingRequiresClause);
9616 // User defined destructors start as not selected if the class definition is still
9617 // not done.
9618 if (Record->isBeingDefined())
9619 NewDD->setIneligibleOrNotSelected(true);
9620
9621 // If the destructor needs an implicit exception specification, set it
9622 // now. FIXME: It'd be nice to be able to create the right type to start
9623 // with, but the type needs to reference the destructor declaration.
9624 if (SemaRef.getLangOpts().CPlusPlus11)
9625 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9626
9627 IsVirtualOkay = true;
9628 return NewDD;
9629
9630 } else {
9631 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9632 D.setInvalidType();
9633
9634 // Create a FunctionDecl to satisfy the function definition parsing
9635 // code path.
9636 return FunctionDecl::Create(
9637 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9638 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9639 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9640 }
9641
9642 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9643 if (!DC->isRecord()) {
9644 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9645 DiagID: diag::err_conv_function_not_member);
9646 return nullptr;
9647 }
9648
9649 SemaRef.CheckConversionDeclarator(D, R, SC);
9650 if (D.isInvalidType())
9651 return nullptr;
9652
9653 IsVirtualOkay = true;
9654 return CXXConversionDecl::Create(
9655 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9656 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9657 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9658 TrailingRequiresClause);
9659
9660 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9661 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9662 return nullptr;
9663 return CXXDeductionGuideDecl::Create(
9664 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9665 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9666 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9667 } else if (DC->isRecord()) {
9668 // If the name of the function is the same as the name of the record,
9669 // then this must be an invalid constructor that has a return type.
9670 // (The parser checks for a return type and makes the declarator a
9671 // constructor if it has no return type).
9672 if (Name.getAsIdentifierInfo() &&
9673 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9674 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9675 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9676 << SourceRange(D.getIdentifierLoc());
9677 return nullptr;
9678 }
9679
9680 // This is a C++ method declaration.
9681 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9682 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9683 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9684 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9685 IsVirtualOkay = !Ret->isStatic();
9686 return Ret;
9687 } else {
9688 bool isFriend =
9689 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9690 if (!isFriend && SemaRef.CurContext->isRecord())
9691 return nullptr;
9692
9693 // Determine whether the function was written with a
9694 // prototype. This true when:
9695 // - we're in C++ (where every function has a prototype),
9696 return FunctionDecl::Create(
9697 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9698 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9699 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9700 }
9701}
9702
9703enum OpenCLParamType {
9704 ValidKernelParam,
9705 PtrPtrKernelParam,
9706 PtrKernelParam,
9707 InvalidAddrSpacePtrKernelParam,
9708 InvalidKernelParam,
9709 RecordKernelParam
9710};
9711
9712static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9713 // Size dependent types are just typedefs to normal integer types
9714 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9715 // integers other than by their names.
9716 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9717
9718 // Remove typedefs one by one until we reach a typedef
9719 // for a size dependent type.
9720 QualType DesugaredTy = Ty;
9721 do {
9722 ArrayRef<StringRef> Names(SizeTypeNames);
9723 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9724 if (Names.end() != Match)
9725 return true;
9726
9727 Ty = DesugaredTy;
9728 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9729 } while (DesugaredTy != Ty);
9730
9731 return false;
9732}
9733
9734static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9735 if (PT->isDependentType())
9736 return InvalidKernelParam;
9737
9738 if (PT->isPointerOrReferenceType()) {
9739 QualType PointeeType = PT->getPointeeType();
9740 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9741 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9742 PointeeType.getAddressSpace() == LangAS::Default)
9743 return InvalidAddrSpacePtrKernelParam;
9744
9745 if (PointeeType->isPointerType()) {
9746 // This is a pointer to pointer parameter.
9747 // Recursively check inner type.
9748 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9749 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9750 ParamKind == InvalidKernelParam)
9751 return ParamKind;
9752
9753 // OpenCL v3.0 s6.11.a:
9754 // A restriction to pass pointers to pointers only applies to OpenCL C
9755 // v1.2 or below.
9756 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9757 return ValidKernelParam;
9758
9759 return PtrPtrKernelParam;
9760 }
9761
9762 // C++ for OpenCL v1.0 s2.4:
9763 // Moreover the types used in parameters of the kernel functions must be:
9764 // Standard layout types for pointer parameters. The same applies to
9765 // reference if an implementation supports them in kernel parameters.
9766 if (S.getLangOpts().OpenCLCPlusPlus &&
9767 !S.getOpenCLOptions().isAvailableOption(
9768 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9769 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9770 bool IsStandardLayoutType = true;
9771 if (CXXRec) {
9772 // If template type is not ODR-used its definition is only available
9773 // in the template definition not its instantiation.
9774 // FIXME: This logic doesn't work for types that depend on template
9775 // parameter (PR58590).
9776 if (!CXXRec->hasDefinition())
9777 CXXRec = CXXRec->getTemplateInstantiationPattern();
9778 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9779 IsStandardLayoutType = false;
9780 }
9781 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9782 !IsStandardLayoutType)
9783 return InvalidKernelParam;
9784 }
9785
9786 // OpenCL v1.2 s6.9.p:
9787 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9788 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9789 return ValidKernelParam;
9790
9791 return PtrKernelParam;
9792 }
9793
9794 // OpenCL v1.2 s6.9.k:
9795 // Arguments to kernel functions in a program cannot be declared with the
9796 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9797 // uintptr_t or a struct and/or union that contain fields declared to be one
9798 // of these built-in scalar types.
9799 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9800 return InvalidKernelParam;
9801
9802 if (PT->isImageType())
9803 return PtrKernelParam;
9804
9805 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9806 return InvalidKernelParam;
9807
9808 // OpenCL extension spec v1.2 s9.5:
9809 // This extension adds support for half scalar and vector types as built-in
9810 // types that can be used for arithmetic operations, conversions etc.
9811 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9812 PT->isHalfType())
9813 return InvalidKernelParam;
9814
9815 // Look into an array argument to check if it has a forbidden type.
9816 if (PT->isArrayType()) {
9817 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9818 // Call ourself to check an underlying type of an array. Since the
9819 // getPointeeOrArrayElementType returns an innermost type which is not an
9820 // array, this recursive call only happens once.
9821 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9822 }
9823
9824 // C++ for OpenCL v1.0 s2.4:
9825 // Moreover the types used in parameters of the kernel functions must be:
9826 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9827 // types) for parameters passed by value;
9828 if (S.getLangOpts().OpenCLCPlusPlus &&
9829 !S.getOpenCLOptions().isAvailableOption(
9830 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9831 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9832 return InvalidKernelParam;
9833
9834 if (PT->isRecordType())
9835 return RecordKernelParam;
9836
9837 return ValidKernelParam;
9838}
9839
9840static void checkIsValidOpenCLKernelParameter(
9841 Sema &S,
9842 Declarator &D,
9843 ParmVarDecl *Param,
9844 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9845 QualType PT = Param->getType();
9846
9847 // Cache the valid types we encounter to avoid rechecking structs that are
9848 // used again
9849 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9850 return;
9851
9852 switch (getOpenCLKernelParameterType(S, PT)) {
9853 case PtrPtrKernelParam:
9854 // OpenCL v3.0 s6.11.a:
9855 // A kernel function argument cannot be declared as a pointer to a pointer
9856 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9857 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9858 D.setInvalidType();
9859 return;
9860
9861 case InvalidAddrSpacePtrKernelParam:
9862 // OpenCL v1.0 s6.5:
9863 // __kernel function arguments declared to be a pointer of a type can point
9864 // to one of the following address spaces only : __global, __local or
9865 // __constant.
9866 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9867 D.setInvalidType();
9868 return;
9869
9870 // OpenCL v1.2 s6.9.k:
9871 // Arguments to kernel functions in a program cannot be declared with the
9872 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9873 // uintptr_t or a struct and/or union that contain fields declared to be
9874 // one of these built-in scalar types.
9875
9876 case InvalidKernelParam:
9877 // OpenCL v1.2 s6.8 n:
9878 // A kernel function argument cannot be declared
9879 // of event_t type.
9880 // Do not diagnose half type since it is diagnosed as invalid argument
9881 // type for any function elsewhere.
9882 if (!PT->isHalfType()) {
9883 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9884
9885 // Explain what typedefs are involved.
9886 const TypedefType *Typedef = nullptr;
9887 while ((Typedef = PT->getAs<TypedefType>())) {
9888 SourceLocation Loc = Typedef->getDecl()->getLocation();
9889 // SourceLocation may be invalid for a built-in type.
9890 if (Loc.isValid())
9891 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9892 PT = Typedef->desugar();
9893 }
9894 }
9895
9896 D.setInvalidType();
9897 return;
9898
9899 case PtrKernelParam:
9900 case ValidKernelParam:
9901 ValidTypes.insert(Ptr: PT.getTypePtr());
9902 return;
9903
9904 case RecordKernelParam:
9905 break;
9906 }
9907
9908 // Track nested structs we will inspect
9909 SmallVector<const Decl *, 4> VisitStack;
9910
9911 // Track where we are in the nested structs. Items will migrate from
9912 // VisitStack to HistoryStack as we do the DFS for bad field.
9913 SmallVector<const FieldDecl *, 4> HistoryStack;
9914 HistoryStack.push_back(Elt: nullptr);
9915
9916 // At this point we already handled everything except of a RecordType.
9917 assert(PT->isRecordType() && "Unexpected type.");
9918 const auto *PD = PT->castAsRecordDecl();
9919 VisitStack.push_back(Elt: PD);
9920 assert(VisitStack.back() && "First decl null?");
9921
9922 do {
9923 const Decl *Next = VisitStack.pop_back_val();
9924 if (!Next) {
9925 assert(!HistoryStack.empty());
9926 // Found a marker, we have gone up a level
9927 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9928 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9929
9930 continue;
9931 }
9932
9933 // Adds everything except the original parameter declaration (which is not a
9934 // field itself) to the history stack.
9935 const RecordDecl *RD;
9936 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9937 HistoryStack.push_back(Elt: Field);
9938
9939 QualType FieldTy = Field->getType();
9940 // Other field types (known to be valid or invalid) are handled while we
9941 // walk around RecordDecl::fields().
9942 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9943 "Unexpected type.");
9944 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9945
9946 RD = FieldRecTy->castAsRecordDecl();
9947 } else {
9948 RD = cast<RecordDecl>(Val: Next);
9949 }
9950
9951 // Add a null marker so we know when we've gone back up a level
9952 VisitStack.push_back(Elt: nullptr);
9953
9954 for (const auto *FD : RD->fields()) {
9955 QualType QT = FD->getType();
9956
9957 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9958 continue;
9959
9960 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9961 if (ParamType == ValidKernelParam)
9962 continue;
9963
9964 if (ParamType == RecordKernelParam) {
9965 VisitStack.push_back(Elt: FD);
9966 continue;
9967 }
9968
9969 // OpenCL v1.2 s6.9.p:
9970 // Arguments to kernel functions that are declared to be a struct or union
9971 // do not allow OpenCL objects to be passed as elements of the struct or
9972 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9973 // of SVM.
9974 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9975 ParamType == InvalidAddrSpacePtrKernelParam) {
9976 S.Diag(Loc: Param->getLocation(),
9977 DiagID: diag::err_record_with_pointers_kernel_param)
9978 << PT->isUnionType()
9979 << PT;
9980 } else {
9981 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9982 }
9983
9984 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
9985 << PD->getDeclName();
9986
9987 // We have an error, now let's go back up through history and show where
9988 // the offending field came from
9989 for (ArrayRef<const FieldDecl *>::const_iterator
9990 I = HistoryStack.begin() + 1,
9991 E = HistoryStack.end();
9992 I != E; ++I) {
9993 const FieldDecl *OuterField = *I;
9994 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
9995 << OuterField->getType();
9996 }
9997
9998 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
9999 << QT->isPointerType()
10000 << QT;
10001 D.setInvalidType();
10002 return;
10003 }
10004 } while (!VisitStack.empty());
10005}
10006
10007/// Find the DeclContext in which a tag is implicitly declared if we see an
10008/// elaborated type specifier in the specified context, and lookup finds
10009/// nothing.
10010static DeclContext *getTagInjectionContext(DeclContext *DC) {
10011 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10012 DC = DC->getParent();
10013 return DC;
10014}
10015
10016/// Find the Scope in which a tag is implicitly declared if we see an
10017/// elaborated type specifier in the specified context, and lookup finds
10018/// nothing.
10019static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10020 while (S->isClassScope() ||
10021 (LangOpts.CPlusPlus &&
10022 S->isFunctionPrototypeScope()) ||
10023 ((S->getFlags() & Scope::DeclScope) == 0) ||
10024 (S->getEntity() && S->getEntity()->isTransparentContext()))
10025 S = S->getParent();
10026 return S;
10027}
10028
10029/// Determine whether a declaration matches a known function in namespace std.
10030static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10031 unsigned BuiltinID) {
10032 switch (BuiltinID) {
10033 case Builtin::BI__GetExceptionInfo:
10034 // No type checking whatsoever.
10035 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10036
10037 case Builtin::BIaddressof:
10038 case Builtin::BI__addressof:
10039 case Builtin::BIforward:
10040 case Builtin::BIforward_like:
10041 case Builtin::BImove:
10042 case Builtin::BImove_if_noexcept:
10043 case Builtin::BIas_const: {
10044 // Ensure that we don't treat the algorithm
10045 // OutputIt std::move(InputIt, InputIt, OutputIt)
10046 // as the builtin std::move.
10047 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10048 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10049 }
10050
10051 default:
10052 return false;
10053 }
10054}
10055
10056NamedDecl*
10057Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10058 TypeSourceInfo *TInfo, LookupResult &Previous,
10059 MultiTemplateParamsArg TemplateParamListsRef,
10060 bool &AddToScope) {
10061 QualType R = TInfo->getType();
10062
10063 assert(R->isFunctionType());
10064 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10065 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10066
10067 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10068 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10069 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10070 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10071 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10072 TemplateParamLists.back() = Invented;
10073 else
10074 TemplateParamLists.push_back(Elt: Invented);
10075 }
10076
10077 // TODO: consider using NameInfo for diagnostic.
10078 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10079 DeclarationName Name = NameInfo.getName();
10080 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10081
10082 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10083 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10084 DiagID: diag::err_invalid_thread)
10085 << DeclSpec::getSpecifierName(S: TSCS);
10086
10087 if (D.isFirstDeclarationOfMember())
10088 adjustMemberFunctionCC(
10089 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10090 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10091
10092 bool isFriend = false;
10093 FunctionTemplateDecl *FunctionTemplate = nullptr;
10094 bool isMemberSpecialization = false;
10095 bool isFunctionTemplateSpecialization = false;
10096
10097 bool HasExplicitTemplateArgs = false;
10098 TemplateArgumentListInfo TemplateArgs;
10099
10100 bool isVirtualOkay = false;
10101
10102 DeclContext *OriginalDC = DC;
10103 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10104
10105 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10106 IsVirtualOkay&: isVirtualOkay);
10107 if (!NewFD) return nullptr;
10108
10109 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10110 NewFD->setTopLevelDeclInObjCContainer();
10111
10112 // Set the lexical context. If this is a function-scope declaration, or has a
10113 // C++ scope specifier, or is the object of a friend declaration, the lexical
10114 // context will be different from the semantic context.
10115 NewFD->setLexicalDeclContext(CurContext);
10116
10117 if (IsLocalExternDecl)
10118 NewFD->setLocalExternDecl();
10119
10120 if (getLangOpts().CPlusPlus) {
10121 // The rules for implicit inlines changed in C++20 for methods and friends
10122 // with an in-class definition (when such a definition is not attached to
10123 // the global module). This does not affect declarations that are already
10124 // inline (whether explicitly or implicitly by being declared constexpr,
10125 // consteval, etc).
10126 // FIXME: We need a better way to separate C++ standard and clang modules.
10127 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10128 !NewFD->getOwningModule() ||
10129 NewFD->isFromGlobalModule() ||
10130 NewFD->getOwningModule()->isHeaderLikeModule();
10131 bool isInline = D.getDeclSpec().isInlineSpecified();
10132 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10133 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10134 isFriend = D.getDeclSpec().isFriendSpecified();
10135 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10136 // Pre-C++20 [class.friend]p5
10137 // A function can be defined in a friend declaration of a
10138 // class . . . . Such a function is implicitly inline.
10139 // Post C++20 [class.friend]p7
10140 // Such a function is implicitly an inline function if it is attached
10141 // to the global module.
10142 NewFD->setImplicitlyInline();
10143 }
10144
10145 // If this is a method defined in an __interface, and is not a constructor
10146 // or an overloaded operator, then set the pure flag (isVirtual will already
10147 // return true).
10148 if (const CXXRecordDecl *Parent =
10149 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10150 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10151 NewFD->setIsPureVirtual(true);
10152
10153 // C++ [class.union]p2
10154 // A union can have member functions, but not virtual functions.
10155 if (isVirtual && Parent->isUnion()) {
10156 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10157 NewFD->setInvalidDecl();
10158 }
10159 if ((Parent->isClass() || Parent->isStruct()) &&
10160 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10161 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10162 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10163 if (auto *Def = Parent->getDefinition())
10164 Def->setInitMethod(true);
10165 }
10166 }
10167
10168 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10169 isMemberSpecialization = false;
10170 isFunctionTemplateSpecialization = false;
10171 if (D.isInvalidType())
10172 NewFD->setInvalidDecl();
10173
10174 // Match up the template parameter lists with the scope specifier, then
10175 // determine whether we have a template or a template specialization.
10176 bool Invalid = false;
10177 TemplateIdAnnotation *TemplateId =
10178 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10179 ? D.getName().TemplateId
10180 : nullptr;
10181 TemplateParameterList *TemplateParams =
10182 MatchTemplateParametersToScopeSpecifier(
10183 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10184 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10185 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10186 if (TemplateParams) {
10187 // Check that we can declare a template here.
10188 if (CheckTemplateDeclScope(S, TemplateParams))
10189 NewFD->setInvalidDecl();
10190
10191 if (TemplateParams->size() > 0) {
10192 // This is a function template
10193
10194 // A destructor cannot be a template.
10195 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10196 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10197 NewFD->setInvalidDecl();
10198 // Function template with explicit template arguments.
10199 } else if (TemplateId) {
10200 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10201 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10202 NewFD->setInvalidDecl();
10203 }
10204
10205 // If we're adding a template to a dependent context, we may need to
10206 // rebuilding some of the types used within the template parameter list,
10207 // now that we know what the current instantiation is.
10208 if (DC->isDependentContext()) {
10209 ContextRAII SavedContext(*this, DC);
10210 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10211 Invalid = true;
10212 }
10213
10214 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10215 L: NewFD->getLocation(),
10216 Name, Params: TemplateParams,
10217 Decl: NewFD);
10218 FunctionTemplate->setLexicalDeclContext(CurContext);
10219 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10220
10221 // For source fidelity, store the other template param lists.
10222 if (TemplateParamLists.size() > 1) {
10223 NewFD->setTemplateParameterListsInfo(Context,
10224 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10225 .drop_back(N: 1));
10226 }
10227 } else {
10228 // This is a function template specialization.
10229 isFunctionTemplateSpecialization = true;
10230 // For source fidelity, store all the template param lists.
10231 if (TemplateParamLists.size() > 0)
10232 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10233
10234 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10235 if (isFriend) {
10236 // We want to remove the "template<>", found here.
10237 SourceRange RemoveRange = TemplateParams->getSourceRange();
10238
10239 // If we remove the template<> and the name is not a
10240 // template-id, we're actually silently creating a problem:
10241 // the friend declaration will refer to an untemplated decl,
10242 // and clearly the user wants a template specialization. So
10243 // we need to insert '<>' after the name.
10244 SourceLocation InsertLoc;
10245 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10246 InsertLoc = D.getName().getSourceRange().getEnd();
10247 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10248 }
10249
10250 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10251 << Name << RemoveRange
10252 << FixItHint::CreateRemoval(RemoveRange)
10253 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10254 Invalid = true;
10255
10256 // Recover by faking up an empty template argument list.
10257 HasExplicitTemplateArgs = true;
10258 TemplateArgs.setLAngleLoc(InsertLoc);
10259 TemplateArgs.setRAngleLoc(InsertLoc);
10260 }
10261 }
10262 } else {
10263 // Check that we can declare a template here.
10264 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10265 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10266 NewFD->setInvalidDecl();
10267
10268 // All template param lists were matched against the scope specifier:
10269 // this is NOT (an explicit specialization of) a template.
10270 if (TemplateParamLists.size() > 0)
10271 // For source fidelity, store all the template param lists.
10272 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10273
10274 // "friend void foo<>(int);" is an implicit specialization decl.
10275 if (isFriend && TemplateId)
10276 isFunctionTemplateSpecialization = true;
10277 }
10278
10279 // If this is a function template specialization and the unqualified-id of
10280 // the declarator-id is a template-id, convert the template argument list
10281 // into our AST format and check for unexpanded packs.
10282 if (isFunctionTemplateSpecialization && TemplateId) {
10283 HasExplicitTemplateArgs = true;
10284
10285 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10286 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10287 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10288 TemplateId->NumArgs);
10289 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10290
10291 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10292 // declaration of a function template partial specialization? Should we
10293 // consider the unexpanded pack context to be a partial specialization?
10294 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10295 if (DiagnoseUnexpandedParameterPack(
10296 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10297 : UPPC_ExplicitSpecialization))
10298 NewFD->setInvalidDecl();
10299 }
10300 }
10301
10302 if (Invalid) {
10303 NewFD->setInvalidDecl();
10304 if (FunctionTemplate)
10305 FunctionTemplate->setInvalidDecl();
10306 }
10307
10308 // C++ [dcl.fct.spec]p5:
10309 // The virtual specifier shall only be used in declarations of
10310 // nonstatic class member functions that appear within a
10311 // member-specification of a class declaration; see 10.3.
10312 //
10313 if (isVirtual && !NewFD->isInvalidDecl()) {
10314 if (!isVirtualOkay) {
10315 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10316 DiagID: diag::err_virtual_non_function);
10317 } else if (!CurContext->isRecord()) {
10318 // 'virtual' was specified outside of the class.
10319 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10320 DiagID: diag::err_virtual_out_of_class)
10321 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10322 } else if (NewFD->getDescribedFunctionTemplate()) {
10323 // C++ [temp.mem]p3:
10324 // A member function template shall not be virtual.
10325 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10326 DiagID: diag::err_virtual_member_function_template)
10327 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10328 } else {
10329 // Okay: Add virtual to the method.
10330 NewFD->setVirtualAsWritten(true);
10331 }
10332
10333 if (getLangOpts().CPlusPlus14 &&
10334 NewFD->getReturnType()->isUndeducedType())
10335 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10336 }
10337
10338 // C++ [dcl.fct.spec]p3:
10339 // The inline specifier shall not appear on a block scope function
10340 // declaration.
10341 if (isInline && !NewFD->isInvalidDecl()) {
10342 if (CurContext->isFunctionOrMethod()) {
10343 // 'inline' is not allowed on block scope function declaration.
10344 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10345 DiagID: diag::err_inline_declaration_block_scope) << Name
10346 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10347 }
10348 }
10349
10350 // C++ [dcl.fct.spec]p6:
10351 // The explicit specifier shall be used only in the declaration of a
10352 // constructor or conversion function within its class definition;
10353 // see 12.3.1 and 12.3.2.
10354 if (hasExplicit && !NewFD->isInvalidDecl() &&
10355 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10356 if (!CurContext->isRecord()) {
10357 // 'explicit' was specified outside of the class.
10358 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10359 DiagID: diag::err_explicit_out_of_class)
10360 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10361 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10362 !isa<CXXConversionDecl>(Val: NewFD)) {
10363 // 'explicit' was specified on a function that wasn't a constructor
10364 // or conversion function.
10365 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10366 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10367 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10368 }
10369 }
10370
10371 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10372 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10373 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10374 // are implicitly inline.
10375 NewFD->setImplicitlyInline();
10376
10377 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10378 // be either constructors or to return a literal type. Therefore,
10379 // destructors cannot be declared constexpr.
10380 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10381 (!getLangOpts().CPlusPlus20 ||
10382 ConstexprKind == ConstexprSpecKind::Consteval)) {
10383 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10384 << static_cast<int>(ConstexprKind);
10385 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10386 ? ConstexprSpecKind::Unspecified
10387 : ConstexprSpecKind::Constexpr);
10388 }
10389 // C++20 [dcl.constexpr]p2: An allocation function, or a
10390 // deallocation function shall not be declared with the consteval
10391 // specifier.
10392 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10393 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10394 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10395 DiagID: diag::err_invalid_consteval_decl_kind)
10396 << NewFD;
10397 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10398 }
10399 }
10400
10401 // If __module_private__ was specified, mark the function accordingly.
10402 if (D.getDeclSpec().isModulePrivateSpecified()) {
10403 if (isFunctionTemplateSpecialization) {
10404 SourceLocation ModulePrivateLoc
10405 = D.getDeclSpec().getModulePrivateSpecLoc();
10406 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10407 << 0
10408 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10409 } else {
10410 NewFD->setModulePrivate();
10411 if (FunctionTemplate)
10412 FunctionTemplate->setModulePrivate();
10413 }
10414 }
10415
10416 if (isFriend) {
10417 if (FunctionTemplate) {
10418 FunctionTemplate->setObjectOfFriendDecl();
10419 FunctionTemplate->setAccess(AS_public);
10420 }
10421 NewFD->setObjectOfFriendDecl();
10422 NewFD->setAccess(AS_public);
10423 }
10424
10425 // If a function is defined as defaulted or deleted, mark it as such now.
10426 // We'll do the relevant checks on defaulted / deleted functions later.
10427 switch (D.getFunctionDefinitionKind()) {
10428 case FunctionDefinitionKind::Declaration:
10429 case FunctionDefinitionKind::Definition:
10430 break;
10431
10432 case FunctionDefinitionKind::Defaulted:
10433 NewFD->setDefaulted();
10434 break;
10435
10436 case FunctionDefinitionKind::Deleted:
10437 NewFD->setDeletedAsWritten();
10438 break;
10439 }
10440
10441 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10442 D.isFunctionDefinition()) {
10443 // Pre C++20 [class.mfct]p2:
10444 // A member function may be defined (8.4) in its class definition, in
10445 // which case it is an inline member function (7.1.2)
10446 // Post C++20 [class.mfct]p1:
10447 // If a member function is attached to the global module and is defined
10448 // in its class definition, it is inline.
10449 NewFD->setImplicitlyInline();
10450 }
10451
10452 if (!isFriend && SC != SC_None) {
10453 // C++ [temp.expl.spec]p2:
10454 // The declaration in an explicit-specialization shall not be an
10455 // export-declaration. An explicit specialization shall not use a
10456 // storage-class-specifier other than thread_local.
10457 //
10458 // We diagnose friend declarations with storage-class-specifiers
10459 // elsewhere.
10460 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10461 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10462 DiagID: diag::ext_explicit_specialization_storage_class)
10463 << FixItHint::CreateRemoval(
10464 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10465 }
10466
10467 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10468 assert(isa<CXXMethodDecl>(NewFD) &&
10469 "Out-of-line member function should be a CXXMethodDecl");
10470 // C++ [class.static]p1:
10471 // A data or function member of a class may be declared static
10472 // in a class definition, in which case it is a static member of
10473 // the class.
10474
10475 // Complain about the 'static' specifier if it's on an out-of-line
10476 // member function definition.
10477
10478 // MSVC permits the use of a 'static' storage specifier on an
10479 // out-of-line member function template declaration and class member
10480 // template declaration (MSVC versions before 2015), warn about this.
10481 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10482 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10483 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10484 (getLangOpts().MSVCCompat &&
10485 NewFD->getDescribedFunctionTemplate()))
10486 ? diag::ext_static_out_of_line
10487 : diag::err_static_out_of_line)
10488 << FixItHint::CreateRemoval(
10489 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10490 }
10491 }
10492
10493 // C++11 [except.spec]p15:
10494 // A deallocation function with no exception-specification is treated
10495 // as if it were specified with noexcept(true).
10496 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10497 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10498 !FPT->hasExceptionSpec())
10499 NewFD->setType(Context.getFunctionType(
10500 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10501 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10502
10503 // C++20 [dcl.inline]/7
10504 // If an inline function or variable that is attached to a named module
10505 // is declared in a definition domain, it shall be defined in that
10506 // domain.
10507 // So, if the current declaration does not have a definition, we must
10508 // check at the end of the TU (or when the PMF starts) to see that we
10509 // have a definition at that point.
10510 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10511 NewFD->isInNamedModule()) {
10512 PendingInlineFuncDecls.insert(Ptr: NewFD);
10513 }
10514 }
10515
10516 // Filter out previous declarations that don't match the scope.
10517 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10518 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10519 isMemberSpecialization ||
10520 isFunctionTemplateSpecialization);
10521
10522 // Handle GNU asm-label extension (encoded as an attribute).
10523 if (Expr *E = D.getAsmLabel()) {
10524 // The parser guarantees this is a string.
10525 StringLiteral *SE = cast<StringLiteral>(Val: E);
10526 NewFD->addAttr(
10527 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10528 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10529 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10530 ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier());
10531 if (I != ExtnameUndeclaredIdentifiers.end()) {
10532 if (isDeclExternC(D: NewFD)) {
10533 NewFD->addAttr(A: I->second);
10534 ExtnameUndeclaredIdentifiers.erase(I);
10535 } else
10536 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10537 << /*Variable*/0 << NewFD;
10538 }
10539 }
10540
10541 // Copy the parameter declarations from the declarator D to the function
10542 // declaration NewFD, if they are available. First scavenge them into Params.
10543 SmallVector<ParmVarDecl*, 16> Params;
10544 unsigned FTIIdx;
10545 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10546 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10547
10548 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10549 // function that takes no arguments, not a function that takes a
10550 // single void argument.
10551 // We let through "const void" here because Sema::GetTypeForDeclarator
10552 // already checks for that case.
10553 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10554 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10555 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10556 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10557 Param->setDeclContext(NewFD);
10558 Params.push_back(Elt: Param);
10559
10560 if (Param->isInvalidDecl())
10561 NewFD->setInvalidDecl();
10562 }
10563 }
10564
10565 if (!getLangOpts().CPlusPlus) {
10566 // In C, find all the tag declarations from the prototype and move them
10567 // into the function DeclContext. Remove them from the surrounding tag
10568 // injection context of the function, which is typically but not always
10569 // the TU.
10570 DeclContext *PrototypeTagContext =
10571 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10572 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10573 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10574
10575 // We don't want to reparent enumerators. Look at their parent enum
10576 // instead.
10577 if (!TD) {
10578 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10579 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10580 }
10581 if (!TD)
10582 continue;
10583 DeclContext *TagDC = TD->getLexicalDeclContext();
10584 if (!TagDC->containsDecl(D: TD))
10585 continue;
10586 TagDC->removeDecl(D: TD);
10587 TD->setDeclContext(NewFD);
10588 NewFD->addDecl(D: TD);
10589
10590 // Preserve the lexical DeclContext if it is not the surrounding tag
10591 // injection context of the FD. In this example, the semantic context of
10592 // E will be f and the lexical context will be S, while both the
10593 // semantic and lexical contexts of S will be f:
10594 // void f(struct S { enum E { a } f; } s);
10595 if (TagDC != PrototypeTagContext)
10596 TD->setLexicalDeclContext(TagDC);
10597 }
10598 }
10599 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10600 // When we're declaring a function with a typedef, typeof, etc as in the
10601 // following example, we'll need to synthesize (unnamed)
10602 // parameters for use in the declaration.
10603 //
10604 // @code
10605 // typedef void fn(int);
10606 // fn f;
10607 // @endcode
10608
10609 // Synthesize a parameter for each argument type.
10610 for (const auto &AI : FT->param_types()) {
10611 ParmVarDecl *Param =
10612 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10613 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10614 Params.push_back(Elt: Param);
10615 }
10616 } else {
10617 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10618 "Should not need args for typedef of non-prototype fn");
10619 }
10620
10621 // Finally, we know we have the right number of parameters, install them.
10622 NewFD->setParams(Params);
10623
10624 // If this declarator is a declaration and not a definition, its parameters
10625 // will not be pushed onto a scope chain. That means we will not issue any
10626 // reserved identifier warnings for the declaration, but we will for the
10627 // definition. Handle those here.
10628 if (!D.isFunctionDefinition()) {
10629 for (const ParmVarDecl *PVD : Params)
10630 warnOnReservedIdentifier(D: PVD);
10631 }
10632
10633 if (D.getDeclSpec().isNoreturnSpecified())
10634 NewFD->addAttr(
10635 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10636
10637 // Functions returning a variably modified type violate C99 6.7.5.2p2
10638 // because all functions have linkage.
10639 if (!NewFD->isInvalidDecl() &&
10640 NewFD->getReturnType()->isVariablyModifiedType()) {
10641 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10642 NewFD->setInvalidDecl();
10643 }
10644
10645 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10646 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10647 !NewFD->hasAttr<SectionAttr>())
10648 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10649 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10650 Range: PragmaClangTextSection.PragmaLocation));
10651
10652 // Apply an implicit SectionAttr if #pragma code_seg is active.
10653 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10654 !NewFD->hasAttr<SectionAttr>()) {
10655 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10656 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10657 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10658 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10659 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10660 ASTContext::PSF_Read,
10661 TheDecl: NewFD))
10662 NewFD->dropAttr<SectionAttr>();
10663 }
10664
10665 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10666 // active.
10667 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10668 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10669 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10670 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10671
10672 // Apply an implicit CodeSegAttr from class declspec or
10673 // apply an implicit SectionAttr from #pragma code_seg if active.
10674 if (!NewFD->hasAttr<CodeSegAttr>()) {
10675 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10676 IsDefinition: D.isFunctionDefinition())) {
10677 NewFD->addAttr(A: SAttr);
10678 }
10679 }
10680
10681 // Handle attributes.
10682 ProcessDeclAttributes(S, D: NewFD, PD: D);
10683 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10684 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10685 !NewTVA->isDefaultVersion() &&
10686 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10687 // Don't add to scope fmv functions declarations if fmv disabled
10688 AddToScope = false;
10689 return NewFD;
10690 }
10691
10692 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10693 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10694 // type.
10695 //
10696 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10697 // type declaration will generate a compilation error.
10698 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10699 if (AddressSpace != LangAS::Default) {
10700 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10701 NewFD->setInvalidDecl();
10702 }
10703 }
10704
10705 if (!getLangOpts().CPlusPlus) {
10706 // Perform semantic checking on the function declaration.
10707 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10708 CheckMain(FD: NewFD, D: D.getDeclSpec());
10709
10710 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10711 CheckMSVCRTEntryPoint(FD: NewFD);
10712
10713 if (!NewFD->isInvalidDecl())
10714 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10715 IsMemberSpecialization: isMemberSpecialization,
10716 DeclIsDefn: D.isFunctionDefinition()));
10717 else if (!Previous.empty())
10718 // Recover gracefully from an invalid redeclaration.
10719 D.setRedeclaration(true);
10720 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10721 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10722 "previous declaration set still overloaded");
10723
10724 // Diagnose no-prototype function declarations with calling conventions that
10725 // don't support variadic calls. Only do this in C and do it after merging
10726 // possibly prototyped redeclarations.
10727 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10728 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10729 CallingConv CC = FT->getExtInfo().getCC();
10730 if (!supportsVariadicCall(CC)) {
10731 // Windows system headers sometimes accidentally use stdcall without
10732 // (void) parameters, so we relax this to a warning.
10733 int DiagID =
10734 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10735 Diag(Loc: NewFD->getLocation(), DiagID)
10736 << FunctionType::getNameForCallConv(CC);
10737 }
10738 }
10739
10740 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10741 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10742 checkNonTrivialCUnion(
10743 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10744 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10745 } else {
10746 // C++11 [replacement.functions]p3:
10747 // The program's definitions shall not be specified as inline.
10748 //
10749 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10750 //
10751 // Suppress the diagnostic if the function is __attribute__((used)), since
10752 // that forces an external definition to be emitted.
10753 if (D.getDeclSpec().isInlineSpecified() &&
10754 NewFD->isReplaceableGlobalAllocationFunction() &&
10755 !NewFD->hasAttr<UsedAttr>())
10756 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10757 DiagID: diag::ext_operator_new_delete_declared_inline)
10758 << NewFD->getDeclName();
10759
10760 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10761 // C++20 [dcl.decl.general]p4:
10762 // The optional requires-clause in an init-declarator or
10763 // member-declarator shall be present only if the declarator declares a
10764 // templated function.
10765 //
10766 // C++20 [temp.pre]p8:
10767 // An entity is templated if it is
10768 // - a template,
10769 // - an entity defined or created in a templated entity,
10770 // - a member of a templated entity,
10771 // - an enumerator for an enumeration that is a templated entity, or
10772 // - the closure type of a lambda-expression appearing in the
10773 // declaration of a templated entity.
10774 //
10775 // [Note 6: A local class, a local or block variable, or a friend
10776 // function defined in a templated entity is a templated entity.
10777 // — end note]
10778 //
10779 // A templated function is a function template or a function that is
10780 // templated. A templated class is a class template or a class that is
10781 // templated. A templated variable is a variable template or a variable
10782 // that is templated.
10783 if (!FunctionTemplate) {
10784 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10785 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10786 // An explicit specialization shall not have a trailing
10787 // requires-clause unless it declares a function template.
10788 //
10789 // Since a friend function template specialization cannot be
10790 // definition, and since a non-template friend declaration with a
10791 // trailing requires-clause must be a definition, we diagnose
10792 // friend function template specializations with trailing
10793 // requires-clauses on the same path as explicit specializations
10794 // even though they aren't necessarily prohibited by the same
10795 // language rule.
10796 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10797 << isFriend;
10798 } else if (isFriend && NewFD->isTemplated() &&
10799 !D.isFunctionDefinition()) {
10800 // C++ [temp.friend]p9:
10801 // A non-template friend declaration with a requires-clause shall be
10802 // a definition.
10803 Diag(Loc: NewFD->getBeginLoc(),
10804 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10805 NewFD->setInvalidDecl();
10806 } else if (!NewFD->isTemplated() ||
10807 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10808 Diag(Loc: TRC->getBeginLoc(),
10809 DiagID: diag::err_constrained_non_templated_function);
10810 }
10811 }
10812 }
10813
10814 // We do not add HD attributes to specializations here because
10815 // they may have different constexpr-ness compared to their
10816 // templates and, after maybeAddHostDeviceAttrs() is applied,
10817 // may end up with different effective targets. Instead, a
10818 // specialization inherits its target attributes from its template
10819 // in the CheckFunctionTemplateSpecialization() call below.
10820 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10821 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10822
10823 // Handle explicit specializations of function templates
10824 // and friend function declarations with an explicit
10825 // template argument list.
10826 if (isFunctionTemplateSpecialization) {
10827 bool isDependentSpecialization = false;
10828 if (isFriend) {
10829 // For friend function specializations, this is a dependent
10830 // specialization if its semantic context is dependent, its
10831 // type is dependent, or if its template-id is dependent.
10832 isDependentSpecialization =
10833 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10834 (HasExplicitTemplateArgs &&
10835 TemplateSpecializationType::
10836 anyInstantiationDependentTemplateArguments(
10837 Args: TemplateArgs.arguments()));
10838 assert((!isDependentSpecialization ||
10839 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10840 "dependent friend function specialization without template "
10841 "args");
10842 } else {
10843 // For class-scope explicit specializations of function templates,
10844 // if the lexical context is dependent, then the specialization
10845 // is dependent.
10846 isDependentSpecialization =
10847 CurContext->isRecord() && CurContext->isDependentContext();
10848 }
10849
10850 TemplateArgumentListInfo *ExplicitTemplateArgs =
10851 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10852 if (isDependentSpecialization) {
10853 // If it's a dependent specialization, it may not be possible
10854 // to determine the primary template (for explicit specializations)
10855 // or befriended declaration (for friends) until the enclosing
10856 // template is instantiated. In such cases, we store the declarations
10857 // found by name lookup and defer resolution until instantiation.
10858 if (CheckDependentFunctionTemplateSpecialization(
10859 FD: NewFD, ExplicitTemplateArgs, Previous))
10860 NewFD->setInvalidDecl();
10861 } else if (!NewFD->isInvalidDecl()) {
10862 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10863 Previous))
10864 NewFD->setInvalidDecl();
10865 }
10866 } else if (isMemberSpecialization && !FunctionTemplate) {
10867 if (CheckMemberSpecialization(Member: NewFD, Previous))
10868 NewFD->setInvalidDecl();
10869 }
10870
10871 // Perform semantic checking on the function declaration.
10872 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10873 CheckMain(FD: NewFD, D: D.getDeclSpec());
10874
10875 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10876 CheckMSVCRTEntryPoint(FD: NewFD);
10877
10878 if (!NewFD->isInvalidDecl())
10879 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10880 IsMemberSpecialization: isMemberSpecialization,
10881 DeclIsDefn: D.isFunctionDefinition()));
10882 else if (!Previous.empty())
10883 // Recover gracefully from an invalid redeclaration.
10884 D.setRedeclaration(true);
10885
10886 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10887 !D.isRedeclaration() ||
10888 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10889 "previous declaration set still overloaded");
10890
10891 NamedDecl *PrincipalDecl = (FunctionTemplate
10892 ? cast<NamedDecl>(Val: FunctionTemplate)
10893 : NewFD);
10894
10895 if (isFriend && NewFD->getPreviousDecl()) {
10896 AccessSpecifier Access = AS_public;
10897 if (!NewFD->isInvalidDecl())
10898 Access = NewFD->getPreviousDecl()->getAccess();
10899
10900 NewFD->setAccess(Access);
10901 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10902 }
10903
10904 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10905 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10906 PrincipalDecl->setNonMemberOperator();
10907
10908 // If we have a function template, check the template parameter
10909 // list. This will check and merge default template arguments.
10910 if (FunctionTemplate) {
10911 FunctionTemplateDecl *PrevTemplate =
10912 FunctionTemplate->getPreviousDecl();
10913 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10914 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10915 : nullptr,
10916 TPC: D.getDeclSpec().isFriendSpecified()
10917 ? (D.isFunctionDefinition()
10918 ? TPC_FriendFunctionTemplateDefinition
10919 : TPC_FriendFunctionTemplate)
10920 : (D.getCXXScopeSpec().isSet() &&
10921 DC && DC->isRecord() &&
10922 DC->isDependentContext())
10923 ? TPC_ClassTemplateMember
10924 : TPC_FunctionTemplate);
10925 }
10926
10927 if (NewFD->isInvalidDecl()) {
10928 // Ignore all the rest of this.
10929 } else if (!D.isRedeclaration()) {
10930 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10931 .AddToScope: AddToScope };
10932 // Fake up an access specifier if it's supposed to be a class member.
10933 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10934 NewFD->setAccess(AS_public);
10935
10936 // Qualified decls generally require a previous declaration.
10937 if (D.getCXXScopeSpec().isSet()) {
10938 // ...with the major exception of templated-scope or
10939 // dependent-scope friend declarations.
10940
10941 // TODO: we currently also suppress this check in dependent
10942 // contexts because (1) the parameter depth will be off when
10943 // matching friend templates and (2) we might actually be
10944 // selecting a friend based on a dependent factor. But there
10945 // are situations where these conditions don't apply and we
10946 // can actually do this check immediately.
10947 //
10948 // Unless the scope is dependent, it's always an error if qualified
10949 // redeclaration lookup found nothing at all. Diagnose that now;
10950 // nothing will diagnose that error later.
10951 if (isFriend &&
10952 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10953 (!Previous.empty() && CurContext->isDependentContext()))) {
10954 // ignore these
10955 } else if (NewFD->isCPUDispatchMultiVersion() ||
10956 NewFD->isCPUSpecificMultiVersion()) {
10957 // ignore this, we allow the redeclaration behavior here to create new
10958 // versions of the function.
10959 } else {
10960 // The user tried to provide an out-of-line definition for a
10961 // function that is a member of a class or namespace, but there
10962 // was no such member function declared (C++ [class.mfct]p2,
10963 // C++ [namespace.memdef]p2). For example:
10964 //
10965 // class X {
10966 // void f() const;
10967 // };
10968 //
10969 // void X::f() { } // ill-formed
10970 //
10971 // Complain about this problem, and attempt to suggest close
10972 // matches (e.g., those that differ only in cv-qualifiers and
10973 // whether the parameter types are references).
10974
10975 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10976 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10977 AddToScope = ExtraArgs.AddToScope;
10978 return Result;
10979 }
10980 }
10981
10982 // Unqualified local friend declarations are required to resolve
10983 // to something.
10984 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10985 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10986 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10987 AddToScope = ExtraArgs.AddToScope;
10988 return Result;
10989 }
10990 }
10991 } else if (!D.isFunctionDefinition() &&
10992 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10993 !isFriend && !isFunctionTemplateSpecialization &&
10994 !isMemberSpecialization) {
10995 // An out-of-line member function declaration must also be a
10996 // definition (C++ [class.mfct]p2).
10997 // Note that this is not the case for explicit specializations of
10998 // function templates or member functions of class templates, per
10999 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11000 // extension for compatibility with old SWIG code which likes to
11001 // generate them.
11002 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11003 << D.getCXXScopeSpec().getRange();
11004 }
11005 }
11006
11007 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11008 // Any top level function could potentially be specified as an entry.
11009 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11010 HLSL().ActOnTopLevelFunction(FD: NewFD);
11011
11012 if (NewFD->hasAttr<HLSLShaderAttr>())
11013 HLSL().CheckEntryPoint(FD: NewFD);
11014 }
11015
11016 // If this is the first declaration of a library builtin function, add
11017 // attributes as appropriate.
11018 if (!D.isRedeclaration()) {
11019 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11020 if (unsigned BuiltinID = II->getBuiltinID()) {
11021 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11022 if (!InStdNamespace &&
11023 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11024 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11025 // Validate the type matches unless this builtin is specified as
11026 // matching regardless of its declared type.
11027 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11028 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11029 } else {
11030 ASTContext::GetBuiltinTypeError Error;
11031 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11032 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11033
11034 if (!Error && !BuiltinType.isNull() &&
11035 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11036 T: NewFD->getType(), U: BuiltinType))
11037 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11038 }
11039 }
11040 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11041 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11042 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11043 }
11044 }
11045 }
11046 }
11047
11048 ProcessPragmaWeak(S, D: NewFD);
11049 ProcessPragmaExport(NewD: NewFD);
11050 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11051
11052 AddKnownFunctionAttributes(FD: NewFD);
11053
11054 if (NewFD->hasAttr<OverloadableAttr>() &&
11055 !NewFD->getType()->getAs<FunctionProtoType>()) {
11056 Diag(Loc: NewFD->getLocation(),
11057 DiagID: diag::err_attribute_overloadable_no_prototype)
11058 << NewFD;
11059 NewFD->dropAttr<OverloadableAttr>();
11060 }
11061
11062 // If there's a #pragma GCC visibility in scope, and this isn't a class
11063 // member, set the visibility of this function.
11064 if (!DC->isRecord() && NewFD->isExternallyVisible())
11065 AddPushedVisibilityAttribute(RD: NewFD);
11066
11067 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11068 // marking the function.
11069 ObjC().AddCFAuditedAttribute(D: NewFD);
11070
11071 // If this is a function definition, check if we have to apply any
11072 // attributes (i.e. optnone and no_builtin) due to a pragma.
11073 if (D.isFunctionDefinition()) {
11074 AddRangeBasedOptnone(FD: NewFD);
11075 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11076 AddSectionMSAllocText(FD: NewFD);
11077 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11078 }
11079
11080 // If this is the first declaration of an extern C variable, update
11081 // the map of such variables.
11082 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11083 isIncompleteDeclExternC(S&: *this, D: NewFD))
11084 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11085
11086 // Set this FunctionDecl's range up to the right paren.
11087 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11088
11089 if (D.isRedeclaration() && !Previous.empty()) {
11090 NamedDecl *Prev = Previous.getRepresentativeDecl();
11091 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11092 IsSpecialization: isMemberSpecialization ||
11093 isFunctionTemplateSpecialization,
11094 IsDefinition: D.isFunctionDefinition());
11095 }
11096
11097 if (getLangOpts().CUDA) {
11098 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11099 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11100 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11101 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11102 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11103 << CUDA().getConfigureFuncName();
11104 Context.setcudaConfigureCallDecl(NewFD);
11105 }
11106 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11107 !NewFD->isInvalidDecl() &&
11108 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11109 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11110 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11111 << CUDA().getConfigureFuncName();
11112 Context.setcudaGetParameterBufferDecl(NewFD);
11113 }
11114 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11115 !NewFD->isInvalidDecl() &&
11116 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11117 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11118 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11119 << CUDA().getConfigureFuncName();
11120 Context.setcudaLaunchDeviceDecl(NewFD);
11121 }
11122 }
11123 }
11124
11125 MarkUnusedFileScopedDecl(D: NewFD);
11126
11127 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11128 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11129 if (SC == SC_Static) {
11130 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11131 D.setInvalidType();
11132 }
11133
11134 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11135 if (!NewFD->getReturnType()->isVoidType()) {
11136 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11137 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11138 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11139 : FixItHint());
11140 D.setInvalidType();
11141 }
11142
11143 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11144 for (auto *Param : NewFD->parameters())
11145 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11146
11147 if (getLangOpts().OpenCLCPlusPlus) {
11148 if (DC->isRecord()) {
11149 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11150 D.setInvalidType();
11151 }
11152 if (FunctionTemplate) {
11153 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11154 D.setInvalidType();
11155 }
11156 }
11157 }
11158
11159 if (getLangOpts().CPlusPlus) {
11160 // Precalculate whether this is a friend function template with a constraint
11161 // that depends on an enclosing template, per [temp.friend]p9.
11162 if (isFriend && FunctionTemplate &&
11163 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11164 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11165
11166 // C++ [temp.friend]p9:
11167 // A friend function template with a constraint that depends on a
11168 // template parameter from an enclosing template shall be a definition.
11169 if (!D.isFunctionDefinition()) {
11170 Diag(Loc: NewFD->getBeginLoc(),
11171 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11172 NewFD->setInvalidDecl();
11173 }
11174 }
11175
11176 if (FunctionTemplate) {
11177 if (NewFD->isInvalidDecl())
11178 FunctionTemplate->setInvalidDecl();
11179 return FunctionTemplate;
11180 }
11181
11182 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11183 CompleteMemberSpecialization(Member: NewFD, Previous);
11184 }
11185
11186 for (const ParmVarDecl *Param : NewFD->parameters()) {
11187 QualType PT = Param->getType();
11188
11189 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11190 // types.
11191 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11192 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11193 QualType ElemTy = PipeTy->getElementType();
11194 if (ElemTy->isPointerOrReferenceType()) {
11195 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11196 D.setInvalidType();
11197 }
11198 }
11199 }
11200 // WebAssembly tables can't be used as function parameters.
11201 if (Context.getTargetInfo().getTriple().isWasm()) {
11202 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11203 Diag(Loc: Param->getTypeSpecStartLoc(),
11204 DiagID: diag::err_wasm_table_as_function_parameter);
11205 D.setInvalidType();
11206 }
11207 }
11208 }
11209
11210 // Diagnose availability attributes. Availability cannot be used on functions
11211 // that are run during load/unload.
11212 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11213 if (NewFD->hasAttr<ConstructorAttr>()) {
11214 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11215 << 1;
11216 NewFD->dropAttr<AvailabilityAttr>();
11217 }
11218 if (NewFD->hasAttr<DestructorAttr>()) {
11219 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11220 << 2;
11221 NewFD->dropAttr<AvailabilityAttr>();
11222 }
11223 }
11224
11225 // Diagnose no_builtin attribute on function declaration that are not a
11226 // definition.
11227 // FIXME: We should really be doing this in
11228 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11229 // the FunctionDecl and at this point of the code
11230 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11231 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11232 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11233 switch (D.getFunctionDefinitionKind()) {
11234 case FunctionDefinitionKind::Defaulted:
11235 case FunctionDefinitionKind::Deleted:
11236 Diag(Loc: NBA->getLocation(),
11237 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11238 << NBA->getSpelling();
11239 break;
11240 case FunctionDefinitionKind::Declaration:
11241 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11242 << NBA->getSpelling();
11243 break;
11244 case FunctionDefinitionKind::Definition:
11245 break;
11246 }
11247
11248 // Similar to no_builtin logic above, at this point of the code
11249 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11250 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11251 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11252 !NewFD->isInvalidDecl() &&
11253 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11254 ExternalDeclarations.push_back(Elt: NewFD);
11255
11256 // Used for a warning on the 'next' declaration when used with a
11257 // `routine(name)`.
11258 if (getLangOpts().OpenACC)
11259 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11260
11261 return NewFD;
11262}
11263
11264/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11265/// when __declspec(code_seg) "is applied to a class, all member functions of
11266/// the class and nested classes -- this includes compiler-generated special
11267/// member functions -- are put in the specified segment."
11268/// The actual behavior is a little more complicated. The Microsoft compiler
11269/// won't check outer classes if there is an active value from #pragma code_seg.
11270/// The CodeSeg is always applied from the direct parent but only from outer
11271/// classes when the #pragma code_seg stack is empty. See:
11272/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11273/// available since MS has removed the page.
11274static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11275 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11276 if (!Method)
11277 return nullptr;
11278 const CXXRecordDecl *Parent = Method->getParent();
11279 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11280 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11281 NewAttr->setImplicit(true);
11282 return NewAttr;
11283 }
11284
11285 // The Microsoft compiler won't check outer classes for the CodeSeg
11286 // when the #pragma code_seg stack is active.
11287 if (S.CodeSegStack.CurrentValue)
11288 return nullptr;
11289
11290 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11291 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11292 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11293 NewAttr->setImplicit(true);
11294 return NewAttr;
11295 }
11296 }
11297 return nullptr;
11298}
11299
11300Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11301 bool IsDefinition) {
11302 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11303 return A;
11304 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11305 CodeSegStack.CurrentValue)
11306 return SectionAttr::CreateImplicit(
11307 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11308 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11309 return nullptr;
11310}
11311
11312bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11313 QualType NewT, QualType OldT) {
11314 if (!NewD->getLexicalDeclContext()->isDependentContext())
11315 return true;
11316
11317 // For dependently-typed local extern declarations and friends, we can't
11318 // perform a correct type check in general until instantiation:
11319 //
11320 // int f();
11321 // template<typename T> void g() { T f(); }
11322 //
11323 // (valid if g() is only instantiated with T = int).
11324 if (NewT->isDependentType() &&
11325 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11326 return false;
11327
11328 // Similarly, if the previous declaration was a dependent local extern
11329 // declaration, we don't really know its type yet.
11330 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11331 return false;
11332
11333 return true;
11334}
11335
11336bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11337 if (!D->getLexicalDeclContext()->isDependentContext())
11338 return true;
11339
11340 // Don't chain dependent friend function definitions until instantiation, to
11341 // permit cases like
11342 //
11343 // void func();
11344 // template<typename T> class C1 { friend void func() {} };
11345 // template<typename T> class C2 { friend void func() {} };
11346 //
11347 // ... which is valid if only one of C1 and C2 is ever instantiated.
11348 //
11349 // FIXME: This need only apply to function definitions. For now, we proxy
11350 // this by checking for a file-scope function. We do not want this to apply
11351 // to friend declarations nominating member functions, because that gets in
11352 // the way of access checks.
11353 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11354 return false;
11355
11356 auto *VD = dyn_cast<ValueDecl>(Val: D);
11357 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11358 return !VD || !PrevVD ||
11359 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11360 OldT: PrevVD->getType());
11361}
11362
11363/// Check the target or target_version attribute of the function for
11364/// MultiVersion validity.
11365///
11366/// Returns true if there was an error, false otherwise.
11367static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11368 const auto *TA = FD->getAttr<TargetAttr>();
11369 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11370
11371 assert((TA || TVA) && "Expecting target or target_version attribute");
11372
11373 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11374 enum ErrType { Feature = 0, Architecture = 1 };
11375
11376 if (TA) {
11377 ParsedTargetAttr ParseInfo =
11378 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11379 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11380 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11381 << Architecture << ParseInfo.CPU;
11382 return true;
11383 }
11384 for (const auto &Feat : ParseInfo.Features) {
11385 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11386 if (Feat[0] == '-') {
11387 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11388 << Feature << ("no-" + BareFeat).str();
11389 return true;
11390 }
11391
11392 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11393 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11394 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11395 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11396 << Feature << BareFeat;
11397 return true;
11398 }
11399 }
11400 }
11401
11402 if (TVA) {
11403 llvm::SmallVector<StringRef, 8> Feats;
11404 ParsedTargetAttr ParseInfo;
11405 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11406 ParseInfo =
11407 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11408 for (auto &Feat : ParseInfo.Features)
11409 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11410 } else {
11411 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11412 TVA->getFeatures(Out&: Feats);
11413 }
11414 for (const auto &Feat : Feats) {
11415 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11416 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11417 << Feature << Feat;
11418 return true;
11419 }
11420 }
11421 }
11422 return false;
11423}
11424
11425// Provide a white-list of attributes that are allowed to be combined with
11426// multiversion functions.
11427static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11428 MultiVersionKind MVKind) {
11429 // Note: this list/diagnosis must match the list in
11430 // checkMultiversionAttributesAllSame.
11431 switch (Kind) {
11432 default:
11433 return false;
11434 case attr::ArmLocallyStreaming:
11435 return MVKind == MultiVersionKind::TargetVersion ||
11436 MVKind == MultiVersionKind::TargetClones;
11437 case attr::Used:
11438 return MVKind == MultiVersionKind::Target;
11439 case attr::NonNull:
11440 case attr::NoThrow:
11441 return true;
11442 }
11443}
11444
11445static bool checkNonMultiVersionCompatAttributes(Sema &S,
11446 const FunctionDecl *FD,
11447 const FunctionDecl *CausedFD,
11448 MultiVersionKind MVKind) {
11449 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11450 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11451 << static_cast<unsigned>(MVKind) << A;
11452 if (CausedFD)
11453 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11454 return true;
11455 };
11456
11457 for (const Attr *A : FD->attrs()) {
11458 switch (A->getKind()) {
11459 case attr::CPUDispatch:
11460 case attr::CPUSpecific:
11461 if (MVKind != MultiVersionKind::CPUDispatch &&
11462 MVKind != MultiVersionKind::CPUSpecific)
11463 return Diagnose(S, A);
11464 break;
11465 case attr::Target:
11466 if (MVKind != MultiVersionKind::Target)
11467 return Diagnose(S, A);
11468 break;
11469 case attr::TargetVersion:
11470 if (MVKind != MultiVersionKind::TargetVersion &&
11471 MVKind != MultiVersionKind::TargetClones)
11472 return Diagnose(S, A);
11473 break;
11474 case attr::TargetClones:
11475 if (MVKind != MultiVersionKind::TargetClones &&
11476 MVKind != MultiVersionKind::TargetVersion)
11477 return Diagnose(S, A);
11478 break;
11479 default:
11480 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11481 return Diagnose(S, A);
11482 break;
11483 }
11484 }
11485 return false;
11486}
11487
11488bool Sema::areMultiversionVariantFunctionsCompatible(
11489 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11490 const PartialDiagnostic &NoProtoDiagID,
11491 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11492 const PartialDiagnosticAt &NoSupportDiagIDAt,
11493 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11494 bool ConstexprSupported, bool CLinkageMayDiffer) {
11495 enum DoesntSupport {
11496 FuncTemplates = 0,
11497 VirtFuncs = 1,
11498 DeducedReturn = 2,
11499 Constructors = 3,
11500 Destructors = 4,
11501 DeletedFuncs = 5,
11502 DefaultedFuncs = 6,
11503 ConstexprFuncs = 7,
11504 ConstevalFuncs = 8,
11505 Lambda = 9,
11506 };
11507 enum Different {
11508 CallingConv = 0,
11509 ReturnType = 1,
11510 ConstexprSpec = 2,
11511 InlineSpec = 3,
11512 Linkage = 4,
11513 LanguageLinkage = 5,
11514 };
11515
11516 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11517 !OldFD->getType()->getAs<FunctionProtoType>()) {
11518 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11519 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11520 return true;
11521 }
11522
11523 if (NoProtoDiagID.getDiagID() != 0 &&
11524 !NewFD->getType()->getAs<FunctionProtoType>())
11525 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11526
11527 if (!TemplatesSupported &&
11528 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11529 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11530 << FuncTemplates;
11531
11532 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11533 if (NewCXXFD->isVirtual())
11534 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11535 << VirtFuncs;
11536
11537 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11538 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11539 << Constructors;
11540
11541 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11542 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11543 << Destructors;
11544 }
11545
11546 if (NewFD->isDeleted())
11547 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11548 << DeletedFuncs;
11549
11550 if (NewFD->isDefaulted())
11551 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11552 << DefaultedFuncs;
11553
11554 if (!ConstexprSupported && NewFD->isConstexpr())
11555 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11556 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11557
11558 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11559 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11560 QualType NewReturnType = NewType->getReturnType();
11561
11562 if (NewReturnType->isUndeducedType())
11563 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11564 << DeducedReturn;
11565
11566 // Ensure the return type is identical.
11567 if (OldFD) {
11568 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11569 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11570 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11571 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11572
11573 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11574 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11575
11576 bool ArmStreamingCCMismatched = false;
11577 if (OldFPT && NewFPT) {
11578 unsigned Diff =
11579 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11580 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11581 // cannot be mixed.
11582 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11583 FunctionType::SME_PStateSMCompatibleMask))
11584 ArmStreamingCCMismatched = true;
11585 }
11586
11587 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11588 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11589
11590 QualType OldReturnType = OldType->getReturnType();
11591
11592 if (OldReturnType != NewReturnType)
11593 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11594
11595 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11596 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11597
11598 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11599 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11600
11601 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11602 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11603
11604 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11605 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11606
11607 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11608 NewLoc: NewFD->getLocation()))
11609 return true;
11610 }
11611 return false;
11612}
11613
11614static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11615 const FunctionDecl *NewFD,
11616 bool CausesMV,
11617 MultiVersionKind MVKind) {
11618 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11619 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11620 if (OldFD)
11621 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11622 return true;
11623 }
11624
11625 bool IsCPUSpecificCPUDispatchMVKind =
11626 MVKind == MultiVersionKind::CPUDispatch ||
11627 MVKind == MultiVersionKind::CPUSpecific;
11628
11629 if (CausesMV && OldFD &&
11630 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11631 return true;
11632
11633 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11634 return true;
11635
11636 // Only allow transition to MultiVersion if it hasn't been used.
11637 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11638 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11639 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11640 return true;
11641 }
11642
11643 return S.areMultiversionVariantFunctionsCompatible(
11644 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11645 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11646 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11647 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11648 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11649 << static_cast<unsigned>(MVKind)),
11650 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11651 S.PDiag(DiagID: diag::err_multiversion_diff)),
11652 /*TemplatesSupported=*/false,
11653 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11654 /*CLinkageMayDiffer=*/false);
11655}
11656
11657/// Check the validity of a multiversion function declaration that is the
11658/// first of its kind. Also sets the multiversion'ness' of the function itself.
11659///
11660/// This sets NewFD->isInvalidDecl() to true if there was an error.
11661///
11662/// Returns true if there was an error, false otherwise.
11663static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11664 MultiVersionKind MVKind = FD->getMultiVersionKind();
11665 assert(MVKind != MultiVersionKind::None &&
11666 "Function lacks multiversion attribute");
11667 const auto *TA = FD->getAttr<TargetAttr>();
11668 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11669 // The target attribute only causes MV if this declaration is the default,
11670 // otherwise it is treated as a normal function.
11671 if (TA && !TA->isDefaultVersion())
11672 return false;
11673
11674 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11675 FD->setInvalidDecl();
11676 return true;
11677 }
11678
11679 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11680 FD->setInvalidDecl();
11681 return true;
11682 }
11683
11684 FD->setIsMultiVersion();
11685 return false;
11686}
11687
11688static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11689 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11690 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11691 return true;
11692 }
11693
11694 return false;
11695}
11696
11697static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11698 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11699 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11700 return;
11701
11702 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11703 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11704
11705 if (MVKindTo == MultiVersionKind::None &&
11706 (MVKindFrom == MultiVersionKind::TargetVersion ||
11707 MVKindFrom == MultiVersionKind::TargetClones))
11708 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11709 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11710}
11711
11712static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11713 FunctionDecl *NewFD,
11714 bool &Redeclaration,
11715 NamedDecl *&OldDecl,
11716 LookupResult &Previous) {
11717 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11718
11719 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11720 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11721 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11722 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11723
11724 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11725
11726 // The definitions should be allowed in any order. If we have discovered
11727 // a new target version and the preceeding was the default, then add the
11728 // corresponding attribute to it.
11729 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11730
11731 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11732 // to change, this is a simple redeclaration.
11733 if (NewTA && !NewTA->isDefaultVersion() &&
11734 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11735 return false;
11736
11737 // Otherwise, this decl causes MultiVersioning.
11738 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11739 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11740 : MultiVersionKind::Target)) {
11741 NewFD->setInvalidDecl();
11742 return true;
11743 }
11744
11745 if (CheckMultiVersionValue(S, FD: NewFD)) {
11746 NewFD->setInvalidDecl();
11747 return true;
11748 }
11749
11750 // If this is 'default', permit the forward declaration.
11751 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11752 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11753 Redeclaration = true;
11754 OldDecl = OldFD;
11755 OldFD->setIsMultiVersion();
11756 NewFD->setIsMultiVersion();
11757 return false;
11758 }
11759
11760 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11761 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11762 NewFD->setInvalidDecl();
11763 return true;
11764 }
11765
11766 if (NewTA) {
11767 ParsedTargetAttr OldParsed =
11768 S.getASTContext().getTargetInfo().parseTargetAttr(
11769 Str: OldTA->getFeaturesStr());
11770 llvm::sort(C&: OldParsed.Features);
11771 ParsedTargetAttr NewParsed =
11772 S.getASTContext().getTargetInfo().parseTargetAttr(
11773 Str: NewTA->getFeaturesStr());
11774 // Sort order doesn't matter, it just needs to be consistent.
11775 llvm::sort(C&: NewParsed.Features);
11776 if (OldParsed == NewParsed) {
11777 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11778 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11779 NewFD->setInvalidDecl();
11780 return true;
11781 }
11782 }
11783
11784 for (const auto *FD : OldFD->redecls()) {
11785 const auto *CurTA = FD->getAttr<TargetAttr>();
11786 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11787 // We allow forward declarations before ANY multiversioning attributes, but
11788 // nothing after the fact.
11789 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11790 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11791 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11792 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11793 << (NewTA ? 0 : 2);
11794 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11795 NewFD->setInvalidDecl();
11796 return true;
11797 }
11798 }
11799
11800 OldFD->setIsMultiVersion();
11801 NewFD->setIsMultiVersion();
11802 Redeclaration = false;
11803 OldDecl = nullptr;
11804 Previous.clear();
11805 return false;
11806}
11807
11808static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11809 MultiVersionKind OldKind = Old->getMultiVersionKind();
11810 MultiVersionKind NewKind = New->getMultiVersionKind();
11811
11812 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11813 NewKind == MultiVersionKind::None)
11814 return true;
11815
11816 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11817 switch (OldKind) {
11818 case MultiVersionKind::TargetVersion:
11819 return NewKind == MultiVersionKind::TargetClones;
11820 case MultiVersionKind::TargetClones:
11821 return NewKind == MultiVersionKind::TargetVersion;
11822 default:
11823 return false;
11824 }
11825 } else {
11826 switch (OldKind) {
11827 case MultiVersionKind::CPUDispatch:
11828 return NewKind == MultiVersionKind::CPUSpecific;
11829 case MultiVersionKind::CPUSpecific:
11830 return NewKind == MultiVersionKind::CPUDispatch;
11831 default:
11832 return false;
11833 }
11834 }
11835}
11836
11837/// Check the validity of a new function declaration being added to an existing
11838/// multiversioned declaration collection.
11839static bool CheckMultiVersionAdditionalDecl(
11840 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11841 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11842 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11843 LookupResult &Previous) {
11844
11845 // Disallow mixing of multiversioning types.
11846 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11847 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11848 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11849 NewFD->setInvalidDecl();
11850 return true;
11851 }
11852
11853 // Add the default target_version attribute if it's missing.
11854 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11855 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11856
11857 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11858 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11859 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11860 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11861
11862 ParsedTargetAttr NewParsed;
11863 if (NewTA) {
11864 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11865 Str: NewTA->getFeaturesStr());
11866 llvm::sort(C&: NewParsed.Features);
11867 }
11868 llvm::SmallVector<StringRef, 8> NewFeats;
11869 if (NewTVA) {
11870 NewTVA->getFeatures(Out&: NewFeats);
11871 llvm::sort(C&: NewFeats);
11872 }
11873
11874 bool UseMemberUsingDeclRules =
11875 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11876
11877 bool MayNeedOverloadableChecks =
11878 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11879
11880 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11881 // of a previous member of the MultiVersion set.
11882 for (NamedDecl *ND : Previous) {
11883 FunctionDecl *CurFD = ND->getAsFunction();
11884 if (!CurFD || CurFD->isInvalidDecl())
11885 continue;
11886 if (MayNeedOverloadableChecks &&
11887 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11888 continue;
11889
11890 switch (NewMVKind) {
11891 case MultiVersionKind::None:
11892 assert(OldMVKind == MultiVersionKind::TargetClones &&
11893 "Only target_clones can be omitted in subsequent declarations");
11894 break;
11895 case MultiVersionKind::Target: {
11896 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11897 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11898 NewFD->setIsMultiVersion();
11899 Redeclaration = true;
11900 OldDecl = ND;
11901 return false;
11902 }
11903
11904 ParsedTargetAttr CurParsed =
11905 S.getASTContext().getTargetInfo().parseTargetAttr(
11906 Str: CurTA->getFeaturesStr());
11907 llvm::sort(C&: CurParsed.Features);
11908 if (CurParsed == NewParsed) {
11909 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11910 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11911 NewFD->setInvalidDecl();
11912 return true;
11913 }
11914 break;
11915 }
11916 case MultiVersionKind::TargetVersion: {
11917 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11918 if (CurTVA->getName() == NewTVA->getName()) {
11919 NewFD->setIsMultiVersion();
11920 Redeclaration = true;
11921 OldDecl = ND;
11922 return false;
11923 }
11924 llvm::SmallVector<StringRef, 8> CurFeats;
11925 CurTVA->getFeatures(Out&: CurFeats);
11926 llvm::sort(C&: CurFeats);
11927
11928 if (CurFeats == NewFeats) {
11929 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11930 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11931 NewFD->setInvalidDecl();
11932 return true;
11933 }
11934 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11935 // Default
11936 if (NewFeats.empty())
11937 break;
11938
11939 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11940 llvm::SmallVector<StringRef, 8> CurFeats;
11941 CurClones->getFeatures(Out&: CurFeats, Index: I);
11942 llvm::sort(C&: CurFeats);
11943
11944 if (CurFeats == NewFeats) {
11945 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11946 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11947 NewFD->setInvalidDecl();
11948 return true;
11949 }
11950 }
11951 }
11952 break;
11953 }
11954 case MultiVersionKind::TargetClones: {
11955 assert(NewClones && "MultiVersionKind does not match attribute type");
11956 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11957 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11958 !std::equal(first1: CurClones->featuresStrs_begin(),
11959 last1: CurClones->featuresStrs_end(),
11960 first2: NewClones->featuresStrs_begin())) {
11961 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11962 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11963 NewFD->setInvalidDecl();
11964 return true;
11965 }
11966 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11967 llvm::SmallVector<StringRef, 8> CurFeats;
11968 CurTVA->getFeatures(Out&: CurFeats);
11969 llvm::sort(C&: CurFeats);
11970
11971 // Default
11972 if (CurFeats.empty())
11973 break;
11974
11975 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11976 NewFeats.clear();
11977 NewClones->getFeatures(Out&: NewFeats, Index: I);
11978 llvm::sort(C&: NewFeats);
11979
11980 if (CurFeats == NewFeats) {
11981 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11982 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11983 NewFD->setInvalidDecl();
11984 return true;
11985 }
11986 }
11987 break;
11988 }
11989 Redeclaration = true;
11990 OldDecl = CurFD;
11991 NewFD->setIsMultiVersion();
11992 return false;
11993 }
11994 case MultiVersionKind::CPUSpecific:
11995 case MultiVersionKind::CPUDispatch: {
11996 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11997 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11998 // Handle CPUDispatch/CPUSpecific versions.
11999 // Only 1 CPUDispatch function is allowed, this will make it go through
12000 // the redeclaration errors.
12001 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12002 CurFD->hasAttr<CPUDispatchAttr>()) {
12003 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12004 std::equal(
12005 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12006 first2: NewCPUDisp->cpus_begin(),
12007 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12008 return Cur->getName() == New->getName();
12009 })) {
12010 NewFD->setIsMultiVersion();
12011 Redeclaration = true;
12012 OldDecl = ND;
12013 return false;
12014 }
12015
12016 // If the declarations don't match, this is an error condition.
12017 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12018 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12019 NewFD->setInvalidDecl();
12020 return true;
12021 }
12022 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12023 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12024 std::equal(
12025 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12026 first2: NewCPUSpec->cpus_begin(),
12027 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12028 return Cur->getName() == New->getName();
12029 })) {
12030 NewFD->setIsMultiVersion();
12031 Redeclaration = true;
12032 OldDecl = ND;
12033 return false;
12034 }
12035
12036 // Only 1 version of CPUSpecific is allowed for each CPU.
12037 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12038 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12039 if (CurII == NewII) {
12040 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12041 << NewII;
12042 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12043 NewFD->setInvalidDecl();
12044 return true;
12045 }
12046 }
12047 }
12048 }
12049 break;
12050 }
12051 }
12052 }
12053
12054 // Redeclarations of a target_clones function may omit the attribute, in which
12055 // case it will be inherited during declaration merging.
12056 if (NewMVKind == MultiVersionKind::None &&
12057 OldMVKind == MultiVersionKind::TargetClones) {
12058 NewFD->setIsMultiVersion();
12059 Redeclaration = true;
12060 OldDecl = OldFD;
12061 return false;
12062 }
12063
12064 // Else, this is simply a non-redecl case. Checking the 'value' is only
12065 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12066 // handled in the attribute adding step.
12067 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12068 NewFD->setInvalidDecl();
12069 return true;
12070 }
12071
12072 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12073 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12074 NewFD->setInvalidDecl();
12075 return true;
12076 }
12077
12078 // Permit forward declarations in the case where these two are compatible.
12079 if (!OldFD->isMultiVersion()) {
12080 OldFD->setIsMultiVersion();
12081 NewFD->setIsMultiVersion();
12082 Redeclaration = true;
12083 OldDecl = OldFD;
12084 return false;
12085 }
12086
12087 NewFD->setIsMultiVersion();
12088 Redeclaration = false;
12089 OldDecl = nullptr;
12090 Previous.clear();
12091 return false;
12092}
12093
12094/// Check the validity of a mulitversion function declaration.
12095/// Also sets the multiversion'ness' of the function itself.
12096///
12097/// This sets NewFD->isInvalidDecl() to true if there was an error.
12098///
12099/// Returns true if there was an error, false otherwise.
12100static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12101 bool &Redeclaration, NamedDecl *&OldDecl,
12102 LookupResult &Previous) {
12103 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12104
12105 // Check if FMV is disabled.
12106 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12107 return false;
12108
12109 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12110 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12111 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12112 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12113 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12114 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12115
12116 // Main isn't allowed to become a multiversion function, however it IS
12117 // permitted to have 'main' be marked with the 'target' optimization hint,
12118 // for 'target_version' only default is allowed.
12119 if (NewFD->isMain()) {
12120 if (MVKind != MultiVersionKind::None &&
12121 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12122 !(MVKind == MultiVersionKind::TargetVersion &&
12123 NewTVA->isDefaultVersion())) {
12124 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12125 NewFD->setInvalidDecl();
12126 return true;
12127 }
12128 return false;
12129 }
12130
12131 // Target attribute on AArch64 is not used for multiversioning
12132 if (NewTA && TI.getTriple().isAArch64())
12133 return false;
12134
12135 // Target attribute on RISCV is not used for multiversioning
12136 if (NewTA && TI.getTriple().isRISCV())
12137 return false;
12138
12139 if (!OldDecl || !OldDecl->getAsFunction() ||
12140 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12141 DC: NewFD->getDeclContext()->getRedeclContext())) {
12142 // If there's no previous declaration, AND this isn't attempting to cause
12143 // multiversioning, this isn't an error condition.
12144 if (MVKind == MultiVersionKind::None)
12145 return false;
12146 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12147 }
12148
12149 FunctionDecl *OldFD = OldDecl->getAsFunction();
12150
12151 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12152 return false;
12153
12154 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12155 // for target_clones and target_version.
12156 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12157 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12158 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12159 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12160 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12161 NewFD->setInvalidDecl();
12162 return true;
12163 }
12164
12165 if (!OldFD->isMultiVersion()) {
12166 switch (MVKind) {
12167 case MultiVersionKind::Target:
12168 case MultiVersionKind::TargetVersion:
12169 return CheckDeclarationCausesMultiVersioning(
12170 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12171 case MultiVersionKind::TargetClones:
12172 if (OldFD->isUsed(CheckUsedAttr: false)) {
12173 NewFD->setInvalidDecl();
12174 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12175 }
12176 OldFD->setIsMultiVersion();
12177 break;
12178
12179 case MultiVersionKind::CPUDispatch:
12180 case MultiVersionKind::CPUSpecific:
12181 case MultiVersionKind::None:
12182 break;
12183 }
12184 }
12185
12186 // At this point, we have a multiversion function decl (in OldFD) AND an
12187 // appropriate attribute in the current function decl (unless it's allowed to
12188 // omit the attribute). Resolve that these are still compatible with previous
12189 // declarations.
12190 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12191 NewCPUSpec, NewClones, Redeclaration,
12192 OldDecl, Previous);
12193}
12194
12195static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12196 bool IsPure = NewFD->hasAttr<PureAttr>();
12197 bool IsConst = NewFD->hasAttr<ConstAttr>();
12198
12199 // If there are no pure or const attributes, there's nothing to check.
12200 if (!IsPure && !IsConst)
12201 return;
12202
12203 // If the function is marked both pure and const, we retain the const
12204 // attribute because it makes stronger guarantees than the pure attribute, and
12205 // we drop the pure attribute explicitly to prevent later confusion about
12206 // semantics.
12207 if (IsPure && IsConst) {
12208 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12209 NewFD->dropAttrs<PureAttr>();
12210 }
12211
12212 // Constructors and destructors are functions which return void, so are
12213 // handled here as well.
12214 if (NewFD->getReturnType()->isVoidType()) {
12215 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12216 << IsConst;
12217 NewFD->dropAttrs<PureAttr, ConstAttr>();
12218 }
12219}
12220
12221bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12222 LookupResult &Previous,
12223 bool IsMemberSpecialization,
12224 bool DeclIsDefn) {
12225 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12226 "Variably modified return types are not handled here");
12227
12228 // Determine whether the type of this function should be merged with
12229 // a previous visible declaration. This never happens for functions in C++,
12230 // and always happens in C if the previous declaration was visible.
12231 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12232 !Previous.isShadowed();
12233
12234 bool Redeclaration = false;
12235 NamedDecl *OldDecl = nullptr;
12236 bool MayNeedOverloadableChecks = false;
12237
12238 inferLifetimeCaptureByAttribute(FD: NewFD);
12239 // Merge or overload the declaration with an existing declaration of
12240 // the same name, if appropriate.
12241 if (!Previous.empty()) {
12242 // Determine whether NewFD is an overload of PrevDecl or
12243 // a declaration that requires merging. If it's an overload,
12244 // there's no more work to do here; we'll just add the new
12245 // function to the scope.
12246 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12247 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12248 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12249 Redeclaration = true;
12250 OldDecl = Candidate;
12251 }
12252 } else {
12253 MayNeedOverloadableChecks = true;
12254 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12255 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12256 case OverloadKind::Match:
12257 Redeclaration = true;
12258 break;
12259
12260 case OverloadKind::NonFunction:
12261 Redeclaration = true;
12262 break;
12263
12264 case OverloadKind::Overload:
12265 Redeclaration = false;
12266 break;
12267 }
12268 }
12269 }
12270
12271 // Check for a previous extern "C" declaration with this name.
12272 if (!Redeclaration &&
12273 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12274 if (!Previous.empty()) {
12275 // This is an extern "C" declaration with the same name as a previous
12276 // declaration, and thus redeclares that entity...
12277 Redeclaration = true;
12278 OldDecl = Previous.getFoundDecl();
12279 MergeTypeWithPrevious = false;
12280
12281 // ... except in the presence of __attribute__((overloadable)).
12282 if (OldDecl->hasAttr<OverloadableAttr>() ||
12283 NewFD->hasAttr<OverloadableAttr>()) {
12284 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12285 MayNeedOverloadableChecks = true;
12286 Redeclaration = false;
12287 OldDecl = nullptr;
12288 }
12289 }
12290 }
12291 }
12292
12293 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12294 return Redeclaration;
12295
12296 // PPC MMA non-pointer types are not allowed as function return types.
12297 if (Context.getTargetInfo().getTriple().isPPC64() &&
12298 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12299 NewFD->setInvalidDecl();
12300 }
12301
12302 CheckConstPureAttributesUsage(S&: *this, NewFD);
12303
12304 // C++ [dcl.spec.auto.general]p12:
12305 // Return type deduction for a templated function with a placeholder in its
12306 // declared type occurs when the definition is instantiated even if the
12307 // function body contains a return statement with a non-type-dependent
12308 // operand.
12309 //
12310 // C++ [temp.dep.expr]p3:
12311 // An id-expression is type-dependent if it is a template-id that is not a
12312 // concept-id and is dependent; or if its terminal name is:
12313 // - [...]
12314 // - associated by name lookup with one or more declarations of member
12315 // functions of a class that is the current instantiation declared with a
12316 // return type that contains a placeholder type,
12317 // - [...]
12318 //
12319 // If this is a templated function with a placeholder in its return type,
12320 // make the placeholder type dependent since it won't be deduced until the
12321 // definition is instantiated. We do this here because it needs to happen
12322 // for implicitly instantiated member functions/member function templates.
12323 if (getLangOpts().CPlusPlus14 &&
12324 (NewFD->isDependentContext() &&
12325 NewFD->getReturnType()->isUndeducedType())) {
12326 const FunctionProtoType *FPT =
12327 NewFD->getType()->castAs<FunctionProtoType>();
12328 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12329 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12330 EPI: FPT->getExtProtoInfo()));
12331 }
12332
12333 // C++11 [dcl.constexpr]p8:
12334 // A constexpr specifier for a non-static member function that is not
12335 // a constructor declares that member function to be const.
12336 //
12337 // This needs to be delayed until we know whether this is an out-of-line
12338 // definition of a static member function.
12339 //
12340 // This rule is not present in C++1y, so we produce a backwards
12341 // compatibility warning whenever it happens in C++11.
12342 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12343 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12344 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12345 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12346 CXXMethodDecl *OldMD = nullptr;
12347 if (OldDecl)
12348 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12349 if (!OldMD || !OldMD->isStatic()) {
12350 const FunctionProtoType *FPT =
12351 MD->getType()->castAs<FunctionProtoType>();
12352 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12353 EPI.TypeQuals.addConst();
12354 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12355 Args: FPT->getParamTypes(), EPI));
12356
12357 // Warn that we did this, if we're not performing template instantiation.
12358 // In that case, we'll have warned already when the template was defined.
12359 if (!inTemplateInstantiation()) {
12360 SourceLocation AddConstLoc;
12361 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12362 .IgnoreParens().getAs<FunctionTypeLoc>())
12363 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12364
12365 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12366 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12367 }
12368 }
12369 }
12370
12371 if (Redeclaration) {
12372 // NewFD and OldDecl represent declarations that need to be
12373 // merged.
12374 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12375 NewDeclIsDefn: DeclIsDefn)) {
12376 NewFD->setInvalidDecl();
12377 return Redeclaration;
12378 }
12379
12380 Previous.clear();
12381 Previous.addDecl(D: OldDecl);
12382
12383 if (FunctionTemplateDecl *OldTemplateDecl =
12384 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12385 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12386 FunctionTemplateDecl *NewTemplateDecl
12387 = NewFD->getDescribedFunctionTemplate();
12388 assert(NewTemplateDecl && "Template/non-template mismatch");
12389
12390 // The call to MergeFunctionDecl above may have created some state in
12391 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12392 // can add it as a redeclaration.
12393 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12394
12395 NewFD->setPreviousDeclaration(OldFD);
12396 if (NewFD->isCXXClassMember()) {
12397 NewFD->setAccess(OldTemplateDecl->getAccess());
12398 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12399 }
12400
12401 // If this is an explicit specialization of a member that is a function
12402 // template, mark it as a member specialization.
12403 if (IsMemberSpecialization &&
12404 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12405 NewTemplateDecl->setMemberSpecialization();
12406 assert(OldTemplateDecl->isMemberSpecialization());
12407 // Explicit specializations of a member template do not inherit deleted
12408 // status from the parent member template that they are specializing.
12409 if (OldFD->isDeleted()) {
12410 // FIXME: This assert will not hold in the presence of modules.
12411 assert(OldFD->getCanonicalDecl() == OldFD);
12412 // FIXME: We need an update record for this AST mutation.
12413 OldFD->setDeletedAsWritten(D: false);
12414 }
12415 }
12416
12417 } else {
12418 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12419 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12420 // This needs to happen first so that 'inline' propagates.
12421 NewFD->setPreviousDeclaration(OldFD);
12422 if (NewFD->isCXXClassMember())
12423 NewFD->setAccess(OldFD->getAccess());
12424 }
12425 }
12426 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12427 !NewFD->getAttr<OverloadableAttr>()) {
12428 assert((Previous.empty() ||
12429 llvm::any_of(Previous,
12430 [](const NamedDecl *ND) {
12431 return ND->hasAttr<OverloadableAttr>();
12432 })) &&
12433 "Non-redecls shouldn't happen without overloadable present");
12434
12435 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12436 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12437 return FD && !FD->hasAttr<OverloadableAttr>();
12438 });
12439
12440 if (OtherUnmarkedIter != Previous.end()) {
12441 Diag(Loc: NewFD->getLocation(),
12442 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12443 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12444 DiagID: diag::note_attribute_overloadable_prev_overload)
12445 << false;
12446
12447 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12448 }
12449 }
12450
12451 if (LangOpts.OpenMP)
12452 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12453
12454 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12455 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12456
12457 if (NewFD->hasAttr<SYCLExternalAttr>())
12458 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12459
12460 // Semantic checking for this function declaration (in isolation).
12461
12462 if (getLangOpts().CPlusPlus) {
12463 // C++-specific checks.
12464 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12465 CheckConstructor(Constructor);
12466 } else if (CXXDestructorDecl *Destructor =
12467 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12468 // We check here for invalid destructor names.
12469 // If we have a friend destructor declaration that is dependent, we can't
12470 // diagnose right away because cases like this are still valid:
12471 // template <class T> struct A { friend T::X::~Y(); };
12472 // struct B { struct Y { ~Y(); }; using X = Y; };
12473 // template struct A<B>;
12474 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12475 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12476 CanQualType ClassType =
12477 Context.getCanonicalTagType(TD: Destructor->getParent());
12478
12479 DeclarationName Name =
12480 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12481 if (NewFD->getDeclName() != Name) {
12482 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12483 NewFD->setInvalidDecl();
12484 return Redeclaration;
12485 }
12486 }
12487 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12488 if (auto *TD = Guide->getDescribedFunctionTemplate())
12489 CheckDeductionGuideTemplate(TD);
12490
12491 // A deduction guide is not on the list of entities that can be
12492 // explicitly specialized.
12493 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12494 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12495 << /*explicit specialization*/ 1;
12496 }
12497
12498 // Find any virtual functions that this function overrides.
12499 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12500 if (!Method->isFunctionTemplateSpecialization() &&
12501 !Method->getDescribedFunctionTemplate() &&
12502 Method->isCanonicalDecl()) {
12503 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12504 }
12505 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12506 // C++2a [class.virtual]p6
12507 // A virtual method shall not have a requires-clause.
12508 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12509 DiagID: diag::err_constrained_virtual_method);
12510
12511 if (Method->isStatic())
12512 checkThisInStaticMemberFunctionType(Method);
12513 }
12514
12515 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12516 ActOnConversionDeclarator(Conversion);
12517
12518 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12519 if (NewFD->isOverloadedOperator() &&
12520 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12521 NewFD->setInvalidDecl();
12522 return Redeclaration;
12523 }
12524
12525 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12526 if (NewFD->getLiteralIdentifier() &&
12527 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12528 NewFD->setInvalidDecl();
12529 return Redeclaration;
12530 }
12531
12532 // In C++, check default arguments now that we have merged decls. Unless
12533 // the lexical context is the class, because in this case this is done
12534 // during delayed parsing anyway.
12535 if (!CurContext->isRecord())
12536 CheckCXXDefaultArguments(FD: NewFD);
12537
12538 // If this function is declared as being extern "C", then check to see if
12539 // the function returns a UDT (class, struct, or union type) that is not C
12540 // compatible, and if it does, warn the user.
12541 // But, issue any diagnostic on the first declaration only.
12542 if (Previous.empty() && NewFD->isExternC()) {
12543 QualType R = NewFD->getReturnType();
12544 if (R->isIncompleteType() && !R->isVoidType())
12545 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12546 << NewFD << R;
12547 else if (!R.isPODType(Context) && !R->isVoidType() &&
12548 !R->isObjCObjectPointerType())
12549 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12550 }
12551
12552 // C++1z [dcl.fct]p6:
12553 // [...] whether the function has a non-throwing exception-specification
12554 // [is] part of the function type
12555 //
12556 // This results in an ABI break between C++14 and C++17 for functions whose
12557 // declared type includes an exception-specification in a parameter or
12558 // return type. (Exception specifications on the function itself are OK in
12559 // most cases, and exception specifications are not permitted in most other
12560 // contexts where they could make it into a mangling.)
12561 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12562 auto HasNoexcept = [&](QualType T) -> bool {
12563 // Strip off declarator chunks that could be between us and a function
12564 // type. We don't need to look far, exception specifications are very
12565 // restricted prior to C++17.
12566 if (auto *RT = T->getAs<ReferenceType>())
12567 T = RT->getPointeeType();
12568 else if (T->isAnyPointerType())
12569 T = T->getPointeeType();
12570 else if (auto *MPT = T->getAs<MemberPointerType>())
12571 T = MPT->getPointeeType();
12572 if (auto *FPT = T->getAs<FunctionProtoType>())
12573 if (FPT->isNothrow())
12574 return true;
12575 return false;
12576 };
12577
12578 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12579 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12580 for (QualType T : FPT->param_types())
12581 AnyNoexcept |= HasNoexcept(T);
12582 if (AnyNoexcept)
12583 Diag(Loc: NewFD->getLocation(),
12584 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12585 << NewFD;
12586 }
12587
12588 if (!Redeclaration && LangOpts.CUDA) {
12589 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12590 for (auto *Parm : NewFD->parameters()) {
12591 if (!Parm->getType()->isDependentType() &&
12592 Parm->hasAttr<CUDAGridConstantAttr>() &&
12593 !(IsKernel && Parm->getType().isConstQualified()))
12594 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12595 DiagID: diag::err_cuda_grid_constant_not_allowed);
12596 }
12597 CUDA().checkTargetOverload(NewFD, Previous);
12598 }
12599 }
12600
12601 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12602 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12603
12604 return Redeclaration;
12605}
12606
12607void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12608 // [basic.start.main]p3
12609 // The main function shall not be declared with C linkage-specification.
12610 if (FD->isExternCContext())
12611 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12612
12613 // C++11 [basic.start.main]p3:
12614 // A program that [...] declares main to be inline, static or
12615 // constexpr is ill-formed.
12616 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12617 // appear in a declaration of main.
12618 // static main is not an error under C99, but we should warn about it.
12619 // We accept _Noreturn main as an extension.
12620 if (FD->getStorageClass() == SC_Static)
12621 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12622 ? diag::err_static_main : diag::warn_static_main)
12623 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12624 if (FD->isInlineSpecified())
12625 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12626 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12627 if (DS.isNoreturnSpecified()) {
12628 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12629 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12630 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12631 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12632 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12633 }
12634 if (FD->isConstexpr()) {
12635 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12636 << FD->isConsteval()
12637 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12638 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12639 }
12640
12641 if (getLangOpts().OpenCL) {
12642 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12643 << FD->hasAttr<DeviceKernelAttr>();
12644 FD->setInvalidDecl();
12645 return;
12646 }
12647
12648 if (FD->hasAttr<SYCLExternalAttr>()) {
12649 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12650 << FD->getAttr<SYCLExternalAttr>();
12651 FD->setInvalidDecl();
12652 return;
12653 }
12654
12655 // Functions named main in hlsl are default entries, but don't have specific
12656 // signatures they are required to conform to.
12657 if (getLangOpts().HLSL)
12658 return;
12659
12660 QualType T = FD->getType();
12661 assert(T->isFunctionType() && "function decl is not of function type");
12662 const FunctionType* FT = T->castAs<FunctionType>();
12663
12664 // Set default calling convention for main()
12665 if (FT->getCallConv() != CC_C) {
12666 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12667 FD->setType(QualType(FT, 0));
12668 T = Context.getCanonicalType(T: FD->getType());
12669 }
12670
12671 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12672 // In C with GNU extensions we allow main() to have non-integer return
12673 // type, but we should warn about the extension, and we disable the
12674 // implicit-return-zero rule.
12675
12676 // GCC in C mode accepts qualified 'int'.
12677 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12678 FD->setHasImplicitReturnZero(true);
12679 else {
12680 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12681 SourceRange RTRange = FD->getReturnTypeSourceRange();
12682 if (RTRange.isValid())
12683 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12684 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12685 }
12686 } else {
12687 // In C and C++, main magically returns 0 if you fall off the end;
12688 // set the flag which tells us that.
12689 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12690
12691 // All the standards say that main() should return 'int'.
12692 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12693 FD->setHasImplicitReturnZero(true);
12694 else {
12695 // Otherwise, this is just a flat-out error.
12696 SourceRange RTRange = FD->getReturnTypeSourceRange();
12697 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12698 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12699 : FixItHint());
12700 FD->setInvalidDecl(true);
12701 }
12702
12703 // [basic.start.main]p3:
12704 // A program that declares a function main that belongs to the global scope
12705 // and is attached to a named module is ill-formed.
12706 if (FD->isInNamedModule()) {
12707 const SourceLocation start = FD->getTypeSpecStartLoc();
12708 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12709 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12710 }
12711 }
12712
12713 // Treat protoless main() as nullary.
12714 if (isa<FunctionNoProtoType>(Val: FT)) return;
12715
12716 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12717 unsigned nparams = FTP->getNumParams();
12718 assert(FD->getNumParams() == nparams);
12719
12720 bool HasExtraParameters = (nparams > 3);
12721
12722 if (FTP->isVariadic()) {
12723 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12724 // FIXME: if we had information about the location of the ellipsis, we
12725 // could add a FixIt hint to remove it as a parameter.
12726 }
12727
12728 // Darwin passes an undocumented fourth argument of type char**. If
12729 // other platforms start sprouting these, the logic below will start
12730 // getting shifty.
12731 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12732 HasExtraParameters = false;
12733
12734 if (HasExtraParameters) {
12735 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12736 FD->setInvalidDecl(true);
12737 nparams = 3;
12738 }
12739
12740 // FIXME: a lot of the following diagnostics would be improved
12741 // if we had some location information about types.
12742
12743 QualType CharPP =
12744 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12745 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12746
12747 for (unsigned i = 0; i < nparams; ++i) {
12748 QualType AT = FTP->getParamType(i);
12749
12750 bool mismatch = true;
12751
12752 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12753 mismatch = false;
12754 else if (Expected[i] == CharPP) {
12755 // As an extension, the following forms are okay:
12756 // char const **
12757 // char const * const *
12758 // char * const *
12759
12760 QualifierCollector qs;
12761 const PointerType* PT;
12762 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12763 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12764 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12765 T2: Context.CharTy)) {
12766 qs.removeConst();
12767 mismatch = !qs.empty();
12768 }
12769 }
12770
12771 if (mismatch) {
12772 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12773 // TODO: suggest replacing given type with expected type
12774 FD->setInvalidDecl(true);
12775 }
12776 }
12777
12778 if (nparams == 1 && !FD->isInvalidDecl()) {
12779 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12780 }
12781
12782 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12783 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12784 FD->setInvalidDecl();
12785 }
12786}
12787
12788static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12789
12790 // Default calling convention for main and wmain is __cdecl
12791 if (FD->getName() == "main" || FD->getName() == "wmain")
12792 return false;
12793
12794 // Default calling convention for MinGW and Cygwin is __cdecl
12795 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12796 if (T.isOSCygMing())
12797 return false;
12798
12799 // Default calling convention for WinMain, wWinMain and DllMain
12800 // is __stdcall on 32 bit Windows
12801 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12802 return true;
12803
12804 return false;
12805}
12806
12807void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12808 QualType T = FD->getType();
12809 assert(T->isFunctionType() && "function decl is not of function type");
12810 const FunctionType *FT = T->castAs<FunctionType>();
12811
12812 // Set an implicit return of 'zero' if the function can return some integral,
12813 // enumeration, pointer or nullptr type.
12814 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12815 FT->getReturnType()->isAnyPointerType() ||
12816 FT->getReturnType()->isNullPtrType())
12817 // DllMain is exempt because a return value of zero means it failed.
12818 if (FD->getName() != "DllMain")
12819 FD->setHasImplicitReturnZero(true);
12820
12821 // Explicitly specified calling conventions are applied to MSVC entry points
12822 if (!hasExplicitCallingConv(T)) {
12823 if (isDefaultStdCall(FD, S&: *this)) {
12824 if (FT->getCallConv() != CC_X86StdCall) {
12825 FT = Context.adjustFunctionType(
12826 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12827 FD->setType(QualType(FT, 0));
12828 }
12829 } else if (FT->getCallConv() != CC_C) {
12830 FT = Context.adjustFunctionType(Fn: FT,
12831 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12832 FD->setType(QualType(FT, 0));
12833 }
12834 }
12835
12836 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12837 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12838 FD->setInvalidDecl();
12839 }
12840}
12841
12842bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12843 // FIXME: Need strict checking. In C89, we need to check for
12844 // any assignment, increment, decrement, function-calls, or
12845 // commas outside of a sizeof. In C99, it's the same list,
12846 // except that the aforementioned are allowed in unevaluated
12847 // expressions. Everything else falls under the
12848 // "may accept other forms of constant expressions" exception.
12849 //
12850 // Regular C++ code will not end up here (exceptions: language extensions,
12851 // OpenCL C++ etc), so the constant expression rules there don't matter.
12852 if (Init->isValueDependent()) {
12853 assert(Init->containsErrors() &&
12854 "Dependent code should only occur in error-recovery path.");
12855 return true;
12856 }
12857 const Expr *Culprit;
12858 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12859 return false;
12860 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12861 return true;
12862}
12863
12864namespace {
12865 // Visits an initialization expression to see if OrigDecl is evaluated in
12866 // its own initialization and throws a warning if it does.
12867 class SelfReferenceChecker
12868 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12869 Sema &S;
12870 Decl *OrigDecl;
12871 bool isRecordType;
12872 bool isPODType;
12873 bool isReferenceType;
12874 bool isInCXXOperatorCall;
12875
12876 bool isInitList;
12877 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12878
12879 public:
12880 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12881
12882 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12883 S(S), OrigDecl(OrigDecl) {
12884 isPODType = false;
12885 isRecordType = false;
12886 isReferenceType = false;
12887 isInCXXOperatorCall = false;
12888 isInitList = false;
12889 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12890 isPODType = VD->getType().isPODType(Context: S.Context);
12891 isRecordType = VD->getType()->isRecordType();
12892 isReferenceType = VD->getType()->isReferenceType();
12893 }
12894 }
12895
12896 // For most expressions, just call the visitor. For initializer lists,
12897 // track the index of the field being initialized since fields are
12898 // initialized in order allowing use of previously initialized fields.
12899 void CheckExpr(Expr *E) {
12900 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12901 if (!InitList) {
12902 Visit(S: E);
12903 return;
12904 }
12905
12906 // Track and increment the index here.
12907 isInitList = true;
12908 InitFieldIndex.push_back(Elt: 0);
12909 for (auto *Child : InitList->children()) {
12910 CheckExpr(E: cast<Expr>(Val: Child));
12911 ++InitFieldIndex.back();
12912 }
12913 InitFieldIndex.pop_back();
12914 }
12915
12916 // Returns true if MemberExpr is checked and no further checking is needed.
12917 // Returns false if additional checking is required.
12918 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12919 llvm::SmallVector<FieldDecl*, 4> Fields;
12920 Expr *Base = E;
12921 bool ReferenceField = false;
12922
12923 // Get the field members used.
12924 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12925 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12926 if (!FD)
12927 return false;
12928 Fields.push_back(Elt: FD);
12929 if (FD->getType()->isReferenceType())
12930 ReferenceField = true;
12931 Base = ME->getBase()->IgnoreParenImpCasts();
12932 }
12933
12934 // Keep checking only if the base Decl is the same.
12935 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12936 if (!DRE || DRE->getDecl() != OrigDecl)
12937 return false;
12938
12939 // A reference field can be bound to an unininitialized field.
12940 if (CheckReference && !ReferenceField)
12941 return true;
12942
12943 // Convert FieldDecls to their index number.
12944 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12945 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12946 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12947
12948 // See if a warning is needed by checking the first difference in index
12949 // numbers. If field being used has index less than the field being
12950 // initialized, then the use is safe.
12951 for (auto UsedIter = UsedFieldIndex.begin(),
12952 UsedEnd = UsedFieldIndex.end(),
12953 OrigIter = InitFieldIndex.begin(),
12954 OrigEnd = InitFieldIndex.end();
12955 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12956 if (*UsedIter < *OrigIter)
12957 return true;
12958 if (*UsedIter > *OrigIter)
12959 break;
12960 }
12961
12962 // TODO: Add a different warning which will print the field names.
12963 HandleDeclRefExpr(DRE);
12964 return true;
12965 }
12966
12967 // For most expressions, the cast is directly above the DeclRefExpr.
12968 // For conditional operators, the cast can be outside the conditional
12969 // operator if both expressions are DeclRefExpr's.
12970 void HandleValue(Expr *E) {
12971 E = E->IgnoreParens();
12972 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12973 HandleDeclRefExpr(DRE);
12974 return;
12975 }
12976
12977 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12978 Visit(S: CO->getCond());
12979 HandleValue(E: CO->getTrueExpr());
12980 HandleValue(E: CO->getFalseExpr());
12981 return;
12982 }
12983
12984 if (BinaryConditionalOperator *BCO =
12985 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12986 Visit(S: BCO->getCond());
12987 HandleValue(E: BCO->getFalseExpr());
12988 return;
12989 }
12990
12991 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12992 if (Expr *SE = OVE->getSourceExpr())
12993 HandleValue(E: SE);
12994 return;
12995 }
12996
12997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
12998 if (BO->getOpcode() == BO_Comma) {
12999 Visit(S: BO->getLHS());
13000 HandleValue(E: BO->getRHS());
13001 return;
13002 }
13003 }
13004
13005 if (isa<MemberExpr>(Val: E)) {
13006 if (isInitList) {
13007 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13008 CheckReference: false /*CheckReference*/))
13009 return;
13010 }
13011
13012 Expr *Base = E->IgnoreParenImpCasts();
13013 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13014 // Check for static member variables and don't warn on them.
13015 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13016 return;
13017 Base = ME->getBase()->IgnoreParenImpCasts();
13018 }
13019 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13020 HandleDeclRefExpr(DRE);
13021 return;
13022 }
13023
13024 Visit(S: E);
13025 }
13026
13027 // Reference types not handled in HandleValue are handled here since all
13028 // uses of references are bad, not just r-value uses.
13029 void VisitDeclRefExpr(DeclRefExpr *E) {
13030 if (isReferenceType)
13031 HandleDeclRefExpr(DRE: E);
13032 }
13033
13034 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13035 if (E->getCastKind() == CK_LValueToRValue) {
13036 HandleValue(E: E->getSubExpr());
13037 return;
13038 }
13039
13040 Inherited::VisitImplicitCastExpr(S: E);
13041 }
13042
13043 void VisitMemberExpr(MemberExpr *E) {
13044 if (isInitList) {
13045 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13046 return;
13047 }
13048
13049 // Don't warn on arrays since they can be treated as pointers.
13050 if (E->getType()->canDecayToPointerType()) return;
13051
13052 // Warn when a non-static method call is followed by non-static member
13053 // field accesses, which is followed by a DeclRefExpr.
13054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13055 bool Warn = (MD && !MD->isStatic());
13056 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13057 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13058 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13059 Warn = false;
13060 Base = ME->getBase()->IgnoreParenImpCasts();
13061 }
13062
13063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13064 if (Warn)
13065 HandleDeclRefExpr(DRE);
13066 return;
13067 }
13068
13069 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13070 // Visit that expression.
13071 Visit(S: Base);
13072 }
13073
13074 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13075 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13076 Expr *Callee = E->getCallee();
13077
13078 if (isa<UnresolvedLookupExpr>(Val: Callee))
13079 return Inherited::VisitCXXOperatorCallExpr(S: E);
13080
13081 Visit(S: Callee);
13082 for (auto Arg: E->arguments())
13083 HandleValue(E: Arg->IgnoreParenImpCasts());
13084 }
13085
13086 void VisitLambdaExpr(LambdaExpr *E) {
13087 if (!isInCXXOperatorCall) {
13088 Inherited::VisitLambdaExpr(LE: E);
13089 return;
13090 }
13091
13092 for (Expr *Init : E->capture_inits())
13093 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13094 HandleDeclRefExpr(DRE);
13095 else if (Init)
13096 Visit(S: Init);
13097 }
13098
13099 void VisitUnaryOperator(UnaryOperator *E) {
13100 // For POD record types, addresses of its own members are well-defined.
13101 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13102 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13103 if (!isPODType)
13104 HandleValue(E: E->getSubExpr());
13105 return;
13106 }
13107
13108 if (E->isIncrementDecrementOp()) {
13109 HandleValue(E: E->getSubExpr());
13110 return;
13111 }
13112
13113 Inherited::VisitUnaryOperator(S: E);
13114 }
13115
13116 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13117
13118 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13119 if (E->getConstructor()->isCopyConstructor()) {
13120 Expr *ArgExpr = E->getArg(Arg: 0);
13121 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13122 if (ILE->getNumInits() == 1)
13123 ArgExpr = ILE->getInit(Init: 0);
13124 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13125 if (ICE->getCastKind() == CK_NoOp)
13126 ArgExpr = ICE->getSubExpr();
13127 HandleValue(E: ArgExpr);
13128 return;
13129 }
13130 Inherited::VisitCXXConstructExpr(S: E);
13131 }
13132
13133 void VisitCallExpr(CallExpr *E) {
13134 // Treat std::move as a use.
13135 if (E->isCallToStdMove()) {
13136 HandleValue(E: E->getArg(Arg: 0));
13137 return;
13138 }
13139
13140 Inherited::VisitCallExpr(CE: E);
13141 }
13142
13143 void VisitBinaryOperator(BinaryOperator *E) {
13144 if (E->isCompoundAssignmentOp()) {
13145 HandleValue(E: E->getLHS());
13146 Visit(S: E->getRHS());
13147 return;
13148 }
13149
13150 Inherited::VisitBinaryOperator(S: E);
13151 }
13152
13153 // A custom visitor for BinaryConditionalOperator is needed because the
13154 // regular visitor would check the condition and true expression separately
13155 // but both point to the same place giving duplicate diagnostics.
13156 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13157 Visit(S: E->getCond());
13158 Visit(S: E->getFalseExpr());
13159 }
13160
13161 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13162 Decl* ReferenceDecl = DRE->getDecl();
13163 if (OrigDecl != ReferenceDecl) return;
13164 unsigned diag;
13165 if (isReferenceType) {
13166 diag = diag::warn_uninit_self_reference_in_reference_init;
13167 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13168 diag = diag::warn_static_self_reference_in_init;
13169 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13170 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13171 DRE->getDecl()->getType()->isRecordType()) {
13172 diag = diag::warn_uninit_self_reference_in_init;
13173 } else {
13174 // Local variables will be handled by the CFG analysis.
13175 return;
13176 }
13177
13178 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13179 PD: S.PDiag(DiagID: diag)
13180 << DRE->getDecl() << OrigDecl->getLocation()
13181 << DRE->getSourceRange());
13182 }
13183 };
13184
13185 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13186 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13187 bool DirectInit) {
13188 // Parameters arguments are occassionially constructed with itself,
13189 // for instance, in recursive functions. Skip them.
13190 if (isa<ParmVarDecl>(Val: OrigDecl))
13191 return;
13192
13193 // Skip checking for file-scope constexpr variables - constant evaluation
13194 // will produce appropriate errors without needing runtime diagnostics.
13195 // Local constexpr should still emit runtime warnings.
13196 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13197 VD && VD->isConstexpr() && VD->isFileVarDecl())
13198 return;
13199
13200 E = E->IgnoreParens();
13201
13202 // Skip checking T a = a where T is not a record or reference type.
13203 // Doing so is a way to silence uninitialized warnings.
13204 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13205 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13206 if (ICE->getCastKind() == CK_LValueToRValue)
13207 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13208 if (DRE->getDecl() == OrigDecl)
13209 return;
13210
13211 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13212 }
13213} // end anonymous namespace
13214
13215namespace {
13216 // Simple wrapper to add the name of a variable or (if no variable is
13217 // available) a DeclarationName into a diagnostic.
13218 struct VarDeclOrName {
13219 VarDecl *VDecl;
13220 DeclarationName Name;
13221
13222 friend const Sema::SemaDiagnosticBuilder &
13223 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13224 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13225 }
13226 };
13227} // end anonymous namespace
13228
13229QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13230 DeclarationName Name, QualType Type,
13231 TypeSourceInfo *TSI,
13232 SourceRange Range, bool DirectInit,
13233 Expr *Init) {
13234 bool IsInitCapture = !VDecl;
13235 assert((!VDecl || !VDecl->isInitCapture()) &&
13236 "init captures are expected to be deduced prior to initialization");
13237
13238 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13239
13240 DeducedType *Deduced = Type->getContainedDeducedType();
13241 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13242
13243 // Diagnose auto array declarations in C23, unless it's a supported extension.
13244 if (getLangOpts().C23 && Type->isArrayType() &&
13245 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13246 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13247 << (int)Deduced->getContainedAutoType()->getKeyword()
13248 << /*in array decl*/ 23 << Range;
13249 return QualType();
13250 }
13251
13252 // C++11 [dcl.spec.auto]p3
13253 if (!Init) {
13254 assert(VDecl && "no init for init capture deduction?");
13255
13256 // Except for class argument deduction, and then for an initializing
13257 // declaration only, i.e. no static at class scope or extern.
13258 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13259 VDecl->hasExternalStorage() ||
13260 VDecl->isStaticDataMember()) {
13261 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13262 << VDecl->getDeclName() << Type;
13263 return QualType();
13264 }
13265 }
13266
13267 ArrayRef<Expr*> DeduceInits;
13268 if (Init)
13269 DeduceInits = Init;
13270
13271 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13272 if (DirectInit && PL)
13273 DeduceInits = PL->exprs();
13274
13275 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13276 assert(VDecl && "non-auto type for init capture deduction?");
13277 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13278 InitializationKind Kind = InitializationKind::CreateForInit(
13279 Loc: VDecl->getLocation(), DirectInit, Init);
13280 // FIXME: Initialization should not be taking a mutable list of inits.
13281 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13282 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13283 Init: InitsCopy);
13284 }
13285
13286 if (DirectInit) {
13287 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13288 DeduceInits = IL->inits();
13289 }
13290
13291 // Deduction only works if we have exactly one source expression.
13292 if (DeduceInits.empty()) {
13293 // It isn't possible to write this directly, but it is possible to
13294 // end up in this situation with "auto x(some_pack...);"
13295 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13296 ? diag::err_init_capture_no_expression
13297 : diag::err_auto_var_init_no_expression)
13298 << VN << Type << Range;
13299 return QualType();
13300 }
13301
13302 if (DeduceInits.size() > 1) {
13303 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13304 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13305 : diag::err_auto_var_init_multiple_expressions)
13306 << VN << Type << Range;
13307 return QualType();
13308 }
13309
13310 Expr *DeduceInit = DeduceInits[0];
13311 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13312 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13313 ? diag::err_init_capture_paren_braces
13314 : diag::err_auto_var_init_paren_braces)
13315 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13316 return QualType();
13317 }
13318
13319 // Expressions default to 'id' when we're in a debugger.
13320 bool DefaultedAnyToId = false;
13321 if (getLangOpts().DebuggerCastResultToId &&
13322 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13323 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13324 if (Result.isInvalid()) {
13325 return QualType();
13326 }
13327 Init = Result.get();
13328 DefaultedAnyToId = true;
13329 }
13330
13331 // C++ [dcl.decomp]p1:
13332 // If the assignment-expression [...] has array type A and no ref-qualifier
13333 // is present, e has type cv A
13334 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13335 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13336 DeduceInit->getType()->isConstantArrayType())
13337 return Context.getQualifiedType(T: DeduceInit->getType(),
13338 Qs: Type.getQualifiers());
13339
13340 QualType DeducedType;
13341 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13342 TemplateDeductionResult Result =
13343 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13344 if (Result != TemplateDeductionResult::Success &&
13345 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13346 if (!IsInitCapture)
13347 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13348 else if (isa<InitListExpr>(Val: Init))
13349 Diag(Loc: Range.getBegin(),
13350 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13351 << VN
13352 << (DeduceInit->getType().isNull() ? TSI->getType()
13353 : DeduceInit->getType())
13354 << DeduceInit->getSourceRange();
13355 else
13356 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13357 << VN << TSI->getType()
13358 << (DeduceInit->getType().isNull() ? TSI->getType()
13359 : DeduceInit->getType())
13360 << DeduceInit->getSourceRange();
13361 }
13362
13363 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13364 // 'id' instead of a specific object type prevents most of our usual
13365 // checks.
13366 // We only want to warn outside of template instantiations, though:
13367 // inside a template, the 'id' could have come from a parameter.
13368 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13369 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13370 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13371 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13372 }
13373
13374 return DeducedType;
13375}
13376
13377bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13378 Expr *Init) {
13379 assert(!Init || !Init->containsErrors());
13380 QualType DeducedType = deduceVarTypeFromInitializer(
13381 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13382 Range: VDecl->getSourceRange(), DirectInit, Init);
13383 if (DeducedType.isNull()) {
13384 VDecl->setInvalidDecl();
13385 return true;
13386 }
13387
13388 VDecl->setType(DeducedType);
13389 assert(VDecl->isLinkageValid());
13390
13391 // In ARC, infer lifetime.
13392 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13393 VDecl->setInvalidDecl();
13394
13395 if (getLangOpts().OpenCL)
13396 deduceOpenCLAddressSpace(Decl: VDecl);
13397
13398 if (getLangOpts().HLSL)
13399 HLSL().deduceAddressSpace(Decl: VDecl);
13400
13401 // If this is a redeclaration, check that the type we just deduced matches
13402 // the previously declared type.
13403 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13404 // We never need to merge the type, because we cannot form an incomplete
13405 // array of auto, nor deduce such a type.
13406 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13407 }
13408
13409 // Check the deduced type is valid for a variable declaration.
13410 CheckVariableDeclarationType(NewVD: VDecl);
13411 return VDecl->isInvalidDecl();
13412}
13413
13414void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13415 SourceLocation Loc) {
13416 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13417 Init = EWC->getSubExpr();
13418
13419 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13420 Init = CE->getSubExpr();
13421
13422 QualType InitType = Init->getType();
13423 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13424 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13425 "shouldn't be called if type doesn't have a non-trivial C struct");
13426 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13427 for (auto *I : ILE->inits()) {
13428 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13429 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13430 continue;
13431 SourceLocation SL = I->getExprLoc();
13432 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13433 }
13434 return;
13435 }
13436
13437 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13438 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13439 checkNonTrivialCUnion(QT: InitType, Loc,
13440 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13441 NonTrivialKind: NTCUK_Init);
13442 } else {
13443 // Assume all other explicit initializers involving copying some existing
13444 // object.
13445 // TODO: ignore any explicit initializers where we can guarantee
13446 // copy-elision.
13447 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13448 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13449 NonTrivialKind: NTCUK_Copy);
13450 }
13451}
13452
13453namespace {
13454
13455bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13456 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13457 // in the source code or implicitly by the compiler if it is in a union
13458 // defined in a system header and has non-trivial ObjC ownership
13459 // qualifications. We don't want those fields to participate in determining
13460 // whether the containing union is non-trivial.
13461 return FD->hasAttr<UnavailableAttr>();
13462}
13463
13464struct DiagNonTrivalCUnionDefaultInitializeVisitor
13465 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13466 void> {
13467 using Super =
13468 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13469 void>;
13470
13471 DiagNonTrivalCUnionDefaultInitializeVisitor(
13472 QualType OrigTy, SourceLocation OrigLoc,
13473 NonTrivialCUnionContext UseContext, Sema &S)
13474 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13475
13476 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13477 const FieldDecl *FD, bool InNonTrivialUnion) {
13478 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13479 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13480 Args&: InNonTrivialUnion);
13481 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13482 }
13483
13484 void visitARCStrong(QualType QT, const FieldDecl *FD,
13485 bool InNonTrivialUnion) {
13486 if (InNonTrivialUnion)
13487 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13488 << 1 << 0 << QT << FD->getName();
13489 }
13490
13491 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13492 if (InNonTrivialUnion)
13493 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13494 << 1 << 0 << QT << FD->getName();
13495 }
13496
13497 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13498 const auto *RD = QT->castAsRecordDecl();
13499 if (RD->isUnion()) {
13500 if (OrigLoc.isValid()) {
13501 bool IsUnion = false;
13502 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13503 IsUnion = OrigRD->isUnion();
13504 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13505 << 0 << OrigTy << IsUnion << UseContext;
13506 // Reset OrigLoc so that this diagnostic is emitted only once.
13507 OrigLoc = SourceLocation();
13508 }
13509 InNonTrivialUnion = true;
13510 }
13511
13512 if (InNonTrivialUnion)
13513 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13514 << 0 << 0 << QT.getUnqualifiedType() << "";
13515
13516 for (const FieldDecl *FD : RD->fields())
13517 if (!shouldIgnoreForRecordTriviality(FD))
13518 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13519 }
13520
13521 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13522
13523 // The non-trivial C union type or the struct/union type that contains a
13524 // non-trivial C union.
13525 QualType OrigTy;
13526 SourceLocation OrigLoc;
13527 NonTrivialCUnionContext UseContext;
13528 Sema &S;
13529};
13530
13531struct DiagNonTrivalCUnionDestructedTypeVisitor
13532 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13533 using Super =
13534 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13535
13536 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13537 SourceLocation OrigLoc,
13538 NonTrivialCUnionContext UseContext,
13539 Sema &S)
13540 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13541
13542 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13543 const FieldDecl *FD, bool InNonTrivialUnion) {
13544 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13545 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13546 Args&: InNonTrivialUnion);
13547 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13548 }
13549
13550 void visitARCStrong(QualType QT, const FieldDecl *FD,
13551 bool InNonTrivialUnion) {
13552 if (InNonTrivialUnion)
13553 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13554 << 1 << 1 << QT << FD->getName();
13555 }
13556
13557 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13558 if (InNonTrivialUnion)
13559 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13560 << 1 << 1 << QT << FD->getName();
13561 }
13562
13563 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13564 const auto *RD = QT->castAsRecordDecl();
13565 if (RD->isUnion()) {
13566 if (OrigLoc.isValid()) {
13567 bool IsUnion = false;
13568 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13569 IsUnion = OrigRD->isUnion();
13570 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13571 << 1 << OrigTy << IsUnion << UseContext;
13572 // Reset OrigLoc so that this diagnostic is emitted only once.
13573 OrigLoc = SourceLocation();
13574 }
13575 InNonTrivialUnion = true;
13576 }
13577
13578 if (InNonTrivialUnion)
13579 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13580 << 0 << 1 << QT.getUnqualifiedType() << "";
13581
13582 for (const FieldDecl *FD : RD->fields())
13583 if (!shouldIgnoreForRecordTriviality(FD))
13584 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13585 }
13586
13587 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13588 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13589 bool InNonTrivialUnion) {}
13590
13591 // The non-trivial C union type or the struct/union type that contains a
13592 // non-trivial C union.
13593 QualType OrigTy;
13594 SourceLocation OrigLoc;
13595 NonTrivialCUnionContext UseContext;
13596 Sema &S;
13597};
13598
13599struct DiagNonTrivalCUnionCopyVisitor
13600 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13601 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13602
13603 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13604 NonTrivialCUnionContext UseContext, Sema &S)
13605 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13606
13607 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13608 const FieldDecl *FD, bool InNonTrivialUnion) {
13609 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13610 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13611 Args&: InNonTrivialUnion);
13612 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13613 }
13614
13615 void visitARCStrong(QualType QT, const FieldDecl *FD,
13616 bool InNonTrivialUnion) {
13617 if (InNonTrivialUnion)
13618 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13619 << 1 << 2 << QT << FD->getName();
13620 }
13621
13622 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13623 if (InNonTrivialUnion)
13624 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13625 << 1 << 2 << QT << FD->getName();
13626 }
13627
13628 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13629 const auto *RD = QT->castAsRecordDecl();
13630 if (RD->isUnion()) {
13631 if (OrigLoc.isValid()) {
13632 bool IsUnion = false;
13633 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13634 IsUnion = OrigRD->isUnion();
13635 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13636 << 2 << OrigTy << IsUnion << UseContext;
13637 // Reset OrigLoc so that this diagnostic is emitted only once.
13638 OrigLoc = SourceLocation();
13639 }
13640 InNonTrivialUnion = true;
13641 }
13642
13643 if (InNonTrivialUnion)
13644 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13645 << 0 << 2 << QT.getUnqualifiedType() << "";
13646
13647 for (const FieldDecl *FD : RD->fields())
13648 if (!shouldIgnoreForRecordTriviality(FD))
13649 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13650 }
13651
13652 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13653 if (InNonTrivialUnion)
13654 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13655 << 1 << 2 << QT << FD->getName();
13656 }
13657
13658 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13659 const FieldDecl *FD, bool InNonTrivialUnion) {}
13660 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13661 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13662 bool InNonTrivialUnion) {}
13663
13664 // The non-trivial C union type or the struct/union type that contains a
13665 // non-trivial C union.
13666 QualType OrigTy;
13667 SourceLocation OrigLoc;
13668 NonTrivialCUnionContext UseContext;
13669 Sema &S;
13670};
13671
13672} // namespace
13673
13674void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13675 NonTrivialCUnionContext UseContext,
13676 unsigned NonTrivialKind) {
13677 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13678 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13679 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13680 "shouldn't be called if type doesn't have a non-trivial C union");
13681
13682 if ((NonTrivialKind & NTCUK_Init) &&
13683 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13684 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13685 .visit(FT: QT, Args: nullptr, Args: false);
13686 if ((NonTrivialKind & NTCUK_Destruct) &&
13687 QT.hasNonTrivialToPrimitiveDestructCUnion())
13688 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13689 .visit(FT: QT, Args: nullptr, Args: false);
13690 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13691 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13692 .visit(FT: QT, Args: nullptr, Args: false);
13693}
13694
13695bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13696 const VarDecl *Dcl) {
13697 if (!getLangOpts().CPlusPlus)
13698 return false;
13699
13700 // We only need to warn if the definition is in a header file, so wait to
13701 // diagnose until we've seen the definition.
13702 if (!Dcl->isThisDeclarationADefinition())
13703 return false;
13704
13705 // If an object is defined in a source file, its definition can't get
13706 // duplicated since it will never appear in more than one TU.
13707 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13708 return false;
13709
13710 // If the variable we're looking at is a static local, then we actually care
13711 // about the properties of the function containing it.
13712 const ValueDecl *Target = Dcl;
13713 // VarDecls and FunctionDecls have different functions for checking
13714 // inline-ness, and whether they were originally templated, so we have to
13715 // call the appropriate functions manually.
13716 bool TargetIsInline = Dcl->isInline();
13717 bool TargetWasTemplated =
13718 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13719
13720 // Update the Target and TargetIsInline property if necessary
13721 if (Dcl->isStaticLocal()) {
13722 const DeclContext *Ctx = Dcl->getDeclContext();
13723 if (!Ctx)
13724 return false;
13725
13726 const FunctionDecl *FunDcl =
13727 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13728 if (!FunDcl)
13729 return false;
13730
13731 Target = FunDcl;
13732 // IsInlined() checks for the C++ inline property
13733 TargetIsInline = FunDcl->isInlined();
13734 TargetWasTemplated =
13735 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13736 }
13737
13738 // Non-inline functions/variables can only legally appear in one TU
13739 // unless they were part of a template. Unfortunately, making complex
13740 // template instantiations visible is infeasible in practice, since
13741 // everything the template depends on also has to be visible. To avoid
13742 // giving impractical-to-fix warnings, don't warn if we're inside
13743 // something that was templated, even on inline stuff.
13744 if (!TargetIsInline || TargetWasTemplated)
13745 return false;
13746
13747 // If the object isn't hidden, the dynamic linker will prevent duplication.
13748 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13749
13750 // The target is "hidden" (from the dynamic linker) if:
13751 // 1. On posix, it has hidden visibility, or
13752 // 2. On windows, it has no import/export annotation, and neither does the
13753 // class which directly contains it.
13754 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13755 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13756 return false;
13757
13758 // If the variable isn't directly annotated, check to see if it's a member
13759 // of an annotated class.
13760 const CXXRecordDecl *Ctx =
13761 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13762 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13763 return false;
13764
13765 } else if (Lnk.getVisibility() != HiddenVisibility) {
13766 // Posix case
13767 return false;
13768 }
13769
13770 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13771 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13772 return false;
13773
13774 return true;
13775}
13776
13777// Determine whether the object seems mutable for the purpose of diagnosing
13778// possible unique object duplication, i.e. non-const-qualified, and
13779// not an always-constant type like a function.
13780// Not perfect: doesn't account for mutable members, for example, or
13781// elements of container types.
13782// For nested pointers, any individual level being non-const is sufficient.
13783static bool looksMutable(QualType T, const ASTContext &Ctx) {
13784 T = T.getNonReferenceType();
13785 if (T->isFunctionType())
13786 return false;
13787 if (!T.isConstant(Ctx))
13788 return true;
13789 if (T->isPointerType())
13790 return looksMutable(T: T->getPointeeType(), Ctx);
13791 return false;
13792}
13793
13794void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13795 // If this object has external linkage and hidden visibility, it might be
13796 // duplicated when built into a shared library, which causes problems if it's
13797 // mutable (since the copies won't be in sync) or its initialization has side
13798 // effects (since it will run once per copy instead of once globally).
13799
13800 // Don't diagnose if we're inside a template, because it's not practical to
13801 // fix the warning in most cases.
13802 if (!VD->isTemplated() &&
13803 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13804
13805 QualType Type = VD->getType();
13806 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13807 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13808 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13809 }
13810
13811 // To keep false positives low, only warn if we're certain that the
13812 // initializer has side effects. Don't warn on operator new, since a mutable
13813 // pointer will trigger the previous warning, and an immutable pointer
13814 // getting duplicated just results in a little extra memory usage.
13815 const Expr *Init = VD->getAnyInitializer();
13816 if (Init &&
13817 Init->HasSideEffects(Ctx: VD->getASTContext(),
13818 /*IncludePossibleEffects=*/false) &&
13819 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13820 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13821 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13822 }
13823 }
13824}
13825
13826void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13827 llvm::scope_exit ResetDeclForInitializer([this]() {
13828 if (!this->ExprEvalContexts.empty())
13829 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13830 });
13831
13832 // If there is no declaration, there was an error parsing it. Just ignore
13833 // the initializer.
13834 if (!RealDecl) {
13835 return;
13836 }
13837
13838 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13839 if (!Method->isInvalidDecl()) {
13840 // Pure-specifiers are handled in ActOnPureSpecifier.
13841 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13842 << Method->getDeclName() << Init->getSourceRange();
13843 Method->setInvalidDecl();
13844 }
13845 return;
13846 }
13847
13848 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13849 if (!VDecl) {
13850 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13851 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13852 RealDecl->setInvalidDecl();
13853 return;
13854 }
13855
13856 if (VDecl->isInvalidDecl()) {
13857 ExprResult Recovery =
13858 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13859 if (Expr *E = Recovery.get())
13860 VDecl->setInit(E);
13861 return;
13862 }
13863
13864 // WebAssembly tables can't be used to initialise a variable.
13865 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13866 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13867 VDecl->setInvalidDecl();
13868 return;
13869 }
13870
13871 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13872 if (VDecl->getType()->isUndeducedType()) {
13873 if (Init->containsErrors()) {
13874 // Invalidate the decl as we don't know the type for recovery-expr yet.
13875 RealDecl->setInvalidDecl();
13876 VDecl->setInit(Init);
13877 return;
13878 }
13879
13880 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
13881 assert(VDecl->isInvalidDecl() &&
13882 "decl should be invalidated when deduce fails");
13883 if (auto *RecoveryExpr =
13884 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
13885 .get())
13886 VDecl->setInit(RecoveryExpr);
13887 return;
13888 }
13889 }
13890
13891 this->CheckAttributesOnDeducedType(D: RealDecl);
13892
13893 // dllimport cannot be used on variable definitions.
13894 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13895 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13896 VDecl->setInvalidDecl();
13897 return;
13898 }
13899
13900 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13901 // the identifier has external or internal linkage, the declaration shall
13902 // have no initializer for the identifier.
13903 // C++14 [dcl.init]p5 is the same restriction for C++.
13904 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13905 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
13906 VDecl->setInvalidDecl();
13907 return;
13908 }
13909
13910 if (!VDecl->getType()->isDependentType()) {
13911 // A definition must end up with a complete type, which means it must be
13912 // complete with the restriction that an array type might be completed by
13913 // the initializer; note that later code assumes this restriction.
13914 QualType BaseDeclType = VDecl->getType();
13915 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13916 BaseDeclType = Array->getElementType();
13917 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
13918 DiagID: diag::err_typecheck_decl_incomplete_type)) {
13919 RealDecl->setInvalidDecl();
13920 return;
13921 }
13922
13923 // The variable can not have an abstract class type.
13924 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
13925 DiagID: diag::err_abstract_type_in_decl,
13926 Args: AbstractVariableType))
13927 VDecl->setInvalidDecl();
13928 }
13929
13930 // C++ [module.import/6]
13931 // ...
13932 // A header unit shall not contain a definition of a non-inline function or
13933 // variable whose name has external linkage.
13934 //
13935 // We choose to allow weak & selectany definitions, as they are common in
13936 // headers, and have semantics similar to inline definitions which are allowed
13937 // in header units.
13938 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13939 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13940 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13941 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
13942 !VDecl->getInstantiatedFromStaticDataMember() &&
13943 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13944 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
13945 VDecl->setInvalidDecl();
13946 }
13947
13948 // If adding the initializer will turn this declaration into a definition,
13949 // and we already have a definition for this variable, diagnose or otherwise
13950 // handle the situation.
13951 if (VarDecl *Def = VDecl->getDefinition())
13952 if (Def != VDecl &&
13953 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13954 !VDecl->isThisDeclarationADemotedDefinition() &&
13955 checkVarDeclRedefinition(Old: Def, New: VDecl))
13956 return;
13957
13958 if (getLangOpts().CPlusPlus) {
13959 // C++ [class.static.data]p4
13960 // If a static data member is of const integral or const
13961 // enumeration type, its declaration in the class definition can
13962 // specify a constant-initializer which shall be an integral
13963 // constant expression (5.19). In that case, the member can appear
13964 // in integral constant expressions. The member shall still be
13965 // defined in a namespace scope if it is used in the program and the
13966 // namespace scope definition shall not contain an initializer.
13967 //
13968 // We already performed a redefinition check above, but for static
13969 // data members we also need to check whether there was an in-class
13970 // declaration with an initializer.
13971 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13972 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
13973 << VDecl->getDeclName();
13974 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13975 DiagID: diag::note_previous_initializer)
13976 << 0;
13977 return;
13978 }
13979
13980 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13981 VDecl->setInvalidDecl();
13982 return;
13983 }
13984 }
13985
13986 // If the variable has an initializer and local storage, check whether
13987 // anything jumps over the initialization.
13988 if (VDecl->hasLocalStorage())
13989 setFunctionHasBranchProtectedScope();
13990
13991 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13992 // a kernel function cannot be initialized."
13993 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13994 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
13995 VDecl->setInvalidDecl();
13996 return;
13997 }
13998
13999 // The LoaderUninitialized attribute acts as a definition (of undef).
14000 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14001 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14002 VDecl->setInvalidDecl();
14003 return;
14004 }
14005
14006 if (getLangOpts().HLSL)
14007 if (!HLSL().handleInitialization(VDecl, Init))
14008 return;
14009
14010 // Get the decls type and save a reference for later, since
14011 // CheckInitializerTypes may change it.
14012 QualType DclT = VDecl->getType(), SavT = DclT;
14013
14014 // Expressions default to 'id' when we're in a debugger
14015 // and we are assigning it to a variable of Objective-C pointer type.
14016 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14017 Init->getType() == Context.UnknownAnyTy) {
14018 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14019 if (!Result.isUsable()) {
14020 VDecl->setInvalidDecl();
14021 return;
14022 }
14023 Init = Result.get();
14024 }
14025
14026 // Perform the initialization.
14027 bool InitializedFromParenListExpr = false;
14028 bool IsParenListInit = false;
14029 if (!VDecl->isInvalidDecl()) {
14030 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14031 InitializationKind Kind = InitializationKind::CreateForInit(
14032 Loc: VDecl->getLocation(), DirectInit, Init);
14033
14034 MultiExprArg Args = Init;
14035 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14036 Args =
14037 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14038 InitializedFromParenListExpr = true;
14039 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14040 Args = CXXDirectInit->getInitExprs();
14041 InitializedFromParenListExpr = true;
14042 }
14043
14044 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14045 /*TopLevelOfInitList=*/false,
14046 /*TreatUnavailableAsInvalid=*/false);
14047 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14048 if (!Result.isUsable()) {
14049 // If the provided initializer fails to initialize the var decl,
14050 // we attach a recovery expr for better recovery.
14051 auto RecoveryExpr =
14052 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14053 if (RecoveryExpr.get())
14054 VDecl->setInit(RecoveryExpr.get());
14055 // In general, for error recovery purposes, the initializer doesn't play
14056 // part in the valid bit of the declaration. There are a few exceptions:
14057 // 1) if the var decl has a deduced auto type, and the type cannot be
14058 // deduced by an invalid initializer;
14059 // 2) if the var decl is a decomposition decl with a non-deduced type,
14060 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14061 // Case 1) was already handled elsewhere.
14062 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14063 VDecl->setInvalidDecl();
14064 return;
14065 }
14066
14067 Init = Result.getAs<Expr>();
14068 IsParenListInit = !InitSeq.steps().empty() &&
14069 InitSeq.step_begin()->Kind ==
14070 InitializationSequence::SK_ParenthesizedListInit;
14071 QualType VDeclType = VDecl->getType();
14072 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14073 !VDeclType->isDependentType() &&
14074 Context.getAsIncompleteArrayType(T: VDeclType) &&
14075 Context.getAsIncompleteArrayType(T: Init->getType())) {
14076 // Bail out if it is not possible to deduce array size from the
14077 // initializer.
14078 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14079 << VDeclType;
14080 VDecl->setInvalidDecl();
14081 return;
14082 }
14083 }
14084
14085 // Check for self-references within variable initializers.
14086 // Variables declared within a function/method body (except for references)
14087 // are handled by a dataflow analysis.
14088 // This is undefined behavior in C++, but valid in C.
14089 if (getLangOpts().CPlusPlus)
14090 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14091 VDecl->getType()->isReferenceType())
14092 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14093
14094 // If the type changed, it means we had an incomplete type that was
14095 // completed by the initializer. For example:
14096 // int ary[] = { 1, 3, 5 };
14097 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14098 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14099 VDecl->setType(DclT);
14100
14101 if (!VDecl->isInvalidDecl()) {
14102 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14103
14104 if (VDecl->hasAttr<BlocksAttr>())
14105 ObjC().checkRetainCycles(Var: VDecl, Init);
14106
14107 // It is safe to assign a weak reference into a strong variable.
14108 // Although this code can still have problems:
14109 // id x = self.weakProp;
14110 // id y = self.weakProp;
14111 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14112 // paths through the function. This should be revisited if
14113 // -Wrepeated-use-of-weak is made flow-sensitive.
14114 if (FunctionScopeInfo *FSI = getCurFunction())
14115 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14116 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14117 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14118 Loc: Init->getBeginLoc()))
14119 FSI->markSafeWeakUse(E: Init);
14120 }
14121
14122 // The initialization is usually a full-expression.
14123 //
14124 // FIXME: If this is a braced initialization of an aggregate, it is not
14125 // an expression, and each individual field initializer is a separate
14126 // full-expression. For instance, in:
14127 //
14128 // struct Temp { ~Temp(); };
14129 // struct S { S(Temp); };
14130 // struct T { S a, b; } t = { Temp(), Temp() }
14131 //
14132 // we should destroy the first Temp before constructing the second.
14133 ExprResult Result =
14134 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14135 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14136 if (!Result.isUsable()) {
14137 VDecl->setInvalidDecl();
14138 return;
14139 }
14140 Init = Result.get();
14141
14142 // Attach the initializer to the decl.
14143 VDecl->setInit(Init);
14144
14145 if (VDecl->isLocalVarDecl()) {
14146 // Don't check the initializer if the declaration is malformed.
14147 if (VDecl->isInvalidDecl()) {
14148 // do nothing
14149
14150 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14151 // This is true even in C++ for OpenCL.
14152 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14153 CheckForConstantInitializer(Init);
14154
14155 // Otherwise, C++ does not restrict the initializer.
14156 } else if (getLangOpts().CPlusPlus) {
14157 // do nothing
14158
14159 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14160 // static storage duration shall be constant expressions or string literals.
14161 } else if (VDecl->getStorageClass() == SC_Static) {
14162 // Avoid evaluating the initializer twice for constexpr variables. It will
14163 // be evaluated later.
14164 if (!VDecl->isConstexpr())
14165 CheckForConstantInitializer(Init);
14166
14167 // C89 is stricter than C99 for aggregate initializers.
14168 // C89 6.5.7p3: All the expressions [...] in an initializer list
14169 // for an object that has aggregate or union type shall be
14170 // constant expressions.
14171 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14172 isa<InitListExpr>(Val: Init)) {
14173 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14174 }
14175
14176 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14177 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14178 if (VDecl->hasLocalStorage())
14179 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14180 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14181 VDecl->getLexicalDeclContext()->isRecord()) {
14182 // This is an in-class initialization for a static data member, e.g.,
14183 //
14184 // struct S {
14185 // static const int value = 17;
14186 // };
14187
14188 // C++ [class.mem]p4:
14189 // A member-declarator can contain a constant-initializer only
14190 // if it declares a static member (9.4) of const integral or
14191 // const enumeration type, see 9.4.2.
14192 //
14193 // C++11 [class.static.data]p3:
14194 // If a non-volatile non-inline const static data member is of integral
14195 // or enumeration type, its declaration in the class definition can
14196 // specify a brace-or-equal-initializer in which every initializer-clause
14197 // that is an assignment-expression is a constant expression. A static
14198 // data member of literal type can be declared in the class definition
14199 // with the constexpr specifier; if so, its declaration shall specify a
14200 // brace-or-equal-initializer in which every initializer-clause that is
14201 // an assignment-expression is a constant expression.
14202
14203 // Do nothing on dependent types.
14204 if (DclT->isDependentType()) {
14205
14206 // Allow any 'static constexpr' members, whether or not they are of literal
14207 // type. We separately check that every constexpr variable is of literal
14208 // type.
14209 } else if (VDecl->isConstexpr()) {
14210
14211 // Require constness.
14212 } else if (!DclT.isConstQualified()) {
14213 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14214 << Init->getSourceRange();
14215 VDecl->setInvalidDecl();
14216
14217 // We allow integer constant expressions in all cases.
14218 } else if (DclT->isIntegralOrEnumerationType()) {
14219 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14220 // In C++11, a non-constexpr const static data member with an
14221 // in-class initializer cannot be volatile.
14222 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14223
14224 // We allow foldable floating-point constants as an extension.
14225 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14226 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14227 // it anyway and provide a fixit to add the 'constexpr'.
14228 if (getLangOpts().CPlusPlus11) {
14229 Diag(Loc: VDecl->getLocation(),
14230 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14231 << DclT << Init->getSourceRange();
14232 Diag(Loc: VDecl->getBeginLoc(),
14233 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14234 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14235 } else {
14236 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14237 << DclT << Init->getSourceRange();
14238
14239 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14240 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14241 << Init->getSourceRange();
14242 VDecl->setInvalidDecl();
14243 }
14244 }
14245
14246 // Suggest adding 'constexpr' in C++11 for literal types.
14247 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14248 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14249 << DclT << Init->getSourceRange()
14250 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14251 VDecl->setConstexpr(true);
14252
14253 } else {
14254 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14255 << DclT << Init->getSourceRange();
14256 VDecl->setInvalidDecl();
14257 }
14258 } else if (VDecl->isFileVarDecl()) {
14259 // In C, extern is typically used to avoid tentative definitions when
14260 // declaring variables in headers, but adding an initializer makes it a
14261 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14262 // In C++, extern is often used to give implicitly static const variables
14263 // external linkage, so don't warn in that case. If selectany is present,
14264 // this might be header code intended for C and C++ inclusion, so apply the
14265 // C++ rules.
14266 if (VDecl->getStorageClass() == SC_Extern &&
14267 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14268 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14269 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14270 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14271 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14272
14273 // In Microsoft C++ mode, a const variable defined in namespace scope has
14274 // external linkage by default if the variable is declared with
14275 // __declspec(dllexport).
14276 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14277 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14278 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14279 VDecl->setStorageClass(SC_Extern);
14280
14281 // C99 6.7.8p4. All file scoped initializers need to be constant.
14282 // Avoid duplicate diagnostics for constexpr variables.
14283 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14284 !VDecl->isConstexpr())
14285 CheckForConstantInitializer(Init);
14286 }
14287
14288 QualType InitType = Init->getType();
14289 if (!InitType.isNull() &&
14290 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14291 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14292 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14293
14294 // We will represent direct-initialization similarly to copy-initialization:
14295 // int x(1); -as-> int x = 1;
14296 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14297 //
14298 // Clients that want to distinguish between the two forms, can check for
14299 // direct initializer using VarDecl::getInitStyle().
14300 // A major benefit is that clients that don't particularly care about which
14301 // exactly form was it (like the CodeGen) can handle both cases without
14302 // special case code.
14303
14304 // C++ 8.5p11:
14305 // The form of initialization (using parentheses or '=') matters
14306 // when the entity being initialized has class type.
14307 if (InitializedFromParenListExpr) {
14308 assert(DirectInit && "Call-style initializer must be direct init.");
14309 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14310 : VarDecl::CallInit);
14311 } else if (DirectInit) {
14312 // This must be list-initialization. No other way is direct-initialization.
14313 VDecl->setInitStyle(VarDecl::ListInit);
14314 }
14315
14316 if (LangOpts.OpenMP &&
14317 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14318 VDecl->isFileVarDecl())
14319 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14320 CheckCompleteVariableDeclaration(VD: VDecl);
14321
14322 if (LangOpts.OpenACC && !InitType.isNull())
14323 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14324}
14325
14326void Sema::ActOnInitializerError(Decl *D) {
14327 // Our main concern here is re-establishing invariants like "a
14328 // variable's type is either dependent or complete".
14329 if (!D || D->isInvalidDecl()) return;
14330
14331 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14332 if (!VD) return;
14333
14334 // Bindings are not usable if we can't make sense of the initializer.
14335 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14336 for (auto *BD : DD->bindings())
14337 BD->setInvalidDecl();
14338
14339 // Auto types are meaningless if we can't make sense of the initializer.
14340 if (VD->getType()->isUndeducedType()) {
14341 D->setInvalidDecl();
14342 return;
14343 }
14344
14345 QualType Ty = VD->getType();
14346 if (Ty->isDependentType()) return;
14347
14348 // Require a complete type.
14349 if (RequireCompleteType(Loc: VD->getLocation(),
14350 T: Context.getBaseElementType(QT: Ty),
14351 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14352 VD->setInvalidDecl();
14353 return;
14354 }
14355
14356 // Require a non-abstract type.
14357 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14358 DiagID: diag::err_abstract_type_in_decl,
14359 Args: AbstractVariableType)) {
14360 VD->setInvalidDecl();
14361 return;
14362 }
14363
14364 // Don't bother complaining about constructors or destructors,
14365 // though.
14366}
14367
14368void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14369 // If there is no declaration, there was an error parsing it. Just ignore it.
14370 if (!RealDecl)
14371 return;
14372
14373 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14374 QualType Type = Var->getType();
14375
14376 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14377 if (isa<DecompositionDecl>(Val: RealDecl)) {
14378 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14379 Var->setInvalidDecl();
14380 return;
14381 }
14382
14383 if (Type->isUndeducedType() &&
14384 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14385 return;
14386
14387 this->CheckAttributesOnDeducedType(D: RealDecl);
14388
14389 // C++11 [class.static.data]p3: A static data member can be declared with
14390 // the constexpr specifier; if so, its declaration shall specify
14391 // a brace-or-equal-initializer.
14392 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14393 // the definition of a variable [...] or the declaration of a static data
14394 // member.
14395 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14396 !Var->isThisDeclarationADemotedDefinition()) {
14397 if (Var->isStaticDataMember()) {
14398 // C++1z removes the relevant rule; the in-class declaration is always
14399 // a definition there.
14400 if (!getLangOpts().CPlusPlus17 &&
14401 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14402 Diag(Loc: Var->getLocation(),
14403 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14404 << Var;
14405 Var->setInvalidDecl();
14406 return;
14407 }
14408 } else {
14409 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14410 Var->setInvalidDecl();
14411 return;
14412 }
14413 }
14414
14415 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14416 // be initialized.
14417 if (!Var->isInvalidDecl() &&
14418 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14419 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14420 bool HasConstExprDefaultConstructor = false;
14421 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14422 for (auto *Ctor : RD->ctors()) {
14423 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14424 Ctor->getMethodQualifiers().getAddressSpace() ==
14425 LangAS::opencl_constant) {
14426 HasConstExprDefaultConstructor = true;
14427 }
14428 }
14429 }
14430 if (!HasConstExprDefaultConstructor) {
14431 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14432 Var->setInvalidDecl();
14433 return;
14434 }
14435 }
14436
14437 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14438 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14439 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14440 Var->setInvalidDecl();
14441 return;
14442 }
14443
14444 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14445 if (Var->getStorageClass() == SC_Extern) {
14446 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14447 << Var;
14448 Var->setInvalidDecl();
14449 return;
14450 }
14451 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14452 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14453 Var->setInvalidDecl();
14454 return;
14455 }
14456 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14457 if (!RD->hasTrivialDefaultConstructor()) {
14458 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14459 Var->setInvalidDecl();
14460 return;
14461 }
14462 }
14463 // The declaration is uninitialized, no need for further checks.
14464 return;
14465 }
14466
14467 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14468 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14469 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14470 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14471 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14472 NonTrivialKind: NTCUK_Init);
14473
14474 switch (DefKind) {
14475 case VarDecl::Definition:
14476 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14477 break;
14478
14479 // We have an out-of-line definition of a static data member
14480 // that has an in-class initializer, so we type-check this like
14481 // a declaration.
14482 //
14483 [[fallthrough]];
14484
14485 case VarDecl::DeclarationOnly:
14486 // It's only a declaration.
14487
14488 // Block scope. C99 6.7p7: If an identifier for an object is
14489 // declared with no linkage (C99 6.2.2p6), the type for the
14490 // object shall be complete.
14491 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14492 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14493 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14494 DiagID: diag::err_typecheck_decl_incomplete_type))
14495 Var->setInvalidDecl();
14496
14497 // Make sure that the type is not abstract.
14498 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14499 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14500 DiagID: diag::err_abstract_type_in_decl,
14501 Args: AbstractVariableType))
14502 Var->setInvalidDecl();
14503 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14504 Var->getStorageClass() == SC_PrivateExtern) {
14505 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14506 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14507 }
14508
14509 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14510 !Var->isInvalidDecl())
14511 ExternalDeclarations.push_back(Elt: Var);
14512
14513 return;
14514
14515 case VarDecl::TentativeDefinition:
14516 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14517 // object that has file scope without an initializer, and without a
14518 // storage-class specifier or with the storage-class specifier "static",
14519 // constitutes a tentative definition. Note: A tentative definition with
14520 // external linkage is valid (C99 6.2.2p5).
14521 if (!Var->isInvalidDecl()) {
14522 if (const IncompleteArrayType *ArrayT
14523 = Context.getAsIncompleteArrayType(T: Type)) {
14524 if (RequireCompleteSizedType(
14525 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14526 DiagID: diag::err_array_incomplete_or_sizeless_type))
14527 Var->setInvalidDecl();
14528 }
14529 if (Var->getStorageClass() == SC_Static) {
14530 // C99 6.9.2p3: If the declaration of an identifier for an object is
14531 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14532 // declared type shall not be an incomplete type.
14533 // NOTE: code such as the following
14534 // static struct s;
14535 // struct s { int a; };
14536 // is accepted by gcc. Hence here we issue a warning instead of
14537 // an error and we do not invalidate the static declaration.
14538 // NOTE: to avoid multiple warnings, only check the first declaration.
14539 if (Var->isFirstDecl())
14540 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14541 DiagID: diag::ext_typecheck_decl_incomplete_type,
14542 Args: Type->isArrayType());
14543 }
14544 }
14545
14546 // Record the tentative definition; we're done.
14547 if (!Var->isInvalidDecl())
14548 TentativeDefinitions.push_back(LocalValue: Var);
14549 return;
14550 }
14551
14552 // Provide a specific diagnostic for uninitialized variable definitions
14553 // with incomplete array type, unless it is a global unbounded HLSL resource
14554 // array.
14555 if (Type->isIncompleteArrayType() &&
14556 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14557 Type->isHLSLResourceRecordArray())) {
14558 if (Var->isConstexpr())
14559 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14560 << Var;
14561 else
14562 Diag(Loc: Var->getLocation(),
14563 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14564 Var->setInvalidDecl();
14565 return;
14566 }
14567
14568 // Provide a specific diagnostic for uninitialized variable
14569 // definitions with reference type.
14570 if (Type->isReferenceType()) {
14571 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14572 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14573 return;
14574 }
14575
14576 // Do not attempt to type-check the default initializer for a
14577 // variable with dependent type.
14578 if (Type->isDependentType())
14579 return;
14580
14581 if (Var->isInvalidDecl())
14582 return;
14583
14584 if (!Var->hasAttr<AliasAttr>()) {
14585 if (RequireCompleteType(Loc: Var->getLocation(),
14586 T: Context.getBaseElementType(QT: Type),
14587 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14588 Var->setInvalidDecl();
14589 return;
14590 }
14591 } else {
14592 return;
14593 }
14594
14595 // The variable can not have an abstract class type.
14596 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14597 DiagID: diag::err_abstract_type_in_decl,
14598 Args: AbstractVariableType)) {
14599 Var->setInvalidDecl();
14600 return;
14601 }
14602
14603 // In C, if the definition is const-qualified and has no initializer, it
14604 // is left uninitialized unless it has static or thread storage duration.
14605 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14606 unsigned DiagID = diag::warn_default_init_const_unsafe;
14607 if (Var->getStorageDuration() == SD_Static ||
14608 Var->getStorageDuration() == SD_Thread)
14609 DiagID = diag::warn_default_init_const;
14610
14611 bool EmitCppCompat = !Diags.isIgnored(
14612 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14613 Loc: Var->getLocation());
14614
14615 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14616 }
14617
14618 // Check for jumps past the implicit initializer. C++0x
14619 // clarifies that this applies to a "variable with automatic
14620 // storage duration", not a "local variable".
14621 // C++11 [stmt.dcl]p3
14622 // A program that jumps from a point where a variable with automatic
14623 // storage duration is not in scope to a point where it is in scope is
14624 // ill-formed unless the variable has scalar type, class type with a
14625 // trivial default constructor and a trivial destructor, a cv-qualified
14626 // version of one of these types, or an array of one of the preceding
14627 // types and is declared without an initializer.
14628 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14629 if (const auto *CXXRecord =
14630 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14631 // Mark the function (if we're in one) for further checking even if the
14632 // looser rules of C++11 do not require such checks, so that we can
14633 // diagnose incompatibilities with C++98.
14634 if (!CXXRecord->isPOD())
14635 setFunctionHasBranchProtectedScope();
14636 }
14637 }
14638 // In OpenCL, we can't initialize objects in the __local address space,
14639 // even implicitly, so don't synthesize an implicit initializer.
14640 if (getLangOpts().OpenCL &&
14641 Var->getType().getAddressSpace() == LangAS::opencl_local)
14642 return;
14643
14644 // Handle HLSL uninitialized decls
14645 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14646 return;
14647
14648 // HLSL input & push-constant variables are expected to be externally
14649 // initialized, even when marked `static`.
14650 if (getLangOpts().HLSL &&
14651 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14652 return;
14653
14654 // C++03 [dcl.init]p9:
14655 // If no initializer is specified for an object, and the
14656 // object is of (possibly cv-qualified) non-POD class type (or
14657 // array thereof), the object shall be default-initialized; if
14658 // the object is of const-qualified type, the underlying class
14659 // type shall have a user-declared default
14660 // constructor. Otherwise, if no initializer is specified for
14661 // a non- static object, the object and its subobjects, if
14662 // any, have an indeterminate initial value); if the object
14663 // or any of its subobjects are of const-qualified type, the
14664 // program is ill-formed.
14665 // C++0x [dcl.init]p11:
14666 // If no initializer is specified for an object, the object is
14667 // default-initialized; [...].
14668 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14669 InitializationKind Kind
14670 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14671
14672 InitializationSequence InitSeq(*this, Entity, Kind, {});
14673 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14674
14675 if (Init.get()) {
14676 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14677 // This is important for template substitution.
14678 Var->setInitStyle(VarDecl::CallInit);
14679 } else if (Init.isInvalid()) {
14680 // If default-init fails, attach a recovery-expr initializer to track
14681 // that initialization was attempted and failed.
14682 auto RecoveryExpr =
14683 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14684 if (RecoveryExpr.get())
14685 Var->setInit(RecoveryExpr.get());
14686 }
14687
14688 CheckCompleteVariableDeclaration(VD: Var);
14689 }
14690}
14691
14692void Sema::ActOnCXXForRangeDecl(Decl *D) {
14693 // If there is no declaration, there was an error parsing it. Ignore it.
14694 if (!D)
14695 return;
14696
14697 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14698 if (!VD) {
14699 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14700 D->setInvalidDecl();
14701 return;
14702 }
14703
14704 VD->setCXXForRangeDecl(true);
14705
14706 // for-range-declaration cannot be given a storage class specifier.
14707 int Error = -1;
14708 switch (VD->getStorageClass()) {
14709 case SC_None:
14710 break;
14711 case SC_Extern:
14712 Error = 0;
14713 break;
14714 case SC_Static:
14715 Error = 1;
14716 break;
14717 case SC_PrivateExtern:
14718 Error = 2;
14719 break;
14720 case SC_Auto:
14721 Error = 3;
14722 break;
14723 case SC_Register:
14724 Error = 4;
14725 break;
14726 }
14727
14728 // for-range-declaration cannot be given a storage class specifier con't.
14729 switch (VD->getTSCSpec()) {
14730 case TSCS_thread_local:
14731 Error = 6;
14732 break;
14733 case TSCS___thread:
14734 case TSCS__Thread_local:
14735 case TSCS_unspecified:
14736 break;
14737 }
14738
14739 if (Error != -1) {
14740 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14741 << VD << Error;
14742 D->setInvalidDecl();
14743 }
14744}
14745
14746StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14747 IdentifierInfo *Ident,
14748 ParsedAttributes &Attrs) {
14749 // C++1y [stmt.iter]p1:
14750 // A range-based for statement of the form
14751 // for ( for-range-identifier : for-range-initializer ) statement
14752 // is equivalent to
14753 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14754 DeclSpec DS(Attrs.getPool().getFactory());
14755
14756 const char *PrevSpec;
14757 unsigned DiagID;
14758 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14759 Policy: getPrintingPolicy());
14760
14761 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14762 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14763 D.takeAttributesAppending(attrs&: Attrs);
14764
14765 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14766 EndLoc: IdentLoc);
14767 Decl *Var = ActOnDeclarator(S, D);
14768 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14769 FinalizeDeclaration(D: Var);
14770 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14771 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14772 : IdentLoc);
14773}
14774
14775void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
14776 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
14777 return;
14778 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
14779 QualType MethodType = MD->getType();
14780 QualType AttributedType =
14781 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
14782 TypeLocBuilder TLB;
14783 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14784 TLB.pushFullCopy(L: TSI->getTypeLoc());
14785 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
14786 TyLoc.setAttr(Attr);
14787 MD->setType(AttributedType);
14788 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
14789}
14790
14791void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14792 if (var->isInvalidDecl()) return;
14793
14794 CUDA().MaybeAddConstantAttr(VD: var);
14795
14796 if (getLangOpts().OpenCL) {
14797 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14798 // initialiser
14799 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14800 !var->hasInit()) {
14801 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14802 << 1 /*Init*/;
14803 var->setInvalidDecl();
14804 return;
14805 }
14806 }
14807
14808 // In Objective-C, don't allow jumps past the implicit initialization of a
14809 // local retaining variable.
14810 if (getLangOpts().ObjC &&
14811 var->hasLocalStorage()) {
14812 switch (var->getType().getObjCLifetime()) {
14813 case Qualifiers::OCL_None:
14814 case Qualifiers::OCL_ExplicitNone:
14815 case Qualifiers::OCL_Autoreleasing:
14816 break;
14817
14818 case Qualifiers::OCL_Weak:
14819 case Qualifiers::OCL_Strong:
14820 setFunctionHasBranchProtectedScope();
14821 break;
14822 }
14823 }
14824
14825 if (var->hasLocalStorage() &&
14826 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14827 setFunctionHasBranchProtectedScope();
14828
14829 // Warn about externally-visible variables being defined without a
14830 // prior declaration. We only want to do this for global
14831 // declarations, but we also specifically need to avoid doing it for
14832 // class members because the linkage of an anonymous class can
14833 // change if it's later given a typedef name.
14834 if (var->isThisDeclarationADefinition() &&
14835 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14836 var->isExternallyVisible() && var->hasLinkage() &&
14837 !var->isInline() && !var->getDescribedVarTemplate() &&
14838 var->getStorageClass() != SC_Register &&
14839 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14840 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14841 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14842 Loc: var->getLocation())) {
14843 // Find a previous declaration that's not a definition.
14844 VarDecl *prev = var->getPreviousDecl();
14845 while (prev && prev->isThisDeclarationADefinition())
14846 prev = prev->getPreviousDecl();
14847
14848 if (!prev) {
14849 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14850 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14851 << /* variable */ 0;
14852 }
14853 }
14854
14855 // Cache the result of checking for constant initialization.
14856 std::optional<bool> CacheHasConstInit;
14857 const Expr *CacheCulprit = nullptr;
14858 auto checkConstInit = [&]() mutable {
14859 const Expr *Init = var->getInit();
14860 if (Init->isInstantiationDependent())
14861 return true;
14862
14863 if (!CacheHasConstInit)
14864 CacheHasConstInit = var->getInit()->isConstantInitializer(
14865 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14866 return *CacheHasConstInit;
14867 };
14868
14869 if (var->getTLSKind() == VarDecl::TLS_Static) {
14870 if (var->getType().isDestructedType()) {
14871 // GNU C++98 edits for __thread, [basic.start.term]p3:
14872 // The type of an object with thread storage duration shall not
14873 // have a non-trivial destructor.
14874 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14875 if (getLangOpts().CPlusPlus11)
14876 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14877 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14878 if (!checkConstInit()) {
14879 // GNU C++98 edits for __thread, [basic.start.init]p4:
14880 // An object of thread storage duration shall not require dynamic
14881 // initialization.
14882 // FIXME: Need strict checking here.
14883 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14884 << CacheCulprit->getSourceRange();
14885 if (getLangOpts().CPlusPlus11)
14886 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14887 }
14888 }
14889 }
14890
14891
14892 if (!var->getType()->isStructureType() && var->hasInit() &&
14893 isa<InitListExpr>(Val: var->getInit())) {
14894 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14895 unsigned NumInits = ILE->getNumInits();
14896 if (NumInits > 2)
14897 for (unsigned I = 0; I < NumInits; ++I) {
14898 const auto *Init = ILE->getInit(Init: I);
14899 if (!Init)
14900 break;
14901 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14902 if (!SL)
14903 break;
14904
14905 unsigned NumConcat = SL->getNumConcatenated();
14906 // Diagnose missing comma in string array initialization.
14907 // Do not warn when all the elements in the initializer are concatenated
14908 // together. Do not warn for macros too.
14909 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14910 bool OnlyOneMissingComma = true;
14911 for (unsigned J = I + 1; J < NumInits; ++J) {
14912 const auto *Init = ILE->getInit(Init: J);
14913 if (!Init)
14914 break;
14915 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14916 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14917 OnlyOneMissingComma = false;
14918 break;
14919 }
14920 }
14921
14922 if (OnlyOneMissingComma) {
14923 SmallVector<FixItHint, 1> Hints;
14924 for (unsigned i = 0; i < NumConcat - 1; ++i)
14925 Hints.push_back(Elt: FixItHint::CreateInsertion(
14926 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14927
14928 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
14929 DiagID: diag::warn_concatenated_literal_array_init)
14930 << Hints;
14931 Diag(Loc: SL->getBeginLoc(),
14932 DiagID: diag::note_concatenated_string_literal_silence);
14933 }
14934 // In any case, stop now.
14935 break;
14936 }
14937 }
14938 }
14939
14940
14941 QualType type = var->getType();
14942
14943 if (var->hasAttr<BlocksAttr>())
14944 getCurFunction()->addByrefBlockVar(VD: var);
14945
14946 Expr *Init = var->getInit();
14947 bool GlobalStorage = var->hasGlobalStorage();
14948 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14949 QualType baseType = Context.getBaseElementType(QT: type);
14950 bool HasConstInit = true;
14951
14952 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14953 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14954 << var;
14955
14956 // Check whether the initializer is sufficiently constant.
14957 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14958 !type->isDependentType() && Init && !Init->isValueDependent() &&
14959 (GlobalStorage || var->isConstexpr() ||
14960 var->mightBeUsableInConstantExpressions(C: Context))) {
14961 // If this variable might have a constant initializer or might be usable in
14962 // constant expressions, check whether or not it actually is now. We can't
14963 // do this lazily, because the result might depend on things that change
14964 // later, such as which constexpr functions happen to be defined.
14965 SmallVector<PartialDiagnosticAt, 8> Notes;
14966 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14967 // Prior to C++11, in contexts where a constant initializer is required,
14968 // the set of valid constant initializers is described by syntactic rules
14969 // in [expr.const]p2-6.
14970 // FIXME: Stricter checking for these rules would be useful for constinit /
14971 // -Wglobal-constructors.
14972 HasConstInit = checkConstInit();
14973
14974 // Compute and cache the constant value, and remember that we have a
14975 // constant initializer.
14976 if (HasConstInit) {
14977 if (var->isStaticDataMember() && !var->isInline() &&
14978 var->getLexicalDeclContext()->isRecord() &&
14979 type->isIntegralOrEnumerationType()) {
14980 // In C++98, in-class initialization for a static data member must
14981 // be an integer constant expression.
14982 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
14983 Diag(Loc: Init->getExprLoc(),
14984 DiagID: diag::ext_in_class_initializer_non_constant)
14985 << Init->getSourceRange();
14986 }
14987 }
14988 (void)var->checkForConstantInitialization(Notes);
14989 Notes.clear();
14990 } else if (CacheCulprit) {
14991 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
14992 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
14993 Notes.back().second << CacheCulprit->getSourceRange();
14994 }
14995 } else {
14996 // Evaluate the initializer to see if it's a constant initializer.
14997 HasConstInit = var->checkForConstantInitialization(Notes);
14998 }
14999
15000 if (HasConstInit) {
15001 // FIXME: Consider replacing the initializer with a ConstantExpr.
15002 } else if (var->isConstexpr()) {
15003 SourceLocation DiagLoc = var->getLocation();
15004 // If the note doesn't add any useful information other than a source
15005 // location, fold it into the primary diagnostic.
15006 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15007 diag::note_invalid_subexpr_in_const_expr) {
15008 DiagLoc = Notes[0].first;
15009 Notes.clear();
15010 }
15011 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15012 << var << Init->getSourceRange();
15013 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15014 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15015 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15016 auto *Attr = var->getAttr<ConstInitAttr>();
15017 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15018 << Init->getSourceRange();
15019 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15020 << Attr->getRange() << Attr->isConstinit();
15021 for (auto &it : Notes)
15022 Diag(Loc: it.first, PD: it.second);
15023 } else if (var->isStaticDataMember() && !var->isInline() &&
15024 var->getLexicalDeclContext()->isRecord()) {
15025 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15026 << Init->getSourceRange();
15027 for (auto &it : Notes)
15028 Diag(Loc: it.first, PD: it.second);
15029 var->setInvalidDecl();
15030 } else if (IsGlobal &&
15031 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15032 Loc: var->getLocation())) {
15033 // Warn about globals which don't have a constant initializer. Don't
15034 // warn about globals with a non-trivial destructor because we already
15035 // warned about them.
15036 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15037 if (!(RD && !RD->hasTrivialDestructor())) {
15038 // checkConstInit() here permits trivial default initialization even in
15039 // C++11 onwards, where such an initializer is not a constant initializer
15040 // but nonetheless doesn't require a global constructor.
15041 if (!checkConstInit())
15042 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15043 << Init->getSourceRange();
15044 }
15045 }
15046 }
15047
15048 // Apply section attributes and pragmas to global variables.
15049 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15050 !inTemplateInstantiation()) {
15051 PragmaStack<StringLiteral *> *Stack = nullptr;
15052 int SectionFlags = ASTContext::PSF_Read;
15053 bool MSVCEnv =
15054 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15055 std::optional<QualType::NonConstantStorageReason> Reason;
15056 if (HasConstInit &&
15057 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15058 Stack = &ConstSegStack;
15059 } else {
15060 SectionFlags |= ASTContext::PSF_Write;
15061 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15062 }
15063 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15064 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15065 SectionFlags |= ASTContext::PSF_Implicit;
15066 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15067 } else if (Stack->CurrentValue) {
15068 if (Stack != &ConstSegStack && MSVCEnv &&
15069 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15070 var->getType().isConstQualified()) {
15071 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15072 NonConstNonReferenceType) &&
15073 "This case should've already been handled elsewhere");
15074 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15075 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15076 ? QualType::NonConstantStorageReason::NonTrivialCtor
15077 : *Reason);
15078 }
15079 SectionFlags |= ASTContext::PSF_Implicit;
15080 auto SectionName = Stack->CurrentValue->getString();
15081 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15082 Range: Stack->CurrentPragmaLocation,
15083 S: SectionAttr::Declspec_allocate));
15084 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15085 var->dropAttr<SectionAttr>();
15086 }
15087
15088 // Apply the init_seg attribute if this has an initializer. If the
15089 // initializer turns out to not be dynamic, we'll end up ignoring this
15090 // attribute.
15091 if (CurInitSeg && var->getInit())
15092 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15093 Range: CurInitSegLoc));
15094 }
15095
15096 // All the following checks are C++ only.
15097 if (!getLangOpts().CPlusPlus) {
15098 // If this variable must be emitted, add it as an initializer for the
15099 // current module.
15100 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15101 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15102 return;
15103 }
15104
15105 DiagnoseUniqueObjectDuplication(VD: var);
15106
15107 // Require the destructor.
15108 if (!type->isDependentType())
15109 if (auto *RD = baseType->getAsCXXRecordDecl())
15110 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15111
15112 // If this variable must be emitted, add it as an initializer for the current
15113 // module.
15114 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15115 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15116
15117 // Build the bindings if this is a structured binding declaration.
15118 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15119 CheckCompleteDecompositionDeclaration(DD);
15120}
15121
15122void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15123 assert(VD->isStaticLocal());
15124
15125 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15126
15127 // Find outermost function when VD is in lambda function.
15128 while (FD && !getDLLAttr(D: FD) &&
15129 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15130 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15131 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15132 }
15133
15134 if (!FD)
15135 return;
15136
15137 // Static locals inherit dll attributes from their function.
15138 if (Attr *A = getDLLAttr(D: FD)) {
15139 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15140 NewAttr->setInherited(true);
15141 VD->addAttr(A: NewAttr);
15142 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15143 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15144 NewAttr->setInherited(true);
15145 VD->addAttr(A: NewAttr);
15146
15147 // Export this function to enforce exporting this static variable even
15148 // if it is not used in this compilation unit.
15149 if (!FD->hasAttr<DLLExportAttr>())
15150 FD->addAttr(A: NewAttr);
15151
15152 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15153 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15154 NewAttr->setInherited(true);
15155 VD->addAttr(A: NewAttr);
15156 }
15157}
15158
15159void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15160 assert(VD->getTLSKind());
15161
15162 // Perform TLS alignment check here after attributes attached to the variable
15163 // which may affect the alignment have been processed. Only perform the check
15164 // if the target has a maximum TLS alignment (zero means no constraints).
15165 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15166 // Protect the check so that it's not performed on dependent types and
15167 // dependent alignments (we can't determine the alignment in that case).
15168 if (!VD->hasDependentAlignment()) {
15169 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15170 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15171 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15172 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15173 << (unsigned)MaxAlignChars.getQuantity();
15174 }
15175 }
15176 }
15177}
15178
15179void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15180 // Note that we are no longer parsing the initializer for this declaration.
15181 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15182
15183 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15184 if (!VD)
15185 return;
15186
15187 // Emit any deferred warnings for the variable's initializer, even if the
15188 // variable is invalid
15189 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15190
15191 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15192 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15193 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15194 if (PragmaClangBSSSection.Valid)
15195 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15196 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15197 Range: PragmaClangBSSSection.PragmaLocation));
15198 if (PragmaClangDataSection.Valid)
15199 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15200 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15201 Range: PragmaClangDataSection.PragmaLocation));
15202 if (PragmaClangRodataSection.Valid)
15203 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15204 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15205 Range: PragmaClangRodataSection.PragmaLocation));
15206 if (PragmaClangRelroSection.Valid)
15207 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15208 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15209 Range: PragmaClangRelroSection.PragmaLocation));
15210 }
15211
15212 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15213 for (auto *BD : DD->bindings()) {
15214 FinalizeDeclaration(ThisDecl: BD);
15215 }
15216 }
15217
15218 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15219 K: BuiltinCountedByRefKind::Initializer);
15220
15221 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15222
15223 if (VD->isStaticLocal())
15224 CheckStaticLocalForDllExport(VD);
15225
15226 if (VD->getTLSKind())
15227 CheckThreadLocalForLargeAlignment(VD);
15228
15229 // Perform check for initializers of device-side global variables.
15230 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15231 // 7.5). We must also apply the same checks to all __shared__
15232 // variables whether they are local or not. CUDA also allows
15233 // constant initializers for __constant__ and __device__ variables.
15234 if (getLangOpts().CUDA)
15235 CUDA().checkAllowedInitializer(VD);
15236
15237 // Grab the dllimport or dllexport attribute off of the VarDecl.
15238 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15239
15240 // Imported static data members cannot be defined out-of-line.
15241 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15242 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15243 VD->isThisDeclarationADefinition()) {
15244 // We allow definitions of dllimport class template static data members
15245 // with a warning.
15246 CXXRecordDecl *Context =
15247 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15248 bool IsClassTemplateMember =
15249 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15250 Context->getDescribedClassTemplate();
15251
15252 Diag(Loc: VD->getLocation(),
15253 DiagID: IsClassTemplateMember
15254 ? diag::warn_attribute_dllimport_static_field_definition
15255 : diag::err_attribute_dllimport_static_field_definition);
15256 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15257 if (!IsClassTemplateMember)
15258 VD->setInvalidDecl();
15259 }
15260 }
15261
15262 // dllimport/dllexport variables cannot be thread local, their TLS index
15263 // isn't exported with the variable.
15264 if (DLLAttr && VD->getTLSKind()) {
15265 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15266 if (F && getDLLAttr(D: F)) {
15267 assert(VD->isStaticLocal());
15268 // But if this is a static local in a dlimport/dllexport function, the
15269 // function will never be inlined, which means the var would never be
15270 // imported, so having it marked import/export is safe.
15271 } else {
15272 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15273 << DLLAttr;
15274 VD->setInvalidDecl();
15275 }
15276 }
15277
15278 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15279 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15280 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15281 << Attr;
15282 VD->dropAttr<UsedAttr>();
15283 }
15284 }
15285 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15286 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15287 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15288 << Attr;
15289 VD->dropAttr<RetainAttr>();
15290 }
15291 }
15292
15293 const DeclContext *DC = VD->getDeclContext();
15294 // If there's a #pragma GCC visibility in scope, and this isn't a class
15295 // member, set the visibility of this variable.
15296 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15297 AddPushedVisibilityAttribute(RD: VD);
15298
15299 // FIXME: Warn on unused var template partial specializations.
15300 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15301 MarkUnusedFileScopedDecl(D: VD);
15302
15303 // Now we have parsed the initializer and can update the table of magic
15304 // tag values.
15305 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15306 !VD->getType()->isIntegralOrEnumerationType())
15307 return;
15308
15309 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15310 const Expr *MagicValueExpr = VD->getInit();
15311 if (!MagicValueExpr) {
15312 continue;
15313 }
15314 std::optional<llvm::APSInt> MagicValueInt;
15315 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15316 Diag(Loc: I->getRange().getBegin(),
15317 DiagID: diag::err_type_tag_for_datatype_not_ice)
15318 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15319 continue;
15320 }
15321 if (MagicValueInt->getActiveBits() > 64) {
15322 Diag(Loc: I->getRange().getBegin(),
15323 DiagID: diag::err_type_tag_for_datatype_too_large)
15324 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15325 continue;
15326 }
15327 uint64_t MagicValue = MagicValueInt->getZExtValue();
15328 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15329 MagicValue,
15330 Type: I->getMatchingCType(),
15331 LayoutCompatible: I->getLayoutCompatible(),
15332 MustBeNull: I->getMustBeNull());
15333 }
15334}
15335
15336static bool hasDeducedAuto(DeclaratorDecl *DD) {
15337 auto *VD = dyn_cast<VarDecl>(Val: DD);
15338 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15339}
15340
15341Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15342 ArrayRef<Decl *> Group) {
15343 SmallVector<Decl*, 8> Decls;
15344
15345 if (DS.isTypeSpecOwned())
15346 Decls.push_back(Elt: DS.getRepAsDecl());
15347
15348 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15349 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15350 bool DiagnosedMultipleDecomps = false;
15351 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15352 bool DiagnosedNonDeducedAuto = false;
15353
15354 for (Decl *D : Group) {
15355 if (!D)
15356 continue;
15357 // Check if the Decl has been declared in '#pragma omp declare target'
15358 // directive and has static storage duration.
15359 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15360 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15361 VD->hasGlobalStorage())
15362 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15363 // For declarators, there are some additional syntactic-ish checks we need
15364 // to perform.
15365 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15366 if (!FirstDeclaratorInGroup)
15367 FirstDeclaratorInGroup = DD;
15368 if (!FirstDecompDeclaratorInGroup)
15369 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15370 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15371 !hasDeducedAuto(DD))
15372 FirstNonDeducedAutoInGroup = DD;
15373
15374 if (FirstDeclaratorInGroup != DD) {
15375 // A decomposition declaration cannot be combined with any other
15376 // declaration in the same group.
15377 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15378 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15379 DiagID: diag::err_decomp_decl_not_alone)
15380 << FirstDeclaratorInGroup->getSourceRange()
15381 << DD->getSourceRange();
15382 DiagnosedMultipleDecomps = true;
15383 }
15384
15385 // A declarator that uses 'auto' in any way other than to declare a
15386 // variable with a deduced type cannot be combined with any other
15387 // declarator in the same group.
15388 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15389 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15390 DiagID: diag::err_auto_non_deduced_not_alone)
15391 << FirstNonDeducedAutoInGroup->getType()
15392 ->hasAutoForTrailingReturnType()
15393 << FirstDeclaratorInGroup->getSourceRange()
15394 << DD->getSourceRange();
15395 DiagnosedNonDeducedAuto = true;
15396 }
15397 }
15398 }
15399
15400 Decls.push_back(Elt: D);
15401 }
15402
15403 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15404 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15405 handleTagNumbering(Tag, TagScope: S);
15406 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15407 getLangOpts().CPlusPlus)
15408 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15409 }
15410 }
15411
15412 return BuildDeclaratorGroup(Group: Decls);
15413}
15414
15415Sema::DeclGroupPtrTy
15416Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15417 // C++14 [dcl.spec.auto]p7: (DR1347)
15418 // If the type that replaces the placeholder type is not the same in each
15419 // deduction, the program is ill-formed.
15420 if (Group.size() > 1) {
15421 QualType Deduced;
15422 VarDecl *DeducedDecl = nullptr;
15423 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15424 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15425 if (!D || D->isInvalidDecl())
15426 break;
15427 DeducedType *DT = D->getType()->getContainedDeducedType();
15428 if (!DT || DT->getDeducedType().isNull())
15429 continue;
15430 if (Deduced.isNull()) {
15431 Deduced = DT->getDeducedType();
15432 DeducedDecl = D;
15433 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15434 auto *AT = dyn_cast<AutoType>(Val: DT);
15435 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15436 DiagID: diag::err_auto_different_deductions)
15437 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15438 << DeducedDecl->getDeclName() << DT->getDeducedType()
15439 << D->getDeclName();
15440 if (DeducedDecl->hasInit())
15441 Dia << DeducedDecl->getInit()->getSourceRange();
15442 if (D->getInit())
15443 Dia << D->getInit()->getSourceRange();
15444 D->setInvalidDecl();
15445 break;
15446 }
15447 }
15448 }
15449
15450 ActOnDocumentableDecls(Group);
15451
15452 return DeclGroupPtrTy::make(
15453 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15454}
15455
15456void Sema::ActOnDocumentableDecl(Decl *D) {
15457 ActOnDocumentableDecls(Group: D);
15458}
15459
15460void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15461 // Don't parse the comment if Doxygen diagnostics are ignored.
15462 if (Group.empty() || !Group[0])
15463 return;
15464
15465 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15466 Loc: Group[0]->getLocation()) &&
15467 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15468 Loc: Group[0]->getLocation()))
15469 return;
15470
15471 if (Group.size() >= 2) {
15472 // This is a decl group. Normally it will contain only declarations
15473 // produced from declarator list. But in case we have any definitions or
15474 // additional declaration references:
15475 // 'typedef struct S {} S;'
15476 // 'typedef struct S *S;'
15477 // 'struct S *pS;'
15478 // FinalizeDeclaratorGroup adds these as separate declarations.
15479 Decl *MaybeTagDecl = Group[0];
15480 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15481 Group = Group.slice(N: 1);
15482 }
15483 }
15484
15485 // FIXME: We assume every Decl in the group is in the same file.
15486 // This is false when preprocessor constructs the group from decls in
15487 // different files (e. g. macros or #include).
15488 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15489}
15490
15491void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15492 // Check that there are no default arguments inside the type of this
15493 // parameter.
15494 if (getLangOpts().CPlusPlus)
15495 CheckExtraCXXDefaultArguments(D);
15496
15497 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15498 if (D.getCXXScopeSpec().isSet()) {
15499 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15500 << D.getCXXScopeSpec().getRange();
15501 }
15502
15503 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15504 // simple identifier except [...irrelevant cases...].
15505 switch (D.getName().getKind()) {
15506 case UnqualifiedIdKind::IK_Identifier:
15507 break;
15508
15509 case UnqualifiedIdKind::IK_OperatorFunctionId:
15510 case UnqualifiedIdKind::IK_ConversionFunctionId:
15511 case UnqualifiedIdKind::IK_LiteralOperatorId:
15512 case UnqualifiedIdKind::IK_ConstructorName:
15513 case UnqualifiedIdKind::IK_DestructorName:
15514 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15515 case UnqualifiedIdKind::IK_DeductionGuideName:
15516 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15517 << GetNameForDeclarator(D).getName();
15518 break;
15519
15520 case UnqualifiedIdKind::IK_TemplateId:
15521 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15522 // GetNameForDeclarator would not produce a useful name in this case.
15523 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15524 break;
15525 }
15526}
15527
15528void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15529 // This only matters in C.
15530 if (getLangOpts().CPlusPlus)
15531 return;
15532
15533 // This only matters if the declaration has a type.
15534 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15535 if (!VD)
15536 return;
15537
15538 // Get the type, this only matters for tag types.
15539 QualType QT = VD->getType();
15540 const auto *TD = QT->getAsTagDecl();
15541 if (!TD)
15542 return;
15543
15544 // Check if the tag declaration is lexically declared somewhere different
15545 // from the lexical declaration of the given object, then it will be hidden
15546 // in C++ and we should warn on it.
15547 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15548 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15549 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15550 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15551 }
15552}
15553
15554static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15555 SourceLocation ExplicitThisLoc) {
15556 if (!ExplicitThisLoc.isValid())
15557 return;
15558 assert(S.getLangOpts().CPlusPlus &&
15559 "explicit parameter in non-cplusplus mode");
15560 if (!S.getLangOpts().CPlusPlus23)
15561 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15562 << P->getSourceRange();
15563
15564 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15565 // parameter pack.
15566 if (P->isParameterPack()) {
15567 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15568 << P->getSourceRange();
15569 return;
15570 }
15571 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15572 if (LambdaScopeInfo *LSI = S.getCurLambda())
15573 LSI->ExplicitObjectParameter = P;
15574}
15575
15576Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15577 SourceLocation ExplicitThisLoc) {
15578 const DeclSpec &DS = D.getDeclSpec();
15579
15580 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15581 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15582 // except for the special case of a single unnamed parameter of type void
15583 // with no storage class specifier, no type qualifier, and no following
15584 // ellipsis terminator.
15585 // Clang applies the C2y rules for 'register void' in all C language modes,
15586 // same as GCC, because it's questionable what that could possibly mean.
15587
15588 // C++03 [dcl.stc]p2 also permits 'auto'.
15589 StorageClass SC = SC_None;
15590 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15591 SC = SC_Register;
15592 // In C++11, the 'register' storage class specifier is deprecated.
15593 // In C++17, it is not allowed, but we tolerate it as an extension.
15594 if (getLangOpts().CPlusPlus11) {
15595 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15596 ? diag::ext_register_storage_class
15597 : diag::warn_deprecated_register)
15598 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15599 } else if (!getLangOpts().CPlusPlus &&
15600 DS.getTypeSpecType() == DeclSpec::TST_void &&
15601 D.getNumTypeObjects() == 0) {
15602 Diag(Loc: DS.getStorageClassSpecLoc(),
15603 DiagID: diag::err_invalid_storage_class_in_func_decl)
15604 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15605 D.getMutableDeclSpec().ClearStorageClassSpecs();
15606 }
15607 } else if (getLangOpts().CPlusPlus &&
15608 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15609 SC = SC_Auto;
15610 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15611 Diag(Loc: DS.getStorageClassSpecLoc(),
15612 DiagID: diag::err_invalid_storage_class_in_func_decl);
15613 D.getMutableDeclSpec().ClearStorageClassSpecs();
15614 }
15615
15616 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15617 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15618 << DeclSpec::getSpecifierName(S: TSCS);
15619 if (DS.isInlineSpecified())
15620 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15621 << getLangOpts().CPlusPlus17;
15622 if (DS.hasConstexprSpecifier())
15623 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15624 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15625
15626 DiagnoseFunctionSpecifiers(DS);
15627
15628 CheckFunctionOrTemplateParamDeclarator(S, D);
15629
15630 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15631 QualType parmDeclType = TInfo->getType();
15632
15633 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15634 const IdentifierInfo *II = D.getIdentifier();
15635 if (II) {
15636 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15637 RedeclarationKind::ForVisibleRedeclaration);
15638 LookupName(R, S);
15639 if (!R.empty()) {
15640 NamedDecl *PrevDecl = *R.begin();
15641 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15642 // Maybe we will complain about the shadowed template parameter.
15643 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15644 // Just pretend that we didn't see the previous declaration.
15645 PrevDecl = nullptr;
15646 }
15647 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15648 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15649 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15650 // Recover by removing the name
15651 II = nullptr;
15652 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15653 D.setInvalidType(true);
15654 }
15655 }
15656 }
15657
15658 // Incomplete resource arrays are not allowed as function parameters in HLSL
15659 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15660 parmDeclType->isHLSLResourceRecordArray()) {
15661 Diag(Loc: D.getIdentifierLoc(),
15662 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15663 D.setInvalidType(true);
15664 }
15665
15666 // Temporarily put parameter variables in the translation unit, not
15667 // the enclosing context. This prevents them from accidentally
15668 // looking like class members in C++.
15669 ParmVarDecl *New =
15670 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15671 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15672
15673 if (D.isInvalidType())
15674 New->setInvalidDecl();
15675
15676 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15677
15678 assert(S->isFunctionPrototypeScope());
15679 assert(S->getFunctionPrototypeDepth() >= 1);
15680 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15681 parameterIndex: S->getNextFunctionPrototypeIndex());
15682
15683 warnOnCTypeHiddenInCPlusPlus(D: New);
15684
15685 // Add the parameter declaration into this scope.
15686 S->AddDecl(D: New);
15687 if (II)
15688 IdResolver.AddDecl(D: New);
15689
15690 ProcessDeclAttributes(S, D: New, PD: D);
15691
15692 if (D.getDeclSpec().isModulePrivateSpecified())
15693 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15694 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15695 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15696
15697 if (New->hasAttr<BlocksAttr>()) {
15698 Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal);
15699 }
15700
15701 if (getLangOpts().OpenCL)
15702 deduceOpenCLAddressSpace(Decl: New);
15703
15704 return New;
15705}
15706
15707ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15708 SourceLocation Loc,
15709 QualType T) {
15710 /* FIXME: setting StartLoc == Loc.
15711 Would it be worth to modify callers so as to provide proper source
15712 location for the unnamed parameters, embedding the parameter's type? */
15713 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15714 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15715 S: SC_None, DefArg: nullptr);
15716 Param->setImplicit();
15717 return Param;
15718}
15719
15720void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15721 // Don't diagnose unused-parameter errors in template instantiations; we
15722 // will already have done so in the template itself.
15723 if (inTemplateInstantiation())
15724 return;
15725
15726 for (const ParmVarDecl *Parameter : Parameters) {
15727 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15728 !Parameter->hasAttr<UnusedAttr>() &&
15729 !Parameter->getIdentifier()->isPlaceholder()) {
15730 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15731 << Parameter->getDeclName();
15732 }
15733 }
15734}
15735
15736void Sema::DiagnoseSizeOfParametersAndReturnValue(
15737 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15738 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15739 return;
15740
15741 // Warn if the return value is pass-by-value and larger than the specified
15742 // threshold.
15743 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15744 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15745 if (Size > LangOpts.NumLargeByValueCopy)
15746 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15747 }
15748
15749 // Warn if any parameter is pass-by-value and larger than the specified
15750 // threshold.
15751 for (const ParmVarDecl *Parameter : Parameters) {
15752 QualType T = Parameter->getType();
15753 if (T->isDependentType() || !T.isPODType(Context))
15754 continue;
15755 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15756 if (Size > LangOpts.NumLargeByValueCopy)
15757 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15758 << Parameter << Size;
15759 }
15760}
15761
15762ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15763 SourceLocation NameLoc,
15764 const IdentifierInfo *Name, QualType T,
15765 TypeSourceInfo *TSInfo, StorageClass SC) {
15766 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15767 if (getLangOpts().ObjCAutoRefCount &&
15768 T.getObjCLifetime() == Qualifiers::OCL_None &&
15769 T->isObjCLifetimeType()) {
15770
15771 Qualifiers::ObjCLifetime lifetime;
15772
15773 // Special cases for arrays:
15774 // - if it's const, use __unsafe_unretained
15775 // - otherwise, it's an error
15776 if (T->isArrayType()) {
15777 if (!T.isConstQualified()) {
15778 if (DelayedDiagnostics.shouldDelayDiagnostics())
15779 DelayedDiagnostics.add(
15780 diag: sema::DelayedDiagnostic::makeForbiddenType(
15781 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15782 else
15783 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15784 << TSInfo->getTypeLoc().getSourceRange();
15785 }
15786 lifetime = Qualifiers::OCL_ExplicitNone;
15787 } else {
15788 lifetime = T->getObjCARCImplicitLifetime();
15789 }
15790 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15791 }
15792
15793 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15794 T: Context.getAdjustedParameterType(T),
15795 TInfo: TSInfo, S: SC, DefArg: nullptr);
15796
15797 // Make a note if we created a new pack in the scope of a lambda, so that
15798 // we know that references to that pack must also be expanded within the
15799 // lambda scope.
15800 if (New->isParameterPack())
15801 if (auto *CSI = getEnclosingLambdaOrBlock())
15802 CSI->LocalPacks.push_back(Elt: New);
15803
15804 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15805 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15806 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15807 UseContext: NonTrivialCUnionContext::FunctionParam,
15808 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15809
15810 // Parameter declarators cannot be interface types. All ObjC objects are
15811 // passed by reference.
15812 if (T->isObjCObjectType()) {
15813 SourceLocation TypeEndLoc =
15814 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15815 Diag(Loc: NameLoc,
15816 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15817 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15818 T = Context.getObjCObjectPointerType(OIT: T);
15819 New->setType(T);
15820 }
15821
15822 // __ptrauth is forbidden on parameters.
15823 if (T.getPointerAuth()) {
15824 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15825 New->setInvalidDecl();
15826 }
15827
15828 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15829 // duration shall not be qualified by an address-space qualifier."
15830 // Since all parameters have automatic store duration, they can not have
15831 // an address space.
15832 if (T.getAddressSpace() != LangAS::Default &&
15833 // OpenCL allows function arguments declared to be an array of a type
15834 // to be qualified with an address space.
15835 !(getLangOpts().OpenCL &&
15836 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15837 // WebAssembly allows reference types as parameters. Funcref in particular
15838 // lives in a different address space.
15839 !(T->isFunctionPointerType() &&
15840 T.getAddressSpace() == LangAS::wasm_funcref)) {
15841 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15842 New->setInvalidDecl();
15843 }
15844
15845 // PPC MMA non-pointer types are not allowed as function argument types.
15846 if (Context.getTargetInfo().getTriple().isPPC64() &&
15847 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15848 New->setInvalidDecl();
15849 }
15850
15851 return New;
15852}
15853
15854void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15855 SourceLocation LocAfterDecls) {
15856 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15857
15858 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15859 // in the declaration list shall have at least one declarator, those
15860 // declarators shall only declare identifiers from the identifier list, and
15861 // every identifier in the identifier list shall be declared.
15862 //
15863 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15864 // identifiers it names shall be declared in the declaration list."
15865 //
15866 // This is why we only diagnose in C99 and later. Note, the other conditions
15867 // listed are checked elsewhere.
15868 if (!FTI.hasPrototype) {
15869 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15870 --i;
15871 if (FTI.Params[i].Param == nullptr) {
15872 if (getLangOpts().C99) {
15873 SmallString<256> Code;
15874 llvm::raw_svector_ostream(Code)
15875 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15876 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
15877 << FTI.Params[i].Ident
15878 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
15879 }
15880
15881 // Implicitly declare the argument as type 'int' for lack of a better
15882 // type.
15883 AttributeFactory attrs;
15884 DeclSpec DS(attrs);
15885 const char* PrevSpec; // unused
15886 unsigned DiagID; // unused
15887 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15888 DiagID, Policy: Context.getPrintingPolicy());
15889 // Use the identifier location for the type source range.
15890 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15891 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15892 Declarator ParamD(DS, ParsedAttributesView::none(),
15893 DeclaratorContext::KNRTypeList);
15894 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15895 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15896 }
15897 }
15898 }
15899}
15900
15901Decl *
15902Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15903 MultiTemplateParamsArg TemplateParameterLists,
15904 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15905 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15906 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15907 Scope *ParentScope = FnBodyScope->getParent();
15908
15909 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15910 // we define a non-templated function definition, we will create a declaration
15911 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15912 // The base function declaration will have the equivalent of an `omp declare
15913 // variant` annotation which specifies the mangled definition as a
15914 // specialization function under the OpenMP context defined as part of the
15915 // `omp begin declare variant`.
15916 SmallVector<FunctionDecl *, 4> Bases;
15917 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15918 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15919 S: ParentScope, D, TemplateParameterLists, Bases);
15920
15921 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15922 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15923 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15924
15925 if (!Bases.empty())
15926 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15927 Bases);
15928
15929 return Dcl;
15930}
15931
15932void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15933 Consumer.HandleInlineFunctionDefinition(D);
15934}
15935
15936static bool FindPossiblePrototype(const FunctionDecl *FD,
15937 const FunctionDecl *&PossiblePrototype) {
15938 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15939 Prev = Prev->getPreviousDecl()) {
15940 // Ignore any declarations that occur in function or method
15941 // scope, because they aren't visible from the header.
15942 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15943 continue;
15944
15945 PossiblePrototype = Prev;
15946 return Prev->getType()->isFunctionProtoType();
15947 }
15948 return false;
15949}
15950
15951static bool
15952ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15953 const FunctionDecl *&PossiblePrototype) {
15954 // Don't warn about invalid declarations.
15955 if (FD->isInvalidDecl())
15956 return false;
15957
15958 // Or declarations that aren't global.
15959 if (!FD->isGlobal())
15960 return false;
15961
15962 // Don't warn about C++ member functions.
15963 if (isa<CXXMethodDecl>(Val: FD))
15964 return false;
15965
15966 // Don't warn about 'main'.
15967 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
15968 if (IdentifierInfo *II = FD->getIdentifier())
15969 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15970 return false;
15971
15972 if (FD->isMSVCRTEntryPoint())
15973 return false;
15974
15975 // Don't warn about inline functions.
15976 if (FD->isInlined())
15977 return false;
15978
15979 // Don't warn about function templates.
15980 if (FD->getDescribedFunctionTemplate())
15981 return false;
15982
15983 // Don't warn about function template specializations.
15984 if (FD->isFunctionTemplateSpecialization())
15985 return false;
15986
15987 // Don't warn for OpenCL kernels.
15988 if (FD->hasAttr<DeviceKernelAttr>())
15989 return false;
15990
15991 // Don't warn on explicitly deleted functions.
15992 if (FD->isDeleted())
15993 return false;
15994
15995 // Don't warn on implicitly local functions (such as having local-typed
15996 // parameters).
15997 if (!FD->isExternallyVisible())
15998 return false;
15999
16000 // If we were able to find a potential prototype, don't warn.
16001 if (FindPossiblePrototype(FD, PossiblePrototype))
16002 return false;
16003
16004 return true;
16005}
16006
16007void
16008Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16009 const FunctionDecl *EffectiveDefinition,
16010 SkipBodyInfo *SkipBody) {
16011 const FunctionDecl *Definition = EffectiveDefinition;
16012 if (!Definition &&
16013 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16014 return;
16015
16016 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16017 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16018 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16019 // A merged copy of the same function, instantiated as a member of
16020 // the same class, is OK.
16021 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16022 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16023 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16024 return;
16025 }
16026 }
16027 }
16028
16029 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16030 return;
16031
16032 // Don't emit an error when this is redefinition of a typo-corrected
16033 // definition.
16034 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16035 return;
16036
16037 bool DefinitionVisible = false;
16038 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16039 (Definition->getFormalLinkage() == Linkage::Internal ||
16040 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16041 Definition->getNumTemplateParameterLists())) {
16042 SkipBody->ShouldSkip = true;
16043 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16044 if (!DefinitionVisible) {
16045 if (auto *TD = Definition->getDescribedFunctionTemplate())
16046 makeMergedDefinitionVisible(ND: TD);
16047 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16048 }
16049 return;
16050 }
16051
16052 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16053 Definition->getStorageClass() == SC_Extern)
16054 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16055 << FD << getLangOpts().CPlusPlus;
16056 else
16057 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16058
16059 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16060 FD->setInvalidDecl();
16061}
16062
16063LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16064 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16065
16066 LambdaScopeInfo *LSI = PushLambdaScope();
16067 LSI->CallOperator = CallOperator;
16068 LSI->Lambda = LambdaClass;
16069 LSI->ReturnType = CallOperator->getReturnType();
16070 // When this function is called in situation where the context of the call
16071 // operator is not entered, we set AfterParameterList to false, so that
16072 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16073 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16074 // where we would set the CurContext to the lambda operator before
16075 // substituting into it. In this case the flag needs to be true such that
16076 // tryCaptureVariable can correctly handle potential captures thereof.
16077 LSI->AfterParameterList = CurContext == CallOperator;
16078
16079 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16080 // used at the point of dealing with potential captures.
16081 //
16082 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16083 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16084 // associated. (Technically, we could recover that list from their
16085 // instantiation patterns, but for now, the GLTemplateParameterList seems
16086 // unnecessary in these cases.)
16087 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16088 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16089 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16090
16091 if (LCD == LCD_None)
16092 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16093 else if (LCD == LCD_ByCopy)
16094 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16095 else if (LCD == LCD_ByRef)
16096 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16097 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16098
16099 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16100 LSI->Mutable = !CallOperator->isConst();
16101 if (CallOperator->isExplicitObjectMemberFunction())
16102 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16103
16104 // Add the captures to the LSI so they can be noted as already
16105 // captured within tryCaptureVar.
16106 auto I = LambdaClass->field_begin();
16107 for (const auto &C : LambdaClass->captures()) {
16108 if (C.capturesVariable()) {
16109 ValueDecl *VD = C.getCapturedVar();
16110 if (VD->isInitCapture())
16111 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16112 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16113 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16114 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16115 /*EllipsisLoc*/C.isPackExpansion()
16116 ? C.getEllipsisLoc() : SourceLocation(),
16117 CaptureType: I->getType(), /*Invalid*/false);
16118
16119 } else if (C.capturesThis()) {
16120 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16121 ByCopy: C.getCaptureKind() == LCK_StarThis);
16122 } else {
16123 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16124 CaptureType: I->getType());
16125 }
16126 ++I;
16127 }
16128 return LSI;
16129}
16130
16131Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16132 SkipBodyInfo *SkipBody,
16133 FnBodyKind BodyKind) {
16134 if (!D) {
16135 // Parsing the function declaration failed in some way. Push on a fake scope
16136 // anyway so we can try to parse the function body.
16137 PushFunctionScope();
16138 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16139 return D;
16140 }
16141
16142 FunctionDecl *FD = nullptr;
16143
16144 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16145 FD = FunTmpl->getTemplatedDecl();
16146 else
16147 FD = cast<FunctionDecl>(Val: D);
16148
16149 // Do not push if it is a lambda because one is already pushed when building
16150 // the lambda in ActOnStartOfLambdaDefinition().
16151 if (!isLambdaCallOperator(DC: FD))
16152 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16153 FD);
16154
16155 // Check for defining attributes before the check for redefinition.
16156 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16157 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16158 FD->dropAttr<AliasAttr>();
16159 FD->setInvalidDecl();
16160 }
16161 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16162 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16163 FD->dropAttr<IFuncAttr>();
16164 FD->setInvalidDecl();
16165 }
16166 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16167 if (Context.getTargetInfo().getTriple().isAArch64() &&
16168 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16169 !Attr->isDefaultVersion()) {
16170 // If function multi versioning disabled skip parsing function body
16171 // defined with non-default target_version attribute
16172 if (SkipBody)
16173 SkipBody->ShouldSkip = true;
16174 return nullptr;
16175 }
16176 }
16177
16178 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16179 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16180 Ctor->isDefaultConstructor() &&
16181 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16182 // If this is an MS ABI dllexport default constructor, instantiate any
16183 // default arguments.
16184 InstantiateDefaultCtorDefaultArgs(Ctor);
16185 }
16186 }
16187
16188 // See if this is a redefinition. If 'will have body' (or similar) is already
16189 // set, then these checks were already performed when it was set.
16190 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16191 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16192 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16193
16194 // If we're skipping the body, we're done. Don't enter the scope.
16195 if (SkipBody && SkipBody->ShouldSkip)
16196 return D;
16197 }
16198
16199 // Mark this function as "will have a body eventually". This lets users to
16200 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16201 // this function.
16202 FD->setWillHaveBody();
16203
16204 // If we are instantiating a generic lambda call operator, push
16205 // a LambdaScopeInfo onto the function stack. But use the information
16206 // that's already been calculated (ActOnLambdaExpr) to prime the current
16207 // LambdaScopeInfo.
16208 // When the template operator is being specialized, the LambdaScopeInfo,
16209 // has to be properly restored so that tryCaptureVariable doesn't try
16210 // and capture any new variables. In addition when calculating potential
16211 // captures during transformation of nested lambdas, it is necessary to
16212 // have the LSI properly restored.
16213 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16214 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16215 // instantiated, explicitly specialized.
16216 if (FD->getTemplateSpecializationInfo()
16217 ->isExplicitInstantiationOrSpecialization()) {
16218 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec);
16219 FD->setInvalidDecl();
16220 PushFunctionScope();
16221 } else {
16222 assert(inTemplateInstantiation() &&
16223 "There should be an active template instantiation on the stack "
16224 "when instantiating a generic lambda!");
16225 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16226 }
16227 } else {
16228 // Enter a new function scope
16229 PushFunctionScope();
16230 }
16231
16232 // Builtin functions cannot be defined.
16233 if (unsigned BuiltinID = FD->getBuiltinID()) {
16234 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16235 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16236 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16237 FD->setInvalidDecl();
16238 }
16239 }
16240
16241 // The return type of a function definition must be complete (C99 6.9.1p3).
16242 // C++23 [dcl.fct.def.general]/p2
16243 // The type of [...] the return for a function definition
16244 // shall not be a (possibly cv-qualified) class type that is incomplete
16245 // or abstract within the function body unless the function is deleted.
16246 QualType ResultType = FD->getReturnType();
16247 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16248 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16249 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16250 DiagID: diag::err_func_def_incomplete_result) ||
16251 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16252 DiagID: diag::err_abstract_type_in_decl,
16253 Args: AbstractReturnType)))
16254 FD->setInvalidDecl();
16255
16256 if (FnBodyScope)
16257 PushDeclContext(S: FnBodyScope, DC: FD);
16258
16259 // Check the validity of our function parameters
16260 if (BodyKind != FnBodyKind::Delete)
16261 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16262 /*CheckParameterNames=*/true);
16263
16264 // Add non-parameter declarations already in the function to the current
16265 // scope.
16266 if (FnBodyScope) {
16267 for (Decl *NPD : FD->decls()) {
16268 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16269 if (!NonParmDecl)
16270 continue;
16271 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16272 "parameters should not be in newly created FD yet");
16273
16274 // If the decl has a name, make it accessible in the current scope.
16275 if (NonParmDecl->getDeclName())
16276 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16277
16278 // Similarly, dive into enums and fish their constants out, making them
16279 // accessible in this scope.
16280 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16281 for (auto *EI : ED->enumerators())
16282 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16283 }
16284 }
16285 }
16286
16287 // Introduce our parameters into the function scope
16288 for (auto *Param : FD->parameters()) {
16289 Param->setOwningFunction(FD);
16290
16291 // If this has an identifier, add it to the scope stack.
16292 if (Param->getIdentifier() && FnBodyScope) {
16293 CheckShadow(S: FnBodyScope, D: Param);
16294
16295 PushOnScopeChains(D: Param, S: FnBodyScope);
16296 }
16297 }
16298
16299 // C++ [module.import/6]
16300 // ...
16301 // A header unit shall not contain a definition of a non-inline function or
16302 // variable whose name has external linkage.
16303 //
16304 // Deleted and Defaulted functions are implicitly inline (but the
16305 // inline state is not set at this point, so check the BodyKind explicitly).
16306 // We choose to allow weak & selectany definitions, as they are common in
16307 // headers, and have semantics similar to inline definitions which are allowed
16308 // in header units.
16309 // FIXME: Consider an alternate location for the test where the inlined()
16310 // state is complete.
16311 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16312 !FD->isInvalidDecl() && !FD->isInlined() &&
16313 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16314 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16315 !FD->isTemplateInstantiation() &&
16316 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16317 assert(FD->isThisDeclarationADefinition());
16318 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16319 FD->setInvalidDecl();
16320 }
16321
16322 // Ensure that the function's exception specification is instantiated.
16323 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16324 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16325
16326 // dllimport cannot be applied to non-inline function definitions.
16327 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16328 !FD->isTemplateInstantiation()) {
16329 assert(!FD->hasAttr<DLLExportAttr>());
16330 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16331 FD->setInvalidDecl();
16332 return D;
16333 }
16334
16335 // Some function attributes (like OptimizeNoneAttr) need actions before
16336 // parsing body started.
16337 applyFunctionAttributesBeforeParsingBody(FD: D);
16338
16339 // We want to attach documentation to original Decl (which might be
16340 // a function template).
16341 ActOnDocumentableDecl(D);
16342 if (getCurLexicalContext()->isObjCContainer() &&
16343 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16344 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16345 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16346
16347 maybeAddDeclWithEffects(D: FD);
16348
16349 return D;
16350}
16351
16352void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16353 if (!FD || FD->isInvalidDecl())
16354 return;
16355 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16356 FD = TD->getTemplatedDecl();
16357 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16358 FPOptionsOverride FPO;
16359 FPO.setDisallowOptimizations();
16360 CurFPFeatures.applyChanges(FPO);
16361 FpPragmaStack.CurrentValue =
16362 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16363 }
16364}
16365
16366void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16367 ReturnStmt **Returns = Scope->Returns.data();
16368
16369 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16370 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16371 if (!NRVOCandidate->isNRVOVariable()) {
16372 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16373 DiagID: diag::warn_not_eliding_copy_on_return);
16374 Returns[I]->setNRVOCandidate(nullptr);
16375 }
16376 }
16377 }
16378}
16379
16380bool Sema::canDelayFunctionBody(const Declarator &D) {
16381 // We can't delay parsing the body of a constexpr function template (yet).
16382 if (D.getDeclSpec().hasConstexprSpecifier())
16383 return false;
16384
16385 // We can't delay parsing the body of a function template with a deduced
16386 // return type (yet).
16387 if (D.getDeclSpec().hasAutoTypeSpec()) {
16388 // If the placeholder introduces a non-deduced trailing return type,
16389 // we can still delay parsing it.
16390 if (D.getNumTypeObjects()) {
16391 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16392 if (Outer.Kind == DeclaratorChunk::Function &&
16393 Outer.Fun.hasTrailingReturnType()) {
16394 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16395 return Ty.isNull() || !Ty->isUndeducedType();
16396 }
16397 }
16398 return false;
16399 }
16400
16401 return true;
16402}
16403
16404bool Sema::canSkipFunctionBody(Decl *D) {
16405 // We cannot skip the body of a function (or function template) which is
16406 // constexpr, since we may need to evaluate its body in order to parse the
16407 // rest of the file.
16408 // We cannot skip the body of a function with an undeduced return type,
16409 // because any callers of that function need to know the type.
16410 if (const FunctionDecl *FD = D->getAsFunction()) {
16411 if (FD->isConstexpr())
16412 return false;
16413 // We can't simply call Type::isUndeducedType here, because inside template
16414 // auto can be deduced to a dependent type, which is not considered
16415 // "undeduced".
16416 if (FD->getReturnType()->getContainedDeducedType())
16417 return false;
16418 }
16419 return Consumer.shouldSkipFunctionBody(D);
16420}
16421
16422Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16423 if (!Decl)
16424 return nullptr;
16425 if (FunctionDecl *FD = Decl->getAsFunction())
16426 FD->setHasSkippedBody();
16427 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16428 MD->setHasSkippedBody();
16429 return Decl;
16430}
16431
16432/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16433/// body.
16434class ExitFunctionBodyRAII {
16435public:
16436 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16437 ~ExitFunctionBodyRAII() {
16438 if (!IsLambda)
16439 S.PopExpressionEvaluationContext();
16440 }
16441
16442private:
16443 Sema &S;
16444 bool IsLambda = false;
16445};
16446
16447static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16448 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16449
16450 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16451 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16452 if (!Inserted)
16453 return It->second;
16454
16455 bool R = false;
16456 const BlockDecl *CurBD = BD;
16457
16458 do {
16459 R = !CurBD->doesNotEscape();
16460 if (R)
16461 break;
16462 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16463 } while (CurBD);
16464
16465 return It->second = R;
16466 };
16467
16468 // If the location where 'self' is implicitly retained is inside a escaping
16469 // block, emit a diagnostic.
16470 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16471 S.ImplicitlyRetainedSelfLocs)
16472 if (IsOrNestedInEscapingBlock(P.second))
16473 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16474 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16475}
16476
16477static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16478 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16479 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16480}
16481
16482bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16483 return methodHasName(FD, Name: "get_return_object");
16484}
16485
16486bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16487 return FD->isStatic() &&
16488 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16489}
16490
16491void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16492 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16493 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16494 return;
16495 // Allow some_promise_type::get_return_object().
16496 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16497 return;
16498 if (!FD->hasAttr<CoroWrapperAttr>())
16499 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16500}
16501
16502Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16503 bool RetainFunctionScopeInfo) {
16504 FunctionScopeInfo *FSI = getCurFunction();
16505 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16506
16507 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16508 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16509
16510 SourceLocation AnalysisLoc;
16511 if (Body)
16512 AnalysisLoc = Body->getEndLoc();
16513 else if (FD)
16514 AnalysisLoc = FD->getEndLoc();
16515 sema::AnalysisBasedWarnings::Policy WP =
16516 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16517 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16518
16519 // If we skip function body, we can't tell if a function is a coroutine.
16520 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16521 if (FSI->isCoroutine())
16522 CheckCompletedCoroutineBody(FD, Body);
16523 else
16524 CheckCoroutineWrapper(FD);
16525 }
16526
16527 // Diagnose invalid SYCL kernel entry point function declarations
16528 // and build SYCLKernelCallStmts for valid ones.
16529 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16530 SYCLKernelEntryPointAttr *SKEPAttr =
16531 FD->getAttr<SYCLKernelEntryPointAttr>();
16532 if (FD->isDefaulted()) {
16533 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16534 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16535 SKEPAttr->setInvalidAttr();
16536 } else if (FD->isDeleted()) {
16537 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16538 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16539 SKEPAttr->setInvalidAttr();
16540 } else if (FSI->isCoroutine()) {
16541 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16542 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16543 SKEPAttr->setInvalidAttr();
16544 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16545 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16546 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16547 SKEPAttr->setInvalidAttr();
16548 }
16549
16550 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16551 StmtResult SR =
16552 SYCL().BuildSYCLKernelCallStmt(FD, Body: cast<CompoundStmt>(Val: Body));
16553 if (SR.isInvalid())
16554 return nullptr;
16555 Body = SR.get();
16556 }
16557 }
16558
16559 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16560 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16561 if (FD->isDeletedAsWritten())
16562 Diag(Loc: SEAttr->getLocation(),
16563 DiagID: diag::err_sycl_external_invalid_deleted_function)
16564 << SEAttr;
16565 }
16566
16567 {
16568 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16569 // one is already popped when finishing the lambda in BuildLambdaExpr().
16570 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16571 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16572 if (FD) {
16573 // The function body and the DefaultedOrDeletedInfo, if present, use
16574 // the same storage; don't overwrite the latter if the former is null
16575 // (the body is initialised to null anyway, so even if the latter isn't
16576 // present, this would still be a no-op).
16577 if (Body)
16578 FD->setBody(Body);
16579 FD->setWillHaveBody(false);
16580
16581 if (getLangOpts().CPlusPlus14) {
16582 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16583 FD->getReturnType()->isUndeducedType()) {
16584 // For a function with a deduced result type to return void,
16585 // the result type as written must be 'auto' or 'decltype(auto)',
16586 // possibly cv-qualified or constrained, but not ref-qualified.
16587 if (!FD->getReturnType()->getAs<AutoType>()) {
16588 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16589 << FD->getReturnType();
16590 FD->setInvalidDecl();
16591 } else {
16592 // Falling off the end of the function is the same as 'return;'.
16593 Expr *Dummy = nullptr;
16594 if (DeduceFunctionTypeFromReturnExpr(
16595 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16596 AT: FD->getReturnType()->getAs<AutoType>()))
16597 FD->setInvalidDecl();
16598 }
16599 }
16600 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16601 // In C++11, we don't use 'auto' deduction rules for lambda call
16602 // operators because we don't support return type deduction.
16603 auto *LSI = getCurLambda();
16604 if (LSI->HasImplicitReturnType) {
16605 deduceClosureReturnType(CSI&: *LSI);
16606
16607 // C++11 [expr.prim.lambda]p4:
16608 // [...] if there are no return statements in the compound-statement
16609 // [the deduced type is] the type void
16610 QualType RetType =
16611 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16612
16613 // Update the return type to the deduced type.
16614 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16615 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16616 EPI: Proto->getExtProtoInfo()));
16617 }
16618 }
16619
16620 // If the function implicitly returns zero (like 'main') or is naked,
16621 // don't complain about missing return statements.
16622 // Clang implicitly returns 0 in C89 mode, but that's considered an
16623 // extension. The check is necessary to ensure the expected extension
16624 // warning is emitted in C89 mode.
16625 if ((FD->hasImplicitReturnZero() &&
16626 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16627 FD->hasAttr<NakedAttr>())
16628 WP.disableCheckFallThrough();
16629
16630 // MSVC permits the use of pure specifier (=0) on function definition,
16631 // defined at class scope, warn about this non-standard construct.
16632 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16633 !FD->isOutOfLine())
16634 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16635
16636 if (!FD->isInvalidDecl()) {
16637 // Don't diagnose unused parameters of defaulted, deleted or naked
16638 // functions.
16639 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16640 !FD->hasAttr<NakedAttr>())
16641 DiagnoseUnusedParameters(Parameters: FD->parameters());
16642 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16643 ReturnTy: FD->getReturnType(), D: FD);
16644
16645 // If this is a structor, we need a vtable.
16646 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16647 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16648 else if (CXXDestructorDecl *Destructor =
16649 dyn_cast<CXXDestructorDecl>(Val: FD))
16650 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16651
16652 // Try to apply the named return value optimization. We have to check
16653 // if we can do this here because lambdas keep return statements around
16654 // to deduce an implicit return type.
16655 if (FD->getReturnType()->isRecordType() &&
16656 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16657 computeNRVO(Body, Scope: FSI);
16658 }
16659
16660 // GNU warning -Wmissing-prototypes:
16661 // Warn if a global function is defined without a previous
16662 // prototype declaration. This warning is issued even if the
16663 // definition itself provides a prototype. The aim is to detect
16664 // global functions that fail to be declared in header files.
16665 const FunctionDecl *PossiblePrototype = nullptr;
16666 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16667 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16668
16669 if (PossiblePrototype) {
16670 // We found a declaration that is not a prototype,
16671 // but that could be a zero-parameter prototype
16672 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16673 TypeLoc TL = TI->getTypeLoc();
16674 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16675 Diag(Loc: PossiblePrototype->getLocation(),
16676 DiagID: diag::note_declaration_not_a_prototype)
16677 << (FD->getNumParams() != 0)
16678 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16679 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16680 : FixItHint{});
16681 }
16682 } else {
16683 // Returns true if the token beginning at this Loc is `const`.
16684 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16685 const LangOptions &LangOpts) {
16686 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16687 if (LocInfo.first.isInvalid())
16688 return false;
16689
16690 bool Invalid = false;
16691 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16692 if (Invalid)
16693 return false;
16694
16695 if (LocInfo.second > Buffer.size())
16696 return false;
16697
16698 const char *LexStart = Buffer.data() + LocInfo.second;
16699 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16700
16701 return StartTok.consume_front(Prefix: "const") &&
16702 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16703 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16704 };
16705
16706 auto findBeginLoc = [&]() {
16707 // If the return type has `const` qualifier, we want to insert
16708 // `static` before `const` (and not before the typename).
16709 if ((FD->getReturnType()->isAnyPointerType() &&
16710 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16711 FD->getReturnType().isConstQualified()) {
16712 // But only do this if we can determine where the `const` is.
16713
16714 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16715 getLangOpts()))
16716
16717 return FD->getBeginLoc();
16718 }
16719 return FD->getTypeSpecStartLoc();
16720 };
16721 Diag(Loc: FD->getTypeSpecStartLoc(),
16722 DiagID: diag::note_static_for_internal_linkage)
16723 << /* function */ 1
16724 << (FD->getStorageClass() == SC_None
16725 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16726 : FixItHint{});
16727 }
16728 }
16729
16730 // We might not have found a prototype because we didn't wish to warn on
16731 // the lack of a missing prototype. Try again without the checks for
16732 // whether we want to warn on the missing prototype.
16733 if (!PossiblePrototype)
16734 (void)FindPossiblePrototype(FD, PossiblePrototype);
16735
16736 // If the function being defined does not have a prototype, then we may
16737 // need to diagnose it as changing behavior in C23 because we now know
16738 // whether the function accepts arguments or not. This only handles the
16739 // case where the definition has no prototype but does have parameters
16740 // and either there is no previous potential prototype, or the previous
16741 // potential prototype also has no actual prototype. This handles cases
16742 // like:
16743 // void f(); void f(a) int a; {}
16744 // void g(a) int a; {}
16745 // See MergeFunctionDecl() for other cases of the behavior change
16746 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16747 // type without a prototype.
16748 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16749 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16750 !PossiblePrototype->isImplicit()))) {
16751 // The function definition has parameters, so this will change behavior
16752 // in C23. If there is a possible prototype, it comes before the
16753 // function definition.
16754 // FIXME: The declaration may have already been diagnosed as being
16755 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16756 // there's no way to test for the "changes behavior" condition in
16757 // SemaType.cpp when forming the declaration's function type. So, we do
16758 // this awkward dance instead.
16759 //
16760 // If we have a possible prototype and it declares a function with a
16761 // prototype, we don't want to diagnose it; if we have a possible
16762 // prototype and it has no prototype, it may have already been
16763 // diagnosed in SemaType.cpp as deprecated depending on whether
16764 // -Wstrict-prototypes is enabled. If we already warned about it being
16765 // deprecated, add a note that it also changes behavior. If we didn't
16766 // warn about it being deprecated (because the diagnostic is not
16767 // enabled), warn now that it is deprecated and changes behavior.
16768
16769 // This K&R C function definition definitely changes behavior in C23,
16770 // so diagnose it.
16771 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16772 << /*definition*/ 1 << /* not supported in C23 */ 0;
16773
16774 // If we have a possible prototype for the function which is a user-
16775 // visible declaration, we already tested that it has no prototype.
16776 // This will change behavior in C23. This gets a warning rather than a
16777 // note because it's the same behavior-changing problem as with the
16778 // definition.
16779 if (PossiblePrototype)
16780 Diag(Loc: PossiblePrototype->getLocation(),
16781 DiagID: diag::warn_non_prototype_changes_behavior)
16782 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16783 << /*definition*/ 1;
16784 }
16785
16786 // Warn on CPUDispatch with an actual body.
16787 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16788 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16789 if (!CmpndBody->body_empty())
16790 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16791 DiagID: diag::warn_dispatch_body_ignored);
16792
16793 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16794 const CXXMethodDecl *KeyFunction;
16795 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16796 MD->isVirtual() &&
16797 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16798 MD == KeyFunction->getCanonicalDecl()) {
16799 // Update the key-function state if necessary for this ABI.
16800 if (FD->isInlined() &&
16801 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16802 Context.setNonKeyFunction(MD);
16803
16804 // If the newly-chosen key function is already defined, then we
16805 // need to mark the vtable as used retroactively.
16806 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16807 const FunctionDecl *Definition;
16808 if (KeyFunction && KeyFunction->isDefined(Definition))
16809 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16810 } else {
16811 // We just defined they key function; mark the vtable as used.
16812 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16813 }
16814 }
16815 }
16816
16817 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16818 "Function parsing confused");
16819 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16820 assert(MD == getCurMethodDecl() && "Method parsing confused");
16821 MD->setBody(Body);
16822 if (!MD->isInvalidDecl()) {
16823 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
16824 ReturnTy: MD->getReturnType(), D: MD);
16825
16826 if (Body)
16827 computeNRVO(Body, Scope: FSI);
16828 }
16829 if (FSI->ObjCShouldCallSuper) {
16830 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
16831 << MD->getSelector().getAsString();
16832 FSI->ObjCShouldCallSuper = false;
16833 }
16834 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16835 const ObjCMethodDecl *InitMethod = nullptr;
16836 bool isDesignated =
16837 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16838 assert(isDesignated && InitMethod);
16839 (void)isDesignated;
16840
16841 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16842 auto IFace = MD->getClassInterface();
16843 if (!IFace)
16844 return false;
16845 auto SuperD = IFace->getSuperClass();
16846 if (!SuperD)
16847 return false;
16848 return SuperD->getIdentifier() ==
16849 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
16850 };
16851 // Don't issue this warning for unavailable inits or direct subclasses
16852 // of NSObject.
16853 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16854 Diag(Loc: MD->getLocation(),
16855 DiagID: diag::warn_objc_designated_init_missing_super_call);
16856 Diag(Loc: InitMethod->getLocation(),
16857 DiagID: diag::note_objc_designated_init_marked_here);
16858 }
16859 FSI->ObjCWarnForNoDesignatedInitChain = false;
16860 }
16861 if (FSI->ObjCWarnForNoInitDelegation) {
16862 // Don't issue this warning for unavailable inits.
16863 if (!MD->isUnavailable())
16864 Diag(Loc: MD->getLocation(),
16865 DiagID: diag::warn_objc_secondary_init_missing_init_call);
16866 FSI->ObjCWarnForNoInitDelegation = false;
16867 }
16868
16869 diagnoseImplicitlyRetainedSelf(S&: *this);
16870 } else {
16871 // Parsing the function declaration failed in some way. Pop the fake scope
16872 // we pushed on.
16873 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16874 return nullptr;
16875 }
16876
16877 if (Body && FSI->HasPotentialAvailabilityViolations)
16878 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16879
16880 assert(!FSI->ObjCShouldCallSuper &&
16881 "This should only be set for ObjC methods, which should have been "
16882 "handled in the block above.");
16883
16884 // Verify and clean out per-function state.
16885 if (Body && (!FD || !FD->isDefaulted())) {
16886 // C++ constructors that have function-try-blocks can't have return
16887 // statements in the handlers of that block. (C++ [except.handle]p14)
16888 // Verify this.
16889 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16890 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16891
16892 // Verify that gotos and switch cases don't jump into scopes illegally.
16893 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16894 DiagnoseInvalidJumps(Body);
16895
16896 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16897 if (!Destructor->getParent()->isDependentType())
16898 CheckDestructor(Destructor);
16899
16900 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16901 Record: Destructor->getParent());
16902 }
16903
16904 // If any errors have occurred, clear out any temporaries that may have
16905 // been leftover. This ensures that these temporaries won't be picked up
16906 // for deletion in some later function.
16907 if (hasUncompilableErrorOccurred() ||
16908 hasAnyUnrecoverableErrorsInThisFunction() ||
16909 getDiagnostics().getSuppressAllDiagnostics()) {
16910 DiscardCleanupsInEvaluationContext();
16911 }
16912 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16913 // Since the body is valid, issue any analysis-based warnings that are
16914 // enabled.
16915 ActivePolicy = &WP;
16916 }
16917
16918 if (!IsInstantiation && FD &&
16919 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16920 !FD->isInvalidDecl() &&
16921 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
16922 FD->setInvalidDecl();
16923
16924 if (FD && FD->hasAttr<NakedAttr>()) {
16925 for (const Stmt *S : Body->children()) {
16926 // Allow local register variables without initializer as they don't
16927 // require prologue.
16928 bool RegisterVariables = false;
16929 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16930 for (const auto *Decl : DS->decls()) {
16931 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16932 RegisterVariables =
16933 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16934 if (!RegisterVariables)
16935 break;
16936 }
16937 }
16938 }
16939 if (RegisterVariables)
16940 continue;
16941 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16942 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
16943 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
16944 FD->setInvalidDecl();
16945 break;
16946 }
16947 }
16948 }
16949
16950 assert(ExprCleanupObjects.size() ==
16951 ExprEvalContexts.back().NumCleanupObjects &&
16952 "Leftover temporaries in function");
16953 assert(!Cleanup.exprNeedsCleanups() &&
16954 "Unaccounted cleanups in function");
16955 assert(MaybeODRUseExprs.empty() &&
16956 "Leftover expressions for odr-use checking");
16957 }
16958 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16959 // the declaration context below. Otherwise, we're unable to transform
16960 // 'this' expressions when transforming immediate context functions.
16961
16962 if (FD)
16963 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
16964
16965 if (!IsInstantiation)
16966 PopDeclContext();
16967
16968 if (!RetainFunctionScopeInfo)
16969 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16970 // If any errors have occurred, clear out any temporaries that may have
16971 // been leftover. This ensures that these temporaries won't be picked up for
16972 // deletion in some later function.
16973 if (hasUncompilableErrorOccurred()) {
16974 DiscardCleanupsInEvaluationContext();
16975 }
16976
16977 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16978 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16979 auto ES = getEmissionStatus(Decl: FD);
16980 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16981 ES == Sema::FunctionEmissionStatus::Unknown)
16982 DeclsToCheckForDeferredDiags.insert(X: FD);
16983 }
16984
16985 if (FD && !FD->isDeleted())
16986 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16987
16988 return dcl;
16989}
16990
16991/// When we finish delayed parsing of an attribute, we must attach it to the
16992/// relevant Decl.
16993void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16994 ParsedAttributes &Attrs) {
16995 // Always attach attributes to the underlying decl.
16996 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
16997 D = TD->getTemplatedDecl();
16998 ProcessDeclAttributeList(S, D, AttrList: Attrs);
16999 ProcessAPINotes(D);
17000
17001 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17002 if (Method->isStatic())
17003 checkThisInStaticMemberFunctionAttributes(Method);
17004}
17005
17006NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17007 IdentifierInfo &II, Scope *S) {
17008 // It is not valid to implicitly define a function in C23.
17009 assert(LangOpts.implicitFunctionsAllowed() &&
17010 "Implicit function declarations aren't allowed in this language mode");
17011
17012 // Find the scope in which the identifier is injected and the corresponding
17013 // DeclContext.
17014 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17015 // In that case, we inject the declaration into the translation unit scope
17016 // instead.
17017 Scope *BlockScope = S;
17018 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17019 BlockScope = BlockScope->getParent();
17020
17021 // Loop until we find a DeclContext that is either a function/method or the
17022 // translation unit, which are the only two valid places to implicitly define
17023 // a function. This avoids accidentally defining the function within a tag
17024 // declaration, for example.
17025 Scope *ContextScope = BlockScope;
17026 while (!ContextScope->getEntity() ||
17027 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17028 !ContextScope->getEntity()->isTranslationUnit()))
17029 ContextScope = ContextScope->getParent();
17030 ContextRAII SavedContext(*this, ContextScope->getEntity());
17031
17032 // Before we produce a declaration for an implicitly defined
17033 // function, see whether there was a locally-scoped declaration of
17034 // this name as a function or variable. If so, use that
17035 // (non-visible) declaration, and complain about it.
17036 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17037 if (ExternCPrev) {
17038 // We still need to inject the function into the enclosing block scope so
17039 // that later (non-call) uses can see it.
17040 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17041
17042 // C89 footnote 38:
17043 // If in fact it is not defined as having type "function returning int",
17044 // the behavior is undefined.
17045 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17046 !Context.typesAreCompatible(
17047 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17048 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17049 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17050 << ExternCPrev << !getLangOpts().C99;
17051 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17052 return ExternCPrev;
17053 }
17054 }
17055
17056 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17057 unsigned diag_id;
17058 if (II.getName().starts_with(Prefix: "__builtin_"))
17059 diag_id = diag::warn_builtin_unknown;
17060 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17061 else if (getLangOpts().C99)
17062 diag_id = diag::ext_implicit_function_decl_c99;
17063 else
17064 diag_id = diag::warn_implicit_function_decl;
17065
17066 TypoCorrection Corrected;
17067 // Because typo correction is expensive, only do it if the implicit
17068 // function declaration is going to be treated as an error.
17069 //
17070 // Perform the correction before issuing the main diagnostic, as some
17071 // consumers use typo-correction callbacks to enhance the main diagnostic.
17072 if (S && !ExternCPrev &&
17073 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17074 DeclFilterCCC<FunctionDecl> CCC{};
17075 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17076 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17077 }
17078
17079 Diag(Loc, DiagID: diag_id) << &II;
17080 if (Corrected) {
17081 // If the correction is going to suggest an implicitly defined function,
17082 // skip the correction as not being a particularly good idea.
17083 bool Diagnose = true;
17084 if (const auto *D = Corrected.getCorrectionDecl())
17085 Diagnose = !D->isImplicit();
17086 if (Diagnose)
17087 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17088 /*ErrorRecovery*/ false);
17089 }
17090
17091 // If we found a prior declaration of this function, don't bother building
17092 // another one. We've already pushed that one into scope, so there's nothing
17093 // more to do.
17094 if (ExternCPrev)
17095 return ExternCPrev;
17096
17097 // Set a Declarator for the implicit definition: int foo();
17098 const char *Dummy;
17099 AttributeFactory attrFactory;
17100 DeclSpec DS(attrFactory);
17101 unsigned DiagID;
17102 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17103 Policy: Context.getPrintingPolicy());
17104 (void)Error; // Silence warning.
17105 assert(!Error && "Error setting up implicit decl!");
17106 SourceLocation NoLoc;
17107 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17108 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17109 /*IsAmbiguous=*/false,
17110 /*LParenLoc=*/NoLoc,
17111 /*Params=*/nullptr,
17112 /*NumParams=*/0,
17113 /*EllipsisLoc=*/NoLoc,
17114 /*RParenLoc=*/NoLoc,
17115 /*RefQualifierIsLvalueRef=*/true,
17116 /*RefQualifierLoc=*/NoLoc,
17117 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17118 /*ESpecRange=*/SourceRange(),
17119 /*Exceptions=*/nullptr,
17120 /*ExceptionRanges=*/nullptr,
17121 /*NumExceptions=*/0,
17122 /*NoexceptExpr=*/nullptr,
17123 /*ExceptionSpecTokens=*/nullptr,
17124 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17125 TheDeclarator&: D),
17126 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17127 D.SetIdentifier(Id: &II, IdLoc: Loc);
17128
17129 // Insert this function into the enclosing block scope.
17130 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17131 FD->setImplicit();
17132
17133 AddKnownFunctionAttributes(FD);
17134
17135 return FD;
17136}
17137
17138void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17139 FunctionDecl *FD) {
17140 if (FD->isInvalidDecl())
17141 return;
17142
17143 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17144 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17145 return;
17146
17147 UnsignedOrNone AlignmentParam = std::nullopt;
17148 bool IsNothrow = false;
17149 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17150 return;
17151
17152 // C++2a [basic.stc.dynamic.allocation]p4:
17153 // An allocation function that has a non-throwing exception specification
17154 // indicates failure by returning a null pointer value. Any other allocation
17155 // function never returns a null pointer value and indicates failure only by
17156 // throwing an exception [...]
17157 //
17158 // However, -fcheck-new invalidates this possible assumption, so don't add
17159 // NonNull when that is enabled.
17160 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17161 !getLangOpts().CheckNew)
17162 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17163
17164 // C++2a [basic.stc.dynamic.allocation]p2:
17165 // An allocation function attempts to allocate the requested amount of
17166 // storage. [...] If the request succeeds, the value returned by a
17167 // replaceable allocation function is a [...] pointer value p0 different
17168 // from any previously returned value p1 [...]
17169 //
17170 // However, this particular information is being added in codegen,
17171 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17172
17173 // C++2a [basic.stc.dynamic.allocation]p2:
17174 // An allocation function attempts to allocate the requested amount of
17175 // storage. If it is successful, it returns the address of the start of a
17176 // block of storage whose length in bytes is at least as large as the
17177 // requested size.
17178 if (!FD->hasAttr<AllocSizeAttr>()) {
17179 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17180 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17181 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17182 }
17183
17184 // C++2a [basic.stc.dynamic.allocation]p3:
17185 // For an allocation function [...], the pointer returned on a successful
17186 // call shall represent the address of storage that is aligned as follows:
17187 // (3.1) If the allocation function takes an argument of type
17188 // std​::​align_­val_­t, the storage will have the alignment
17189 // specified by the value of this argument.
17190 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17191 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17192 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17193 }
17194
17195 // FIXME:
17196 // C++2a [basic.stc.dynamic.allocation]p3:
17197 // For an allocation function [...], the pointer returned on a successful
17198 // call shall represent the address of storage that is aligned as follows:
17199 // (3.2) Otherwise, if the allocation function is named operator new[],
17200 // the storage is aligned for any object that does not have
17201 // new-extended alignment ([basic.align]) and is no larger than the
17202 // requested size.
17203 // (3.3) Otherwise, the storage is aligned for any object that does not
17204 // have new-extended alignment and is of the requested size.
17205}
17206
17207void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17208 if (FD->isInvalidDecl())
17209 return;
17210
17211 // If this is a built-in function, map its builtin attributes to
17212 // actual attributes.
17213 if (unsigned BuiltinID = FD->getBuiltinID()) {
17214 // Handle printf-formatting attributes.
17215 unsigned FormatIdx;
17216 bool HasVAListArg;
17217 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17218 if (!FD->hasAttr<FormatAttr>()) {
17219 const char *fmt = "printf";
17220 unsigned int NumParams = FD->getNumParams();
17221 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17222 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17223 fmt = "NSString";
17224 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17225 Type: &Context.Idents.get(Name: fmt),
17226 FormatIdx: FormatIdx+1,
17227 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17228 Range: FD->getLocation()));
17229 }
17230 }
17231 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17232 HasVAListArg)) {
17233 if (!FD->hasAttr<FormatAttr>())
17234 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17235 Type: &Context.Idents.get(Name: "scanf"),
17236 FormatIdx: FormatIdx+1,
17237 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17238 Range: FD->getLocation()));
17239 }
17240
17241 // Handle automatically recognized callbacks.
17242 SmallVector<int, 4> Encoding;
17243 if (!FD->hasAttr<CallbackAttr>() &&
17244 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17245 FD->addAttr(A: CallbackAttr::CreateImplicit(
17246 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17247
17248 // Mark const if we don't care about errno and/or floating point exceptions
17249 // that are the only thing preventing the function from being const. This
17250 // allows IRgen to use LLVM intrinsics for such functions.
17251 bool NoExceptions =
17252 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17253 bool ConstWithoutErrnoAndExceptions =
17254 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17255 bool ConstWithoutExceptions =
17256 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17257 if (!FD->hasAttr<ConstAttr>() &&
17258 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17259 (!ConstWithoutErrnoAndExceptions ||
17260 (!getLangOpts().MathErrno && NoExceptions)) &&
17261 (!ConstWithoutExceptions || NoExceptions))
17262 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17263
17264 // We make "fma" on GNU or Windows const because we know it does not set
17265 // errno in those environments even though it could set errno based on the
17266 // C standard.
17267 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17268 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17269 !FD->hasAttr<ConstAttr>()) {
17270 switch (BuiltinID) {
17271 case Builtin::BI__builtin_fma:
17272 case Builtin::BI__builtin_fmaf:
17273 case Builtin::BI__builtin_fmal:
17274 case Builtin::BIfma:
17275 case Builtin::BIfmaf:
17276 case Builtin::BIfmal:
17277 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17278 break;
17279 default:
17280 break;
17281 }
17282 }
17283
17284 SmallVector<int, 4> Indxs;
17285 Builtin::Info::NonNullMode OptMode;
17286 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17287 !FD->hasAttr<NonNullAttr>()) {
17288 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17289 for (int I : Indxs) {
17290 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17291 QualType T = PVD->getType();
17292 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17293 PVD->setType(T);
17294 }
17295 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17296 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17297 for (int I : Indxs)
17298 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17299 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17300 ArgsSize: ParamIndxs.size()));
17301 }
17302 }
17303 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17304 !FD->hasAttr<ReturnsTwiceAttr>())
17305 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17306 Range: FD->getLocation()));
17307 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17308 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17309 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17310 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17311 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17312 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17313 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17314 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17315 // Add the appropriate attribute, depending on the CUDA compilation mode
17316 // and which target the builtin belongs to. For example, during host
17317 // compilation, aux builtins are __device__, while the rest are __host__.
17318 if (getLangOpts().CUDAIsDevice !=
17319 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17320 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17321 else
17322 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17323 }
17324
17325 // Add known guaranteed alignment for allocation functions.
17326 switch (BuiltinID) {
17327 case Builtin::BImemalign:
17328 case Builtin::BIaligned_alloc:
17329 if (!FD->hasAttr<AllocAlignAttr>())
17330 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17331 Range: FD->getLocation()));
17332 break;
17333 default:
17334 break;
17335 }
17336
17337 // Add allocsize attribute for allocation functions.
17338 switch (BuiltinID) {
17339 case Builtin::BIcalloc:
17340 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17341 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17342 break;
17343 case Builtin::BImemalign:
17344 case Builtin::BIaligned_alloc:
17345 case Builtin::BIrealloc:
17346 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17347 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17348 break;
17349 case Builtin::BImalloc:
17350 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17351 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17352 break;
17353 default:
17354 break;
17355 }
17356 }
17357
17358 LazyProcessLifetimeCaptureByParams(FD);
17359 inferLifetimeBoundAttribute(FD);
17360 inferLifetimeCaptureByAttribute(FD);
17361 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17362
17363 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17364 // throw, add an implicit nothrow attribute to any extern "C" function we come
17365 // across.
17366 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17367 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17368 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17369 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17370 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17371 }
17372
17373 IdentifierInfo *Name = FD->getIdentifier();
17374 if (!Name)
17375 return;
17376 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17377 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17378 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17379 LinkageSpecLanguageIDs::C)) {
17380 // Okay: this could be a libc/libm/Objective-C function we know
17381 // about.
17382 } else
17383 return;
17384
17385 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17386 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17387 // target-specific builtins, perhaps?
17388 if (!FD->hasAttr<FormatAttr>())
17389 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17390 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17391 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17392 Range: FD->getLocation()));
17393 }
17394
17395 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17396 // We already have a __builtin___CFStringMakeConstantString,
17397 // but builds that use -fno-constant-cfstrings don't go through that.
17398 if (!FD->hasAttr<FormatArgAttr>())
17399 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17400 Range: FD->getLocation()));
17401 }
17402}
17403
17404TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17405 TypeSourceInfo *TInfo) {
17406 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17407 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17408
17409 if (!TInfo) {
17410 assert(D.isInvalidType() && "no declarator info for valid type");
17411 TInfo = Context.getTrivialTypeSourceInfo(T);
17412 }
17413
17414 // Scope manipulation handled by caller.
17415 TypedefDecl *NewTD =
17416 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17417 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17418
17419 // Bail out immediately if we have an invalid declaration.
17420 if (D.isInvalidType()) {
17421 NewTD->setInvalidDecl();
17422 return NewTD;
17423 }
17424
17425 if (D.getDeclSpec().isModulePrivateSpecified()) {
17426 if (CurContext->isFunctionOrMethod())
17427 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17428 << 2 << NewTD
17429 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17430 << FixItHint::CreateRemoval(
17431 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17432 else
17433 NewTD->setModulePrivate();
17434 }
17435
17436 // C++ [dcl.typedef]p8:
17437 // If the typedef declaration defines an unnamed class (or
17438 // enum), the first typedef-name declared by the declaration
17439 // to be that class type (or enum type) is used to denote the
17440 // class type (or enum type) for linkage purposes only.
17441 // We need to check whether the type was declared in the declaration.
17442 switch (D.getDeclSpec().getTypeSpecType()) {
17443 case TST_enum:
17444 case TST_struct:
17445 case TST_interface:
17446 case TST_union:
17447 case TST_class: {
17448 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17449 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17450 break;
17451 }
17452
17453 default:
17454 break;
17455 }
17456
17457 return NewTD;
17458}
17459
17460bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17461 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17462 QualType T = TI->getType();
17463
17464 if (T->isDependentType())
17465 return false;
17466
17467 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17468 // integral type; any cv-qualification is ignored.
17469 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17470 // non-atomic version of the type specified by the type specifiers in the
17471 // specifier qualifier list.
17472 // Because of how odd C's rule is, we'll let the user know that operations
17473 // involving the enumeration type will be non-atomic.
17474 if (T->isAtomicType())
17475 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17476
17477 Qualifiers Q = T.getQualifiers();
17478 std::optional<unsigned> QualSelect;
17479 if (Q.hasConst() && Q.hasVolatile())
17480 QualSelect = diag::CVQualList::Both;
17481 else if (Q.hasConst())
17482 QualSelect = diag::CVQualList::Const;
17483 else if (Q.hasVolatile())
17484 QualSelect = diag::CVQualList::Volatile;
17485
17486 if (QualSelect)
17487 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17488
17489 T = T.getAtomicUnqualifiedType();
17490
17491 // This doesn't use 'isIntegralType' despite the error message mentioning
17492 // integral type because isIntegralType would also allow enum types in C.
17493 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17494 if (BT->isInteger())
17495 return false;
17496
17497 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17498 << T << T->isBitIntType();
17499}
17500
17501bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17502 QualType EnumUnderlyingTy, bool IsFixed,
17503 const EnumDecl *Prev) {
17504 if (IsScoped != Prev->isScoped()) {
17505 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17506 << Prev->isScoped();
17507 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17508 return true;
17509 }
17510
17511 if (IsFixed && Prev->isFixed()) {
17512 if (!EnumUnderlyingTy->isDependentType() &&
17513 !Prev->getIntegerType()->isDependentType() &&
17514 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17515 T2: Prev->getIntegerType())) {
17516 // TODO: Highlight the underlying type of the redeclaration.
17517 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17518 << EnumUnderlyingTy << Prev->getIntegerType();
17519 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17520 << Prev->getIntegerTypeRange();
17521 return true;
17522 }
17523 } else if (IsFixed != Prev->isFixed()) {
17524 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17525 << Prev->isFixed();
17526 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17527 return true;
17528 }
17529
17530 return false;
17531}
17532
17533/// Get diagnostic %select index for tag kind for
17534/// redeclaration diagnostic message.
17535/// WARNING: Indexes apply to particular diagnostics only!
17536///
17537/// \returns diagnostic %select index.
17538static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17539 switch (Tag) {
17540 case TagTypeKind::Struct:
17541 return 0;
17542 case TagTypeKind::Interface:
17543 return 1;
17544 case TagTypeKind::Class:
17545 return 2;
17546 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17547 }
17548}
17549
17550/// Determine if tag kind is a class-key compatible with
17551/// class for redeclaration (class, struct, or __interface).
17552///
17553/// \returns true iff the tag kind is compatible.
17554static bool isClassCompatTagKind(TagTypeKind Tag)
17555{
17556 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17557 Tag == TagTypeKind::Interface;
17558}
17559
17560NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17561 if (isa<TypedefDecl>(Val: PrevDecl))
17562 return NonTagKind::Typedef;
17563 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17564 return NonTagKind::TypeAlias;
17565 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17566 return NonTagKind::Template;
17567 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17568 return NonTagKind::TypeAliasTemplate;
17569 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17570 return NonTagKind::TemplateTemplateArgument;
17571 switch (TTK) {
17572 case TagTypeKind::Struct:
17573 case TagTypeKind::Interface:
17574 case TagTypeKind::Class:
17575 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17576 : NonTagKind::NonStruct;
17577 case TagTypeKind::Union:
17578 return NonTagKind::NonUnion;
17579 case TagTypeKind::Enum:
17580 return NonTagKind::NonEnum;
17581 }
17582 llvm_unreachable("invalid TTK");
17583}
17584
17585bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17586 TagTypeKind NewTag, bool isDefinition,
17587 SourceLocation NewTagLoc,
17588 const IdentifierInfo *Name) {
17589 // C++ [dcl.type.elab]p3:
17590 // The class-key or enum keyword present in the
17591 // elaborated-type-specifier shall agree in kind with the
17592 // declaration to which the name in the elaborated-type-specifier
17593 // refers. This rule also applies to the form of
17594 // elaborated-type-specifier that declares a class-name or
17595 // friend class since it can be construed as referring to the
17596 // definition of the class. Thus, in any
17597 // elaborated-type-specifier, the enum keyword shall be used to
17598 // refer to an enumeration (7.2), the union class-key shall be
17599 // used to refer to a union (clause 9), and either the class or
17600 // struct class-key shall be used to refer to a class (clause 9)
17601 // declared using the class or struct class-key.
17602 TagTypeKind OldTag = Previous->getTagKind();
17603 if (OldTag != NewTag &&
17604 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17605 return false;
17606
17607 // Tags are compatible, but we might still want to warn on mismatched tags.
17608 // Non-class tags can't be mismatched at this point.
17609 if (!isClassCompatTagKind(Tag: NewTag))
17610 return true;
17611
17612 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17613 // by our warning analysis. We don't want to warn about mismatches with (eg)
17614 // declarations in system headers that are designed to be specialized, but if
17615 // a user asks us to warn, we should warn if their code contains mismatched
17616 // declarations.
17617 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17618 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17619 Loc);
17620 };
17621 if (IsIgnoredLoc(NewTagLoc))
17622 return true;
17623
17624 auto IsIgnored = [&](const TagDecl *Tag) {
17625 return IsIgnoredLoc(Tag->getLocation());
17626 };
17627 while (IsIgnored(Previous)) {
17628 Previous = Previous->getPreviousDecl();
17629 if (!Previous)
17630 return true;
17631 OldTag = Previous->getTagKind();
17632 }
17633
17634 bool isTemplate = false;
17635 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17636 isTemplate = Record->getDescribedClassTemplate();
17637
17638 if (inTemplateInstantiation()) {
17639 if (OldTag != NewTag) {
17640 // In a template instantiation, do not offer fix-its for tag mismatches
17641 // since they usually mess up the template instead of fixing the problem.
17642 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17643 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17644 << getRedeclDiagFromTagKind(Tag: OldTag);
17645 // FIXME: Note previous location?
17646 }
17647 return true;
17648 }
17649
17650 if (isDefinition) {
17651 // On definitions, check all previous tags and issue a fix-it for each
17652 // one that doesn't match the current tag.
17653 if (Previous->getDefinition()) {
17654 // Don't suggest fix-its for redefinitions.
17655 return true;
17656 }
17657
17658 bool previousMismatch = false;
17659 for (const TagDecl *I : Previous->redecls()) {
17660 if (I->getTagKind() != NewTag) {
17661 // Ignore previous declarations for which the warning was disabled.
17662 if (IsIgnored(I))
17663 continue;
17664
17665 if (!previousMismatch) {
17666 previousMismatch = true;
17667 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17668 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17669 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17670 }
17671 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17672 << getRedeclDiagFromTagKind(Tag: NewTag)
17673 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17674 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17675 }
17676 }
17677 return true;
17678 }
17679
17680 // Identify the prevailing tag kind: this is the kind of the definition (if
17681 // there is a non-ignored definition), or otherwise the kind of the prior
17682 // (non-ignored) declaration.
17683 const TagDecl *PrevDef = Previous->getDefinition();
17684 if (PrevDef && IsIgnored(PrevDef))
17685 PrevDef = nullptr;
17686 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17687 if (Redecl->getTagKind() != NewTag) {
17688 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17689 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17690 << getRedeclDiagFromTagKind(Tag: OldTag);
17691 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17692
17693 // If there is a previous definition, suggest a fix-it.
17694 if (PrevDef) {
17695 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17696 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17697 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17698 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17699 }
17700 }
17701
17702 return true;
17703}
17704
17705/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17706/// from an outer enclosing namespace or file scope inside a friend declaration.
17707/// This should provide the commented out code in the following snippet:
17708/// namespace N {
17709/// struct X;
17710/// namespace M {
17711/// struct Y { friend struct /*N::*/ X; };
17712/// }
17713/// }
17714static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17715 SourceLocation NameLoc) {
17716 // While the decl is in a namespace, do repeated lookup of that name and see
17717 // if we get the same namespace back. If we do not, continue until
17718 // translation unit scope, at which point we have a fully qualified NNS.
17719 SmallVector<IdentifierInfo *, 4> Namespaces;
17720 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17721 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17722 // This tag should be declared in a namespace, which can only be enclosed by
17723 // other namespaces. Bail if there's an anonymous namespace in the chain.
17724 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17725 if (!Namespace || Namespace->isAnonymousNamespace())
17726 return FixItHint();
17727 IdentifierInfo *II = Namespace->getIdentifier();
17728 Namespaces.push_back(Elt: II);
17729 NamedDecl *Lookup = SemaRef.LookupSingleName(
17730 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17731 if (Lookup == Namespace)
17732 break;
17733 }
17734
17735 // Once we have all the namespaces, reverse them to go outermost first, and
17736 // build an NNS.
17737 SmallString<64> Insertion;
17738 llvm::raw_svector_ostream OS(Insertion);
17739 if (DC->isTranslationUnit())
17740 OS << "::";
17741 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17742 for (auto *II : Namespaces)
17743 OS << II->getName() << "::";
17744 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17745}
17746
17747/// Determine whether a tag originally declared in context \p OldDC can
17748/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17749/// found a declaration in \p OldDC as a previous decl, perhaps through a
17750/// using-declaration).
17751static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17752 DeclContext *NewDC) {
17753 OldDC = OldDC->getRedeclContext();
17754 NewDC = NewDC->getRedeclContext();
17755
17756 if (OldDC->Equals(DC: NewDC))
17757 return true;
17758
17759 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17760 // encloses the other).
17761 if (S.getLangOpts().MSVCCompat &&
17762 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17763 return true;
17764
17765 return false;
17766}
17767
17768DeclResult
17769Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17770 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17771 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17772 SourceLocation ModulePrivateLoc,
17773 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17774 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17775 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17776 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17777 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17778 // If this is not a definition, it must have a name.
17779 IdentifierInfo *OrigName = Name;
17780 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17781 "Nameless record must be a definition!");
17782 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17783
17784 OwnedDecl = false;
17785 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17786 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17787
17788 // FIXME: Check member specializations more carefully.
17789 bool isMemberSpecialization = false;
17790 bool IsInjectedClassName = false;
17791 bool Invalid = false;
17792
17793 // We only need to do this matching if we have template parameters
17794 // or a scope specifier, which also conveniently avoids this work
17795 // for non-C++ cases.
17796 if (TemplateParameterLists.size() > 0 ||
17797 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17798 TemplateParameterList *TemplateParams =
17799 MatchTemplateParametersToScopeSpecifier(
17800 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17801 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17802
17803 // C++23 [dcl.type.elab] p2:
17804 // If an elaborated-type-specifier is the sole constituent of a
17805 // declaration, the declaration is ill-formed unless it is an explicit
17806 // specialization, an explicit instantiation or it has one of the
17807 // following forms: [...]
17808 // C++23 [dcl.enum] p1:
17809 // If the enum-head-name of an opaque-enum-declaration contains a
17810 // nested-name-specifier, the declaration shall be an explicit
17811 // specialization.
17812 //
17813 // FIXME: Class template partial specializations can be forward declared
17814 // per CWG2213, but the resolution failed to allow qualified forward
17815 // declarations. This is almost certainly unintentional, so we allow them.
17816 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17817 !isMemberSpecialization)
17818 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
17819 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17820
17821 if (TemplateParams) {
17822 if (Kind == TagTypeKind::Enum) {
17823 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
17824 return true;
17825 }
17826
17827 if (TemplateParams->size() > 0) {
17828 // This is a declaration or definition of a class template (which may
17829 // be a member of another template).
17830
17831 if (Invalid)
17832 return true;
17833
17834 OwnedDecl = false;
17835 DeclResult Result = CheckClassTemplate(
17836 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17837 AS, ModulePrivateLoc,
17838 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17839 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17840 return Result.get();
17841 } else {
17842 // The "template<>" header is extraneous.
17843 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
17844 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17845 isMemberSpecialization = true;
17846 }
17847 }
17848
17849 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17850 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17851 return true;
17852 }
17853
17854 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17855 // C++23 [dcl.type.elab]p4:
17856 // If an elaborated-type-specifier appears with the friend specifier as
17857 // an entire member-declaration, the member-declaration shall have one
17858 // of the following forms:
17859 // friend class-key nested-name-specifier(opt) identifier ;
17860 // friend class-key simple-template-id ;
17861 // friend class-key nested-name-specifier template(opt)
17862 // simple-template-id ;
17863 //
17864 // Since enum is not a class-key, so declarations like "friend enum E;"
17865 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17866 // invalid, most implementations accept so we issue a pedantic warning.
17867 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
17868 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17869 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17870 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
17871 << (ScopedEnum + ScopedEnumUsesClassTag);
17872 }
17873
17874 // Figure out the underlying type if this a enum declaration. We need to do
17875 // this early, because it's needed to detect if this is an incompatible
17876 // redeclaration.
17877 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17878 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17879
17880 if (Kind == TagTypeKind::Enum) {
17881 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17882 // No underlying type explicitly specified, or we failed to parse the
17883 // type, default to int.
17884 EnumUnderlying = Context.IntTy.getTypePtr();
17885 } else if (UnderlyingType.get()) {
17886 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17887 // integral type; any cv-qualification is ignored.
17888 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17889 // unqualified, non-atomic version of the type specified by the type
17890 // specifiers in the specifier qualifier list.
17891 TypeSourceInfo *TI = nullptr;
17892 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17893 EnumUnderlying = TI;
17894
17895 if (CheckEnumUnderlyingType(TI))
17896 // Recover by falling back to int.
17897 EnumUnderlying = Context.IntTy.getTypePtr();
17898
17899 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17900 UPPC: UPPC_FixedUnderlyingType))
17901 EnumUnderlying = Context.IntTy.getTypePtr();
17902
17903 // If the underlying type is atomic, we need to adjust the type before
17904 // continuing. This only happens in the case we stored a TypeSourceInfo
17905 // into EnumUnderlying because the other cases are error recovery up to
17906 // this point. But because it's not possible to gin up a TypeSourceInfo
17907 // for a non-atomic type from an atomic one, we'll store into the Type
17908 // field instead. FIXME: it would be nice to have an easy way to get a
17909 // derived TypeSourceInfo which strips qualifiers including the weird
17910 // ones like _Atomic where it forms a different type.
17911 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
17912 TI && TI->getType()->isAtomicType())
17913 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17914
17915 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17916 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17917 // of 'int'. However, if this is an unfixed forward declaration, don't set
17918 // the underlying type unless the user enables -fms-compatibility. This
17919 // makes unfixed forward declared enums incomplete and is more conforming.
17920 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17921 EnumUnderlying = Context.IntTy.getTypePtr();
17922 }
17923 }
17924
17925 DeclContext *SearchDC = CurContext;
17926 DeclContext *DC = CurContext;
17927 bool isStdBadAlloc = false;
17928 bool isStdAlignValT = false;
17929
17930 RedeclarationKind Redecl = forRedeclarationInCurContext();
17931 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17932 Redecl = RedeclarationKind::NotForRedeclaration;
17933
17934 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17935 /// implemented asks for structural equivalence checking, the returned decl
17936 /// here is passed back to the parser, allowing the tag body to be parsed.
17937 auto createTagFromNewDecl = [&]() -> TagDecl * {
17938 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17939 // If there is an identifier, use the location of the identifier as the
17940 // location of the decl, otherwise use the location of the struct/union
17941 // keyword.
17942 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17943 TagDecl *New = nullptr;
17944
17945 if (Kind == TagTypeKind::Enum) {
17946 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17947 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17948 // If this is an undefined enum, bail.
17949 if (TUK != TagUseKind::Definition && !Invalid)
17950 return nullptr;
17951 if (EnumUnderlying) {
17952 EnumDecl *ED = cast<EnumDecl>(Val: New);
17953 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
17954 ED->setIntegerTypeSourceInfo(TI);
17955 else
17956 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
17957 QualType EnumTy = ED->getIntegerType();
17958 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17959 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17960 : EnumTy);
17961 }
17962 } else { // struct/union
17963 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17964 PrevDecl: nullptr);
17965 }
17966
17967 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17968 // Add alignment attributes if necessary; these attributes are checked
17969 // when the ASTContext lays out the structure.
17970 //
17971 // It is important for implementing the correct semantics that this
17972 // happen here (in ActOnTag). The #pragma pack stack is
17973 // maintained as a result of parser callbacks which can occur at
17974 // many points during the parsing of a struct declaration (because
17975 // the #pragma tokens are effectively skipped over during the
17976 // parsing of the struct).
17977 if (TUK == TagUseKind::Definition &&
17978 (!SkipBody || !SkipBody->ShouldSkip)) {
17979 if (LangOpts.HLSL)
17980 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
17981 AddAlignmentAttributesForRecord(RD);
17982 AddMsStructLayoutForRecord(RD);
17983 }
17984 }
17985 New->setLexicalDeclContext(CurContext);
17986 return New;
17987 };
17988
17989 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17990 if (Name && SS.isNotEmpty()) {
17991 // We have a nested-name tag ('struct foo::bar').
17992
17993 // Check for invalid 'foo::'.
17994 if (SS.isInvalid()) {
17995 Name = nullptr;
17996 goto CreateNewDecl;
17997 }
17998
17999 // If this is a friend or a reference to a class in a dependent
18000 // context, don't try to make a decl for it.
18001 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18002 DC = computeDeclContext(SS, EnteringContext: false);
18003 if (!DC) {
18004 IsDependent = true;
18005 return true;
18006 }
18007 } else {
18008 DC = computeDeclContext(SS, EnteringContext: true);
18009 if (!DC) {
18010 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18011 << SS.getRange();
18012 return true;
18013 }
18014 }
18015
18016 if (RequireCompleteDeclContext(SS, DC))
18017 return true;
18018
18019 SearchDC = DC;
18020 // Look-up name inside 'foo::'.
18021 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18022
18023 if (Previous.isAmbiguous())
18024 return true;
18025
18026 if (Previous.empty()) {
18027 // Name lookup did not find anything. However, if the
18028 // nested-name-specifier refers to the current instantiation,
18029 // and that current instantiation has any dependent base
18030 // classes, we might find something at instantiation time: treat
18031 // this as a dependent elaborated-type-specifier.
18032 // But this only makes any sense for reference-like lookups.
18033 if (Previous.wasNotFoundInCurrentInstantiation() &&
18034 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18035 IsDependent = true;
18036 return true;
18037 }
18038
18039 // A tag 'foo::bar' must already exist.
18040 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18041 << Kind << Name << DC << SS.getRange();
18042 Name = nullptr;
18043 Invalid = true;
18044 goto CreateNewDecl;
18045 }
18046 } else if (Name) {
18047 // C++14 [class.mem]p14:
18048 // If T is the name of a class, then each of the following shall have a
18049 // name different from T:
18050 // -- every member of class T that is itself a type
18051 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18052 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18053 return true;
18054
18055 // If this is a named struct, check to see if there was a previous forward
18056 // declaration or definition.
18057 // FIXME: We're looking into outer scopes here, even when we
18058 // shouldn't be. Doing so can result in ambiguities that we
18059 // shouldn't be diagnosing.
18060 LookupName(R&: Previous, S);
18061
18062 // When declaring or defining a tag, ignore ambiguities introduced
18063 // by types using'ed into this scope.
18064 if (Previous.isAmbiguous() &&
18065 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18066 LookupResult::Filter F = Previous.makeFilter();
18067 while (F.hasNext()) {
18068 NamedDecl *ND = F.next();
18069 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18070 DC: SearchDC->getRedeclContext()))
18071 F.erase();
18072 }
18073 F.done();
18074 }
18075
18076 // C++11 [namespace.memdef]p3:
18077 // If the name in a friend declaration is neither qualified nor
18078 // a template-id and the declaration is a function or an
18079 // elaborated-type-specifier, the lookup to determine whether
18080 // the entity has been previously declared shall not consider
18081 // any scopes outside the innermost enclosing namespace.
18082 //
18083 // MSVC doesn't implement the above rule for types, so a friend tag
18084 // declaration may be a redeclaration of a type declared in an enclosing
18085 // scope. They do implement this rule for friend functions.
18086 //
18087 // Does it matter that this should be by scope instead of by
18088 // semantic context?
18089 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18090 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18091 LookupResult::Filter F = Previous.makeFilter();
18092 bool FriendSawTagOutsideEnclosingNamespace = false;
18093 while (F.hasNext()) {
18094 NamedDecl *ND = F.next();
18095 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18096 if (DC->isFileContext() &&
18097 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18098 if (getLangOpts().MSVCCompat)
18099 FriendSawTagOutsideEnclosingNamespace = true;
18100 else
18101 F.erase();
18102 }
18103 }
18104 F.done();
18105
18106 // Diagnose this MSVC extension in the easy case where lookup would have
18107 // unambiguously found something outside the enclosing namespace.
18108 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18109 NamedDecl *ND = Previous.getFoundDecl();
18110 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18111 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18112 }
18113 }
18114
18115 // Note: there used to be some attempt at recovery here.
18116 if (Previous.isAmbiguous())
18117 return true;
18118
18119 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18120 // FIXME: This makes sure that we ignore the contexts associated
18121 // with C structs, unions, and enums when looking for a matching
18122 // tag declaration or definition. See the similar lookup tweak
18123 // in Sema::LookupName; is there a better way to deal with this?
18124 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18125 SearchDC = SearchDC->getParent();
18126 } else if (getLangOpts().CPlusPlus) {
18127 // Inside ObjCContainer want to keep it as a lexical decl context but go
18128 // past it (most often to TranslationUnit) to find the semantic decl
18129 // context.
18130 while (isa<ObjCContainerDecl>(Val: SearchDC))
18131 SearchDC = SearchDC->getParent();
18132 }
18133 } else if (getLangOpts().CPlusPlus) {
18134 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18135 // TagDecl the same way as we skip it for named TagDecl.
18136 while (isa<ObjCContainerDecl>(Val: SearchDC))
18137 SearchDC = SearchDC->getParent();
18138 }
18139
18140 if (Previous.isSingleResult() &&
18141 Previous.getFoundDecl()->isTemplateParameter()) {
18142 // Maybe we will complain about the shadowed template parameter.
18143 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18144 // Just pretend that we didn't see the previous declaration.
18145 Previous.clear();
18146 }
18147
18148 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18149 DC->Equals(DC: getStdNamespace())) {
18150 if (Name->isStr(Str: "bad_alloc")) {
18151 // This is a declaration of or a reference to "std::bad_alloc".
18152 isStdBadAlloc = true;
18153
18154 // If std::bad_alloc has been implicitly declared (but made invisible to
18155 // name lookup), fill in this implicit declaration as the previous
18156 // declaration, so that the declarations get chained appropriately.
18157 if (Previous.empty() && StdBadAlloc)
18158 Previous.addDecl(D: getStdBadAlloc());
18159 } else if (Name->isStr(Str: "align_val_t")) {
18160 isStdAlignValT = true;
18161 if (Previous.empty() && StdAlignValT)
18162 Previous.addDecl(D: getStdAlignValT());
18163 }
18164 }
18165
18166 // If we didn't find a previous declaration, and this is a reference
18167 // (or friend reference), move to the correct scope. In C++, we
18168 // also need to do a redeclaration lookup there, just in case
18169 // there's a shadow friend decl.
18170 if (Name && Previous.empty() &&
18171 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18172 IsTemplateParamOrArg)) {
18173 if (Invalid) goto CreateNewDecl;
18174 assert(SS.isEmpty());
18175
18176 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18177 // C++ [basic.scope.pdecl]p5:
18178 // -- for an elaborated-type-specifier of the form
18179 //
18180 // class-key identifier
18181 //
18182 // if the elaborated-type-specifier is used in the
18183 // decl-specifier-seq or parameter-declaration-clause of a
18184 // function defined in namespace scope, the identifier is
18185 // declared as a class-name in the namespace that contains
18186 // the declaration; otherwise, except as a friend
18187 // declaration, the identifier is declared in the smallest
18188 // non-class, non-function-prototype scope that contains the
18189 // declaration.
18190 //
18191 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18192 // C structs and unions.
18193 //
18194 // It is an error in C++ to declare (rather than define) an enum
18195 // type, including via an elaborated type specifier. We'll
18196 // diagnose that later; for now, declare the enum in the same
18197 // scope as we would have picked for any other tag type.
18198 //
18199 // GNU C also supports this behavior as part of its incomplete
18200 // enum types extension, while GNU C++ does not.
18201 //
18202 // Find the context where we'll be declaring the tag.
18203 // FIXME: We would like to maintain the current DeclContext as the
18204 // lexical context,
18205 SearchDC = getTagInjectionContext(DC: SearchDC);
18206
18207 // Find the scope where we'll be declaring the tag.
18208 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18209 } else {
18210 assert(TUK == TagUseKind::Friend);
18211 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18212
18213 // C++ [namespace.memdef]p3:
18214 // If a friend declaration in a non-local class first declares a
18215 // class or function, the friend class or function is a member of
18216 // the innermost enclosing namespace.
18217 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18218 : SearchDC->getEnclosingNamespaceContext();
18219 }
18220
18221 // In C++, we need to do a redeclaration lookup to properly
18222 // diagnose some problems.
18223 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18224 // hidden declaration so that we don't get ambiguity errors when using a
18225 // type declared by an elaborated-type-specifier. In C that is not correct
18226 // and we should instead merge compatible types found by lookup.
18227 if (getLangOpts().CPlusPlus) {
18228 // FIXME: This can perform qualified lookups into function contexts,
18229 // which are meaningless.
18230 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18231 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18232 } else {
18233 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18234 LookupName(R&: Previous, S);
18235 }
18236 }
18237
18238 // If we have a known previous declaration to use, then use it.
18239 if (Previous.empty() && SkipBody && SkipBody->Previous)
18240 Previous.addDecl(D: SkipBody->Previous);
18241
18242 if (!Previous.empty()) {
18243 NamedDecl *PrevDecl = Previous.getFoundDecl();
18244 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18245
18246 // It's okay to have a tag decl in the same scope as a typedef
18247 // which hides a tag decl in the same scope. Finding this
18248 // with a redeclaration lookup can only actually happen in C++.
18249 //
18250 // This is also okay for elaborated-type-specifiers, which is
18251 // technically forbidden by the current standard but which is
18252 // okay according to the likely resolution of an open issue;
18253 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18254 if (getLangOpts().CPlusPlus) {
18255 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18256 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18257 if (Tag->getDeclName() == Name &&
18258 Tag->getDeclContext()->getRedeclContext()
18259 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18260 PrevDecl = Tag;
18261 Previous.clear();
18262 Previous.addDecl(D: Tag);
18263 Previous.resolveKind();
18264 }
18265 }
18266 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18267 TUK == TagUseKind::Reference && RD &&
18268 RD->isInjectedClassName()) {
18269 // If lookup found the injected class name, the previous declaration is
18270 // the class being injected into.
18271 PrevDecl = cast<TagDecl>(Val: RD->getDeclContext());
18272 Previous.clear();
18273 Previous.addDecl(D: PrevDecl);
18274 Previous.resolveKind();
18275 IsInjectedClassName = true;
18276 }
18277 }
18278
18279 // If this is a redeclaration of a using shadow declaration, it must
18280 // declare a tag in the same context. In MSVC mode, we allow a
18281 // redefinition if either context is within the other.
18282 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18283 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18284 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18285 TUK != TagUseKind::Friend &&
18286 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18287 !(OldTag && isAcceptableTagRedeclContext(
18288 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18289 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18290 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18291 DiagID: diag::note_using_decl_target);
18292 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18293 << 0;
18294 // Recover by ignoring the old declaration.
18295 Previous.clear();
18296 goto CreateNewDecl;
18297 }
18298 }
18299
18300 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18301 // If this is a use of a previous tag, or if the tag is already declared
18302 // in the same scope (so that the definition/declaration completes or
18303 // rementions the tag), reuse the decl.
18304 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18305 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18306 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18307 // Make sure that this wasn't declared as an enum and now used as a
18308 // struct or something similar.
18309 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18310 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18311 Name)) {
18312 bool SafeToContinue =
18313 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18314 Kind != TagTypeKind::Enum);
18315 if (SafeToContinue)
18316 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18317 << Name
18318 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18319 Code: PrevTagDecl->getKindName());
18320 else
18321 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18322 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18323
18324 if (SafeToContinue)
18325 Kind = PrevTagDecl->getTagKind();
18326 else {
18327 // Recover by making this an anonymous redefinition.
18328 Name = nullptr;
18329 Previous.clear();
18330 Invalid = true;
18331 }
18332 }
18333
18334 if (Kind == TagTypeKind::Enum &&
18335 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18336 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18337 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18338 return PrevTagDecl;
18339
18340 QualType EnumUnderlyingTy;
18341 if (TypeSourceInfo *TI =
18342 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18343 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18344 else if (const Type *T =
18345 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18346 EnumUnderlyingTy = QualType(T, 0);
18347
18348 // All conflicts with previous declarations are recovered by
18349 // returning the previous declaration, unless this is a definition,
18350 // in which case we want the caller to bail out.
18351 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18352 IsScoped: ScopedEnum, EnumUnderlyingTy,
18353 IsFixed, Prev: PrevEnum))
18354 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18355 }
18356
18357 // C++11 [class.mem]p1:
18358 // A member shall not be declared twice in the member-specification,
18359 // except that a nested class or member class template can be declared
18360 // and then later defined.
18361 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18362 S->isDeclScope(D: PrevDecl)) {
18363 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18364 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18365 }
18366
18367 if (!Invalid) {
18368 // If this is a use, just return the declaration we found, unless
18369 // we have attributes.
18370 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18371 if (!Attrs.empty()) {
18372 // FIXME: Diagnose these attributes. For now, we create a new
18373 // declaration to hold them.
18374 } else if (TUK == TagUseKind::Reference &&
18375 (PrevTagDecl->getFriendObjectKind() ==
18376 Decl::FOK_Undeclared ||
18377 PrevDecl->getOwningModule() != getCurrentModule()) &&
18378 SS.isEmpty()) {
18379 // This declaration is a reference to an existing entity, but
18380 // has different visibility from that entity: it either makes
18381 // a friend visible or it makes a type visible in a new module.
18382 // In either case, create a new declaration. We only do this if
18383 // the declaration would have meant the same thing if no prior
18384 // declaration were found, that is, if it was found in the same
18385 // scope where we would have injected a declaration.
18386 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18387 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18388 return PrevTagDecl;
18389 // This is in the injected scope, create a new declaration in
18390 // that scope.
18391 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18392 } else {
18393 return PrevTagDecl;
18394 }
18395 }
18396
18397 // Diagnose attempts to redefine a tag.
18398 if (TUK == TagUseKind::Definition) {
18399 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18400 // If the type is currently being defined, complain
18401 // about a nested redefinition.
18402 if (Def->isBeingDefined()) {
18403 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18404 Diag(Loc: PrevTagDecl->getLocation(),
18405 DiagID: diag::note_previous_definition);
18406 Name = nullptr;
18407 Previous.clear();
18408 Invalid = true;
18409 } else {
18410 // If we're defining a specialization and the previous
18411 // definition is from an implicit instantiation, don't emit an
18412 // error here; we'll catch this in the general case below.
18413 bool IsExplicitSpecializationAfterInstantiation = false;
18414 if (isMemberSpecialization) {
18415 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18416 IsExplicitSpecializationAfterInstantiation =
18417 RD->getTemplateSpecializationKind() !=
18418 TSK_ExplicitSpecialization;
18419 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18420 IsExplicitSpecializationAfterInstantiation =
18421 ED->getTemplateSpecializationKind() !=
18422 TSK_ExplicitSpecialization;
18423 }
18424
18425 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18426 // do not keep more that one definition around (merge them).
18427 // However, ensure the decl passes the structural compatibility
18428 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18429 NamedDecl *Hidden = nullptr;
18430 bool HiddenDefVisible = false;
18431 if (SkipBody &&
18432 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18433 getLangOpts().C23)) {
18434 // There is a definition of this tag, but it is not visible.
18435 // We explicitly make use of C++'s one definition rule here,
18436 // and assume that this definition is identical to the hidden
18437 // one we already have. Make the existing definition visible
18438 // and use it in place of this one.
18439 if (!getLangOpts().CPlusPlus) {
18440 // Postpone making the old definition visible until after we
18441 // complete parsing the new one and do the structural
18442 // comparison.
18443 SkipBody->CheckSameAsPrevious = true;
18444 SkipBody->New = createTagFromNewDecl();
18445 SkipBody->Previous = Def;
18446
18447 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18448 return Def;
18449 }
18450
18451 SkipBody->ShouldSkip = true;
18452 SkipBody->Previous = Def;
18453 if (!HiddenDefVisible && Hidden)
18454 makeMergedDefinitionVisible(ND: Hidden);
18455 // Carry on and handle it like a normal definition. We'll
18456 // skip starting the definition later.
18457
18458 } else if (!IsExplicitSpecializationAfterInstantiation) {
18459 // A redeclaration in function prototype scope in C isn't
18460 // visible elsewhere, so merely issue a warning.
18461 if (!getLangOpts().CPlusPlus &&
18462 S->containedInPrototypeScope())
18463 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18464 << Name;
18465 else
18466 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18467 notePreviousDefinition(Old: Def,
18468 New: NameLoc.isValid() ? NameLoc : KWLoc);
18469 // If this is a redefinition, recover by making this
18470 // struct be anonymous, which will make any later
18471 // references get the previous definition.
18472 Name = nullptr;
18473 Previous.clear();
18474 Invalid = true;
18475 }
18476 }
18477 }
18478
18479 // Okay, this is definition of a previously declared or referenced
18480 // tag. We're going to create a new Decl for it.
18481 }
18482
18483 // Okay, we're going to make a redeclaration. If this is some kind
18484 // of reference, make sure we build the redeclaration in the same DC
18485 // as the original, and ignore the current access specifier.
18486 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18487 SearchDC = PrevTagDecl->getDeclContext();
18488 AS = AS_none;
18489 }
18490 }
18491 // If we get here we have (another) forward declaration or we
18492 // have a definition. Just create a new decl.
18493
18494 } else {
18495 // If we get here, this is a definition of a new tag type in a nested
18496 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18497 // new decl/type. We set PrevDecl to NULL so that the entities
18498 // have distinct types.
18499 Previous.clear();
18500 }
18501 // If we get here, we're going to create a new Decl. If PrevDecl
18502 // is non-NULL, it's a definition of the tag declared by
18503 // PrevDecl. If it's NULL, we have a new definition.
18504
18505 // Otherwise, PrevDecl is not a tag, but was found with tag
18506 // lookup. This is only actually possible in C++, where a few
18507 // things like templates still live in the tag namespace.
18508 } else {
18509 // Use a better diagnostic if an elaborated-type-specifier
18510 // found the wrong kind of type on the first
18511 // (non-redeclaration) lookup.
18512 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18513 !Previous.isForRedeclaration()) {
18514 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18515 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18516 << PrevDecl << NTK << Kind;
18517 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18518 Invalid = true;
18519
18520 // Otherwise, only diagnose if the declaration is in scope.
18521 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18522 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18523 // do nothing
18524
18525 // Diagnose implicit declarations introduced by elaborated types.
18526 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18527 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18528 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18529 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18530 Invalid = true;
18531
18532 // Otherwise it's a declaration. Call out a particularly common
18533 // case here.
18534 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18535 unsigned Kind = 0;
18536 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18537 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18538 << Name << Kind << TND->getUnderlyingType();
18539 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18540 Invalid = true;
18541
18542 // Otherwise, diagnose.
18543 } else {
18544 // The tag name clashes with something else in the target scope,
18545 // issue an error and recover by making this tag be anonymous.
18546 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18547 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18548 Name = nullptr;
18549 Invalid = true;
18550 }
18551
18552 // The existing declaration isn't relevant to us; we're in a
18553 // new scope, so clear out the previous declaration.
18554 Previous.clear();
18555 }
18556 }
18557
18558CreateNewDecl:
18559
18560 TagDecl *PrevDecl = nullptr;
18561 if (Previous.isSingleResult())
18562 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18563
18564 // If there is an identifier, use the location of the identifier as the
18565 // location of the decl, otherwise use the location of the struct/union
18566 // keyword.
18567 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18568
18569 // Otherwise, create a new declaration. If there is a previous
18570 // declaration of the same entity, the two will be linked via
18571 // PrevDecl.
18572 TagDecl *New;
18573
18574 if (Kind == TagTypeKind::Enum) {
18575 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18576 // enum X { A, B, C } D; D should chain to X.
18577 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18578 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18579 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18580
18581 EnumDecl *ED = cast<EnumDecl>(Val: New);
18582 ED->setEnumKeyRange(SourceRange(
18583 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18584
18585 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18586 StdAlignValT = cast<EnumDecl>(Val: New);
18587
18588 // If this is an undefined enum, warn.
18589 if (TUK != TagUseKind::Definition && !Invalid) {
18590 TagDecl *Def;
18591 if (IsFixed && ED->isFixed()) {
18592 // C++0x: 7.2p2: opaque-enum-declaration.
18593 // Conflicts are diagnosed above. Do nothing.
18594 } else if (PrevDecl &&
18595 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18596 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18597 << New;
18598 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18599 } else {
18600 unsigned DiagID = diag::ext_forward_ref_enum;
18601 if (getLangOpts().MSVCCompat)
18602 DiagID = diag::ext_ms_forward_ref_enum;
18603 else if (getLangOpts().CPlusPlus)
18604 DiagID = diag::err_forward_ref_enum;
18605 Diag(Loc, DiagID);
18606 }
18607 }
18608
18609 if (EnumUnderlying) {
18610 EnumDecl *ED = cast<EnumDecl>(Val: New);
18611 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18612 ED->setIntegerTypeSourceInfo(TI);
18613 else
18614 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18615 QualType EnumTy = ED->getIntegerType();
18616 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18617 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18618 : EnumTy);
18619 assert(ED->isComplete() && "enum with type should be complete");
18620 }
18621 } else {
18622 // struct/union/class
18623
18624 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18625 // struct X { int A; } D; D should chain to X.
18626 if (getLangOpts().CPlusPlus) {
18627 // FIXME: Look for a way to use RecordDecl for simple structs.
18628 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18629 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18630
18631 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18632 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18633 } else
18634 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18635 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18636 }
18637
18638 // Only C23 and later allow defining new types in 'offsetof()'.
18639 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18640 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18641 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18642 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18643
18644 // C++11 [dcl.type]p3:
18645 // A type-specifier-seq shall not define a class or enumeration [...].
18646 if (!Invalid && getLangOpts().CPlusPlus &&
18647 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18648 TUK == TagUseKind::Definition) {
18649 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18650 << Context.getCanonicalTagType(TD: New);
18651 Invalid = true;
18652 }
18653
18654 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18655 DC->getDeclKind() == Decl::Enum) {
18656 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18657 << Context.getCanonicalTagType(TD: New);
18658 Invalid = true;
18659 }
18660
18661 // Maybe add qualifier info.
18662 if (SS.isNotEmpty()) {
18663 if (SS.isSet()) {
18664 // If this is either a declaration or a definition, check the
18665 // nested-name-specifier against the current context.
18666 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18667 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18668 /*TemplateId=*/nullptr,
18669 IsMemberSpecialization: isMemberSpecialization))
18670 Invalid = true;
18671
18672 New->setQualifierInfo(SS.getWithLocInContext(Context));
18673 if (TemplateParameterLists.size() > 0) {
18674 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18675 }
18676 }
18677 else
18678 Invalid = true;
18679 }
18680
18681 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18682 // Add alignment attributes if necessary; these attributes are checked when
18683 // the ASTContext lays out the structure.
18684 //
18685 // It is important for implementing the correct semantics that this
18686 // happen here (in ActOnTag). The #pragma pack stack is
18687 // maintained as a result of parser callbacks which can occur at
18688 // many points during the parsing of a struct declaration (because
18689 // the #pragma tokens are effectively skipped over during the
18690 // parsing of the struct).
18691 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18692 if (LangOpts.HLSL)
18693 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18694 AddAlignmentAttributesForRecord(RD);
18695 AddMsStructLayoutForRecord(RD);
18696 }
18697 }
18698
18699 if (ModulePrivateLoc.isValid()) {
18700 if (isMemberSpecialization)
18701 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18702 << 2
18703 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18704 // __module_private__ does not apply to local classes. However, we only
18705 // diagnose this as an error when the declaration specifiers are
18706 // freestanding. Here, we just ignore the __module_private__.
18707 else if (!SearchDC->isFunctionOrMethod())
18708 New->setModulePrivate();
18709 }
18710
18711 // If this is a specialization of a member class (of a class template),
18712 // check the specialization.
18713 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18714 Invalid = true;
18715
18716 // If we're declaring or defining a tag in function prototype scope in C,
18717 // note that this type can only be used within the function and add it to
18718 // the list of decls to inject into the function definition scope. However,
18719 // in C23 and later, while the type is only visible within the function, the
18720 // function can be called with a compatible type defined in the same TU, so
18721 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18722 if ((Name || Kind == TagTypeKind::Enum) &&
18723 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18724 if (getLangOpts().CPlusPlus) {
18725 // C++ [dcl.fct]p6:
18726 // Types shall not be defined in return or parameter types.
18727 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18728 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18729 << Name;
18730 Invalid = true;
18731 }
18732 if (TUK == TagUseKind::Declaration)
18733 Invalid = true;
18734 } else if (!PrevDecl) {
18735 // In C23 mode, if the declaration is complete, we do not want to
18736 // diagnose.
18737 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18738 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
18739 << Context.getCanonicalTagType(TD: New);
18740 }
18741 }
18742
18743 if (Invalid)
18744 New->setInvalidDecl();
18745
18746 // Set the lexical context. If the tag has a C++ scope specifier, the
18747 // lexical context will be different from the semantic context.
18748 New->setLexicalDeclContext(CurContext);
18749
18750 // Mark this as a friend decl if applicable.
18751 // In Microsoft mode, a friend declaration also acts as a forward
18752 // declaration so we always pass true to setObjectOfFriendDecl to make
18753 // the tag name visible.
18754 if (TUK == TagUseKind::Friend)
18755 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18756
18757 // Set the access specifier.
18758 if (!Invalid && SearchDC->isRecord())
18759 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18760
18761 if (PrevDecl)
18762 CheckRedeclarationInModule(New, Old: PrevDecl);
18763
18764 if (TUK == TagUseKind::Definition) {
18765 if (!SkipBody || !SkipBody->ShouldSkip) {
18766 New->startDefinition();
18767 } else {
18768 New->setCompleteDefinition();
18769 New->demoteThisDefinitionToDeclaration();
18770 }
18771 }
18772
18773 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18774 AddPragmaAttributes(S, D: New);
18775
18776 // If this has an identifier, add it to the scope stack.
18777 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18778 // We might be replacing an existing declaration in the lookup tables;
18779 // if so, borrow its access specifier.
18780 if (PrevDecl)
18781 New->setAccess(PrevDecl->getAccess());
18782
18783 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18784 DC->makeDeclVisibleInContext(D: New);
18785 if (Name) // can be null along some error paths
18786 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18787 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18788 } else if (Name) {
18789 S = getNonFieldDeclScope(S);
18790 PushOnScopeChains(D: New, S, AddToContext: true);
18791 } else {
18792 CurContext->addDecl(D: New);
18793 }
18794
18795 // If this is the C FILE type, notify the AST context.
18796 if (IdentifierInfo *II = New->getIdentifier())
18797 if (!New->isInvalidDecl() &&
18798 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18799 II->isStr(Str: "FILE"))
18800 Context.setFILEDecl(New);
18801
18802 if (PrevDecl)
18803 mergeDeclAttributes(New, Old: PrevDecl);
18804
18805 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18806 inferGslOwnerPointerAttribute(Record: CXXRD);
18807 inferNullableClassAttribute(CRD: CXXRD);
18808 }
18809
18810 // If there's a #pragma GCC visibility in scope, set the visibility of this
18811 // record.
18812 AddPushedVisibilityAttribute(RD: New);
18813
18814 // If this is not a definition, process API notes for it now.
18815 if (TUK != TagUseKind::Definition)
18816 ProcessAPINotes(D: New);
18817
18818 if (isMemberSpecialization && !New->isInvalidDecl())
18819 CompleteMemberSpecialization(Member: New, Previous);
18820
18821 OwnedDecl = true;
18822 // In C++, don't return an invalid declaration. We can't recover well from
18823 // the cases where we make the type anonymous.
18824 if (Invalid && getLangOpts().CPlusPlus) {
18825 if (New->isBeingDefined())
18826 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18827 RD->completeDefinition();
18828 return true;
18829 } else if (SkipBody && SkipBody->ShouldSkip) {
18830 return SkipBody->Previous;
18831 } else {
18832 return New;
18833 }
18834}
18835
18836void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18837 AdjustDeclIfTemplate(Decl&: TagD);
18838 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18839
18840 // Enter the tag context.
18841 PushDeclContext(S, DC: Tag);
18842
18843 ActOnDocumentableDecl(D: TagD);
18844
18845 // If there's a #pragma GCC visibility in scope, set the visibility of this
18846 // record.
18847 AddPushedVisibilityAttribute(RD: Tag);
18848}
18849
18850bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18851 SkipBodyInfo &SkipBody) {
18852 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
18853 return false;
18854
18855 // Make the previous decl visible.
18856 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18857 CleanupMergedEnum(S, New: SkipBody.New);
18858 return true;
18859}
18860
18861void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18862 SourceLocation FinalLoc,
18863 bool IsFinalSpelledSealed,
18864 bool IsAbstract,
18865 SourceLocation LBraceLoc) {
18866 AdjustDeclIfTemplate(Decl&: TagD);
18867 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18868
18869 FieldCollector->StartClass();
18870
18871 if (!Record->getIdentifier())
18872 return;
18873
18874 if (IsAbstract)
18875 Record->markAbstract();
18876
18877 if (FinalLoc.isValid()) {
18878 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
18879 S: IsFinalSpelledSealed
18880 ? FinalAttr::Keyword_sealed
18881 : FinalAttr::Keyword_final));
18882 }
18883
18884 // C++ [class]p2:
18885 // [...] The class-name is also inserted into the scope of the
18886 // class itself; this is known as the injected-class-name. For
18887 // purposes of access checking, the injected-class-name is treated
18888 // as if it were a public member name.
18889 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18890 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18891 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
18892 InjectedClassName->setImplicit();
18893 InjectedClassName->setAccess(AS_public);
18894 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18895 InjectedClassName->setDescribedClassTemplate(Template);
18896
18897 PushOnScopeChains(D: InjectedClassName, S);
18898 assert(InjectedClassName->isInjectedClassName() &&
18899 "Broken injected-class-name");
18900}
18901
18902void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18903 SourceRange BraceRange) {
18904 AdjustDeclIfTemplate(Decl&: TagD);
18905 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18906 Tag->setBraceRange(BraceRange);
18907
18908 // Make sure we "complete" the definition even it is invalid.
18909 if (Tag->isBeingDefined()) {
18910 assert(Tag->isInvalidDecl() && "We should already have completed it");
18911 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18912 RD->completeDefinition();
18913 }
18914
18915 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18916 FieldCollector->FinishClass();
18917 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18918 auto *Def = RD->getDefinition();
18919 assert(Def && "The record is expected to have a completed definition");
18920 unsigned NumInitMethods = 0;
18921 for (auto *Method : Def->methods()) {
18922 if (!Method->getIdentifier())
18923 continue;
18924 if (Method->getName() == "__init")
18925 NumInitMethods++;
18926 }
18927 if (NumInitMethods > 1 || !Def->hasInitMethod())
18928 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
18929 }
18930
18931 // If we're defining a dynamic class in a module interface unit, we always
18932 // need to produce the vtable for it, even if the vtable is not used in the
18933 // current TU.
18934 //
18935 // The case where the current class is not dynamic is handled in
18936 // MarkVTableUsed.
18937 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18938 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
18939 }
18940
18941 // Exit this scope of this tag's definition.
18942 PopDeclContext();
18943
18944 if (getCurLexicalContext()->isObjCContainer() &&
18945 Tag->getDeclContext()->isFileContext())
18946 Tag->setTopLevelDeclInObjCContainer();
18947
18948 // Notify the consumer that we've defined a tag.
18949 if (!Tag->isInvalidDecl())
18950 Consumer.HandleTagDeclDefinition(D: Tag);
18951
18952 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18953 // from XLs and instead matches the XL #pragma pack(1) behavior.
18954 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18955 AlignPackStack.hasValue()) {
18956 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18957 // Only diagnose #pragma align(packed).
18958 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18959 return;
18960 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18961 if (!RD)
18962 return;
18963 // Only warn if there is at least 1 bitfield member.
18964 if (llvm::any_of(Range: RD->fields(),
18965 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
18966 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
18967 }
18968}
18969
18970void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18971 AdjustDeclIfTemplate(Decl&: TagD);
18972 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18973 Tag->setInvalidDecl();
18974
18975 // Make sure we "complete" the definition even it is invalid.
18976 if (Tag->isBeingDefined()) {
18977 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18978 RD->completeDefinition();
18979 }
18980
18981 // We're undoing ActOnTagStartDefinition here, not
18982 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18983 // the FieldCollector.
18984
18985 PopDeclContext();
18986}
18987
18988// Note that FieldName may be null for anonymous bitfields.
18989ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18990 const IdentifierInfo *FieldName,
18991 QualType FieldTy, bool IsMsStruct,
18992 Expr *BitWidth) {
18993 assert(BitWidth);
18994 if (BitWidth->containsErrors())
18995 return ExprError();
18996
18997 // C99 6.7.2.1p4 - verify the field type.
18998 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18999 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19000 // Handle incomplete and sizeless types with a specific error.
19001 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19002 DiagID: diag::err_field_incomplete_or_sizeless))
19003 return ExprError();
19004 if (FieldName)
19005 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19006 << FieldName << FieldTy << BitWidth->getSourceRange();
19007 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19008 << FieldTy << BitWidth->getSourceRange();
19009 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19010 return ExprError();
19011
19012 // If the bit-width is type- or value-dependent, don't try to check
19013 // it now.
19014 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19015 return BitWidth;
19016
19017 llvm::APSInt Value;
19018 ExprResult ICE =
19019 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19020 if (ICE.isInvalid())
19021 return ICE;
19022 BitWidth = ICE.get();
19023
19024 // Zero-width bitfield is ok for anonymous field.
19025 if (Value == 0 && FieldName)
19026 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19027 << FieldName << BitWidth->getSourceRange();
19028
19029 if (Value.isSigned() && Value.isNegative()) {
19030 if (FieldName)
19031 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19032 << FieldName << toString(I: Value, Radix: 10);
19033 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19034 << toString(I: Value, Radix: 10);
19035 }
19036
19037 // The size of the bit-field must not exceed our maximum permitted object
19038 // size.
19039 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19040 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19041 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19042 }
19043
19044 if (!FieldTy->isDependentType()) {
19045 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19046 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19047 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19048
19049 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19050 // ABI.
19051 bool CStdConstraintViolation =
19052 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19053 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19054 if (CStdConstraintViolation || MSBitfieldViolation) {
19055 unsigned DiagWidth =
19056 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19057 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19058 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19059 << !CStdConstraintViolation << DiagWidth;
19060 }
19061
19062 // Warn on types where the user might conceivably expect to get all
19063 // specified bits as value bits: that's all integral types other than
19064 // 'bool'.
19065 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19066 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19067 << FieldName << Value << (unsigned)TypeWidth;
19068 }
19069 }
19070
19071 if (isa<ConstantExpr>(Val: BitWidth))
19072 return BitWidth;
19073 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19074}
19075
19076Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19077 Declarator &D, Expr *BitfieldWidth) {
19078 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19079 D, BitfieldWidth,
19080 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19081 return Res;
19082}
19083
19084FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19085 SourceLocation DeclStart,
19086 Declarator &D, Expr *BitWidth,
19087 InClassInitStyle InitStyle,
19088 AccessSpecifier AS) {
19089 if (D.isDecompositionDeclarator()) {
19090 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19091 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19092 << Decomp.getSourceRange();
19093 return nullptr;
19094 }
19095
19096 const IdentifierInfo *II = D.getIdentifier();
19097 SourceLocation Loc = DeclStart;
19098 if (II) Loc = D.getIdentifierLoc();
19099
19100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19101 QualType T = TInfo->getType();
19102 if (getLangOpts().CPlusPlus) {
19103 CheckExtraCXXDefaultArguments(D);
19104
19105 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19106 UPPC: UPPC_DataMemberType)) {
19107 D.setInvalidType();
19108 T = Context.IntTy;
19109 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19110 }
19111 }
19112
19113 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19114
19115 if (D.getDeclSpec().isInlineSpecified())
19116 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19117 << getLangOpts().CPlusPlus17;
19118 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19119 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19120 DiagID: diag::err_invalid_thread)
19121 << DeclSpec::getSpecifierName(S: TSCS);
19122
19123 // Check to see if this name was declared as a member previously
19124 NamedDecl *PrevDecl = nullptr;
19125 LookupResult Previous(*this, II, Loc, LookupMemberName,
19126 RedeclarationKind::ForVisibleRedeclaration);
19127 LookupName(R&: Previous, S);
19128 switch (Previous.getResultKind()) {
19129 case LookupResultKind::Found:
19130 case LookupResultKind::FoundUnresolvedValue:
19131 PrevDecl = Previous.getAsSingle<NamedDecl>();
19132 break;
19133
19134 case LookupResultKind::FoundOverloaded:
19135 PrevDecl = Previous.getRepresentativeDecl();
19136 break;
19137
19138 case LookupResultKind::NotFound:
19139 case LookupResultKind::NotFoundInCurrentInstantiation:
19140 case LookupResultKind::Ambiguous:
19141 break;
19142 }
19143 Previous.suppressDiagnostics();
19144
19145 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19146 // Maybe we will complain about the shadowed template parameter.
19147 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19148 // Just pretend that we didn't see the previous declaration.
19149 PrevDecl = nullptr;
19150 }
19151
19152 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19153 PrevDecl = nullptr;
19154
19155 bool Mutable
19156 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19157 SourceLocation TSSL = D.getBeginLoc();
19158 FieldDecl *NewFD
19159 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19160 TSSL, AS, PrevDecl, D: &D);
19161
19162 if (NewFD->isInvalidDecl())
19163 Record->setInvalidDecl();
19164
19165 if (D.getDeclSpec().isModulePrivateSpecified())
19166 NewFD->setModulePrivate();
19167
19168 if (NewFD->isInvalidDecl() && PrevDecl) {
19169 // Don't introduce NewFD into scope; there's already something
19170 // with the same name in the same scope.
19171 } else if (II) {
19172 PushOnScopeChains(D: NewFD, S);
19173 } else
19174 Record->addDecl(D: NewFD);
19175
19176 return NewFD;
19177}
19178
19179FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19180 TypeSourceInfo *TInfo,
19181 RecordDecl *Record, SourceLocation Loc,
19182 bool Mutable, Expr *BitWidth,
19183 InClassInitStyle InitStyle,
19184 SourceLocation TSSL,
19185 AccessSpecifier AS, NamedDecl *PrevDecl,
19186 Declarator *D) {
19187 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19188 bool InvalidDecl = false;
19189 if (D) InvalidDecl = D->isInvalidType();
19190
19191 // If we receive a broken type, recover by assuming 'int' and
19192 // marking this declaration as invalid.
19193 if (T.isNull() || T->containsErrors()) {
19194 InvalidDecl = true;
19195 T = Context.IntTy;
19196 }
19197
19198 QualType EltTy = Context.getBaseElementType(QT: T);
19199 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19200 bool isIncomplete =
19201 LangOpts.HLSL // HLSL allows sizeless builtin types
19202 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19203 : RequireCompleteSizedType(Loc, T: EltTy,
19204 DiagID: diag::err_field_incomplete_or_sizeless);
19205 if (isIncomplete) {
19206 // Fields of incomplete type force their record to be invalid.
19207 Record->setInvalidDecl();
19208 InvalidDecl = true;
19209 } else {
19210 NamedDecl *Def;
19211 EltTy->isIncompleteType(Def: &Def);
19212 if (Def && Def->isInvalidDecl()) {
19213 Record->setInvalidDecl();
19214 InvalidDecl = true;
19215 }
19216 }
19217 }
19218
19219 // TR 18037 does not allow fields to be declared with address space
19220 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19221 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19222 Diag(Loc, DiagID: diag::err_field_with_address_space);
19223 Record->setInvalidDecl();
19224 InvalidDecl = true;
19225 }
19226
19227 if (LangOpts.OpenCL) {
19228 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19229 // used as structure or union field: image, sampler, event or block types.
19230 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19231 T->isBlockPointerType()) {
19232 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19233 Record->setInvalidDecl();
19234 InvalidDecl = true;
19235 }
19236 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19237 // is enabled.
19238 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19239 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19240 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19241 InvalidDecl = true;
19242 }
19243 }
19244
19245 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19246 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19247 T.hasQualifiers()) {
19248 InvalidDecl = true;
19249 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19250 }
19251
19252 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19253 // than a variably modified type.
19254 if (!InvalidDecl && T->isVariablyModifiedType()) {
19255 if (!tryToFixVariablyModifiedVarType(
19256 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19257 InvalidDecl = true;
19258 }
19259
19260 // Fields can not have abstract class types
19261 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19262 DiagID: diag::err_abstract_type_in_decl,
19263 Args: AbstractFieldType))
19264 InvalidDecl = true;
19265
19266 if (InvalidDecl)
19267 BitWidth = nullptr;
19268 // If this is declared as a bit-field, check the bit-field.
19269 if (BitWidth) {
19270 BitWidth =
19271 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19272 if (!BitWidth) {
19273 InvalidDecl = true;
19274 BitWidth = nullptr;
19275 }
19276 }
19277
19278 // Check that 'mutable' is consistent with the type of the declaration.
19279 if (!InvalidDecl && Mutable) {
19280 unsigned DiagID = 0;
19281 if (T->isReferenceType())
19282 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19283 : diag::err_mutable_reference;
19284 else if (T.isConstQualified())
19285 DiagID = diag::err_mutable_const;
19286
19287 if (DiagID) {
19288 SourceLocation ErrLoc = Loc;
19289 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19290 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19291 Diag(Loc: ErrLoc, DiagID);
19292 if (DiagID != diag::ext_mutable_reference) {
19293 Mutable = false;
19294 InvalidDecl = true;
19295 }
19296 }
19297 }
19298
19299 // C++11 [class.union]p8 (DR1460):
19300 // At most one variant member of a union may have a
19301 // brace-or-equal-initializer.
19302 if (InitStyle != ICIS_NoInit)
19303 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19304
19305 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19306 BW: BitWidth, Mutable, InitStyle);
19307 if (InvalidDecl)
19308 NewFD->setInvalidDecl();
19309
19310 if (!InvalidDecl)
19311 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19312
19313 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19314 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19315 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19316 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19317 NewFD->setInvalidDecl();
19318 }
19319
19320 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19321 if (Record->isUnion()) {
19322 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19323 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19324
19325 // C++ [class.union]p1: An object of a class with a non-trivial
19326 // constructor, a non-trivial copy constructor, a non-trivial
19327 // destructor, or a non-trivial copy assignment operator
19328 // cannot be a member of a union, nor can an array of such
19329 // objects.
19330 if (CheckNontrivialField(FD: NewFD))
19331 NewFD->setInvalidDecl();
19332 }
19333
19334 // C++ [class.union]p1: If a union contains a member of reference type,
19335 // the program is ill-formed, except when compiling with MSVC extensions
19336 // enabled.
19337 if (EltTy->isReferenceType()) {
19338 const bool HaveMSExt =
19339 getLangOpts().MicrosoftExt &&
19340 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19341
19342 Diag(Loc: NewFD->getLocation(),
19343 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19344 : diag::err_union_member_of_reference_type)
19345 << NewFD->getDeclName() << EltTy;
19346 if (!HaveMSExt)
19347 NewFD->setInvalidDecl();
19348 }
19349 }
19350 }
19351
19352 // FIXME: We need to pass in the attributes given an AST
19353 // representation, not a parser representation.
19354 if (D) {
19355 // FIXME: The current scope is almost... but not entirely... correct here.
19356 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19357
19358 if (NewFD->hasAttrs())
19359 CheckAlignasUnderalignment(D: NewFD);
19360 }
19361
19362 // In auto-retain/release, infer strong retension for fields of
19363 // retainable type.
19364 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19365 NewFD->setInvalidDecl();
19366
19367 if (T.isObjCGCWeak())
19368 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19369
19370 // PPC MMA non-pointer types are not allowed as field types.
19371 if (Context.getTargetInfo().getTriple().isPPC64() &&
19372 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19373 NewFD->setInvalidDecl();
19374
19375 NewFD->setAccess(AS);
19376 return NewFD;
19377}
19378
19379bool Sema::CheckNontrivialField(FieldDecl *FD) {
19380 assert(FD);
19381 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19382
19383 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19384 return false;
19385
19386 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19387 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19388 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19389 // We check for copy constructors before constructors
19390 // because otherwise we'll never get complaints about
19391 // copy constructors.
19392
19393 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19394 // We're required to check for any non-trivial constructors. Since the
19395 // implicit default constructor is suppressed if there are any
19396 // user-declared constructors, we just need to check that there is a
19397 // trivial default constructor and a trivial copy constructor. (We don't
19398 // worry about move constructors here, since this is a C++98 check.)
19399 if (RDecl->hasNonTrivialCopyConstructor())
19400 member = CXXSpecialMemberKind::CopyConstructor;
19401 else if (!RDecl->hasTrivialDefaultConstructor())
19402 member = CXXSpecialMemberKind::DefaultConstructor;
19403 else if (RDecl->hasNonTrivialCopyAssignment())
19404 member = CXXSpecialMemberKind::CopyAssignment;
19405 else if (RDecl->hasNonTrivialDestructor())
19406 member = CXXSpecialMemberKind::Destructor;
19407
19408 if (member != CXXSpecialMemberKind::Invalid) {
19409 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19410 RDecl->hasObjectMember()) {
19411 // Objective-C++ ARC: it is an error to have a non-trivial field of
19412 // a union. However, system headers in Objective-C programs
19413 // occasionally have Objective-C lifetime objects within unions,
19414 // and rather than cause the program to fail, we make those
19415 // members unavailable.
19416 SourceLocation Loc = FD->getLocation();
19417 if (getSourceManager().isInSystemHeader(Loc)) {
19418 if (!FD->hasAttr<UnavailableAttr>())
19419 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19420 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19421 return false;
19422 }
19423 }
19424
19425 Diag(Loc: FD->getLocation(),
19426 DiagID: getLangOpts().CPlusPlus11
19427 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19428 : diag::err_illegal_union_or_anon_struct_member)
19429 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19430 DiagnoseNontrivial(Record: RDecl, CSM: member);
19431 return !getLangOpts().CPlusPlus11;
19432 }
19433 }
19434
19435 return false;
19436}
19437
19438void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19439 SmallVectorImpl<Decl *> &AllIvarDecls) {
19440 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19441 return;
19442
19443 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19444 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19445
19446 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19447 return;
19448 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19449 if (!ID) {
19450 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19451 if (!CD->IsClassExtension())
19452 return;
19453 }
19454 // No need to add this to end of @implementation.
19455 else
19456 return;
19457 }
19458 // All conditions are met. Add a new bitfield to the tail end of ivars.
19459 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19460 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19461 Expr *BitWidth =
19462 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19463
19464 Ivar = ObjCIvarDecl::Create(
19465 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19466 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19467 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19468 AllIvarDecls.push_back(Elt: Ivar);
19469}
19470
19471/// [class.dtor]p4:
19472/// At the end of the definition of a class, overload resolution is
19473/// performed among the prospective destructors declared in that class with
19474/// an empty argument list to select the destructor for the class, also
19475/// known as the selected destructor.
19476///
19477/// We do the overload resolution here, then mark the selected constructor in the AST.
19478/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19479static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19480 if (!Record->hasUserDeclaredDestructor()) {
19481 return;
19482 }
19483
19484 SourceLocation Loc = Record->getLocation();
19485 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19486
19487 for (auto *Decl : Record->decls()) {
19488 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19489 if (DD->isInvalidDecl())
19490 continue;
19491 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19492 CandidateSet&: OCS);
19493 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19494 }
19495 }
19496
19497 if (OCS.empty()) {
19498 return;
19499 }
19500 OverloadCandidateSet::iterator Best;
19501 unsigned Msg = 0;
19502 OverloadCandidateDisplayKind DisplayKind;
19503
19504 switch (OCS.BestViableFunction(S, Loc, Best)) {
19505 case OR_Success:
19506 case OR_Deleted:
19507 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19508 break;
19509
19510 case OR_Ambiguous:
19511 Msg = diag::err_ambiguous_destructor;
19512 DisplayKind = OCD_AmbiguousCandidates;
19513 break;
19514
19515 case OR_No_Viable_Function:
19516 Msg = diag::err_no_viable_destructor;
19517 DisplayKind = OCD_AllCandidates;
19518 break;
19519 }
19520
19521 if (Msg) {
19522 // OpenCL have got their own thing going with destructors. It's slightly broken,
19523 // but we allow it.
19524 if (!S.LangOpts.OpenCL) {
19525 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19526 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19527 Record->setInvalidDecl();
19528 }
19529 // It's a bit hacky: At this point we've raised an error but we want the
19530 // rest of the compiler to continue somehow working. However almost
19531 // everything we'll try to do with the class will depend on there being a
19532 // destructor. So let's pretend the first one is selected and hope for the
19533 // best.
19534 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19535 }
19536}
19537
19538/// [class.mem.special]p5
19539/// Two special member functions are of the same kind if:
19540/// - they are both default constructors,
19541/// - they are both copy or move constructors with the same first parameter
19542/// type, or
19543/// - they are both copy or move assignment operators with the same first
19544/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19545static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19546 CXXMethodDecl *M1,
19547 CXXMethodDecl *M2,
19548 CXXSpecialMemberKind CSM) {
19549 // We don't want to compare templates to non-templates: See
19550 // https://github.com/llvm/llvm-project/issues/59206
19551 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19552 return bool(M1->getDescribedFunctionTemplate()) ==
19553 bool(M2->getDescribedFunctionTemplate());
19554 // FIXME: better resolve CWG
19555 // https://cplusplus.github.io/CWG/issues/2787.html
19556 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19557 T2: M2->getNonObjectParameter(I: 0)->getType()))
19558 return false;
19559 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19560 T2: M2->getFunctionObjectParameterReferenceType()))
19561 return false;
19562
19563 return true;
19564}
19565
19566/// [class.mem.special]p6:
19567/// An eligible special member function is a special member function for which:
19568/// - the function is not deleted,
19569/// - the associated constraints, if any, are satisfied, and
19570/// - no special member function of the same kind whose associated constraints
19571/// [CWG2595], if any, are satisfied is more constrained.
19572static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19573 ArrayRef<CXXMethodDecl *> Methods,
19574 CXXSpecialMemberKind CSM) {
19575 SmallVector<bool, 4> SatisfactionStatus;
19576
19577 for (CXXMethodDecl *Method : Methods) {
19578 if (!Method->getTrailingRequiresClause())
19579 SatisfactionStatus.push_back(Elt: true);
19580 else {
19581 ConstraintSatisfaction Satisfaction;
19582 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19583 SatisfactionStatus.push_back(Elt: false);
19584 else
19585 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19586 }
19587 }
19588
19589 for (size_t i = 0; i < Methods.size(); i++) {
19590 if (!SatisfactionStatus[i])
19591 continue;
19592 CXXMethodDecl *Method = Methods[i];
19593 CXXMethodDecl *OrigMethod = Method;
19594 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19595 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19596
19597 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19598 bool AnotherMethodIsMoreConstrained = false;
19599 for (size_t j = 0; j < Methods.size(); j++) {
19600 if (i == j || !SatisfactionStatus[j])
19601 continue;
19602 CXXMethodDecl *OtherMethod = Methods[j];
19603 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19604 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19605
19606 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19607 CSM))
19608 continue;
19609
19610 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19611 if (!Other)
19612 continue;
19613 if (!Orig) {
19614 AnotherMethodIsMoreConstrained = true;
19615 break;
19616 }
19617 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19618 Result&: AnotherMethodIsMoreConstrained)) {
19619 // There was an error with the constraints comparison. Exit the loop
19620 // and don't consider this function eligible.
19621 AnotherMethodIsMoreConstrained = true;
19622 }
19623 if (AnotherMethodIsMoreConstrained)
19624 break;
19625 }
19626 // FIXME: Do not consider deleted methods as eligible after implementing
19627 // DR1734 and DR1496.
19628 if (!AnotherMethodIsMoreConstrained) {
19629 Method->setIneligibleOrNotSelected(false);
19630 Record->addedEligibleSpecialMemberFunction(MD: Method,
19631 SMKind: 1 << llvm::to_underlying(E: CSM));
19632 }
19633 }
19634}
19635
19636static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19637 CXXRecordDecl *Record) {
19638 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19639 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19640 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19641 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19642 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19643
19644 for (auto *Decl : Record->decls()) {
19645 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19646 if (!MD) {
19647 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19648 if (FTD)
19649 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19650 }
19651 if (!MD)
19652 continue;
19653 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19654 if (CD->isInvalidDecl())
19655 continue;
19656 if (CD->isDefaultConstructor())
19657 DefaultConstructors.push_back(Elt: MD);
19658 else if (CD->isCopyConstructor())
19659 CopyConstructors.push_back(Elt: MD);
19660 else if (CD->isMoveConstructor())
19661 MoveConstructors.push_back(Elt: MD);
19662 } else if (MD->isCopyAssignmentOperator()) {
19663 CopyAssignmentOperators.push_back(Elt: MD);
19664 } else if (MD->isMoveAssignmentOperator()) {
19665 MoveAssignmentOperators.push_back(Elt: MD);
19666 }
19667 }
19668
19669 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19670 CSM: CXXSpecialMemberKind::DefaultConstructor);
19671 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19672 CSM: CXXSpecialMemberKind::CopyConstructor);
19673 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19674 CSM: CXXSpecialMemberKind::MoveConstructor);
19675 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19676 CSM: CXXSpecialMemberKind::CopyAssignment);
19677 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19678 CSM: CXXSpecialMemberKind::MoveAssignment);
19679}
19680
19681bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19682 // Check to see if a FieldDecl is a pointer to a function.
19683 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19684 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19685 if (!FD) {
19686 // Check whether this is a forward declaration that was inserted by
19687 // Clang. This happens when a non-forward declared / defined type is
19688 // used, e.g.:
19689 //
19690 // struct foo {
19691 // struct bar *(*f)();
19692 // struct bar *(*g)();
19693 // };
19694 //
19695 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19696 // incomplete definition.
19697 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19698 return !TD->isCompleteDefinition();
19699 return false;
19700 }
19701 QualType FieldType = FD->getType().getDesugaredType(Context);
19702 if (isa<PointerType>(Val: FieldType)) {
19703 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19704 return PointeeType.getDesugaredType(Context)->isFunctionType();
19705 }
19706 // If a member is a struct entirely of function pointers, that counts too.
19707 if (const auto *Record = FieldType->getAsRecordDecl();
19708 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19709 return true;
19710 return false;
19711 };
19712
19713 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19714}
19715
19716void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19717 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19718 SourceLocation RBrac,
19719 const ParsedAttributesView &Attrs) {
19720 assert(EnclosingDecl && "missing record or interface decl");
19721
19722 // If this is an Objective-C @implementation or category and we have
19723 // new fields here we should reset the layout of the interface since
19724 // it will now change.
19725 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19726 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19727 switch (DC->getKind()) {
19728 default: break;
19729 case Decl::ObjCCategory:
19730 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19731 break;
19732 case Decl::ObjCImplementation:
19733 Context.
19734 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19735 break;
19736 }
19737 }
19738
19739 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19740 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19741
19742 // Start counting up the number of named members; make sure to include
19743 // members of anonymous structs and unions in the total.
19744 unsigned NumNamedMembers = 0;
19745 if (Record) {
19746 for (const auto *I : Record->decls()) {
19747 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19748 if (IFD->getDeclName())
19749 ++NumNamedMembers;
19750 }
19751 }
19752
19753 // Verify that all the fields are okay.
19754 SmallVector<FieldDecl*, 32> RecFields;
19755 const FieldDecl *PreviousField = nullptr;
19756 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19757 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19758 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19759
19760 // Get the type for the field.
19761 const Type *FDTy = FD->getType().getTypePtr();
19762
19763 if (!FD->isAnonymousStructOrUnion()) {
19764 // Remember all fields written by the user.
19765 RecFields.push_back(Elt: FD);
19766 }
19767
19768 // If the field is already invalid for some reason, don't emit more
19769 // diagnostics about it.
19770 if (FD->isInvalidDecl()) {
19771 EnclosingDecl->setInvalidDecl();
19772 continue;
19773 }
19774
19775 // C99 6.7.2.1p2:
19776 // A structure or union shall not contain a member with
19777 // incomplete or function type (hence, a structure shall not
19778 // contain an instance of itself, but may contain a pointer to
19779 // an instance of itself), except that the last member of a
19780 // structure with more than one named member may have incomplete
19781 // array type; such a structure (and any union containing,
19782 // possibly recursively, a member that is such a structure)
19783 // shall not be a member of a structure or an element of an
19784 // array.
19785 bool IsLastField = (i + 1 == Fields.end());
19786 if (FDTy->isFunctionType()) {
19787 // Field declared as a function.
19788 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19789 << FD->getDeclName();
19790 FD->setInvalidDecl();
19791 EnclosingDecl->setInvalidDecl();
19792 continue;
19793 } else if (FDTy->isIncompleteArrayType() &&
19794 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19795 if (Record) {
19796 // Flexible array member.
19797 // Microsoft and g++ is more permissive regarding flexible array.
19798 // It will accept flexible array in union and also
19799 // as the sole element of a struct/class.
19800 unsigned DiagID = 0;
19801 if (!Record->isUnion() && !IsLastField) {
19802 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
19803 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19804 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
19805 FD->setInvalidDecl();
19806 EnclosingDecl->setInvalidDecl();
19807 continue;
19808 } else if (Record->isUnion())
19809 DiagID = getLangOpts().MicrosoftExt
19810 ? diag::ext_flexible_array_union_ms
19811 : diag::ext_flexible_array_union_gnu;
19812 else if (NumNamedMembers < 1)
19813 DiagID = getLangOpts().MicrosoftExt
19814 ? diag::ext_flexible_array_empty_aggregate_ms
19815 : diag::ext_flexible_array_empty_aggregate_gnu;
19816
19817 if (DiagID)
19818 Diag(Loc: FD->getLocation(), DiagID)
19819 << FD->getDeclName() << Record->getTagKind();
19820 // While the layout of types that contain virtual bases is not specified
19821 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19822 // virtual bases after the derived members. This would make a flexible
19823 // array member declared at the end of an object not adjacent to the end
19824 // of the type.
19825 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19826 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
19827 << FD->getDeclName() << Record->getTagKind();
19828 if (!getLangOpts().C99)
19829 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
19830 << FD->getDeclName() << Record->getTagKind();
19831
19832 // If the element type has a non-trivial destructor, we would not
19833 // implicitly destroy the elements, so disallow it for now.
19834 //
19835 // FIXME: GCC allows this. We should probably either implicitly delete
19836 // the destructor of the containing class, or just allow this.
19837 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
19838 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19839 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
19840 << FD->getDeclName() << FD->getType();
19841 FD->setInvalidDecl();
19842 EnclosingDecl->setInvalidDecl();
19843 continue;
19844 }
19845 // Okay, we have a legal flexible array member at the end of the struct.
19846 Record->setHasFlexibleArrayMember(true);
19847 } else {
19848 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19849 // unless they are followed by another ivar. That check is done
19850 // elsewhere, after synthesized ivars are known.
19851 }
19852 } else if (!FDTy->isDependentType() &&
19853 (LangOpts.HLSL // HLSL allows sizeless builtin types
19854 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
19855 DiagID: diag::err_incomplete_type)
19856 : RequireCompleteSizedType(
19857 Loc: FD->getLocation(), T: FD->getType(),
19858 DiagID: diag::err_field_incomplete_or_sizeless))) {
19859 // Incomplete type
19860 FD->setInvalidDecl();
19861 EnclosingDecl->setInvalidDecl();
19862 continue;
19863 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19864 if (Record && RD->hasFlexibleArrayMember()) {
19865 // A type which contains a flexible array member is considered to be a
19866 // flexible array member.
19867 Record->setHasFlexibleArrayMember(true);
19868 if (!Record->isUnion()) {
19869 // If this is a struct/class and this is not the last element, reject
19870 // it. Note that GCC supports variable sized arrays in the middle of
19871 // structures.
19872 if (!IsLastField)
19873 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
19874 << FD->getDeclName() << FD->getType();
19875 else {
19876 // We support flexible arrays at the end of structs in
19877 // other structs as an extension.
19878 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
19879 << FD->getDeclName();
19880 }
19881 }
19882 }
19883 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
19884 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
19885 DiagID: diag::err_abstract_type_in_decl,
19886 Args: AbstractIvarType)) {
19887 // Ivars can not have abstract class types
19888 FD->setInvalidDecl();
19889 }
19890 if (Record && RD->hasObjectMember())
19891 Record->setHasObjectMember(true);
19892 if (Record && RD->hasVolatileMember())
19893 Record->setHasVolatileMember(true);
19894 } else if (FDTy->isObjCObjectType()) {
19895 /// A field cannot be an Objective-c object
19896 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
19897 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
19898 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19899 FD->setType(T);
19900 } else if (Record && Record->isUnion() &&
19901 FD->getType().hasNonTrivialObjCLifetime() &&
19902 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
19903 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19904 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19905 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
19906 // For backward compatibility, fields of C unions declared in system
19907 // headers that have non-trivial ObjC ownership qualifications are marked
19908 // as unavailable unless the qualifier is explicit and __strong. This can
19909 // break ABI compatibility between programs compiled with ARC and MRR, but
19910 // is a better option than rejecting programs using those unions under
19911 // ARC.
19912 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19913 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
19914 Range: FD->getLocation()));
19915 } else if (getLangOpts().ObjC &&
19916 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19917 !Record->hasObjectMember()) {
19918 if (FD->getType()->isObjCObjectPointerType() ||
19919 FD->getType().isObjCGCStrong())
19920 Record->setHasObjectMember(true);
19921 else if (Context.getAsArrayType(T: FD->getType())) {
19922 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
19923 if (const auto *RD = BaseType->getAsRecordDecl();
19924 RD && RD->hasObjectMember())
19925 Record->setHasObjectMember(true);
19926 else if (BaseType->isObjCObjectPointerType() ||
19927 BaseType.isObjCGCStrong())
19928 Record->setHasObjectMember(true);
19929 }
19930 }
19931
19932 if (Record && !getLangOpts().CPlusPlus &&
19933 !shouldIgnoreForRecordTriviality(FD)) {
19934 QualType FT = FD->getType();
19935 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19936 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19937 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19938 Record->isUnion())
19939 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19940 }
19941 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19942 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19943 Record->setNonTrivialToPrimitiveCopy(true);
19944 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19945 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19946 }
19947 if (FD->hasAttr<ExplicitInitAttr>())
19948 Record->setHasUninitializedExplicitInitFields(true);
19949 if (FT.isDestructedType()) {
19950 Record->setNonTrivialToPrimitiveDestroy(true);
19951 Record->setParamDestroyedInCallee(true);
19952 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19953 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19954 }
19955
19956 if (const auto *RD = FT->getAsRecordDecl()) {
19957 if (RD->getArgPassingRestrictions() ==
19958 RecordArgPassingKind::CanNeverPassInRegs)
19959 Record->setArgPassingRestrictions(
19960 RecordArgPassingKind::CanNeverPassInRegs);
19961 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19962 Record->setArgPassingRestrictions(
19963 RecordArgPassingKind::CanNeverPassInRegs);
19964 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19965 Q && Q.isAddressDiscriminated()) {
19966 Record->setArgPassingRestrictions(
19967 RecordArgPassingKind::CanNeverPassInRegs);
19968 Record->setNonTrivialToPrimitiveCopy(true);
19969 }
19970 }
19971
19972 if (Record && FD->getType().isVolatileQualified())
19973 Record->setHasVolatileMember(true);
19974 bool ReportMSBitfieldStoragePacking =
19975 Record && PreviousField &&
19976 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
19977 Loc: Record->getLocation());
19978 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19979 return FD->isBitField() && !FD->getType()->isDependentType();
19980 };
19981
19982 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19983 IsNonDependentBitField(PreviousField)) {
19984 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
19985 CharUnits PreviousFieldStorageSize =
19986 Context.getTypeSizeInChars(T: PreviousField->getType());
19987 if (FDStorageSize != PreviousFieldStorageSize) {
19988 Diag(Loc: FD->getLocation(),
19989 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
19990 << FD << FD->getType() << FDStorageSize.getQuantity()
19991 << PreviousFieldStorageSize.getQuantity();
19992 Diag(Loc: PreviousField->getLocation(),
19993 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
19994 << PreviousField << PreviousField->getType();
19995 }
19996 }
19997 // Keep track of the number of named members.
19998 if (FD->getIdentifier())
19999 ++NumNamedMembers;
20000 }
20001
20002 // Okay, we successfully defined 'Record'.
20003 if (Record) {
20004 bool Completed = false;
20005 if (S) {
20006 Scope *Parent = S->getParent();
20007 if (Parent && Parent->isTypeAliasScope() &&
20008 Parent->isTemplateParamScope())
20009 Record->setInvalidDecl();
20010 }
20011
20012 if (CXXRecord) {
20013 if (!CXXRecord->isInvalidDecl()) {
20014 // Set access bits correctly on the directly-declared conversions.
20015 for (CXXRecordDecl::conversion_iterator
20016 I = CXXRecord->conversion_begin(),
20017 E = CXXRecord->conversion_end(); I != E; ++I)
20018 I.setAccess((*I)->getAccess());
20019 }
20020
20021 // Add any implicitly-declared members to this class.
20022 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20023
20024 if (!CXXRecord->isDependentType()) {
20025 if (!CXXRecord->isInvalidDecl()) {
20026 // If we have virtual base classes, we may end up finding multiple
20027 // final overriders for a given virtual function. Check for this
20028 // problem now.
20029 if (CXXRecord->getNumVBases()) {
20030 CXXFinalOverriderMap FinalOverriders;
20031 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20032
20033 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20034 MEnd = FinalOverriders.end();
20035 M != MEnd; ++M) {
20036 for (OverridingMethods::iterator SO = M->second.begin(),
20037 SOEnd = M->second.end();
20038 SO != SOEnd; ++SO) {
20039 assert(SO->second.size() > 0 &&
20040 "Virtual function without overriding functions?");
20041 if (SO->second.size() == 1)
20042 continue;
20043
20044 // C++ [class.virtual]p2:
20045 // In a derived class, if a virtual member function of a base
20046 // class subobject has more than one final overrider the
20047 // program is ill-formed.
20048 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20049 << (const NamedDecl *)M->first << Record;
20050 Diag(Loc: M->first->getLocation(),
20051 DiagID: diag::note_overridden_virtual_function);
20052 for (OverridingMethods::overriding_iterator
20053 OM = SO->second.begin(),
20054 OMEnd = SO->second.end();
20055 OM != OMEnd; ++OM)
20056 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20057 << (const NamedDecl *)M->first << OM->Method->getParent();
20058
20059 Record->setInvalidDecl();
20060 }
20061 }
20062 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20063 Completed = true;
20064 }
20065 }
20066 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20067 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20068 }
20069 }
20070
20071 if (!Completed)
20072 Record->completeDefinition();
20073
20074 // Handle attributes before checking the layout.
20075 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20076
20077 // Maybe randomize the record's decls. We automatically randomize a record
20078 // of function pointers, unless it has the "no_randomize_layout" attribute.
20079 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20080 !Record->isRandomized() && !Record->isUnion() &&
20081 (Record->hasAttr<RandomizeLayoutAttr>() ||
20082 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20083 EntirelyFunctionPointers(Record)))) {
20084 SmallVector<Decl *, 32> NewDeclOrdering;
20085 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20086 FinalOrdering&: NewDeclOrdering))
20087 Record->reorderDecls(Decls: NewDeclOrdering);
20088 }
20089
20090 // We may have deferred checking for a deleted destructor. Check now.
20091 if (CXXRecord) {
20092 auto *Dtor = CXXRecord->getDestructor();
20093 if (Dtor && Dtor->isImplicit() &&
20094 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20095 CXXRecord->setImplicitDestructorIsDeleted();
20096 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20097 }
20098 }
20099
20100 if (Record->hasAttrs()) {
20101 CheckAlignasUnderalignment(D: Record);
20102
20103 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20104 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20105 Range: IA->getRange(), BestCase: IA->getBestCase(),
20106 SemanticSpelling: IA->getInheritanceModel());
20107 }
20108
20109 // Check if the structure/union declaration is a type that can have zero
20110 // size in C. For C this is a language extension, for C++ it may cause
20111 // compatibility problems.
20112 bool CheckForZeroSize;
20113 if (!getLangOpts().CPlusPlus) {
20114 CheckForZeroSize = true;
20115 } else {
20116 // For C++ filter out types that cannot be referenced in C code.
20117 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20118 CheckForZeroSize =
20119 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20120 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20121 CXXRecord->isCLike();
20122 }
20123 if (CheckForZeroSize) {
20124 bool ZeroSize = true;
20125 bool IsEmpty = true;
20126 unsigned NonBitFields = 0;
20127 for (RecordDecl::field_iterator I = Record->field_begin(),
20128 E = Record->field_end();
20129 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20130 IsEmpty = false;
20131 if (I->isUnnamedBitField()) {
20132 if (!I->isZeroLengthBitField())
20133 ZeroSize = false;
20134 } else {
20135 ++NonBitFields;
20136 QualType FieldType = I->getType();
20137 if (FieldType->isIncompleteType() ||
20138 !Context.getTypeSizeInChars(T: FieldType).isZero())
20139 ZeroSize = false;
20140 }
20141 }
20142
20143 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20144 // allowed in C++, but warn if its declaration is inside
20145 // extern "C" block.
20146 if (ZeroSize) {
20147 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20148 diag::warn_zero_size_struct_union_in_extern_c :
20149 diag::warn_zero_size_struct_union_compat)
20150 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20151 }
20152
20153 // Structs without named members are extension in C (C99 6.7.2.1p7),
20154 // but are accepted by GCC. In C2y, this became implementation-defined
20155 // (C2y 6.7.3.2p10).
20156 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20157 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20158 : diag::ext_no_named_members_in_struct_union)
20159 << Record->isUnion();
20160 }
20161 }
20162 } else {
20163 ObjCIvarDecl **ClsFields =
20164 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20165 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20166 ID->setEndOfDefinitionLoc(RBrac);
20167 // Add ivar's to class's DeclContext.
20168 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20169 ClsFields[i]->setLexicalDeclContext(ID);
20170 ID->addDecl(D: ClsFields[i]);
20171 }
20172 // Must enforce the rule that ivars in the base classes may not be
20173 // duplicates.
20174 if (ID->getSuperClass())
20175 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20176 } else if (ObjCImplementationDecl *IMPDecl =
20177 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20178 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20179 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20180 // Ivar declared in @implementation never belongs to the implementation.
20181 // Only it is in implementation's lexical context.
20182 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20183 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20184 Loc: RBrac);
20185 IMPDecl->setIvarLBraceLoc(LBrac);
20186 IMPDecl->setIvarRBraceLoc(RBrac);
20187 } else if (ObjCCategoryDecl *CDecl =
20188 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20189 // case of ivars in class extension; all other cases have been
20190 // reported as errors elsewhere.
20191 // FIXME. Class extension does not have a LocEnd field.
20192 // CDecl->setLocEnd(RBrac);
20193 // Add ivar's to class extension's DeclContext.
20194 // Diagnose redeclaration of private ivars.
20195 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20196 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20197 if (IDecl) {
20198 if (const ObjCIvarDecl *ClsIvar =
20199 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20200 Diag(Loc: ClsFields[i]->getLocation(),
20201 DiagID: diag::err_duplicate_ivar_declaration);
20202 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20203 continue;
20204 }
20205 for (const auto *Ext : IDecl->known_extensions()) {
20206 if (const ObjCIvarDecl *ClsExtIvar
20207 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20208 Diag(Loc: ClsFields[i]->getLocation(),
20209 DiagID: diag::err_duplicate_ivar_declaration);
20210 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20211 continue;
20212 }
20213 }
20214 }
20215 ClsFields[i]->setLexicalDeclContext(CDecl);
20216 CDecl->addDecl(D: ClsFields[i]);
20217 }
20218 CDecl->setIvarLBraceLoc(LBrac);
20219 CDecl->setIvarRBraceLoc(RBrac);
20220 }
20221 }
20222 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20223 ProcessAPINotes(D: Record);
20224}
20225
20226// Given an integral type, return the next larger integral type
20227// (or a NULL type of no such type exists).
20228static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20229 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20230 // enum checking below.
20231 assert((T->isIntegralType(Context) ||
20232 T->isEnumeralType()) && "Integral type required!");
20233 const unsigned NumTypes = 4;
20234 QualType SignedIntegralTypes[NumTypes] = {
20235 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20236 };
20237 QualType UnsignedIntegralTypes[NumTypes] = {
20238 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20239 Context.UnsignedLongLongTy
20240 };
20241
20242 unsigned BitWidth = Context.getTypeSize(T);
20243 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20244 : UnsignedIntegralTypes;
20245 for (unsigned I = 0; I != NumTypes; ++I)
20246 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20247 return Types[I];
20248
20249 return QualType();
20250}
20251
20252EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20253 EnumConstantDecl *LastEnumConst,
20254 SourceLocation IdLoc,
20255 IdentifierInfo *Id,
20256 Expr *Val) {
20257 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20258 llvm::APSInt EnumVal(IntWidth);
20259 QualType EltTy;
20260
20261 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20262 Val = nullptr;
20263
20264 if (Val)
20265 Val = DefaultLvalueConversion(E: Val).get();
20266
20267 if (Val) {
20268 if (Enum->isDependentType() || Val->isTypeDependent() ||
20269 Val->containsErrors())
20270 EltTy = Context.DependentTy;
20271 else {
20272 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20273 // underlying type, but do allow it in all other contexts.
20274 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20275 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20276 // constant-expression in the enumerator-definition shall be a converted
20277 // constant expression of the underlying type.
20278 EltTy = Enum->getIntegerType();
20279 ExprResult Converted = CheckConvertedConstantExpression(
20280 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20281 if (Converted.isInvalid())
20282 Val = nullptr;
20283 else
20284 Val = Converted.get();
20285 } else if (!Val->isValueDependent() &&
20286 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20287 CanFold: AllowFoldKind::Allow)
20288 .get())) {
20289 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20290 } else {
20291 if (Enum->isComplete()) {
20292 EltTy = Enum->getIntegerType();
20293
20294 // In Obj-C and Microsoft mode, require the enumeration value to be
20295 // representable in the underlying type of the enumeration. In C++11,
20296 // we perform a non-narrowing conversion as part of converted constant
20297 // expression checking.
20298 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20299 if (Context.getTargetInfo()
20300 .getTriple()
20301 .isWindowsMSVCEnvironment()) {
20302 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20303 } else {
20304 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20305 }
20306 }
20307
20308 // Cast to the underlying type.
20309 Val = ImpCastExprToType(E: Val, Type: EltTy,
20310 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20311 : CK_IntegralCast)
20312 .get();
20313 } else if (getLangOpts().CPlusPlus) {
20314 // C++11 [dcl.enum]p5:
20315 // If the underlying type is not fixed, the type of each enumerator
20316 // is the type of its initializing value:
20317 // - If an initializer is specified for an enumerator, the
20318 // initializing value has the same type as the expression.
20319 EltTy = Val->getType();
20320 } else {
20321 // C99 6.7.2.2p2:
20322 // The expression that defines the value of an enumeration constant
20323 // shall be an integer constant expression that has a value
20324 // representable as an int.
20325
20326 // Complain if the value is not representable in an int.
20327 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20328 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20329 ? diag::warn_c17_compat_enum_value_not_int
20330 : diag::ext_c23_enum_value_not_int)
20331 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20332 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20333 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20334 // Force the type of the expression to 'int'.
20335 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20336 }
20337 EltTy = Val->getType();
20338 }
20339 }
20340 }
20341 }
20342
20343 if (!Val) {
20344 if (Enum->isDependentType())
20345 EltTy = Context.DependentTy;
20346 else if (!LastEnumConst) {
20347 // C++0x [dcl.enum]p5:
20348 // If the underlying type is not fixed, the type of each enumerator
20349 // is the type of its initializing value:
20350 // - If no initializer is specified for the first enumerator, the
20351 // initializing value has an unspecified integral type.
20352 //
20353 // GCC uses 'int' for its unspecified integral type, as does
20354 // C99 6.7.2.2p3.
20355 if (Enum->isFixed()) {
20356 EltTy = Enum->getIntegerType();
20357 }
20358 else {
20359 EltTy = Context.IntTy;
20360 }
20361 } else {
20362 // Assign the last value + 1.
20363 EnumVal = LastEnumConst->getInitVal();
20364 ++EnumVal;
20365 EltTy = LastEnumConst->getType();
20366
20367 // Check for overflow on increment.
20368 if (EnumVal < LastEnumConst->getInitVal()) {
20369 // C++0x [dcl.enum]p5:
20370 // If the underlying type is not fixed, the type of each enumerator
20371 // is the type of its initializing value:
20372 //
20373 // - Otherwise the type of the initializing value is the same as
20374 // the type of the initializing value of the preceding enumerator
20375 // unless the incremented value is not representable in that type,
20376 // in which case the type is an unspecified integral type
20377 // sufficient to contain the incremented value. If no such type
20378 // exists, the program is ill-formed.
20379 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20380 if (T.isNull() || Enum->isFixed()) {
20381 // There is no integral type larger enough to represent this
20382 // value. Complain, then allow the value to wrap around.
20383 EnumVal = LastEnumConst->getInitVal();
20384 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20385 ++EnumVal;
20386 if (Enum->isFixed())
20387 // When the underlying type is fixed, this is ill-formed.
20388 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20389 << toString(I: EnumVal, Radix: 10)
20390 << EltTy;
20391 else
20392 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20393 << toString(I: EnumVal, Radix: 10);
20394 } else {
20395 EltTy = T;
20396 }
20397
20398 // Retrieve the last enumerator's value, extent that type to the
20399 // type that is supposed to be large enough to represent the incremented
20400 // value, then increment.
20401 EnumVal = LastEnumConst->getInitVal();
20402 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20403 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20404 ++EnumVal;
20405
20406 // If we're not in C++, diagnose the overflow of enumerator values,
20407 // which in C99 means that the enumerator value is not representable in
20408 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20409 // are representable in some larger integral type and we allow it in
20410 // older language modes as an extension.
20411 // Exclude fixed enumerators since they are diagnosed with an error for
20412 // this case.
20413 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20414 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20415 ? diag::warn_c17_compat_enum_value_not_int
20416 : diag::ext_c23_enum_value_not_int)
20417 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20418 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20419 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20420 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20421 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20422 : diag::ext_c23_enum_value_not_int)
20423 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20424 }
20425 }
20426 }
20427
20428 if (!EltTy->isDependentType()) {
20429 // Make the enumerator value match the signedness and size of the
20430 // enumerator's type.
20431 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20432 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20433 }
20434
20435 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20436 E: Val, V: EnumVal);
20437}
20438
20439SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20440 SourceLocation IILoc) {
20441 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20442 !getLangOpts().CPlusPlus)
20443 return SkipBodyInfo();
20444
20445 // We have an anonymous enum definition. Look up the first enumerator to
20446 // determine if we should merge the definition with an existing one and
20447 // skip the body.
20448 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20449 Redecl: forRedeclarationInCurContext());
20450 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20451 if (!PrevECD)
20452 return SkipBodyInfo();
20453
20454 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20455 NamedDecl *Hidden;
20456 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20457 SkipBodyInfo Skip;
20458 Skip.Previous = Hidden;
20459 return Skip;
20460 }
20461
20462 return SkipBodyInfo();
20463}
20464
20465Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20466 SourceLocation IdLoc, IdentifierInfo *Id,
20467 const ParsedAttributesView &Attrs,
20468 SourceLocation EqualLoc, Expr *Val,
20469 SkipBodyInfo *SkipBody) {
20470 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20471 EnumConstantDecl *LastEnumConst =
20472 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20473
20474 // The scope passed in may not be a decl scope. Zip up the scope tree until
20475 // we find one that is.
20476 S = getNonFieldDeclScope(S);
20477
20478 // Verify that there isn't already something declared with this name in this
20479 // scope.
20480 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20481 RedeclarationKind::ForVisibleRedeclaration);
20482 LookupName(R, S);
20483 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20484
20485 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20486 // Maybe we will complain about the shadowed template parameter.
20487 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20488 // Just pretend that we didn't see the previous declaration.
20489 PrevDecl = nullptr;
20490 }
20491
20492 // C++ [class.mem]p15:
20493 // If T is the name of a class, then each of the following shall have a name
20494 // different from T:
20495 // - every enumerator of every member of class T that is an unscoped
20496 // enumerated type
20497 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20498 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20499 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20500 return nullptr;
20501
20502 EnumConstantDecl *New =
20503 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20504 if (!New)
20505 return nullptr;
20506
20507 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20508 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20509 // Check for other kinds of shadowing not already handled.
20510 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20511 }
20512
20513 // When in C++, we may get a TagDecl with the same name; in this case the
20514 // enum constant will 'hide' the tag.
20515 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20516 "Received TagDecl when not in C++!");
20517 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20518 if (isa<EnumConstantDecl>(Val: PrevDecl))
20519 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20520 else
20521 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20522 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20523 return nullptr;
20524 }
20525 }
20526
20527 // Process attributes.
20528 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20529 AddPragmaAttributes(S, D: New);
20530 ProcessAPINotes(D: New);
20531
20532 // Register this decl in the current scope stack.
20533 New->setAccess(TheEnumDecl->getAccess());
20534 PushOnScopeChains(D: New, S);
20535
20536 ActOnDocumentableDecl(D: New);
20537
20538 return New;
20539}
20540
20541// Returns true when the enum initial expression does not trigger the
20542// duplicate enum warning. A few common cases are exempted as follows:
20543// Element2 = Element1
20544// Element2 = Element1 + 1
20545// Element2 = Element1 - 1
20546// Where Element2 and Element1 are from the same enum.
20547static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20548 Expr *InitExpr = ECD->getInitExpr();
20549 if (!InitExpr)
20550 return true;
20551 InitExpr = InitExpr->IgnoreImpCasts();
20552
20553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20554 if (!BO->isAdditiveOp())
20555 return true;
20556 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20557 if (!IL)
20558 return true;
20559 if (IL->getValue() != 1)
20560 return true;
20561
20562 InitExpr = BO->getLHS();
20563 }
20564
20565 // This checks if the elements are from the same enum.
20566 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20567 if (!DRE)
20568 return true;
20569
20570 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20571 if (!EnumConstant)
20572 return true;
20573
20574 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20575 Enum)
20576 return true;
20577
20578 return false;
20579}
20580
20581// Emits a warning when an element is implicitly set a value that
20582// a previous element has already been set to.
20583static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20584 EnumDecl *Enum, QualType EnumType) {
20585 // Avoid anonymous enums
20586 if (!Enum->getIdentifier())
20587 return;
20588
20589 // Only check for small enums.
20590 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20591 return;
20592
20593 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20594 return;
20595
20596 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20597 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20598
20599 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20600
20601 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20602 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20603
20604 // Use int64_t as a key to avoid needing special handling for map keys.
20605 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20606 llvm::APSInt Val = D->getInitVal();
20607 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20608 };
20609
20610 DuplicatesVector DupVector;
20611 ValueToVectorMap EnumMap;
20612
20613 // Populate the EnumMap with all values represented by enum constants without
20614 // an initializer.
20615 for (auto *Element : Elements) {
20616 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20617
20618 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20619 // this constant. Skip this enum since it may be ill-formed.
20620 if (!ECD) {
20621 return;
20622 }
20623
20624 // Constants with initializers are handled in the next loop.
20625 if (ECD->getInitExpr())
20626 continue;
20627
20628 // Duplicate values are handled in the next loop.
20629 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20630 }
20631
20632 if (EnumMap.size() == 0)
20633 return;
20634
20635 // Create vectors for any values that has duplicates.
20636 for (auto *Element : Elements) {
20637 // The last loop returned if any constant was null.
20638 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20639 if (!ValidDuplicateEnum(ECD, Enum))
20640 continue;
20641
20642 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20643 if (Iter == EnumMap.end())
20644 continue;
20645
20646 DeclOrVector& Entry = Iter->second;
20647 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20648 // Ensure constants are different.
20649 if (D == ECD)
20650 continue;
20651
20652 // Create new vector and push values onto it.
20653 auto Vec = std::make_unique<ECDVector>();
20654 Vec->push_back(Elt: D);
20655 Vec->push_back(Elt: ECD);
20656
20657 // Update entry to point to the duplicates vector.
20658 Entry = Vec.get();
20659
20660 // Store the vector somewhere we can consult later for quick emission of
20661 // diagnostics.
20662 DupVector.emplace_back(Args: std::move(Vec));
20663 continue;
20664 }
20665
20666 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20667 // Make sure constants are not added more than once.
20668 if (*Vec->begin() == ECD)
20669 continue;
20670
20671 Vec->push_back(Elt: ECD);
20672 }
20673
20674 // Emit diagnostics.
20675 for (const auto &Vec : DupVector) {
20676 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20677
20678 // Emit warning for one enum constant.
20679 auto *FirstECD = Vec->front();
20680 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20681 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20682 << FirstECD->getSourceRange();
20683
20684 // Emit one note for each of the remaining enum constants with
20685 // the same value.
20686 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20687 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20688 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20689 << ECD->getSourceRange();
20690 }
20691}
20692
20693bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20694 bool AllowMask) const {
20695 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20696 assert(ED->isCompleteDefinition() && "expected enum definition");
20697
20698 auto R = FlagBitsCache.try_emplace(Key: ED);
20699 llvm::APInt &FlagBits = R.first->second;
20700
20701 if (R.second) {
20702 for (auto *E : ED->enumerators()) {
20703 const auto &EVal = E->getInitVal();
20704 // Only single-bit enumerators introduce new flag values.
20705 if (EVal.isPowerOf2())
20706 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20707 }
20708 }
20709
20710 // A value is in a flag enum if either its bits are a subset of the enum's
20711 // flag bits (the first condition) or we are allowing masks and the same is
20712 // true of its complement (the second condition). When masks are allowed, we
20713 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20714 //
20715 // While it's true that any value could be used as a mask, the assumption is
20716 // that a mask will have all of the insignificant bits set. Anything else is
20717 // likely a logic error.
20718 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20719 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20720}
20721
20722// Emits a warning when a suspicious comparison operator is used along side
20723// binary operators in enum initializers.
20724static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20725 const EnumDecl *Enum) {
20726 bool HasBitwiseOp = false;
20727 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20728
20729 // Iterate over all the enum values, gather suspisious comparison ops and
20730 // whether any enum initialisers contain a binary operator.
20731 for (const auto *ECD : Enum->enumerators()) {
20732 const Expr *InitExpr = ECD->getInitExpr();
20733 if (!InitExpr)
20734 continue;
20735
20736 const Expr *E = InitExpr->IgnoreParenImpCasts();
20737
20738 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
20739 BinaryOperatorKind Op = BinOp->getOpcode();
20740
20741 // Check for bitwise ops (<<, >>, &, |)
20742 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20743 HasBitwiseOp = true;
20744 } else if (Op == BO_LT || Op == BO_GT) {
20745 // Check for the typo pattern (Comparison < or >)
20746 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20747 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
20748 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20749 if (IntLiteral->getValue() == 1)
20750 SuspiciousCompares.push_back(Elt: BinOp);
20751 }
20752 }
20753 }
20754 }
20755
20756 // If we found a bitwise op and some sus compares, iterate over the compares
20757 // and warn.
20758 if (HasBitwiseOp) {
20759 for (const auto *BinOp : SuspiciousCompares) {
20760 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20761 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
20762 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
20763 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20764
20765 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
20766 << BinOp->getOpcodeStr() << SuggestedOp;
20767
20768 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
20769 << SuggestedOp
20770 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
20771 }
20772 }
20773}
20774
20775void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20776 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20777 const ParsedAttributesView &Attrs) {
20778 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20779 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
20780
20781 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20782 ProcessAPINotes(D: Enum);
20783
20784 if (Enum->isDependentType()) {
20785 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20786 EnumConstantDecl *ECD =
20787 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20788 if (!ECD) continue;
20789
20790 ECD->setType(EnumType);
20791 }
20792
20793 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20794 return;
20795 }
20796
20797 // Verify that all the values are okay, compute the size of the values, and
20798 // reverse the list.
20799 unsigned NumNegativeBits = 0;
20800 unsigned NumPositiveBits = 0;
20801 bool MembersRepresentableByInt =
20802 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20803
20804 // Figure out the type that should be used for this enum.
20805 QualType BestType;
20806 unsigned BestWidth;
20807
20808 // C++0x N3000 [conv.prom]p3:
20809 // An rvalue of an unscoped enumeration type whose underlying
20810 // type is not fixed can be converted to an rvalue of the first
20811 // of the following types that can represent all the values of
20812 // the enumeration: int, unsigned int, long int, unsigned long
20813 // int, long long int, or unsigned long long int.
20814 // C99 6.4.4.3p2:
20815 // An identifier declared as an enumeration constant has type int.
20816 // The C99 rule is modified by C23.
20817 QualType BestPromotionType;
20818
20819 bool Packed = Enum->hasAttr<PackedAttr>();
20820 // -fshort-enums is the equivalent to specifying the packed attribute on all
20821 // enum definitions.
20822 if (LangOpts.ShortEnums)
20823 Packed = true;
20824
20825 // If the enum already has a type because it is fixed or dictated by the
20826 // target, promote that type instead of analyzing the enumerators.
20827 if (Enum->isComplete()) {
20828 BestType = Enum->getIntegerType();
20829 if (Context.isPromotableIntegerType(T: BestType))
20830 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20831 else
20832 BestPromotionType = BestType;
20833
20834 BestWidth = Context.getIntWidth(T: BestType);
20835 } else {
20836 bool EnumTooLarge = Context.computeBestEnumTypes(
20837 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20838 BestWidth = Context.getIntWidth(T: BestType);
20839 if (EnumTooLarge)
20840 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
20841 }
20842
20843 // Loop over all of the enumerator constants, changing their types to match
20844 // the type of the enum if needed.
20845 for (auto *D : Elements) {
20846 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20847 if (!ECD) continue; // Already issued a diagnostic.
20848
20849 // C99 says the enumerators have int type, but we allow, as an
20850 // extension, the enumerators to be larger than int size. If each
20851 // enumerator value fits in an int, type it as an int, otherwise type it the
20852 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20853 // that X has type 'int', not 'unsigned'.
20854
20855 // Determine whether the value fits into an int.
20856 llvm::APSInt InitVal = ECD->getInitVal();
20857
20858 // If it fits into an integer type, force it. Otherwise force it to match
20859 // the enum decl type.
20860 QualType NewTy;
20861 unsigned NewWidth;
20862 bool NewSign;
20863 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20864 MembersRepresentableByInt) {
20865 // C23 6.7.3.3.3p15:
20866 // The enumeration member type for an enumerated type without fixed
20867 // underlying type upon completion is:
20868 // - int if all the values of the enumeration are representable as an
20869 // int; or,
20870 // - the enumerated type
20871 NewTy = Context.IntTy;
20872 NewWidth = Context.getTargetInfo().getIntWidth();
20873 NewSign = true;
20874 } else if (ECD->getType() == BestType) {
20875 // Already the right type!
20876 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
20877 // C++ [dcl.enum]p4: Following the closing brace of an
20878 // enum-specifier, each enumerator has the type of its
20879 // enumeration.
20880 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20881 // with fixed underlying type is the enumerated type.
20882 ECD->setType(EnumType);
20883 continue;
20884 } else {
20885 NewTy = BestType;
20886 NewWidth = BestWidth;
20887 NewSign = BestType->isSignedIntegerOrEnumerationType();
20888 }
20889
20890 // Adjust the APSInt value.
20891 InitVal = InitVal.extOrTrunc(width: NewWidth);
20892 InitVal.setIsSigned(NewSign);
20893 ECD->setInitVal(C: Context, V: InitVal);
20894
20895 // Adjust the Expr initializer and type.
20896 if (ECD->getInitExpr() &&
20897 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20898 ECD->setInitExpr(ImplicitCastExpr::Create(
20899 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20900 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20901 if (getLangOpts().CPlusPlus ||
20902 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
20903 // C++ [dcl.enum]p4: Following the closing brace of an
20904 // enum-specifier, each enumerator has the type of its
20905 // enumeration.
20906 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20907 // with fixed underlying type is the enumerated type.
20908 ECD->setType(EnumType);
20909 else
20910 ECD->setType(NewTy);
20911 }
20912
20913 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20914 NumPositiveBits, NumNegativeBits);
20915
20916 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20917 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
20918
20919 if (Enum->isClosedFlag()) {
20920 for (Decl *D : Elements) {
20921 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20922 if (!ECD) continue; // Already issued a diagnostic.
20923
20924 llvm::APSInt InitVal = ECD->getInitVal();
20925 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20926 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
20927 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
20928 << ECD << Enum;
20929 }
20930 }
20931
20932 // Now that the enum type is defined, ensure it's not been underaligned.
20933 if (Enum->hasAttrs())
20934 CheckAlignasUnderalignment(D: Enum);
20935}
20936
20937Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
20938 SourceLocation EndLoc) {
20939
20940 FileScopeAsmDecl *New =
20941 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
20942 CurContext->addDecl(D: New);
20943 return New;
20944}
20945
20946TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20947 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
20948 CurContext->addDecl(D: New);
20949 PushDeclContext(S, DC: New);
20950 PushFunctionScope();
20951 PushCompoundScope(IsStmtExpr: false);
20952 return New;
20953}
20954
20955void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20956 if (Statement)
20957 D->setStmt(Statement);
20958 PopCompoundScope();
20959 PopFunctionScopeInfo();
20960 PopDeclContext();
20961}
20962
20963void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20964 IdentifierInfo* AliasName,
20965 SourceLocation PragmaLoc,
20966 SourceLocation NameLoc,
20967 SourceLocation AliasNameLoc) {
20968 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20969 NameKind: LookupOrdinaryName);
20970 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20971 AttributeCommonInfo::Form::Pragma());
20972 AsmLabelAttr *Attr =
20973 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
20974
20975 // If a declaration that:
20976 // 1) declares a function or a variable
20977 // 2) has external linkage
20978 // already exists, add a label attribute to it.
20979 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20980 if (isDeclExternC(D: PrevDecl))
20981 PrevDecl->addAttr(A: Attr);
20982 else
20983 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
20984 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
20985 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20986 } else
20987 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
20988}
20989
20990void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20991 SourceLocation PragmaLoc,
20992 SourceLocation NameLoc) {
20993 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
20994
20995 if (PrevDecl) {
20996 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
20997 } else {
20998 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
20999 }
21000}
21001
21002void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21003 IdentifierInfo* AliasName,
21004 SourceLocation PragmaLoc,
21005 SourceLocation NameLoc,
21006 SourceLocation AliasNameLoc) {
21007 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21008 NameKind: LookupOrdinaryName);
21009 WeakInfo W = WeakInfo(Name, NameLoc);
21010
21011 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21012 if (!PrevDecl->hasAttr<AliasAttr>())
21013 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21014 DeclApplyPragmaWeak(S: TUScope, ND, W);
21015 } else {
21016 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21017 }
21018}
21019
21020Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21021 bool Final) {
21022 assert(FD && "Expected non-null FunctionDecl");
21023
21024 // SYCL functions can be template, so we check if they have appropriate
21025 // attribute prior to checking if it is a template.
21026 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
21027 return FunctionEmissionStatus::Emitted;
21028
21029 // Templates are emitted when they're instantiated.
21030 if (FD->isDependentContext())
21031 return FunctionEmissionStatus::TemplateDiscarded;
21032
21033 // Check whether this function is an externally visible definition.
21034 auto IsEmittedForExternalSymbol = [this, FD]() {
21035 // We have to check the GVA linkage of the function's *definition* -- if we
21036 // only have a declaration, we don't know whether or not the function will
21037 // be emitted, because (say) the definition could include "inline".
21038 const FunctionDecl *Def = FD->getDefinition();
21039
21040 // We can't compute linkage when we skip function bodies.
21041 return Def && !Def->hasSkippedBody() &&
21042 !isDiscardableGVALinkage(
21043 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21044 };
21045
21046 if (LangOpts.OpenMPIsTargetDevice) {
21047 // In OpenMP device mode we will not emit host only functions, or functions
21048 // we don't need due to their linkage.
21049 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21050 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21051 // DevTy may be changed later by
21052 // #pragma omp declare target to(*) device_type(*).
21053 // Therefore DevTy having no value does not imply host. The emission status
21054 // will be checked again at the end of compilation unit with Final = true.
21055 if (DevTy)
21056 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21057 return FunctionEmissionStatus::OMPDiscarded;
21058 // If we have an explicit value for the device type, or we are in a target
21059 // declare context, we need to emit all extern and used symbols.
21060 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21061 if (IsEmittedForExternalSymbol())
21062 return FunctionEmissionStatus::Emitted;
21063 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21064 // we'll omit it.
21065 if (Final)
21066 return FunctionEmissionStatus::OMPDiscarded;
21067 } else if (LangOpts.OpenMP > 45) {
21068 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21069 // function. In 5.0, no_host was introduced which might cause a function to
21070 // be omitted.
21071 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21072 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21073 if (DevTy)
21074 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21075 return FunctionEmissionStatus::OMPDiscarded;
21076 }
21077
21078 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21079 return FunctionEmissionStatus::Emitted;
21080
21081 if (LangOpts.CUDA) {
21082 // When compiling for device, host functions are never emitted. Similarly,
21083 // when compiling for host, device and global functions are never emitted.
21084 // (Technically, we do emit a host-side stub for global functions, but this
21085 // doesn't count for our purposes here.)
21086 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21087 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21088 return FunctionEmissionStatus::CUDADiscarded;
21089 if (!LangOpts.CUDAIsDevice &&
21090 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21091 return FunctionEmissionStatus::CUDADiscarded;
21092
21093 if (IsEmittedForExternalSymbol())
21094 return FunctionEmissionStatus::Emitted;
21095
21096 // If FD is a virtual destructor of an explicit instantiation
21097 // of a template class, return Emitted.
21098 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
21099 if (Destructor->isVirtual()) {
21100 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21101 Val: Destructor->getParent())) {
21102 TemplateSpecializationKind TSK =
21103 Spec->getTemplateSpecializationKind();
21104 if (TSK == TSK_ExplicitInstantiationDeclaration ||
21105 TSK == TSK_ExplicitInstantiationDefinition)
21106 return FunctionEmissionStatus::Emitted;
21107 }
21108 }
21109 }
21110 }
21111
21112 // Otherwise, the function is known-emitted if it's in our set of
21113 // known-emitted functions.
21114 return FunctionEmissionStatus::Unknown;
21115}
21116
21117bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21118 // Host-side references to a __global__ function refer to the stub, so the
21119 // function itself is never emitted and therefore should not be marked.
21120 // If we have host fn calls kernel fn calls host+device, the HD function
21121 // does not get instantiated on the host. We model this by omitting at the
21122 // call to the kernel from the callgraph. This ensures that, when compiling
21123 // for host, only HD functions actually called from the host get marked as
21124 // known-emitted.
21125 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21126 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21127}
21128
21129bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21130 bool &Visible) {
21131 Visible = hasVisibleDefinition(D, Suggested);
21132 // The redefinition of D in the **current** TU is allowed if D is invisible or
21133 // D is defined in the global module of other module units. We didn't check if
21134 // it is in global module as, we'll check the redefinition in named module
21135 // later with better diagnostic message.
21136 return D->isInAnotherModuleUnit() || !Visible;
21137}
21138