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
557 if (getLangOpts().HLSL) {
558 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
559 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
560 /*AllowDependent=*/false))) {
561 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
562 if (!ShorthandTy.isNull())
563 return ParsedType::make(P: ShorthandTy);
564 }
565 }
566
567 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
568 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
569 if (!HasTrailingDot) {
570 // FIXME: Support UsingType for this case.
571 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
572 if (!WantNontrivialTypeSourceInfo)
573 return ParsedType::make(P: T);
574 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
575 TL.setNameLoc(NameLoc);
576 // FIXME: Pass in this source location.
577 TL.setNameEndLoc(NameLoc);
578 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
579 }
580 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
581 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
582 // Recover with 'int'
583 return ParsedType::make(P: Context.IntTy);
584 } else if (AllowDeducedTemplate) {
585 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
586 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
587 // FIXME: Support UsingType here.
588 TemplateName Template = Context.getQualifiedTemplateName(
589 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
590 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
591 QualType T = Context.getDeducedTemplateSpecializationType(
592 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
593 Template);
594 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
595 TL.setElaboratedKeywordLoc(SourceLocation());
596 TL.setNameLoc(NameLoc);
597 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
598 : NestedNameSpecifierLoc());
599 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
600 }
601 }
602
603 // As it's not plausibly a type, suppress diagnostics.
604 Result.suppressDiagnostics();
605 return nullptr;
606}
607
608// Builds a fake NNS for the given decl context.
609static NestedNameSpecifier
610synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
611 for (;; DC = DC->getLookupParent()) {
612 DC = DC->getPrimaryContext();
613 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
614 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
615 return NestedNameSpecifier(Context, ND, std::nullopt);
616 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
617 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
618 if (isa<TranslationUnitDecl>(Val: DC))
619 return NestedNameSpecifier::getGlobal();
620 }
621 llvm_unreachable("something isn't in TU scope?");
622}
623
624/// Find the parent class with dependent bases of the innermost enclosing method
625/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
626/// up allowing unqualified dependent type names at class-level, which MSVC
627/// correctly rejects.
628static const CXXRecordDecl *
629findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
630 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
631 DC = DC->getPrimaryContext();
632 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
633 if (MD->getParent()->hasAnyDependentBases())
634 return MD->getParent();
635 }
636 return nullptr;
637}
638
639ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
640 SourceLocation NameLoc,
641 bool IsTemplateTypeArg) {
642 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
643
644 NestedNameSpecifier NNS = std::nullopt;
645 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
646 // If we weren't able to parse a default template argument, delay lookup
647 // until instantiation time by making a non-dependent DependentTypeName. We
648 // pretend we saw a NestedNameSpecifier referring to the current scope, and
649 // lookup is retried.
650 // FIXME: This hurts our diagnostic quality, since we get errors like "no
651 // type named 'Foo' in 'current_namespace'" when the user didn't write any
652 // name specifiers.
653 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
654 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
655 } else if (const CXXRecordDecl *RD =
656 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
657 // Build a DependentNameType that will perform lookup into RD at
658 // instantiation time.
659 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
660
661 // Diagnose that this identifier was undeclared, and retry the lookup during
662 // template instantiation.
663 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
664 << RD;
665 } else {
666 // This is not a situation that we should recover from.
667 return ParsedType();
668 }
669
670 QualType T =
671 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
672
673 // Build type location information. We synthesized the qualifier, so we have
674 // to build a fake NestedNameSpecifierLoc.
675 NestedNameSpecifierLocBuilder NNSLocBuilder;
676 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
677 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
678
679 TypeLocBuilder Builder;
680 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
681 DepTL.setNameLoc(NameLoc);
682 DepTL.setElaboratedKeywordLoc(SourceLocation());
683 DepTL.setQualifierLoc(QualifierLoc);
684 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
685}
686
687DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
688 // Do a tag name lookup in this scope.
689 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
690 LookupName(R, S, AllowBuiltinCreation: false);
691 R.suppressDiagnostics();
692 if (R.getResultKind() == LookupResultKind::Found)
693 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
694 switch (TD->getTagKind()) {
695 case TagTypeKind::Struct:
696 return DeclSpec::TST_struct;
697 case TagTypeKind::Interface:
698 return DeclSpec::TST_interface;
699 case TagTypeKind::Union:
700 return DeclSpec::TST_union;
701 case TagTypeKind::Class:
702 return DeclSpec::TST_class;
703 case TagTypeKind::Enum:
704 return DeclSpec::TST_enum;
705 }
706 }
707
708 return DeclSpec::TST_unspecified;
709}
710
711bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
712 if (!CurContext->isRecord())
713 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
714
715 switch (SS->getScopeRep().getKind()) {
716 case NestedNameSpecifier::Kind::MicrosoftSuper:
717 return true;
718 case NestedNameSpecifier::Kind::Type: {
719 QualType T(SS->getScopeRep().getAsType(), 0);
720 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
721 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
722 return true;
723 [[fallthrough]];
724 }
725 default:
726 return S->isFunctionPrototypeScope();
727 }
728}
729
730void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
731 SourceLocation IILoc,
732 Scope *S,
733 CXXScopeSpec *SS,
734 ParsedType &SuggestedType,
735 bool IsTemplateName) {
736 // Don't report typename errors for editor placeholders.
737 if (II->isEditorPlaceholder())
738 return;
739 // We don't have anything to suggest (yet).
740 SuggestedType = nullptr;
741
742 // There may have been a typo in the name of the type. Look up typo
743 // results, in case we have something that we can suggest.
744 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
745 /*AllowTemplates=*/IsTemplateName,
746 /*AllowNonTemplates=*/!IsTemplateName);
747 if (TypoCorrection Corrected =
748 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
749 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
750 // FIXME: Support error recovery for the template-name case.
751 bool CanRecover = !IsTemplateName;
752 if (Corrected.isKeyword()) {
753 // We corrected to a keyword.
754 diagnoseTypo(Correction: Corrected,
755 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
756 : diag::err_unknown_typename_suggest)
757 << II);
758 II = Corrected.getCorrectionAsIdentifierInfo();
759 } else {
760 // We found a similarly-named type or interface; suggest that.
761 if (!SS || !SS->isSet()) {
762 diagnoseTypo(Correction: Corrected,
763 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
764 : diag::err_unknown_typename_suggest)
765 << II, ErrorRecovery: CanRecover);
766 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
767 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
768 bool DroppedSpecifier =
769 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
770 diagnoseTypo(Correction: Corrected,
771 TypoDiag: PDiag(DiagID: IsTemplateName
772 ? diag::err_no_member_template_suggest
773 : diag::err_unknown_nested_typename_suggest)
774 << II << DC << DroppedSpecifier << SS->getRange(),
775 ErrorRecovery: CanRecover);
776 } else {
777 llvm_unreachable("could not have corrected a typo here");
778 }
779
780 if (!CanRecover)
781 return;
782
783 CXXScopeSpec tmpSS;
784 if (Corrected.getCorrectionSpecifier())
785 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
786 R: SourceRange(IILoc));
787 // FIXME: Support class template argument deduction here.
788 SuggestedType =
789 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
790 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
791 /*IsCtorOrDtorName=*/false,
792 /*WantNontrivialTypeSourceInfo=*/true);
793 }
794 return;
795 }
796
797 if (getLangOpts().CPlusPlus && !IsTemplateName) {
798 // See if II is a class template that the user forgot to pass arguments to.
799 UnqualifiedId Name;
800 Name.setIdentifier(Id: II, IdLoc: IILoc);
801 CXXScopeSpec EmptySS;
802 TemplateTy TemplateResult;
803 bool MemberOfUnknownSpecialization;
804 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
805 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
806 MemberOfUnknownSpecialization) == TNK_Type_template) {
807 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
808 return;
809 }
810 }
811
812 // FIXME: Should we move the logic that tries to recover from a missing tag
813 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
814
815 if (!SS || (!SS->isSet() && !SS->isInvalid()))
816 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
817 : diag::err_unknown_typename)
818 << II;
819 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
820 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
821 : diag::err_typename_nested_not_found)
822 << II << DC << SS->getRange();
823 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
824 SuggestedType =
825 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
826 } else if (isDependentScopeSpecifier(SS: *SS)) {
827 unsigned DiagID = diag::err_typename_missing;
828 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
829 DiagID = diag::ext_typename_missing;
830
831 SuggestedType =
832 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
833
834 Diag(Loc: SS->getRange().getBegin(), DiagID)
835 << GetTypeFromParser(Ty: SuggestedType)
836 << SourceRange(SS->getRange().getBegin(), IILoc)
837 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
838 } else {
839 assert(SS && SS->isInvalid() &&
840 "Invalid scope specifier has already been diagnosed");
841 }
842}
843
844/// Determine whether the given result set contains either a type name
845/// or
846static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
847 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
848 NextToken.is(K: tok::less);
849
850 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
851 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
852 return true;
853
854 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
855 return true;
856 }
857
858 return false;
859}
860
861static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
862 Scope *S, CXXScopeSpec &SS,
863 IdentifierInfo *&Name,
864 SourceLocation NameLoc) {
865 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
866 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
867 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
868 StringRef FixItTagName;
869 switch (Tag->getTagKind()) {
870 case TagTypeKind::Class:
871 FixItTagName = "class ";
872 break;
873
874 case TagTypeKind::Enum:
875 FixItTagName = "enum ";
876 break;
877
878 case TagTypeKind::Struct:
879 FixItTagName = "struct ";
880 break;
881
882 case TagTypeKind::Interface:
883 FixItTagName = "__interface ";
884 break;
885
886 case TagTypeKind::Union:
887 FixItTagName = "union ";
888 break;
889 }
890
891 StringRef TagName = FixItTagName.drop_back();
892 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
893 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
894 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
895
896 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
897 I != IEnd; ++I)
898 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
899 << Name << TagName;
900
901 // Replace lookup results with just the tag decl.
902 Result.clear(Kind: Sema::LookupTagName);
903 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
904 return true;
905 }
906
907 return false;
908}
909
910Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
911 IdentifierInfo *&Name,
912 SourceLocation NameLoc,
913 const Token &NextToken,
914 CorrectionCandidateCallback *CCC) {
915 DeclarationNameInfo NameInfo(Name, NameLoc);
916 ObjCMethodDecl *CurMethod = getCurMethodDecl();
917
918 assert(NextToken.isNot(tok::coloncolon) &&
919 "parse nested name specifiers before calling ClassifyName");
920 if (getLangOpts().CPlusPlus && SS.isSet() &&
921 isCurrentClassName(II: *Name, S, SS: &SS)) {
922 // Per [class.qual]p2, this names the constructors of SS, not the
923 // injected-class-name. We don't have a classification for that.
924 // There's not much point caching this result, since the parser
925 // will reject it later.
926 return NameClassification::Unknown();
927 }
928
929 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
930 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
931 /*AllowBuiltinCreation=*/!CurMethod);
932
933 if (SS.isInvalid())
934 return NameClassification::Error();
935
936 // For unqualified lookup in a class template in MSVC mode, look into
937 // dependent base classes where the primary class template is known.
938 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
939 if (ParsedType TypeInBase =
940 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
941 return TypeInBase;
942 }
943
944 // Perform lookup for Objective-C instance variables (including automatically
945 // synthesized instance variables), if we're in an Objective-C method.
946 // FIXME: This lookup really, really needs to be folded in to the normal
947 // unqualified lookup mechanism.
948 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
949 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
950 if (Ivar.isInvalid())
951 return NameClassification::Error();
952 if (Ivar.isUsable())
953 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
954
955 // We defer builtin creation until after ivar lookup inside ObjC methods.
956 if (Result.empty())
957 LookupBuiltin(R&: Result);
958 }
959
960 bool SecondTry = false;
961 bool IsFilteredTemplateName = false;
962
963Corrected:
964 switch (Result.getResultKind()) {
965 case LookupResultKind::NotFound:
966 // If an unqualified-id is followed by a '(', then we have a function
967 // call.
968 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
969 // In C++, this is an ADL-only call.
970 // FIXME: Reference?
971 if (getLangOpts().CPlusPlus)
972 return NameClassification::UndeclaredNonType();
973
974 // C90 6.3.2.2:
975 // If the expression that precedes the parenthesized argument list in a
976 // function call consists solely of an identifier, and if no
977 // declaration is visible for this identifier, the identifier is
978 // implicitly declared exactly as if, in the innermost block containing
979 // the function call, the declaration
980 //
981 // extern int identifier ();
982 //
983 // appeared.
984 //
985 // We also allow this in C99 as an extension. However, this is not
986 // allowed in all language modes as functions without prototypes may not
987 // be supported.
988 if (getLangOpts().implicitFunctionsAllowed()) {
989 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
990 return NameClassification::NonType(D);
991 }
992 }
993
994 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
995 // In C++20 onwards, this could be an ADL-only call to a function
996 // template, and we're required to assume that this is a template name.
997 //
998 // FIXME: Find a way to still do typo correction in this case.
999 TemplateName Template =
1000 Context.getAssumedTemplateName(Name: NameInfo.getName());
1001 return NameClassification::UndeclaredTemplate(Name: Template);
1002 }
1003
1004 // In C, we first see whether there is a tag type by the same name, in
1005 // which case it's likely that the user just forgot to write "enum",
1006 // "struct", or "union".
1007 if (!getLangOpts().CPlusPlus && !SecondTry &&
1008 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1009 break;
1010 }
1011
1012 // Perform typo correction to determine if there is another name that is
1013 // close to this name.
1014 if (!SecondTry && CCC) {
1015 SecondTry = true;
1016 if (TypoCorrection Corrected =
1017 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1018 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1019 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1020 unsigned QualifiedDiag = diag::err_no_member_suggest;
1021
1022 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1023 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1024 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1025 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1026 UnqualifiedDiag = diag::err_no_template_suggest;
1027 QualifiedDiag = diag::err_no_member_template_suggest;
1028 } else if (UnderlyingFirstDecl &&
1029 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1030 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1031 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1032 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1033 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1034 }
1035
1036 if (SS.isEmpty()) {
1037 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1038 } else {// FIXME: is this even reachable? Test it.
1039 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1040 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1041 Name->getName() == CorrectedStr;
1042 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1043 << Name << computeDeclContext(SS, EnteringContext: false)
1044 << DroppedSpecifier << SS.getRange());
1045 }
1046
1047 // Update the name, so that the caller has the new name.
1048 Name = Corrected.getCorrectionAsIdentifierInfo();
1049
1050 // Typo correction corrected to a keyword.
1051 if (Corrected.isKeyword())
1052 return Name;
1053
1054 // Also update the LookupResult...
1055 // FIXME: This should probably go away at some point
1056 Result.clear();
1057 Result.setLookupName(Corrected.getCorrection());
1058 if (FirstDecl)
1059 Result.addDecl(D: FirstDecl);
1060
1061 // If we found an Objective-C instance variable, let
1062 // LookupInObjCMethod build the appropriate expression to
1063 // reference the ivar.
1064 // FIXME: This is a gross hack.
1065 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1066 DeclResult R =
1067 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1068 if (R.isInvalid())
1069 return NameClassification::Error();
1070 if (R.isUsable())
1071 return NameClassification::NonType(D: Ivar);
1072 }
1073
1074 goto Corrected;
1075 }
1076 }
1077
1078 // We failed to correct; just fall through and let the parser deal with it.
1079 Result.suppressDiagnostics();
1080 return NameClassification::Unknown();
1081
1082 case LookupResultKind::NotFoundInCurrentInstantiation: {
1083 // We performed name lookup into the current instantiation, and there were
1084 // dependent bases, so we treat this result the same way as any other
1085 // dependent nested-name-specifier.
1086
1087 // C++ [temp.res]p2:
1088 // A name used in a template declaration or definition and that is
1089 // dependent on a template-parameter is assumed not to name a type
1090 // unless the applicable name lookup finds a type name or the name is
1091 // qualified by the keyword typename.
1092 //
1093 // FIXME: If the next token is '<', we might want to ask the parser to
1094 // perform some heroics to see if we actually have a
1095 // template-argument-list, which would indicate a missing 'template'
1096 // keyword here.
1097 return NameClassification::DependentNonType();
1098 }
1099
1100 case LookupResultKind::Found:
1101 case LookupResultKind::FoundOverloaded:
1102 case LookupResultKind::FoundUnresolvedValue:
1103 break;
1104
1105 case LookupResultKind::Ambiguous:
1106 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1107 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1108 /*AllowDependent=*/false)) {
1109 // C++ [temp.local]p3:
1110 // A lookup that finds an injected-class-name (10.2) can result in an
1111 // ambiguity in certain cases (for example, if it is found in more than
1112 // one base class). If all of the injected-class-names that are found
1113 // refer to specializations of the same class template, and if the name
1114 // is followed by a template-argument-list, the reference refers to the
1115 // class template itself and not a specialization thereof, and is not
1116 // ambiguous.
1117 //
1118 // This filtering can make an ambiguous result into an unambiguous one,
1119 // so try again after filtering out template names.
1120 FilterAcceptableTemplateNames(R&: Result);
1121 if (!Result.isAmbiguous()) {
1122 IsFilteredTemplateName = true;
1123 break;
1124 }
1125 }
1126
1127 // Diagnose the ambiguity and return an error.
1128 return NameClassification::Error();
1129 }
1130
1131 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1132 (IsFilteredTemplateName ||
1133 hasAnyAcceptableTemplateNames(
1134 R&: Result, /*AllowFunctionTemplates=*/true,
1135 /*AllowDependent=*/false,
1136 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1137 getLangOpts().CPlusPlus20))) {
1138 // C++ [temp.names]p3:
1139 // After name lookup (3.4) finds that a name is a template-name or that
1140 // an operator-function-id or a literal- operator-id refers to a set of
1141 // overloaded functions any member of which is a function template if
1142 // this is followed by a <, the < is always taken as the delimiter of a
1143 // template-argument-list and never as the less-than operator.
1144 // C++2a [temp.names]p2:
1145 // A name is also considered to refer to a template if it is an
1146 // unqualified-id followed by a < and name lookup finds either one
1147 // or more functions or finds nothing.
1148 if (!IsFilteredTemplateName)
1149 FilterAcceptableTemplateNames(R&: Result);
1150
1151 bool IsFunctionTemplate;
1152 bool IsVarTemplate;
1153 TemplateName Template;
1154 if (Result.end() - Result.begin() > 1) {
1155 IsFunctionTemplate = true;
1156 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1157 End: Result.end());
1158 } else if (!Result.empty()) {
1159 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1160 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1161 /*AllowDependent=*/false));
1162 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1163 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1164
1165 UsingShadowDecl *FoundUsingShadow =
1166 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1167 assert(!FoundUsingShadow ||
1168 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1169 Template = Context.getQualifiedTemplateName(
1170 Qualifier: SS.getScopeRep(),
1171 /*TemplateKeyword=*/false,
1172 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1173 } else {
1174 // All results were non-template functions. This is a function template
1175 // name.
1176 IsFunctionTemplate = true;
1177 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1178 }
1179
1180 if (IsFunctionTemplate) {
1181 // Function templates always go through overload resolution, at which
1182 // point we'll perform the various checks (e.g., accessibility) we need
1183 // to based on which function we selected.
1184 Result.suppressDiagnostics();
1185
1186 return NameClassification::FunctionTemplate(Name: Template);
1187 }
1188
1189 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1190 : NameClassification::TypeTemplate(Name: Template);
1191 }
1192
1193 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1194 QualType T;
1195 TypeLocBuilder TLB;
1196 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1197 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1198 D: USD);
1199 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1200 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1201 } else {
1202 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1203 Decl: Type);
1204 if (isa<TagType>(Val: T)) {
1205 auto TTL = TLB.push<TagTypeLoc>(T);
1206 TTL.setElaboratedKeywordLoc(SourceLocation());
1207 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1208 TTL.setNameLoc(NameLoc);
1209 } else if (isa<TypedefType>(Val: T)) {
1210 TLB.push<TypedefTypeLoc>(T).set(
1211 /*ElaboratedKeywordLoc=*/SourceLocation(),
1212 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1213 } else if (isa<UnresolvedUsingType>(Val: T)) {
1214 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1215 /*ElaboratedKeywordLoc=*/SourceLocation(),
1216 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1217 } else {
1218 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1219 }
1220 }
1221 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1222 };
1223
1224 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1225 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1226 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1227 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1228 return BuildTypeFor(Type, *Result.begin());
1229 }
1230
1231 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1232 if (!Class) {
1233 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1234 if (ObjCCompatibleAliasDecl *Alias =
1235 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1236 Class = Alias->getClassInterface();
1237 }
1238
1239 if (Class) {
1240 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1241
1242 if (NextToken.is(K: tok::period)) {
1243 // Interface. <something> is parsed as a property reference expression.
1244 // Just return "unknown" as a fall-through for now.
1245 Result.suppressDiagnostics();
1246 return NameClassification::Unknown();
1247 }
1248
1249 QualType T = Context.getObjCInterfaceType(Decl: Class);
1250 return ParsedType::make(P: T);
1251 }
1252
1253 if (isa<ConceptDecl>(Val: FirstDecl)) {
1254 // We want to preserve the UsingShadowDecl for concepts.
1255 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1256 return NameClassification::Concept(Name: TemplateName(USD));
1257 return NameClassification::Concept(
1258 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1259 }
1260
1261 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1262 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1263 return NameClassification::Error();
1264 }
1265
1266 // We can have a type template here if we're classifying a template argument.
1267 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1268 !isa<VarTemplateDecl>(Val: FirstDecl))
1269 return NameClassification::TypeTemplate(
1270 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1271
1272 // Check for a tag type hidden by a non-type decl in a few cases where it
1273 // seems likely a type is wanted instead of the non-type that was found.
1274 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1275 if ((NextToken.is(K: tok::identifier) ||
1276 (NextIsOp &&
1277 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1278 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1279 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1280 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1281 return BuildTypeFor(Type, *Result.begin());
1282 }
1283
1284 // If we already know which single declaration is referenced, just annotate
1285 // that declaration directly. Defer resolving even non-overloaded class
1286 // member accesses, as we need to defer certain access checks until we know
1287 // the context.
1288 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1289 if (Result.isSingleResult() && !ADL &&
1290 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1291 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1292
1293 // Otherwise, this is an overload set that we will need to resolve later.
1294 Result.suppressDiagnostics();
1295 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1296 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1297 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1298 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1299}
1300
1301ExprResult
1302Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1303 SourceLocation NameLoc) {
1304 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1305 CXXScopeSpec SS;
1306 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1307 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1308}
1309
1310ExprResult
1311Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1312 IdentifierInfo *Name,
1313 SourceLocation NameLoc,
1314 bool IsAddressOfOperand) {
1315 DeclarationNameInfo NameInfo(Name, NameLoc);
1316 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1317 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1318 /*TemplateArgs=*/nullptr);
1319}
1320
1321ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1322 NamedDecl *Found,
1323 SourceLocation NameLoc,
1324 const Token &NextToken) {
1325 if (getCurMethodDecl() && SS.isEmpty())
1326 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1327 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1328
1329 // Reconstruct the lookup result.
1330 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1331 Result.addDecl(D: Found);
1332 Result.resolveKind();
1333
1334 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1335 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1336}
1337
1338ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1339 // For an implicit class member access, transform the result into a member
1340 // access expression if necessary.
1341 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1342 if ((*ULE->decls_begin())->isCXXClassMember()) {
1343 CXXScopeSpec SS;
1344 SS.Adopt(Other: ULE->getQualifierLoc());
1345
1346 // Reconstruct the lookup result.
1347 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1348 LookupOrdinaryName);
1349 Result.setNamingClass(ULE->getNamingClass());
1350 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1351 Result.addDecl(D: *I, AS: I.getAccess());
1352 Result.resolveKind();
1353 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1354 TemplateArgs: nullptr, S);
1355 }
1356
1357 // Otherwise, this is already in the form we needed, and no further checks
1358 // are necessary.
1359 return ULE;
1360}
1361
1362Sema::TemplateNameKindForDiagnostics
1363Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1364 auto *TD = Name.getAsTemplateDecl();
1365 if (!TD)
1366 return TemplateNameKindForDiagnostics::DependentTemplate;
1367 if (isa<ClassTemplateDecl>(Val: TD))
1368 return TemplateNameKindForDiagnostics::ClassTemplate;
1369 if (isa<FunctionTemplateDecl>(Val: TD))
1370 return TemplateNameKindForDiagnostics::FunctionTemplate;
1371 if (isa<VarTemplateDecl>(Val: TD))
1372 return TemplateNameKindForDiagnostics::VarTemplate;
1373 if (isa<TypeAliasTemplateDecl>(Val: TD))
1374 return TemplateNameKindForDiagnostics::AliasTemplate;
1375 if (isa<TemplateTemplateParmDecl>(Val: TD))
1376 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1377 if (isa<ConceptDecl>(Val: TD))
1378 return TemplateNameKindForDiagnostics::Concept;
1379 return TemplateNameKindForDiagnostics::DependentTemplate;
1380}
1381
1382void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1383 assert(DC->getLexicalParent() == CurContext &&
1384 "The next DeclContext should be lexically contained in the current one.");
1385 CurContext = DC;
1386 S->setEntity(DC);
1387}
1388
1389void Sema::PopDeclContext() {
1390 assert(CurContext && "DeclContext imbalance!");
1391
1392 CurContext = CurContext->getLexicalParent();
1393 assert(CurContext && "Popped translation unit!");
1394}
1395
1396Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1397 Decl *D) {
1398 // Unlike PushDeclContext, the context to which we return is not necessarily
1399 // the containing DC of TD, because the new context will be some pre-existing
1400 // TagDecl definition instead of a fresh one.
1401 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1402 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1403 assert(CurContext && "skipping definition of undefined tag");
1404 // Start lookups from the parent of the current context; we don't want to look
1405 // into the pre-existing complete definition.
1406 S->setEntity(CurContext->getLookupParent());
1407 return Result;
1408}
1409
1410void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1411 CurContext = static_cast<decltype(CurContext)>(Context);
1412}
1413
1414void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1415 // C++0x [basic.lookup.unqual]p13:
1416 // A name used in the definition of a static data member of class
1417 // X (after the qualified-id of the static member) is looked up as
1418 // if the name was used in a member function of X.
1419 // C++0x [basic.lookup.unqual]p14:
1420 // If a variable member of a namespace is defined outside of the
1421 // scope of its namespace then any name used in the definition of
1422 // the variable member (after the declarator-id) is looked up as
1423 // if the definition of the variable member occurred in its
1424 // namespace.
1425 // Both of these imply that we should push a scope whose context
1426 // is the semantic context of the declaration. We can't use
1427 // PushDeclContext here because that context is not necessarily
1428 // lexically contained in the current context. Fortunately,
1429 // the containing scope should have the appropriate information.
1430
1431 assert(!S->getEntity() && "scope already has entity");
1432
1433#ifndef NDEBUG
1434 Scope *Ancestor = S->getParent();
1435 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1436 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1437#endif
1438
1439 CurContext = DC;
1440 S->setEntity(DC);
1441
1442 if (S->getParent()->isTemplateParamScope()) {
1443 // Also set the corresponding entities for all immediately-enclosing
1444 // template parameter scopes.
1445 EnterTemplatedContext(S: S->getParent(), DC);
1446 }
1447}
1448
1449void Sema::ExitDeclaratorContext(Scope *S) {
1450 assert(S->getEntity() == CurContext && "Context imbalance!");
1451
1452 // Switch back to the lexical context. The safety of this is
1453 // enforced by an assert in EnterDeclaratorContext.
1454 Scope *Ancestor = S->getParent();
1455 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1456 CurContext = Ancestor->getEntity();
1457
1458 // We don't need to do anything with the scope, which is going to
1459 // disappear.
1460}
1461
1462void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1463 assert(S->isTemplateParamScope() &&
1464 "expected to be initializing a template parameter scope");
1465
1466 // C++20 [temp.local]p7:
1467 // In the definition of a member of a class template that appears outside
1468 // of the class template definition, the name of a member of the class
1469 // template hides the name of a template-parameter of any enclosing class
1470 // templates (but not a template-parameter of the member if the member is a
1471 // class or function template).
1472 // C++20 [temp.local]p9:
1473 // In the definition of a class template or in the definition of a member
1474 // of such a template that appears outside of the template definition, for
1475 // each non-dependent base class (13.8.2.1), if the name of the base class
1476 // or the name of a member of the base class is the same as the name of a
1477 // template-parameter, the base class name or member name hides the
1478 // template-parameter name (6.4.10).
1479 //
1480 // This means that a template parameter scope should be searched immediately
1481 // after searching the DeclContext for which it is a template parameter
1482 // scope. For example, for
1483 // template<typename T> template<typename U> template<typename V>
1484 // void N::A<T>::B<U>::f(...)
1485 // we search V then B<U> (and base classes) then U then A<T> (and base
1486 // classes) then T then N then ::.
1487 unsigned ScopeDepth = getTemplateDepth(S);
1488 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1489 DeclContext *SearchDCAfterScope = DC;
1490 for (; DC; DC = DC->getLookupParent()) {
1491 if (const TemplateParameterList *TPL =
1492 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1493 unsigned DCDepth = TPL->getDepth() + 1;
1494 if (DCDepth > ScopeDepth)
1495 continue;
1496 if (ScopeDepth == DCDepth)
1497 SearchDCAfterScope = DC = DC->getLookupParent();
1498 break;
1499 }
1500 }
1501 S->setLookupEntity(SearchDCAfterScope);
1502 }
1503}
1504
1505void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1506 // We assume that the caller has already called
1507 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1508 FunctionDecl *FD = D->getAsFunction();
1509 if (!FD)
1510 return;
1511
1512 // Same implementation as PushDeclContext, but enters the context
1513 // from the lexical parent, rather than the top-level class.
1514 assert(CurContext == FD->getLexicalParent() &&
1515 "The next DeclContext should be lexically contained in the current one.");
1516 CurContext = FD;
1517 S->setEntity(CurContext);
1518
1519 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1520 ParmVarDecl *Param = FD->getParamDecl(i: P);
1521 // If the parameter has an identifier, then add it to the scope
1522 if (Param->getIdentifier()) {
1523 S->AddDecl(D: Param);
1524 IdResolver.AddDecl(D: Param);
1525 }
1526 }
1527}
1528
1529void Sema::ActOnExitFunctionContext() {
1530 // Same implementation as PopDeclContext, but returns to the lexical parent,
1531 // rather than the top-level class.
1532 assert(CurContext && "DeclContext imbalance!");
1533 CurContext = CurContext->getLexicalParent();
1534 assert(CurContext && "Popped translation unit!");
1535}
1536
1537/// Determine whether overloading is allowed for a new function
1538/// declaration considering prior declarations of the same name.
1539///
1540/// This routine determines whether overloading is possible, not
1541/// whether a new declaration actually overloads a previous one.
1542/// It will return true in C++ (where overloads are always permitted)
1543/// or, as a C extension, when either the new declaration or a
1544/// previous one is declared with the 'overloadable' attribute.
1545static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1546 ASTContext &Context,
1547 const FunctionDecl *New) {
1548 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1549 return true;
1550
1551 // Multiversion function declarations are not overloads in the
1552 // usual sense of that term, but lookup will report that an
1553 // overload set was found if more than one multiversion function
1554 // declaration is present for the same name. It is therefore
1555 // inadequate to assume that some prior declaration(s) had
1556 // the overloadable attribute; checking is required. Since one
1557 // declaration is permitted to omit the attribute, it is necessary
1558 // to check at least two; hence the 'any_of' check below. Note that
1559 // the overloadable attribute is implicitly added to declarations
1560 // that were required to have it but did not.
1561 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1562 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1563 return ND->hasAttr<OverloadableAttr>();
1564 });
1565 } else if (Previous.getResultKind() == LookupResultKind::Found)
1566 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1567
1568 return false;
1569}
1570
1571void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1572 // Move up the scope chain until we find the nearest enclosing
1573 // non-transparent context. The declaration will be introduced into this
1574 // scope.
1575 while (S->getEntity() && S->getEntity()->isTransparentContext())
1576 S = S->getParent();
1577
1578 // Add scoped declarations into their context, so that they can be
1579 // found later. Declarations without a context won't be inserted
1580 // into any context.
1581 if (AddToContext)
1582 CurContext->addDecl(D);
1583
1584 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1585 // are function-local declarations.
1586 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1587 return;
1588
1589 // Template instantiations should also not be pushed into scope.
1590 if (isa<FunctionDecl>(Val: D) &&
1591 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1592 return;
1593
1594 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1595 S->AddDecl(D);
1596 return;
1597 }
1598 // If this replaces anything in the current scope,
1599 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1600 IEnd = IdResolver.end();
1601 for (; I != IEnd; ++I) {
1602 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1603 S->RemoveDecl(D: *I);
1604 IdResolver.RemoveDecl(D: *I);
1605
1606 // Should only need to replace one decl.
1607 break;
1608 }
1609 }
1610
1611 S->AddDecl(D);
1612
1613 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1614 // Implicitly-generated labels may end up getting generated in an order that
1615 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1616 // the label at the appropriate place in the identifier chain.
1617 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1618 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1619 if (IDC == CurContext) {
1620 if (!S->isDeclScope(D: *I))
1621 continue;
1622 } else if (IDC->Encloses(DC: CurContext))
1623 break;
1624 }
1625
1626 IdResolver.InsertDeclAfter(Pos: I, D);
1627 } else {
1628 IdResolver.AddDecl(D);
1629 }
1630 warnOnReservedIdentifier(D);
1631}
1632
1633bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1634 bool AllowInlineNamespace) const {
1635 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1636}
1637
1638Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1639 DeclContext *TargetDC = DC->getPrimaryContext();
1640 do {
1641 if (DeclContext *ScopeDC = S->getEntity())
1642 if (ScopeDC->getPrimaryContext() == TargetDC)
1643 return S;
1644 } while ((S = S->getParent()));
1645
1646 return nullptr;
1647}
1648
1649static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1650 DeclContext*,
1651 ASTContext&);
1652
1653void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1654 bool ConsiderLinkage,
1655 bool AllowInlineNamespace) {
1656 LookupResult::Filter F = R.makeFilter();
1657 while (F.hasNext()) {
1658 NamedDecl *D = F.next();
1659
1660 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1661 continue;
1662
1663 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1664 continue;
1665
1666 F.erase();
1667 }
1668
1669 F.done();
1670}
1671
1672static bool isImplicitInstantiation(NamedDecl *D) {
1673 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1674 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1675 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1676 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1677 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1678 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1679
1680 return false;
1681}
1682
1683bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1684 // [module.interface]p7:
1685 // A declaration is attached to a module as follows:
1686 // - If the declaration is a non-dependent friend declaration that nominates a
1687 // function with a declarator-id that is a qualified-id or template-id or that
1688 // nominates a class other than with an elaborated-type-specifier with neither
1689 // a nested-name-specifier nor a simple-template-id, it is attached to the
1690 // module to which the friend is attached ([basic.link]).
1691 if (New->getFriendObjectKind() &&
1692 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1693 New->setLocalOwningModule(Old->getOwningModule());
1694 makeMergedDefinitionVisible(ND: New);
1695 return false;
1696 }
1697
1698 // Although we have questions for the module ownership of implicit
1699 // instantiations, it should be sure that we shouldn't diagnose the
1700 // redeclaration of incorrect module ownership for different implicit
1701 // instantiations in different modules. We will diagnose the redeclaration of
1702 // incorrect module ownership for the template itself.
1703 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1704 return false;
1705
1706 Module *NewM = New->getOwningModule();
1707 Module *OldM = Old->getOwningModule();
1708
1709 if (NewM && NewM->isPrivateModule())
1710 NewM = NewM->Parent;
1711 if (OldM && OldM->isPrivateModule())
1712 OldM = OldM->Parent;
1713
1714 if (NewM == OldM)
1715 return false;
1716
1717 if (NewM && OldM) {
1718 // A module implementation unit has visibility of the decls in its
1719 // implicitly imported interface.
1720 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1721 return false;
1722
1723 // Partitions are part of the module, but a partition could import another
1724 // module, so verify that the PMIs agree.
1725 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1726 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1727 return false;
1728 }
1729
1730 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1731 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1732 if (NewIsModuleInterface || OldIsModuleInterface) {
1733 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1734 // if a declaration of D [...] appears in the purview of a module, all
1735 // other such declarations shall appear in the purview of the same module
1736 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1737 << New
1738 << NewIsModuleInterface
1739 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1740 << OldIsModuleInterface
1741 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1742 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1743 New->setInvalidDecl();
1744 return true;
1745 }
1746
1747 return false;
1748}
1749
1750bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1751 // [module.interface]p1:
1752 // An export-declaration shall inhabit a namespace scope.
1753 //
1754 // So it is meaningless to talk about redeclaration which is not at namespace
1755 // scope.
1756 if (!New->getLexicalDeclContext()
1757 ->getNonTransparentContext()
1758 ->isFileContext() ||
1759 !Old->getLexicalDeclContext()
1760 ->getNonTransparentContext()
1761 ->isFileContext())
1762 return false;
1763
1764 bool IsNewExported = New->isInExportDeclContext();
1765 bool IsOldExported = Old->isInExportDeclContext();
1766
1767 // It should be irrevelant if both of them are not exported.
1768 if (!IsNewExported && !IsOldExported)
1769 return false;
1770
1771 if (IsOldExported)
1772 return false;
1773
1774 // If the Old declaration are not attached to named modules
1775 // and the New declaration are attached to global module.
1776 // It should be fine to allow the export since it doesn't change
1777 // the linkage of declarations. See
1778 // https://github.com/llvm/llvm-project/issues/98583 for details.
1779 if (!Old->isInNamedModule() && New->getOwningModule() &&
1780 New->getOwningModule()->isImplicitGlobalModule())
1781 return false;
1782
1783 assert(IsNewExported);
1784
1785 auto Lk = Old->getFormalLinkage();
1786 int S = 0;
1787 if (Lk == Linkage::Internal)
1788 S = 1;
1789 else if (Lk == Linkage::Module)
1790 S = 2;
1791 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1792 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1793 return true;
1794}
1795
1796bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1797 if (CheckRedeclarationModuleOwnership(New, Old))
1798 return true;
1799
1800 if (CheckRedeclarationExported(New, Old))
1801 return true;
1802
1803 return false;
1804}
1805
1806bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1807 const NamedDecl *Old) const {
1808 assert(getASTContext().isSameEntity(New, Old) &&
1809 "New and Old are not the same definition, we should diagnostic it "
1810 "immediately instead of checking it.");
1811 assert(const_cast<Sema *>(this)->isReachable(New) &&
1812 const_cast<Sema *>(this)->isReachable(Old) &&
1813 "We shouldn't see unreachable definitions here.");
1814
1815 Module *NewM = New->getOwningModule();
1816 Module *OldM = Old->getOwningModule();
1817
1818 // We only checks for named modules here. The header like modules is skipped.
1819 // FIXME: This is not right if we import the header like modules in the module
1820 // purview.
1821 //
1822 // For example, assuming "header.h" provides definition for `D`.
1823 // ```C++
1824 // //--- M.cppm
1825 // export module M;
1826 // import "header.h"; // or #include "header.h" but import it by clang modules
1827 // actually.
1828 //
1829 // //--- Use.cpp
1830 // import M;
1831 // import "header.h"; // or uses clang modules.
1832 // ```
1833 //
1834 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1835 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1836 // reject it. But the current implementation couldn't detect the case since we
1837 // don't record the information about the importee modules.
1838 //
1839 // But this might not be painful in practice. Since the design of C++20 Named
1840 // Modules suggests us to use headers in global module fragment instead of
1841 // module purview.
1842 if (NewM && NewM->isHeaderLikeModule())
1843 NewM = nullptr;
1844 if (OldM && OldM->isHeaderLikeModule())
1845 OldM = nullptr;
1846
1847 if (!NewM && !OldM)
1848 return true;
1849
1850 // [basic.def.odr]p14.3
1851 // Each such definition shall not be attached to a named module
1852 // ([module.unit]).
1853 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1854 return true;
1855
1856 // Then New and Old lives in the same TU if their share one same module unit.
1857 if (NewM)
1858 NewM = NewM->getTopLevelModule();
1859 if (OldM)
1860 OldM = OldM->getTopLevelModule();
1861 return OldM == NewM;
1862}
1863
1864static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1865 if (D->getDeclContext()->isFileContext())
1866 return false;
1867
1868 return isa<UsingShadowDecl>(Val: D) ||
1869 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1870 isa<UnresolvedUsingValueDecl>(Val: D);
1871}
1872
1873/// Removes using shadow declarations not at class scope from the lookup
1874/// results.
1875static void RemoveUsingDecls(LookupResult &R) {
1876 LookupResult::Filter F = R.makeFilter();
1877 while (F.hasNext())
1878 if (isUsingDeclNotAtClassScope(D: F.next()))
1879 F.erase();
1880
1881 F.done();
1882}
1883
1884/// Check for this common pattern:
1885/// @code
1886/// class S {
1887/// S(const S&); // DO NOT IMPLEMENT
1888/// void operator=(const S&); // DO NOT IMPLEMENT
1889/// };
1890/// @endcode
1891static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1892 // FIXME: Should check for private access too but access is set after we get
1893 // the decl here.
1894 if (D->doesThisDeclarationHaveABody())
1895 return false;
1896
1897 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1898 return CD->isCopyConstructor();
1899 return D->isCopyAssignmentOperator();
1900}
1901
1902bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1903 const DeclContext *DC = D->getDeclContext();
1904 while (!DC->isTranslationUnit()) {
1905 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1906 if (!RD->hasNameForLinkage())
1907 return true;
1908 }
1909 DC = DC->getParent();
1910 }
1911
1912 return !D->isExternallyVisible();
1913}
1914
1915// FIXME: This needs to be refactored; some other isInMainFile users want
1916// these semantics.
1917static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1918 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1919 return false;
1920 return S.SourceMgr.isInMainFile(Loc);
1921}
1922
1923bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1924 assert(D);
1925
1926 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1927 return false;
1928
1929 // Ignore all entities declared within templates, and out-of-line definitions
1930 // of members of class templates.
1931 if (D->getDeclContext()->isDependentContext() ||
1932 D->getLexicalDeclContext()->isDependentContext())
1933 return false;
1934
1935 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1936 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1937 return false;
1938 // A non-out-of-line declaration of a member specialization was implicitly
1939 // instantiated; it's the out-of-line declaration that we're interested in.
1940 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1941 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1942 return false;
1943
1944 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1945 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1946 return false;
1947 } else {
1948 // 'static inline' functions are defined in headers; don't warn.
1949 if (FD->isInlined() && !isMainFileLoc(S: *this, Loc: FD->getLocation()))
1950 return false;
1951 }
1952
1953 if (FD->doesThisDeclarationHaveABody() &&
1954 Context.DeclMustBeEmitted(D: FD))
1955 return false;
1956 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1957 // Constants and utility variables are defined in headers with internal
1958 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1959 // like "inline".)
1960 if (!isMainFileLoc(S: *this, Loc: VD->getLocation()))
1961 return false;
1962
1963 if (Context.DeclMustBeEmitted(D: VD))
1964 return false;
1965
1966 if (VD->isStaticDataMember() &&
1967 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1968 return false;
1969 if (VD->isStaticDataMember() &&
1970 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1971 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1972 return false;
1973
1974 if (VD->isInline() && !isMainFileLoc(S: *this, Loc: VD->getLocation()))
1975 return false;
1976 } else {
1977 return false;
1978 }
1979
1980 // Only warn for unused decls internal to the translation unit.
1981 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1982 // for inline functions defined in the main source file, for instance.
1983 return mightHaveNonExternalLinkage(D);
1984}
1985
1986void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1987 if (!D)
1988 return;
1989
1990 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1991 const FunctionDecl *First = FD->getFirstDecl();
1992 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1993 return; // First should already be in the vector.
1994 }
1995
1996 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1997 const VarDecl *First = VD->getFirstDecl();
1998 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1999 return; // First should already be in the vector.
2000 }
2001
2002 if (ShouldWarnIfUnusedFileScopedDecl(D))
2003 UnusedFileScopedDecls.push_back(LocalValue: D);
2004}
2005
2006static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2007 const NamedDecl *D) {
2008 if (D->isInvalidDecl())
2009 return false;
2010
2011 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2012 // For a decomposition declaration, warn if none of the bindings are
2013 // referenced, instead of if the variable itself is referenced (which
2014 // it is, by the bindings' expressions).
2015 bool IsAllIgnored = true;
2016 for (const auto *BD : DD->bindings()) {
2017 if (BD->isReferenced())
2018 return false;
2019 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2020 BD->hasAttr<UnusedAttr>());
2021 }
2022 if (IsAllIgnored)
2023 return false;
2024 } else if (!D->getDeclName()) {
2025 return false;
2026 } else if (D->isReferenced() || D->isUsed()) {
2027 return false;
2028 }
2029
2030 if (D->isPlaceholderVar(LangOpts))
2031 return false;
2032
2033 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2034 D->hasAttr<CleanupAttr>())
2035 return false;
2036
2037 if (isa<LabelDecl>(Val: D))
2038 return true;
2039
2040 // Except for labels, we only care about unused decls that are local to
2041 // functions.
2042 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2043 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2044 // For dependent types, the diagnostic is deferred.
2045 WithinFunction =
2046 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2047 if (!WithinFunction)
2048 return false;
2049
2050 if (isa<TypedefNameDecl>(Val: D))
2051 return true;
2052
2053 // White-list anything that isn't a local variable.
2054 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2055 return false;
2056
2057 // Types of valid local variables should be complete, so this should succeed.
2058 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2059
2060 const Expr *Init = VD->getInit();
2061 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2062 Init = Cleanups->getSubExpr();
2063
2064 const auto *Ty = VD->getType().getTypePtr();
2065
2066 // Only look at the outermost level of typedef.
2067 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2068 // Allow anything marked with __attribute__((unused)).
2069 if (TT->getDecl()->hasAttr<UnusedAttr>())
2070 return false;
2071 }
2072
2073 // Warn for reference variables whose initializtion performs lifetime
2074 // extension.
2075 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2076 MTE && MTE->getExtendingDecl()) {
2077 Ty = VD->getType().getNonReferenceType().getTypePtr();
2078 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2079 }
2080
2081 // If we failed to complete the type for some reason, or if the type is
2082 // dependent, don't diagnose the variable.
2083 if (Ty->isIncompleteType() || Ty->isDependentType())
2084 return false;
2085
2086 // Look at the element type to ensure that the warning behaviour is
2087 // consistent for both scalars and arrays.
2088 Ty = Ty->getBaseElementTypeUnsafe();
2089
2090 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2091 if (Tag->hasAttr<UnusedAttr>())
2092 return false;
2093
2094 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2095 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2096 return false;
2097
2098 if (Init) {
2099 const auto *Construct =
2100 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2101 if (Construct && !Construct->isElidable()) {
2102 const CXXConstructorDecl *CD = Construct->getConstructor();
2103 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2104 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2105 return false;
2106 }
2107
2108 // Suppress the warning if we don't know how this is constructed, and
2109 // it could possibly be non-trivial constructor.
2110 if (Init->isTypeDependent()) {
2111 for (const CXXConstructorDecl *Ctor : RD->ctors())
2112 if (!Ctor->isTrivial())
2113 return false;
2114 }
2115
2116 // Suppress the warning if the constructor is unresolved because
2117 // its arguments are dependent.
2118 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2119 return false;
2120 }
2121 }
2122 }
2123
2124 // TODO: __attribute__((unused)) templates?
2125 }
2126
2127 return true;
2128}
2129
2130static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2131 FixItHint &Hint) {
2132 if (isa<LabelDecl>(Val: D)) {
2133 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2134 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2135 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2136 if (AfterColon.isInvalid())
2137 return;
2138 Hint = FixItHint::CreateRemoval(
2139 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2140 }
2141}
2142
2143void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2144 DiagnoseUnusedNestedTypedefs(
2145 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2146}
2147
2148void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2149 DiagReceiverTy DiagReceiver) {
2150 if (D->isDependentType())
2151 return;
2152
2153 for (auto *TmpD : D->decls()) {
2154 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2155 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2156 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2157 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2158 }
2159}
2160
2161void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2162 DiagnoseUnusedDecl(
2163 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2164}
2165
2166void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2167 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2168 return;
2169
2170 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2171 // typedefs can be referenced later on, so the diagnostics are emitted
2172 // at end-of-translation-unit.
2173 UnusedLocalTypedefNameCandidates.insert(X: TD);
2174 return;
2175 }
2176
2177 FixItHint Hint;
2178 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2179
2180 unsigned DiagID;
2181 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2182 DiagID = diag::warn_unused_exception_param;
2183 else if (isa<LabelDecl>(Val: D))
2184 DiagID = diag::warn_unused_label;
2185 else
2186 DiagID = diag::warn_unused_variable;
2187
2188 SourceLocation DiagLoc = D->getLocation();
2189 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2190}
2191
2192void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2193 DiagReceiverTy DiagReceiver) {
2194 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2195 // it's not really unused.
2196 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2197 return;
2198
2199 // In C++, `_` variables behave as if they were maybe_unused
2200 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2201 return;
2202
2203 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2204
2205 if (Ty->isReferenceType() || Ty->isDependentType())
2206 return;
2207
2208 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2209 if (Tag->hasAttr<UnusedAttr>())
2210 return;
2211 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2212 // mimic gcc's behavior.
2213 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2214 RD && !RD->hasAttr<WarnUnusedAttr>())
2215 return;
2216 }
2217
2218 // Don't warn about __block Objective-C pointer variables, as they might
2219 // be assigned in the block but not used elsewhere for the purpose of lifetime
2220 // extension.
2221 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2222 return;
2223
2224 // Don't warn about Objective-C pointer variables with precise lifetime
2225 // semantics; they can be used to ensure ARC releases the object at a known
2226 // time, which may mean assignment but no other references.
2227 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2228 return;
2229
2230 auto iter = RefsMinusAssignments.find(Val: VD);
2231 if (iter == RefsMinusAssignments.end())
2232 return;
2233
2234 assert(iter->getSecond() >= 0 &&
2235 "Found a negative number of references to a VarDecl");
2236 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2237 // Assume the given VarDecl is "used" if its ref count stored in
2238 // `RefMinusAssignments` is positive, with one exception.
2239 //
2240 // For a C++ variable whose decl (with initializer) entirely consist the
2241 // condition expression of a if/while/for construct,
2242 // Clang creates a DeclRefExpr for the condition expression rather than a
2243 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2244 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2245 // used in the body of the if/while/for construct.
2246 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2247 if (!UnusedCXXCondDecl)
2248 return;
2249 }
2250
2251 unsigned DiagID = isa<ParmVarDecl>(Val: VD) ? diag::warn_unused_but_set_parameter
2252 : diag::warn_unused_but_set_variable;
2253 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2254}
2255
2256static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2257 Sema::DiagReceiverTy DiagReceiver) {
2258 // Verify that we have no forward references left. If so, there was a goto
2259 // or address of a label taken, but no definition of it. Label fwd
2260 // definitions are indicated with a null substmt which is also not a resolved
2261 // MS inline assembly label name.
2262 bool Diagnose = false;
2263 if (L->isMSAsmLabel())
2264 Diagnose = !L->isResolvedMSAsmLabel();
2265 else
2266 Diagnose = L->getStmt() == nullptr;
2267 if (Diagnose)
2268 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2269 << L);
2270}
2271
2272void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2273 S->applyNRVO();
2274
2275 if (S->decl_empty()) return;
2276 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2277 "Scope shouldn't contain decls!");
2278
2279 /// We visit the decls in non-deterministic order, but we want diagnostics
2280 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2281 /// and sort the diagnostics before emitting them, after we visited all decls.
2282 struct LocAndDiag {
2283 SourceLocation Loc;
2284 std::optional<SourceLocation> PreviousDeclLoc;
2285 PartialDiagnostic PD;
2286 };
2287 SmallVector<LocAndDiag, 16> DeclDiags;
2288 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2289 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2290 };
2291 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2292 SourceLocation PreviousDeclLoc,
2293 PartialDiagnostic PD) {
2294 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2295 };
2296
2297 for (auto *TmpD : S->decls()) {
2298 assert(TmpD && "This decl didn't get pushed??");
2299
2300 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2301 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2302
2303 // Diagnose unused variables in this scope.
2304 if (!S->hasUnrecoverableErrorOccurred()) {
2305 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2306 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2307 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2308 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2309 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2310 RefsMinusAssignments.erase(Val: VD);
2311 }
2312 }
2313
2314 if (!D->getDeclName()) continue;
2315
2316 // If this was a forward reference to a label, verify it was defined.
2317 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2318 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2319
2320 // Partial translation units that are created in incremental processing must
2321 // not clean up the IdResolver because PTUs should take into account the
2322 // declarations that came from previous PTUs.
2323 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2324 getLangOpts().CPlusPlus)
2325 IdResolver.RemoveDecl(D);
2326
2327 // Warn on it if we are shadowing a declaration.
2328 auto ShadowI = ShadowingDecls.find(Val: D);
2329 if (ShadowI != ShadowingDecls.end()) {
2330 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2331 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2332 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2333 << D << FD << FD->getParent());
2334 }
2335 ShadowingDecls.erase(I: ShadowI);
2336 }
2337 }
2338
2339 llvm::sort(C&: DeclDiags,
2340 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2341 // The particular order for diagnostics is not important, as long
2342 // as the order is deterministic. Using the raw location is going
2343 // to generally be in source order unless there are macro
2344 // expansions involved.
2345 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2346 });
2347 for (const LocAndDiag &D : DeclDiags) {
2348 Diag(Loc: D.Loc, PD: D.PD);
2349 if (D.PreviousDeclLoc)
2350 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2351 }
2352}
2353
2354Scope *Sema::getNonFieldDeclScope(Scope *S) {
2355 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2356 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2357 (S->isClassScope() && !getLangOpts().CPlusPlus))
2358 S = S->getParent();
2359 return S;
2360}
2361
2362static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2363 ASTContext::GetBuiltinTypeError Error) {
2364 switch (Error) {
2365 case ASTContext::GE_None:
2366 return "";
2367 case ASTContext::GE_Missing_type:
2368 return BuiltinInfo.getHeaderName(ID);
2369 case ASTContext::GE_Missing_stdio:
2370 return "stdio.h";
2371 case ASTContext::GE_Missing_setjmp:
2372 return "setjmp.h";
2373 case ASTContext::GE_Missing_ucontext:
2374 return "ucontext.h";
2375 }
2376 llvm_unreachable("unhandled error kind");
2377}
2378
2379FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2380 unsigned ID, SourceLocation Loc) {
2381 DeclContext *Parent = Context.getTranslationUnitDecl();
2382
2383 if (getLangOpts().CPlusPlus) {
2384 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2385 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2386 CLinkageDecl->setImplicit();
2387 Parent->addDecl(D: CLinkageDecl);
2388 Parent = CLinkageDecl;
2389 }
2390
2391 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2392 if (Context.BuiltinInfo.isImmediate(ID)) {
2393 assert(getLangOpts().CPlusPlus20 &&
2394 "consteval builtins should only be available in C++20 mode");
2395 ConstexprKind = ConstexprSpecKind::Consteval;
2396 }
2397
2398 FunctionDecl *New = FunctionDecl::Create(
2399 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2400 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2401 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2402 New->setImplicit();
2403 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2404
2405 // Create Decl objects for each parameter, adding them to the
2406 // FunctionDecl.
2407 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2408 SmallVector<ParmVarDecl *, 16> Params;
2409 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2410 ParmVarDecl *parm = ParmVarDecl::Create(
2411 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2412 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2413 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2414 Params.push_back(Elt: parm);
2415 }
2416 New->setParams(Params);
2417 }
2418
2419 AddKnownFunctionAttributes(FD: New);
2420 return New;
2421}
2422
2423NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2424 Scope *S, bool ForRedeclaration,
2425 SourceLocation Loc) {
2426 LookupNecessaryTypesForBuiltin(S, ID);
2427
2428 ASTContext::GetBuiltinTypeError Error;
2429 QualType R = Context.GetBuiltinType(ID, Error);
2430 if (Error) {
2431 if (!ForRedeclaration)
2432 return nullptr;
2433
2434 // If we have a builtin without an associated type we should not emit a
2435 // warning when we were not able to find a type for it.
2436 if (Error == ASTContext::GE_Missing_type ||
2437 Context.BuiltinInfo.allowTypeMismatch(ID))
2438 return nullptr;
2439
2440 // If we could not find a type for setjmp it is because the jmp_buf type was
2441 // not defined prior to the setjmp declaration.
2442 if (Error == ASTContext::GE_Missing_setjmp) {
2443 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2444 << Context.BuiltinInfo.getName(ID);
2445 return nullptr;
2446 }
2447
2448 // Generally, we emit a warning that the declaration requires the
2449 // appropriate header.
2450 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2451 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2452 << Context.BuiltinInfo.getName(ID);
2453 return nullptr;
2454 }
2455
2456 if (!ForRedeclaration &&
2457 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2458 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2459 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2460 : diag::ext_implicit_lib_function_decl)
2461 << Context.BuiltinInfo.getName(ID) << R;
2462 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2463 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2464 << Header << Context.BuiltinInfo.getName(ID);
2465 }
2466
2467 if (R.isNull())
2468 return nullptr;
2469
2470 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2471 RegisterLocallyScopedExternCDecl(ND: New, S);
2472
2473 // TUScope is the translation-unit scope to insert this function into.
2474 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2475 // relate Scopes to DeclContexts, and probably eliminate CurContext
2476 // entirely, but we're not there yet.
2477 DeclContext *SavedContext = CurContext;
2478 CurContext = New->getDeclContext();
2479 PushOnScopeChains(D: New, S: TUScope);
2480 CurContext = SavedContext;
2481 return New;
2482}
2483
2484/// Typedef declarations don't have linkage, but they still denote the same
2485/// entity if their types are the same.
2486/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2487/// isSameEntity.
2488static void
2489filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2490 LookupResult &Previous) {
2491 // This is only interesting when modules are enabled.
2492 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2493 return;
2494
2495 // Empty sets are uninteresting.
2496 if (Previous.empty())
2497 return;
2498
2499 LookupResult::Filter Filter = Previous.makeFilter();
2500 while (Filter.hasNext()) {
2501 NamedDecl *Old = Filter.next();
2502
2503 // Non-hidden declarations are never ignored.
2504 if (S.isVisible(D: Old))
2505 continue;
2506
2507 // Declarations of the same entity are not ignored, even if they have
2508 // different linkages.
2509 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2510 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2511 T2: Decl->getUnderlyingType()))
2512 continue;
2513
2514 // If both declarations give a tag declaration a typedef name for linkage
2515 // purposes, then they declare the same entity.
2516 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2517 Decl->getAnonDeclWithTypedefName())
2518 continue;
2519 }
2520
2521 Filter.erase();
2522 }
2523
2524 Filter.done();
2525}
2526
2527bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2528 QualType OldType;
2529 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2530 OldType = OldTypedef->getUnderlyingType();
2531 else
2532 OldType = Context.getTypeDeclType(Decl: Old);
2533 QualType NewType = New->getUnderlyingType();
2534
2535 if (NewType->isVariablyModifiedType()) {
2536 // Must not redefine a typedef with a variably-modified type.
2537 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2538 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2539 << Kind << NewType;
2540 if (Old->getLocation().isValid())
2541 notePreviousDefinition(Old, New: New->getLocation());
2542 New->setInvalidDecl();
2543 return true;
2544 }
2545
2546 if (OldType != NewType &&
2547 !OldType->isDependentType() &&
2548 !NewType->isDependentType() &&
2549 !Context.hasSameType(T1: OldType, T2: NewType)) {
2550 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2551 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2552 << Kind << NewType << OldType;
2553 if (Old->getLocation().isValid())
2554 notePreviousDefinition(Old, New: New->getLocation());
2555 New->setInvalidDecl();
2556 return true;
2557 }
2558 return false;
2559}
2560
2561void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2562 LookupResult &OldDecls) {
2563 // If the new decl is known invalid already, don't bother doing any
2564 // merging checks.
2565 if (New->isInvalidDecl()) return;
2566
2567 // Allow multiple definitions for ObjC built-in typedefs.
2568 // FIXME: Verify the underlying types are equivalent!
2569 if (getLangOpts().ObjC) {
2570 const IdentifierInfo *TypeID = New->getIdentifier();
2571 switch (TypeID->getLength()) {
2572 default: break;
2573 case 2:
2574 {
2575 if (!TypeID->isStr(Str: "id"))
2576 break;
2577 QualType T = New->getUnderlyingType();
2578 if (!T->isPointerType())
2579 break;
2580 if (!T->isVoidPointerType()) {
2581 QualType PT = T->castAs<PointerType>()->getPointeeType();
2582 if (!PT->isStructureType())
2583 break;
2584 }
2585 Context.setObjCIdRedefinitionType(T);
2586 // Install the built-in type for 'id', ignoring the current definition.
2587 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2588 modedTy: Context.getObjCIdType());
2589 return;
2590 }
2591 case 5:
2592 if (!TypeID->isStr(Str: "Class"))
2593 break;
2594 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2595 // Install the built-in type for 'Class', ignoring the current definition.
2596 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2597 modedTy: Context.getObjCClassType());
2598 return;
2599 case 3:
2600 if (!TypeID->isStr(Str: "SEL"))
2601 break;
2602 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2603 // Install the built-in type for 'SEL', ignoring the current definition.
2604 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2605 modedTy: Context.getObjCSelType());
2606 return;
2607 }
2608 // Fall through - the typedef name was not a builtin type.
2609 }
2610
2611 // Verify the old decl was also a type.
2612 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2613 if (!Old) {
2614 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2615 << New->getDeclName();
2616
2617 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2618 if (OldD->getLocation().isValid())
2619 notePreviousDefinition(Old: OldD, New: New->getLocation());
2620
2621 return New->setInvalidDecl();
2622 }
2623
2624 // If the old declaration is invalid, just give up here.
2625 if (Old->isInvalidDecl())
2626 return New->setInvalidDecl();
2627
2628 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2629 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2630 auto *NewTag = New->getAnonDeclWithTypedefName();
2631 NamedDecl *Hidden = nullptr;
2632 if (OldTag && NewTag &&
2633 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2634 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2635 // There is a definition of this tag, but it is not visible. Use it
2636 // instead of our tag.
2637 if (OldTD->isModed())
2638 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2639 modedTy: OldTD->getUnderlyingType());
2640 else
2641 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2642
2643 // Make the old tag definition visible.
2644 makeMergedDefinitionVisible(ND: Hidden);
2645
2646 CleanupMergedEnum(S, New: NewTag);
2647 }
2648 }
2649
2650 // If the typedef types are not identical, reject them in all languages and
2651 // with any extensions enabled.
2652 if (isIncompatibleTypedef(Old, New))
2653 return;
2654
2655 // The types match. Link up the redeclaration chain and merge attributes if
2656 // the old declaration was a typedef.
2657 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2658 New->setPreviousDecl(Typedef);
2659 mergeDeclAttributes(New, Old);
2660 }
2661
2662 if (getLangOpts().MicrosoftExt)
2663 return;
2664
2665 if (getLangOpts().CPlusPlus) {
2666 // C++ [dcl.typedef]p2:
2667 // In a given non-class scope, a typedef specifier can be used to
2668 // redefine the name of any type declared in that scope to refer
2669 // to the type to which it already refers.
2670 if (!isa<CXXRecordDecl>(Val: CurContext))
2671 return;
2672
2673 // C++0x [dcl.typedef]p4:
2674 // In a given class scope, a typedef specifier can be used to redefine
2675 // any class-name declared in that scope that is not also a typedef-name
2676 // to refer to the type to which it already refers.
2677 //
2678 // This wording came in via DR424, which was a correction to the
2679 // wording in DR56, which accidentally banned code like:
2680 //
2681 // struct S {
2682 // typedef struct A { } A;
2683 // };
2684 //
2685 // in the C++03 standard. We implement the C++0x semantics, which
2686 // allow the above but disallow
2687 //
2688 // struct S {
2689 // typedef int I;
2690 // typedef int I;
2691 // };
2692 //
2693 // since that was the intent of DR56.
2694 if (!isa<TypedefNameDecl>(Val: Old))
2695 return;
2696
2697 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2698 << New->getDeclName();
2699 notePreviousDefinition(Old, New: New->getLocation());
2700 return New->setInvalidDecl();
2701 }
2702
2703 // Modules always permit redefinition of typedefs, as does C11.
2704 if (getLangOpts().Modules || getLangOpts().C11)
2705 return;
2706
2707 // If we have a redefinition of a typedef in C, emit a warning. This warning
2708 // is normally mapped to an error, but can be controlled with
2709 // -Wtypedef-redefinition. If either the original or the redefinition is
2710 // in a system header, don't emit this for compatibility with GCC.
2711 if (getDiagnostics().getSuppressSystemWarnings() &&
2712 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2713 (Old->isImplicit() ||
2714 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2715 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2716 return;
2717
2718 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2719 << New->getDeclName();
2720 notePreviousDefinition(Old, New: New->getLocation());
2721}
2722
2723void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2724 // If this was an unscoped enumeration, yank all of its enumerators
2725 // out of the scope.
2726 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2727 Scope *EnumScope = getNonFieldDeclScope(S);
2728 for (auto *ECD : ED->enumerators()) {
2729 assert(EnumScope->isDeclScope(ECD));
2730 EnumScope->RemoveDecl(D: ECD);
2731 IdResolver.RemoveDecl(D: ECD);
2732 }
2733 }
2734}
2735
2736/// DeclhasAttr - returns true if decl Declaration already has the target
2737/// attribute.
2738static bool DeclHasAttr(const Decl *D, const Attr *A) {
2739 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2740 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2741 for (const auto *i : D->attrs())
2742 if (i->getKind() == A->getKind()) {
2743 if (Ann) {
2744 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2745 return true;
2746 continue;
2747 }
2748 // FIXME: Don't hardcode this check
2749 if (OA && isa<OwnershipAttr>(Val: i))
2750 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2751 return true;
2752 }
2753
2754 return false;
2755}
2756
2757static bool isAttributeTargetADefinition(Decl *D) {
2758 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2759 return VD->isThisDeclarationADefinition();
2760 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2761 return TD->isCompleteDefinition() || TD->isBeingDefined();
2762 return true;
2763}
2764
2765/// Merge alignment attributes from \p Old to \p New, taking into account the
2766/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2767///
2768/// \return \c true if any attributes were added to \p New.
2769static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2770 // Look for alignas attributes on Old, and pick out whichever attribute
2771 // specifies the strictest alignment requirement.
2772 AlignedAttr *OldAlignasAttr = nullptr;
2773 AlignedAttr *OldStrictestAlignAttr = nullptr;
2774 unsigned OldAlign = 0;
2775 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2776 // FIXME: We have no way of representing inherited dependent alignments
2777 // in a case like:
2778 // template<int A, int B> struct alignas(A) X;
2779 // template<int A, int B> struct alignas(B) X {};
2780 // For now, we just ignore any alignas attributes which are not on the
2781 // definition in such a case.
2782 if (I->isAlignmentDependent())
2783 return false;
2784
2785 if (I->isAlignas())
2786 OldAlignasAttr = I;
2787
2788 unsigned Align = I->getAlignment(Ctx&: S.Context);
2789 if (Align > OldAlign) {
2790 OldAlign = Align;
2791 OldStrictestAlignAttr = I;
2792 }
2793 }
2794
2795 // Look for alignas attributes on New.
2796 AlignedAttr *NewAlignasAttr = nullptr;
2797 unsigned NewAlign = 0;
2798 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2799 if (I->isAlignmentDependent())
2800 return false;
2801
2802 if (I->isAlignas())
2803 NewAlignasAttr = I;
2804
2805 unsigned Align = I->getAlignment(Ctx&: S.Context);
2806 if (Align > NewAlign)
2807 NewAlign = Align;
2808 }
2809
2810 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2811 // Both declarations have 'alignas' attributes. We require them to match.
2812 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2813 // fall short. (If two declarations both have alignas, they must both match
2814 // every definition, and so must match each other if there is a definition.)
2815
2816 // If either declaration only contains 'alignas(0)' specifiers, then it
2817 // specifies the natural alignment for the type.
2818 if (OldAlign == 0 || NewAlign == 0) {
2819 QualType Ty;
2820 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2821 Ty = VD->getType();
2822 else
2823 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2824
2825 if (OldAlign == 0)
2826 OldAlign = S.Context.getTypeAlign(T: Ty);
2827 if (NewAlign == 0)
2828 NewAlign = S.Context.getTypeAlign(T: Ty);
2829 }
2830
2831 if (OldAlign != NewAlign) {
2832 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2833 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2834 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2835 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2836 }
2837 }
2838
2839 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2840 // C++11 [dcl.align]p6:
2841 // if any declaration of an entity has an alignment-specifier,
2842 // every defining declaration of that entity shall specify an
2843 // equivalent alignment.
2844 // C11 6.7.5/7:
2845 // If the definition of an object does not have an alignment
2846 // specifier, any other declaration of that object shall also
2847 // have no alignment specifier.
2848 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2849 << OldAlignasAttr;
2850 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2851 << OldAlignasAttr;
2852 }
2853
2854 bool AnyAdded = false;
2855
2856 // Ensure we have an attribute representing the strictest alignment.
2857 if (OldAlign > NewAlign) {
2858 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2859 Clone->setInherited(true);
2860 New->addAttr(A: Clone);
2861 AnyAdded = true;
2862 }
2863
2864 // Ensure we have an alignas attribute if the old declaration had one.
2865 if (OldAlignasAttr && !NewAlignasAttr &&
2866 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2867 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2868 Clone->setInherited(true);
2869 New->addAttr(A: Clone);
2870 AnyAdded = true;
2871 }
2872
2873 return AnyAdded;
2874}
2875
2876#define WANT_DECL_MERGE_LOGIC
2877#include "clang/Sema/AttrParsedAttrImpl.inc"
2878#undef WANT_DECL_MERGE_LOGIC
2879
2880static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2881 const InheritableAttr *Attr,
2882 AvailabilityMergeKind AMK) {
2883 // Diagnose any mutual exclusions between the attribute that we want to add
2884 // and attributes that already exist on the declaration.
2885 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2886 return false;
2887
2888 // This function copies an attribute Attr from a previous declaration to the
2889 // new declaration D if the new declaration doesn't itself have that attribute
2890 // yet or if that attribute allows duplicates.
2891 // If you're adding a new attribute that requires logic different from
2892 // "use explicit attribute on decl if present, else use attribute from
2893 // previous decl", for example if the attribute needs to be consistent
2894 // between redeclarations, you need to call a custom merge function here.
2895 InheritableAttr *NewAttr = nullptr;
2896 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr))
2897 NewAttr = S.mergeAvailabilityAttr(
2898 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2899 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2900 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2901 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment());
2902 else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2903 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2904 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2905 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2906 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2907 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2908 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2909 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2910 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2911 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2912 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2913 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2914 FirstArg: FA->getFirstArg());
2915 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2916 NewAttr = S.mergeFormatMatchesAttr(
2917 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2918 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2919 NewAttr = S.mergeModularFormatAttr(
2920 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2921 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2922 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2923 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2924 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2925 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2926 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2927 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2928 Model: IA->getInheritanceModel());
2929 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2930 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2931 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2932 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2933 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2934 isa<CUDAGlobalAttr>(Val: Attr))) {
2935 // CUDA target attributes are part of function signature for
2936 // overloading purposes and must not be merged.
2937 return false;
2938 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2939 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2940 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2941 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2942 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2943 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2944 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2945 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2946 else if (isa<AlignedAttr>(Val: Attr))
2947 // AlignedAttrs are handled separately, because we need to handle all
2948 // such attributes on a declaration at the same time.
2949 NewAttr = nullptr;
2950 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2951 (AMK == AvailabilityMergeKind::Override ||
2952 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2953 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2954 NewAttr = nullptr;
2955 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2956 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2957 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2958 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2959 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2960 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2961 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2962 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2963 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2964 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2965 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2966 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2967 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2968 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2969 Z: NT->getZ());
2970 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
2971 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
2972 Preferred: WS->getPreferred(),
2973 SpelledArgsCount: WS->getSpelledArgsCount());
2974 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
2975 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
2976 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
2977 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
2978 else if (isa<SuppressAttr>(Val: Attr))
2979 // Do nothing. Each redeclaration should be suppressed separately.
2980 NewAttr = nullptr;
2981 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
2982 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
2983 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
2984 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
2985 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
2986 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
2987
2988 if (NewAttr) {
2989 NewAttr->setInherited(true);
2990 D->addAttr(A: NewAttr);
2991 if (isa<MSInheritanceAttr>(Val: NewAttr))
2992 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
2993 return true;
2994 }
2995
2996 return false;
2997}
2998
2999static const NamedDecl *getDefinition(const Decl *D) {
3000 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3001 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3002 return Def;
3003 return nullptr;
3004 }
3005 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3006 const VarDecl *Def = VD->getDefinition();
3007 if (Def)
3008 return Def;
3009 return VD->getActingDefinition();
3010 }
3011 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3012 const FunctionDecl *Def = nullptr;
3013 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3014 return Def;
3015 }
3016 return nullptr;
3017}
3018
3019static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3020 for (const auto *Attribute : D->attrs())
3021 if (Attribute->getKind() == Kind)
3022 return true;
3023 return false;
3024}
3025
3026/// checkNewAttributesAfterDef - If we already have a definition, check that
3027/// there are no new attributes in this declaration.
3028static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3029 if (!New->hasAttrs())
3030 return;
3031
3032 const NamedDecl *Def = getDefinition(D: Old);
3033 if (!Def || Def == New)
3034 return;
3035
3036 AttrVec &NewAttributes = New->getAttrs();
3037 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3038 Attr *NewAttribute = NewAttributes[I];
3039
3040 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3042 SkipBodyInfo SkipBody;
3043 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3044
3045 // If we're skipping this definition, drop the "alias" attribute.
3046 if (SkipBody.ShouldSkip) {
3047 NewAttributes.erase(CI: NewAttributes.begin() + I);
3048 --E;
3049 continue;
3050 }
3051 } else {
3052 VarDecl *VD = cast<VarDecl>(Val: New);
3053 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3054 VarDecl::TentativeDefinition
3055 ? diag::err_alias_after_tentative
3056 : diag::err_redefinition;
3057 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3058 if (Diag == diag::err_redefinition)
3059 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3060 else
3061 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3062 VD->setInvalidDecl();
3063 }
3064 ++I;
3065 continue;
3066 }
3067
3068 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3069 // Tentative definitions are only interesting for the alias check above.
3070 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3071 ++I;
3072 continue;
3073 }
3074 }
3075
3076 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3077 ++I;
3078 continue; // regular attr merging will take care of validating this.
3079 }
3080
3081 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3082 // C's _Noreturn is allowed to be added to a function after it is defined.
3083 ++I;
3084 continue;
3085 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3086 // msvc will allow a subsequent definition to add an uuid to a class
3087 ++I;
3088 continue;
3089 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3090 Val: NewAttribute) &&
3091 NewAttribute->isStandardAttributeSyntax()) {
3092 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3093 // deprecated attribute can later be re-declared with the attribute and
3094 // vice-versa.
3095 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3096 // maybe_unused attribute can later be redeclared with the attribute and
3097 // vice versa.
3098 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3099 // nodiscard attribute can later be redeclared with the attribute and
3100 // vice-versa.
3101 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3102 ++I;
3103 continue;
3104 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3105 if (AA->isAlignas()) {
3106 // C++11 [dcl.align]p6:
3107 // if any declaration of an entity has an alignment-specifier,
3108 // every defining declaration of that entity shall specify an
3109 // equivalent alignment.
3110 // C11 6.7.5/7:
3111 // If the definition of an object does not have an alignment
3112 // specifier, any other declaration of that object shall also
3113 // have no alignment specifier.
3114 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3115 << AA;
3116 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3117 << AA;
3118 NewAttributes.erase(CI: NewAttributes.begin() + I);
3119 --E;
3120 continue;
3121 }
3122 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3123 // If there is a C definition followed by a redeclaration with this
3124 // attribute then there are two different definitions. In C++, prefer the
3125 // standard diagnostics.
3126 if (!S.getLangOpts().CPlusPlus) {
3127 S.Diag(Loc: NewAttribute->getLocation(),
3128 DiagID: diag::err_loader_uninitialized_redeclaration);
3129 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3130 NewAttributes.erase(CI: NewAttributes.begin() + I);
3131 --E;
3132 continue;
3133 }
3134 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3135 cast<VarDecl>(Val: New)->isInline() &&
3136 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3137 // Don't warn about applying selectany to implicitly inline variables.
3138 // Older compilers and language modes would require the use of selectany
3139 // to make such variables inline, and it would have no effect if we
3140 // honored it.
3141 ++I;
3142 continue;
3143 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3144 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3145 // declarations after definitions.
3146 ++I;
3147 continue;
3148 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3149 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3150 // error since the definition will have already been created without
3151 // the semantic effects of the attribute having been applied.
3152 S.Diag(Loc: NewAttribute->getLocation(),
3153 DiagID: diag::err_sycl_entry_point_after_definition)
3154 << NewAttribute;
3155 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3156 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3157 ++I;
3158 continue;
3159 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3160 // SYCLExternalAttr may be added after a definition.
3161 ++I;
3162 continue;
3163 }
3164
3165 S.Diag(Loc: NewAttribute->getLocation(),
3166 DiagID: diag::warn_attribute_precede_definition);
3167 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3168 NewAttributes.erase(CI: NewAttributes.begin() + I);
3169 --E;
3170 }
3171}
3172
3173static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3174 const ConstInitAttr *CIAttr,
3175 bool AttrBeforeInit) {
3176 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3177
3178 // Figure out a good way to write this specifier on the old declaration.
3179 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3180 // enough of the attribute list spelling information to extract that without
3181 // heroics.
3182 std::string SuitableSpelling;
3183 if (S.getLangOpts().CPlusPlus20)
3184 SuitableSpelling = std::string(
3185 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3186 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3187 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3188 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3189 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3190 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3191 tok::r_square, tok::r_square}));
3192 if (SuitableSpelling.empty())
3193 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3194 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3195 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3196 tok::r_paren, tok::r_paren}));
3197 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3198 SuitableSpelling = "constinit";
3199 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3200 SuitableSpelling = "[[clang::require_constant_initialization]]";
3201 if (SuitableSpelling.empty())
3202 SuitableSpelling = "__attribute__((require_constant_initialization))";
3203 SuitableSpelling += " ";
3204
3205 if (AttrBeforeInit) {
3206 // extern constinit int a;
3207 // int a = 0; // error (missing 'constinit'), accepted as extension
3208 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3209 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3210 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3211 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3212 } else {
3213 // int a = 0;
3214 // constinit extern int a; // error (missing 'constinit')
3215 S.Diag(Loc: CIAttr->getLocation(),
3216 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3217 : diag::warn_require_const_init_added_too_late)
3218 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3219 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3220 << CIAttr->isConstinit()
3221 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3222 }
3223}
3224
3225void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3226 AvailabilityMergeKind AMK) {
3227 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3228 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3229 NewAttr->setInherited(true);
3230 New->addAttr(A: NewAttr);
3231 }
3232 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3233 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3234 NewAttr->setInherited(true);
3235 New->addAttr(A: NewAttr);
3236 }
3237
3238 if (!Old->hasAttrs() && !New->hasAttrs())
3239 return;
3240
3241 // [dcl.constinit]p1:
3242 // If the [constinit] specifier is applied to any declaration of a
3243 // variable, it shall be applied to the initializing declaration.
3244 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3245 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3246 if (bool(OldConstInit) != bool(NewConstInit)) {
3247 const auto *OldVD = cast<VarDecl>(Val: Old);
3248 auto *NewVD = cast<VarDecl>(Val: New);
3249
3250 // Find the initializing declaration. Note that we might not have linked
3251 // the new declaration into the redeclaration chain yet.
3252 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3253 if (!InitDecl &&
3254 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3255 InitDecl = NewVD;
3256
3257 if (InitDecl == NewVD) {
3258 // This is the initializing declaration. If it would inherit 'constinit',
3259 // that's ill-formed. (Note that we do not apply this to the attribute
3260 // form).
3261 if (OldConstInit && OldConstInit->isConstinit())
3262 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3263 /*AttrBeforeInit=*/true);
3264 } else if (NewConstInit) {
3265 // This is the first time we've been told that this declaration should
3266 // have a constant initializer. If we already saw the initializing
3267 // declaration, this is too late.
3268 if (InitDecl && InitDecl != NewVD) {
3269 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3270 /*AttrBeforeInit=*/false);
3271 NewVD->dropAttr<ConstInitAttr>();
3272 }
3273 }
3274 }
3275
3276 // Attributes declared post-definition are currently ignored.
3277 checkNewAttributesAfterDef(S&: *this, New, Old);
3278
3279 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3280 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3281 if (!OldA->isEquivalent(Other: NewA)) {
3282 // This redeclaration changes __asm__ label.
3283 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3284 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3285 }
3286 } else if (Old->isUsed()) {
3287 // This redeclaration adds an __asm__ label to a declaration that has
3288 // already been ODR-used.
3289 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3290 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3291 }
3292 }
3293
3294 // Re-declaration cannot add abi_tag's.
3295 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3296 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3297 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3298 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3299 Diag(Loc: NewAbiTagAttr->getLocation(),
3300 DiagID: diag::err_new_abi_tag_on_redeclaration)
3301 << NewTag;
3302 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3303 }
3304 }
3305 } else {
3306 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3307 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3308 }
3309 }
3310
3311 // This redeclaration adds a section attribute.
3312 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3313 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3314 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3315 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3316 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3317 }
3318 }
3319 }
3320
3321 // Redeclaration adds code-seg attribute.
3322 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3323 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3324 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3325 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3326 << 0 /*codeseg*/;
3327 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3328 }
3329
3330 if (!Old->hasAttrs())
3331 return;
3332
3333 bool foundAny = New->hasAttrs();
3334
3335 // Ensure that any moving of objects within the allocated map is done before
3336 // we process them.
3337 if (!foundAny) New->setAttrs(AttrVec());
3338
3339 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3340 // Ignore deprecated/unavailable/availability attributes if requested.
3341 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3342 if (isa<DeprecatedAttr>(Val: I) ||
3343 isa<UnavailableAttr>(Val: I) ||
3344 isa<AvailabilityAttr>(Val: I)) {
3345 switch (AMK) {
3346 case AvailabilityMergeKind::None:
3347 continue;
3348
3349 case AvailabilityMergeKind::Redeclaration:
3350 case AvailabilityMergeKind::Override:
3351 case AvailabilityMergeKind::ProtocolImplementation:
3352 case AvailabilityMergeKind::OptionalProtocolImplementation:
3353 LocalAMK = AMK;
3354 break;
3355 }
3356 }
3357
3358 // Already handled.
3359 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3360 continue;
3361
3362 if (isa<InferredNoReturnAttr>(Val: I)) {
3363 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3364 FD &&
3365 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3366 continue; // Don't propagate inferred noreturn attributes to explicit
3367 }
3368
3369 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3370 foundAny = true;
3371 }
3372
3373 if (mergeAlignedAttrs(S&: *this, New, Old))
3374 foundAny = true;
3375
3376 if (!foundAny) New->dropAttrs();
3377}
3378
3379void Sema::CheckAttributesOnDeducedType(Decl *D) {
3380 for (const Attr *A : D->attrs())
3381 checkAttrIsTypeDependent(D, A);
3382}
3383
3384// Returns the number of added attributes.
3385template <class T>
3386static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3387 Sema &S) {
3388 unsigned found = 0;
3389 for (const auto *I : From->specific_attrs<T>()) {
3390 if (!DeclHasAttr(To, I)) {
3391 T *newAttr = cast<T>(I->clone(S.Context));
3392 newAttr->setInherited(true);
3393 To->addAttr(A: newAttr);
3394 ++found;
3395 }
3396 }
3397 return found;
3398}
3399
3400template <class F>
3401static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3402 F &&propagator) {
3403 if (!From->hasAttrs()) {
3404 return;
3405 }
3406
3407 bool foundAny = To->hasAttrs();
3408
3409 // Ensure that any moving of objects within the allocated map is
3410 // done before we process them.
3411 if (!foundAny)
3412 To->setAttrs(AttrVec());
3413
3414 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3415
3416 if (!foundAny)
3417 To->dropAttrs();
3418}
3419
3420/// mergeParamDeclAttributes - Copy attributes from the old parameter
3421/// to the new one.
3422static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3423 const ParmVarDecl *oldDecl,
3424 Sema &S) {
3425 // C++11 [dcl.attr.depend]p2:
3426 // The first declaration of a function shall specify the
3427 // carries_dependency attribute for its declarator-id if any declaration
3428 // of the function specifies the carries_dependency attribute.
3429 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3430 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3431 S.Diag(Loc: CDA->getLocation(),
3432 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3433 // Find the first declaration of the parameter.
3434 // FIXME: Should we build redeclaration chains for function parameters?
3435 const FunctionDecl *FirstFD =
3436 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3437 const ParmVarDecl *FirstVD =
3438 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3439 S.Diag(Loc: FirstVD->getLocation(),
3440 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3441 }
3442
3443 propagateAttributes(
3444 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3445 unsigned found = 0;
3446 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3447 // Propagate the lifetimebound attribute from parameters to the
3448 // most recent declaration. Note that this doesn't include the implicit
3449 // 'this' parameter, as the attribute is applied to the function type in
3450 // that case.
3451 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3452 return found;
3453 });
3454}
3455
3456static bool EquivalentArrayTypes(QualType Old, QualType New,
3457 const ASTContext &Ctx) {
3458
3459 auto NoSizeInfo = [&Ctx](QualType Ty) {
3460 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3461 return true;
3462 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3463 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3464 return false;
3465 };
3466
3467 // `type[]` is equivalent to `type *` and `type[*]`.
3468 if (NoSizeInfo(Old) && NoSizeInfo(New))
3469 return true;
3470
3471 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3472 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3473 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3474 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3475 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3476 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3477 return false;
3478 return true;
3479 }
3480
3481 // Only compare size, ignore Size modifiers and CVR.
3482 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3483 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3484 Ctx.getAsConstantArrayType(T: New)->getSize();
3485 }
3486
3487 // Don't try to compare dependent sized array
3488 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3489 return true;
3490 }
3491
3492 return Old == New;
3493}
3494
3495static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3496 const ParmVarDecl *OldParam,
3497 Sema &S) {
3498 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3499 if (auto Newnullability = NewParam->getType()->getNullability()) {
3500 if (*Oldnullability != *Newnullability) {
3501 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3502 << DiagNullabilityKind(
3503 *Newnullability,
3504 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3505 != 0))
3506 << DiagNullabilityKind(
3507 *Oldnullability,
3508 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3509 != 0));
3510 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3511 }
3512 } else {
3513 QualType NewT = NewParam->getType();
3514 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3515 NewParam->setType(NewT);
3516 }
3517 }
3518 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3519 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3520 if (OldParamDT && NewParamDT &&
3521 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3522 QualType OldParamOT = OldParamDT->getOriginalType();
3523 QualType NewParamOT = NewParamDT->getOriginalType();
3524 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3525 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3526 << NewParam << NewParamOT;
3527 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3528 << OldParamOT;
3529 }
3530 }
3531}
3532
3533namespace {
3534
3535/// Used in MergeFunctionDecl to keep track of function parameters in
3536/// C.
3537struct GNUCompatibleParamWarning {
3538 ParmVarDecl *OldParm;
3539 ParmVarDecl *NewParm;
3540 QualType PromotedType;
3541};
3542
3543} // end anonymous namespace
3544
3545// Determine whether the previous declaration was a definition, implicit
3546// declaration, or a declaration.
3547template <typename T>
3548static std::pair<diag::kind, SourceLocation>
3549getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3550 diag::kind PrevDiag;
3551 SourceLocation OldLocation = Old->getLocation();
3552 if (Old->isThisDeclarationADefinition())
3553 PrevDiag = diag::note_previous_definition;
3554 else if (Old->isImplicit()) {
3555 PrevDiag = diag::note_previous_implicit_declaration;
3556 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3557 if (FD->getBuiltinID())
3558 PrevDiag = diag::note_previous_builtin_declaration;
3559 }
3560 if (OldLocation.isInvalid())
3561 OldLocation = New->getLocation();
3562 } else
3563 PrevDiag = diag::note_previous_declaration;
3564 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3565}
3566
3567/// canRedefineFunction - checks if a function can be redefined. Currently,
3568/// only extern inline functions can be redefined, and even then only in
3569/// GNU89 mode.
3570static bool canRedefineFunction(const FunctionDecl *FD,
3571 const LangOptions& LangOpts) {
3572 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3573 !LangOpts.CPlusPlus &&
3574 FD->isInlineSpecified() &&
3575 FD->getStorageClass() == SC_Extern);
3576}
3577
3578const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3579 const AttributedType *AT = T->getAs<AttributedType>();
3580 while (AT && !AT->isCallingConv())
3581 AT = AT->getModifiedType()->getAs<AttributedType>();
3582 return AT;
3583}
3584
3585template <typename T>
3586static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3587 const DeclContext *DC = Old->getDeclContext();
3588 if (DC->isRecord())
3589 return false;
3590
3591 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3592 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3593 return true;
3594 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3595 return true;
3596 return false;
3597}
3598
3599template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3600static bool isExternC(VarTemplateDecl *) { return false; }
3601static bool isExternC(FunctionTemplateDecl *) { return false; }
3602
3603/// Check whether a redeclaration of an entity introduced by a
3604/// using-declaration is valid, given that we know it's not an overload
3605/// (nor a hidden tag declaration).
3606template<typename ExpectedDecl>
3607static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3608 ExpectedDecl *New) {
3609 // C++11 [basic.scope.declarative]p4:
3610 // Given a set of declarations in a single declarative region, each of
3611 // which specifies the same unqualified name,
3612 // -- they shall all refer to the same entity, or all refer to functions
3613 // and function templates; or
3614 // -- exactly one declaration shall declare a class name or enumeration
3615 // name that is not a typedef name and the other declarations shall all
3616 // refer to the same variable or enumerator, or all refer to functions
3617 // and function templates; in this case the class name or enumeration
3618 // name is hidden (3.3.10).
3619
3620 // C++11 [namespace.udecl]p14:
3621 // If a function declaration in namespace scope or block scope has the
3622 // same name and the same parameter-type-list as a function introduced
3623 // by a using-declaration, and the declarations do not declare the same
3624 // function, the program is ill-formed.
3625
3626 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3627 if (Old &&
3628 !Old->getDeclContext()->getRedeclContext()->Equals(
3629 New->getDeclContext()->getRedeclContext()) &&
3630 !(isExternC(Old) && isExternC(New)))
3631 Old = nullptr;
3632
3633 if (!Old) {
3634 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3635 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3636 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3637 return true;
3638 }
3639 return false;
3640}
3641
3642static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3643 const FunctionDecl *B) {
3644 assert(A->getNumParams() == B->getNumParams());
3645
3646 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3647 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3648 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3649 if (AttrA == AttrB)
3650 return true;
3651 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3652 AttrA->isDynamic() == AttrB->isDynamic();
3653 };
3654
3655 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3656}
3657
3658/// If necessary, adjust the semantic declaration context for a qualified
3659/// declaration to name the correct inline namespace within the qualifier.
3660static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3661 DeclaratorDecl *OldD) {
3662 // The only case where we need to update the DeclContext is when
3663 // redeclaration lookup for a qualified name finds a declaration
3664 // in an inline namespace within the context named by the qualifier:
3665 //
3666 // inline namespace N { int f(); }
3667 // int ::f(); // Sema DC needs adjusting from :: to N::.
3668 //
3669 // For unqualified declarations, the semantic context *can* change
3670 // along the redeclaration chain (for local extern declarations,
3671 // extern "C" declarations, and friend declarations in particular).
3672 if (!NewD->getQualifier())
3673 return;
3674
3675 // NewD is probably already in the right context.
3676 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3677 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3678 if (NamedDC->Equals(DC: SemaDC))
3679 return;
3680
3681 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3682 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3683 "unexpected context for redeclaration");
3684
3685 auto *LexDC = NewD->getLexicalDeclContext();
3686 auto FixSemaDC = [=](NamedDecl *D) {
3687 if (!D)
3688 return;
3689 D->setDeclContext(SemaDC);
3690 D->setLexicalDeclContext(LexDC);
3691 };
3692
3693 FixSemaDC(NewD);
3694 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3695 FixSemaDC(FD->getDescribedFunctionTemplate());
3696 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3697 FixSemaDC(VD->getDescribedVarTemplate());
3698}
3699
3700bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3701 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3702 // Verify the old decl was also a function.
3703 FunctionDecl *Old = OldD->getAsFunction();
3704 if (!Old) {
3705 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3706 // We don't need to check the using friend pattern from other module unit
3707 // since we should have diagnosed such cases in its unit already.
3708 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3709 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3710 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3711 DiagID: diag::note_using_decl_target);
3712 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3713 << 0;
3714 return true;
3715 }
3716
3717 // Check whether the two declarations might declare the same function or
3718 // function template.
3719 if (FunctionTemplateDecl *NewTemplate =
3720 New->getDescribedFunctionTemplate()) {
3721 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3722 New: NewTemplate))
3723 return true;
3724 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3725 ->getAsFunction();
3726 } else {
3727 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3728 return true;
3729 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3730 }
3731 } else {
3732 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3733 << New->getDeclName();
3734 notePreviousDefinition(Old: OldD, New: New->getLocation());
3735 return true;
3736 }
3737 }
3738
3739 // If the old declaration was found in an inline namespace and the new
3740 // declaration was qualified, update the DeclContext to match.
3741 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3742
3743 // If the old declaration is invalid, just give up here.
3744 if (Old->isInvalidDecl())
3745 return true;
3746
3747 // Disallow redeclaration of some builtins.
3748 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3749 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3750 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3751 << Old << Old->getType();
3752 return true;
3753 }
3754
3755 diag::kind PrevDiag;
3756 SourceLocation OldLocation;
3757 std::tie(args&: PrevDiag, args&: OldLocation) =
3758 getNoteDiagForInvalidRedeclaration(Old, New);
3759
3760 // Don't complain about this if we're in GNU89 mode and the old function
3761 // is an extern inline function.
3762 // Don't complain about specializations. They are not supposed to have
3763 // storage classes.
3764 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3765 New->getStorageClass() == SC_Static &&
3766 Old->hasExternalFormalLinkage() &&
3767 !New->getTemplateSpecializationInfo() &&
3768 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3769 if (getLangOpts().MicrosoftExt) {
3770 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3771 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3772 } else {
3773 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3774 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3775 return true;
3776 }
3777 }
3778
3779 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3780 if (!Old->hasAttr<InternalLinkageAttr>()) {
3781 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3782 << ILA;
3783 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3784 New->dropAttr<InternalLinkageAttr>();
3785 }
3786
3787 if (auto *EA = New->getAttr<ErrorAttr>()) {
3788 if (!Old->hasAttr<ErrorAttr>()) {
3789 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3790 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3791 New->dropAttr<ErrorAttr>();
3792 }
3793 }
3794
3795 if (CheckRedeclarationInModule(New, Old))
3796 return true;
3797
3798 if (!getLangOpts().CPlusPlus) {
3799 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3800 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3801 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3802 << New << OldOvl;
3803
3804 // Try our best to find a decl that actually has the overloadable
3805 // attribute for the note. In most cases (e.g. programs with only one
3806 // broken declaration/definition), this won't matter.
3807 //
3808 // FIXME: We could do this if we juggled some extra state in
3809 // OverloadableAttr, rather than just removing it.
3810 const Decl *DiagOld = Old;
3811 if (OldOvl) {
3812 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3813 const auto *A = D->getAttr<OverloadableAttr>();
3814 return A && !A->isImplicit();
3815 });
3816 // If we've implicitly added *all* of the overloadable attrs to this
3817 // chain, emitting a "previous redecl" note is pointless.
3818 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3819 }
3820
3821 if (DiagOld)
3822 Diag(Loc: DiagOld->getLocation(),
3823 DiagID: diag::note_attribute_overloadable_prev_overload)
3824 << OldOvl;
3825
3826 if (OldOvl)
3827 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3828 else
3829 New->dropAttr<OverloadableAttr>();
3830 }
3831 }
3832
3833 // It is not permitted to redeclare an SME function with different SME
3834 // attributes.
3835 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3836 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3837 << New->getType() << Old->getType();
3838 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3839 return true;
3840 }
3841
3842 // If a function is first declared with a calling convention, but is later
3843 // declared or defined without one, all following decls assume the calling
3844 // convention of the first.
3845 //
3846 // It's OK if a function is first declared without a calling convention,
3847 // but is later declared or defined with the default calling convention.
3848 //
3849 // To test if either decl has an explicit calling convention, we look for
3850 // AttributedType sugar nodes on the type as written. If they are missing or
3851 // were canonicalized away, we assume the calling convention was implicit.
3852 //
3853 // Note also that we DO NOT return at this point, because we still have
3854 // other tests to run.
3855 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3856 QualType NewQType = Context.getCanonicalType(T: New->getType());
3857 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3858 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3859 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3860 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3861 bool RequiresAdjustment = false;
3862
3863 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3864 FunctionDecl *First = Old->getFirstDecl();
3865 const FunctionType *FT =
3866 First->getType().getCanonicalType()->castAs<FunctionType>();
3867 FunctionType::ExtInfo FI = FT->getExtInfo();
3868 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3869 if (!NewCCExplicit) {
3870 // Inherit the CC from the previous declaration if it was specified
3871 // there but not here.
3872 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3873 RequiresAdjustment = true;
3874 } else if (Old->getBuiltinID()) {
3875 // Builtin attribute isn't propagated to the new one yet at this point,
3876 // so we check if the old one is a builtin.
3877
3878 // Calling Conventions on a Builtin aren't really useful and setting a
3879 // default calling convention and cdecl'ing some builtin redeclarations is
3880 // common, so warn and ignore the calling convention on the redeclaration.
3881 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3882 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3883 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3884 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3885 RequiresAdjustment = true;
3886 } else {
3887 // Calling conventions aren't compatible, so complain.
3888 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3889 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3890 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3891 << !FirstCCExplicit
3892 << (!FirstCCExplicit ? "" :
3893 FunctionType::getNameForCallConv(CC: FI.getCC()));
3894
3895 // Put the note on the first decl, since it is the one that matters.
3896 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3897 return true;
3898 }
3899 }
3900
3901 // FIXME: diagnose the other way around?
3902 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3903 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3904 RequiresAdjustment = true;
3905 }
3906
3907 // If the declaration is marked with cfi_unchecked_callee but the definition
3908 // isn't, the definition is also cfi_unchecked_callee.
3909 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3910 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3911 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3912 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3913
3914 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3915 EPI2.CFIUncheckedCallee = true;
3916 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3917 Args: FPT2->getParamTypes(), EPI: EPI2);
3918 NewType = cast<FunctionType>(Val&: NewQType);
3919 New->setType(NewQType);
3920 }
3921 }
3922 }
3923
3924 // Merge regparm attribute.
3925 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3926 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3927 if (NewTypeInfo.getHasRegParm()) {
3928 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3929 << NewType->getRegParmType()
3930 << OldType->getRegParmType();
3931 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3932 return true;
3933 }
3934
3935 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3936 RequiresAdjustment = true;
3937 }
3938
3939 // Merge ns_returns_retained attribute.
3940 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3941 if (NewTypeInfo.getProducesResult()) {
3942 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3943 << "'ns_returns_retained'";
3944 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3945 return true;
3946 }
3947
3948 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3949 RequiresAdjustment = true;
3950 }
3951
3952 if (OldTypeInfo.getNoCallerSavedRegs() !=
3953 NewTypeInfo.getNoCallerSavedRegs()) {
3954 if (NewTypeInfo.getNoCallerSavedRegs()) {
3955 AnyX86NoCallerSavedRegistersAttr *Attr =
3956 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3957 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3958 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3959 return true;
3960 }
3961
3962 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3963 RequiresAdjustment = true;
3964 }
3965
3966 if (RequiresAdjustment) {
3967 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3968 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3969 New->setType(QualType(AdjustedType, 0));
3970 NewQType = Context.getCanonicalType(T: New->getType());
3971 }
3972
3973 // If this redeclaration makes the function inline, we may need to add it to
3974 // UndefinedButUsed.
3975 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3976 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
3977 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3978 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
3979 y: SourceLocation()));
3980
3981 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3982 // about it.
3983 if (New->hasAttr<GNUInlineAttr>() &&
3984 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3985 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
3986 }
3987
3988 // If pass_object_size params don't match up perfectly, this isn't a valid
3989 // redeclaration.
3990 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3991 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3992 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
3993 << New->getDeclName();
3994 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3995 return true;
3996 }
3997
3998 QualType OldQTypeForComparison = OldQType;
3999 if (Context.hasAnyFunctionEffects()) {
4000 const auto OldFX = Old->getFunctionEffects();
4001 const auto NewFX = New->getFunctionEffects();
4002 if (OldFX != NewFX) {
4003 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4004 for (const auto &Diff : Diffs) {
4005 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4006 Diag(Loc: New->getLocation(),
4007 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4008 << Diff.effectName();
4009 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4010 }
4011 }
4012 // Following a warning, we could skip merging effects from the previous
4013 // declaration, but that would trigger an additional "conflicting types"
4014 // error.
4015 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4016 FunctionEffectSet::Conflicts MergeErrs;
4017 FunctionEffectSet MergedFX =
4018 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4019 if (!MergeErrs.empty())
4020 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4021 OldLoc: Old->getLocation());
4022
4023 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4024 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4025 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4026 Args: NewFPT->getParamTypes(), EPI);
4027
4028 New->setType(ModQT);
4029 NewQType = New->getType();
4030
4031 // Revise OldQTForComparison to include the merged effects,
4032 // so as not to fail due to differences later.
4033 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4034 EPI = OldFPT->getExtProtoInfo();
4035 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4036 OldQTypeForComparison = Context.getFunctionType(
4037 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4038 }
4039 if (OldFX.empty()) {
4040 // A redeclaration may add the attribute to a previously seen function
4041 // body which needs to be verified.
4042 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4043 }
4044 }
4045 }
4046 }
4047
4048 if (getLangOpts().CPlusPlus) {
4049 OldQType = Context.getCanonicalType(T: Old->getType());
4050 NewQType = Context.getCanonicalType(T: New->getType());
4051
4052 // Go back to the type source info to compare the declared return types,
4053 // per C++1y [dcl.type.auto]p13:
4054 // Redeclarations or specializations of a function or function template
4055 // with a declared return type that uses a placeholder type shall also
4056 // use that placeholder, not a deduced type.
4057 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4058 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4059 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4060 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4061 OldT: OldDeclaredReturnType)) {
4062 QualType ResQT;
4063 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4064 OldDeclaredReturnType->isObjCObjectPointerType())
4065 // FIXME: This does the wrong thing for a deduced return type.
4066 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4067 if (ResQT.isNull()) {
4068 if (New->isCXXClassMember() && New->isOutOfLine())
4069 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4070 << New << New->getReturnTypeSourceRange();
4071 else if (Old->isExternC() && New->isExternC() &&
4072 !Old->hasAttr<OverloadableAttr>() &&
4073 !New->hasAttr<OverloadableAttr>())
4074 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4075 else
4076 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4077 << New->getReturnTypeSourceRange();
4078 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4079 << Old->getReturnTypeSourceRange();
4080 return true;
4081 }
4082 else
4083 NewQType = ResQT;
4084 }
4085
4086 QualType OldReturnType = OldType->getReturnType();
4087 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4088 if (OldReturnType != NewReturnType) {
4089 // If this function has a deduced return type and has already been
4090 // defined, copy the deduced value from the old declaration.
4091 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4092 if (OldAT && OldAT->isDeduced()) {
4093 QualType DT = OldAT->getDeducedType();
4094 if (DT.isNull()) {
4095 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4096 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4097 } else {
4098 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4099 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4100 }
4101 }
4102 }
4103
4104 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4105 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4106 if (OldMethod && NewMethod) {
4107 // Preserve triviality.
4108 NewMethod->setTrivial(OldMethod->isTrivial());
4109
4110 // MSVC allows explicit template specialization at class scope:
4111 // 2 CXXMethodDecls referring to the same function will be injected.
4112 // We don't want a redeclaration error.
4113 bool IsClassScopeExplicitSpecialization =
4114 OldMethod->isFunctionTemplateSpecialization() &&
4115 NewMethod->isFunctionTemplateSpecialization();
4116 bool isFriend = NewMethod->getFriendObjectKind();
4117
4118 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4119 !IsClassScopeExplicitSpecialization) {
4120 // -- Member function declarations with the same name and the
4121 // same parameter types cannot be overloaded if any of them
4122 // is a static member function declaration.
4123 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4124 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4125 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4126 return true;
4127 }
4128
4129 // C++ [class.mem]p1:
4130 // [...] A member shall not be declared twice in the
4131 // member-specification, except that a nested class or member
4132 // class template can be declared and then later defined.
4133 if (!inTemplateInstantiation()) {
4134 unsigned NewDiag;
4135 if (isa<CXXConstructorDecl>(Val: OldMethod))
4136 NewDiag = diag::err_constructor_redeclared;
4137 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4138 NewDiag = diag::err_destructor_redeclared;
4139 else if (isa<CXXConversionDecl>(Val: NewMethod))
4140 NewDiag = diag::err_conv_function_redeclared;
4141 else
4142 NewDiag = diag::err_member_redeclared;
4143
4144 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4145 } else {
4146 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4147 << New << New->getType();
4148 }
4149 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4150 return true;
4151
4152 // Complain if this is an explicit declaration of a special
4153 // member that was initially declared implicitly.
4154 //
4155 // As an exception, it's okay to befriend such methods in order
4156 // to permit the implicit constructor/destructor/operator calls.
4157 } else if (OldMethod->isImplicit()) {
4158 if (isFriend) {
4159 NewMethod->setImplicit();
4160 } else {
4161 Diag(Loc: NewMethod->getLocation(),
4162 DiagID: diag::err_definition_of_implicitly_declared_member)
4163 << New << getSpecialMember(MD: OldMethod);
4164 return true;
4165 }
4166 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4167 Diag(Loc: NewMethod->getLocation(),
4168 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4169 << getSpecialMember(MD: OldMethod);
4170 return true;
4171 }
4172 }
4173
4174 // C++1z [over.load]p2
4175 // Certain function declarations cannot be overloaded:
4176 // -- Function declarations that differ only in the return type,
4177 // the exception specification, or both cannot be overloaded.
4178
4179 // Check the exception specifications match. This may recompute the type of
4180 // both Old and New if it resolved exception specifications, so grab the
4181 // types again after this. Because this updates the type, we do this before
4182 // any of the other checks below, which may update the "de facto" NewQType
4183 // but do not necessarily update the type of New.
4184 if (CheckEquivalentExceptionSpec(Old, New))
4185 return true;
4186
4187 // C++11 [dcl.attr.noreturn]p1:
4188 // The first declaration of a function shall specify the noreturn
4189 // attribute if any declaration of that function specifies the noreturn
4190 // attribute.
4191 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4192 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4193 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4194 << NRA;
4195 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4196 }
4197
4198 // C++11 [dcl.attr.depend]p2:
4199 // The first declaration of a function shall specify the
4200 // carries_dependency attribute for its declarator-id if any declaration
4201 // of the function specifies the carries_dependency attribute.
4202 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4203 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4204 Diag(Loc: CDA->getLocation(),
4205 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4206 Diag(Loc: Old->getFirstDecl()->getLocation(),
4207 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4208 }
4209
4210 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4211 // When a function is declared with SYCL_EXTERNAL, that macro must be
4212 // used on the first declaration of that function in the translation unit.
4213 // Redeclarations of the function in the same translation unit may
4214 // optionally use SYCL_EXTERNAL, but this is not required.
4215 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4216 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4217 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4218 << SEA;
4219 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4220 }
4221
4222 // (C++98 8.3.5p3):
4223 // All declarations for a function shall agree exactly in both the
4224 // return type and the parameter-type-list.
4225 // We also want to respect all the extended bits except noreturn.
4226
4227 // noreturn should now match unless the old type info didn't have it.
4228 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4229 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4230 const FunctionType *OldTypeForComparison
4231 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4232 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4233 assert(OldQTypeForComparison.isCanonical());
4234 }
4235
4236 if (haveIncompatibleLanguageLinkages(Old, New)) {
4237 // As a special case, retain the language linkage from previous
4238 // declarations of a friend function as an extension.
4239 //
4240 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4241 // and is useful because there's otherwise no way to specify language
4242 // linkage within class scope.
4243 //
4244 // Check cautiously as the friend object kind isn't yet complete.
4245 if (New->getFriendObjectKind() != Decl::FOK_None) {
4246 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4247 Diag(Loc: OldLocation, DiagID: PrevDiag);
4248 } else {
4249 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4250 Diag(Loc: OldLocation, DiagID: PrevDiag);
4251 return true;
4252 }
4253 }
4254
4255 // HLSL check parameters for matching ABI specifications.
4256 if (getLangOpts().HLSL) {
4257 if (HLSL().CheckCompatibleParameterABI(New, Old))
4258 return true;
4259
4260 // If no errors are generated when checking parameter ABIs we can check if
4261 // the two declarations have the same type ignoring the ABIs and if so,
4262 // the declarations can be merged. This case for merging is only valid in
4263 // HLSL because there are no valid cases of merging mismatched parameter
4264 // ABIs except the HLSL implicit in and explicit in.
4265 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4266 U: NewQType))
4267 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4268 // Fall through for conflicting redeclarations and redefinitions.
4269 }
4270
4271 // If the function types are compatible, merge the declarations. Ignore the
4272 // exception specifier because it was already checked above in
4273 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4274 // about incompatible types under -fms-compatibility.
4275 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4276 U: NewQType))
4277 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4278
4279 // If the types are imprecise (due to dependent constructs in friends or
4280 // local extern declarations), it's OK if they differ. We'll check again
4281 // during instantiation.
4282 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4283 return false;
4284
4285 // Fall through for conflicting redeclarations and redefinitions.
4286 }
4287
4288 // C: Function types need to be compatible, not identical. This handles
4289 // duplicate function decls like "void f(int); void f(enum X);" properly.
4290 if (!getLangOpts().CPlusPlus) {
4291 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4292 // type is specified by a function definition that contains a (possibly
4293 // empty) identifier list, both shall agree in the number of parameters
4294 // and the type of each parameter shall be compatible with the type that
4295 // results from the application of default argument promotions to the
4296 // type of the corresponding identifier. ...
4297 // This cannot be handled by ASTContext::typesAreCompatible() because that
4298 // doesn't know whether the function type is for a definition or not when
4299 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4300 // we need to cover here is that the number of arguments agree as the
4301 // default argument promotion rules were already checked by
4302 // ASTContext::typesAreCompatible().
4303 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4304 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4305 if (Old->hasInheritedPrototype())
4306 Old = Old->getCanonicalDecl();
4307 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4308 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4309 return true;
4310 }
4311
4312 // If we are merging two functions where only one of them has a prototype,
4313 // we may have enough information to decide to issue a diagnostic that the
4314 // function without a prototype will change behavior in C23. This handles
4315 // cases like:
4316 // void i(); void i(int j);
4317 // void i(int j); void i();
4318 // void i(); void i(int j) {}
4319 // See ActOnFinishFunctionBody() for other cases of the behavior change
4320 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4321 // type without a prototype.
4322 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4323 !New->isImplicit() && !Old->isImplicit()) {
4324 const FunctionDecl *WithProto, *WithoutProto;
4325 if (New->hasWrittenPrototype()) {
4326 WithProto = New;
4327 WithoutProto = Old;
4328 } else {
4329 WithProto = Old;
4330 WithoutProto = New;
4331 }
4332
4333 if (WithProto->getNumParams() != 0) {
4334 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4335 // The one without the prototype will be changing behavior in C23, so
4336 // warn about that one so long as it's a user-visible declaration.
4337 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4338 if (WithoutProto == New)
4339 IsWithoutProtoADef = NewDeclIsDefn;
4340 else
4341 IsWithProtoADef = NewDeclIsDefn;
4342 Diag(Loc: WithoutProto->getLocation(),
4343 DiagID: diag::warn_non_prototype_changes_behavior)
4344 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4345 << (WithoutProto == Old) << IsWithProtoADef;
4346
4347 // The reason the one without the prototype will be changing behavior
4348 // is because of the one with the prototype, so note that so long as
4349 // it's a user-visible declaration. There is one exception to this:
4350 // when the new declaration is a definition without a prototype, the
4351 // old declaration with a prototype is not the cause of the issue,
4352 // and that does not need to be noted because the one with a
4353 // prototype will not change behavior in C23.
4354 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4355 !IsWithoutProtoADef)
4356 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4357 }
4358 }
4359 }
4360
4361 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4362 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4363 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4364 const FunctionProtoType *OldProto = nullptr;
4365 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4366 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4367 // The old declaration provided a function prototype, but the
4368 // new declaration does not. Merge in the prototype.
4369 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4370 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4371 Args: OldProto->getParamTypes(),
4372 EPI: OldProto->getExtProtoInfo());
4373 New->setType(NewQType);
4374 New->setHasInheritedPrototype();
4375
4376 // Synthesize parameters with the same types.
4377 SmallVector<ParmVarDecl *, 16> Params;
4378 for (const auto &ParamType : OldProto->param_types()) {
4379 ParmVarDecl *Param = ParmVarDecl::Create(
4380 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4381 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4382 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4383 Param->setImplicit();
4384 Params.push_back(Elt: Param);
4385 }
4386
4387 New->setParams(Params);
4388 }
4389
4390 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4391 }
4392 }
4393
4394 // Check if the function types are compatible when pointer size address
4395 // spaces are ignored.
4396 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4397 return false;
4398
4399 // GNU C permits a K&R definition to follow a prototype declaration
4400 // if the declared types of the parameters in the K&R definition
4401 // match the types in the prototype declaration, even when the
4402 // promoted types of the parameters from the K&R definition differ
4403 // from the types in the prototype. GCC then keeps the types from
4404 // the prototype.
4405 //
4406 // If a variadic prototype is followed by a non-variadic K&R definition,
4407 // the K&R definition becomes variadic. This is sort of an edge case, but
4408 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4409 // C99 6.9.1p8.
4410 if (!getLangOpts().CPlusPlus &&
4411 Old->hasPrototype() && !New->hasPrototype() &&
4412 New->getType()->getAs<FunctionProtoType>() &&
4413 Old->getNumParams() == New->getNumParams()) {
4414 SmallVector<QualType, 16> ArgTypes;
4415 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4416 const FunctionProtoType *OldProto
4417 = Old->getType()->getAs<FunctionProtoType>();
4418 const FunctionProtoType *NewProto
4419 = New->getType()->getAs<FunctionProtoType>();
4420
4421 // Determine whether this is the GNU C extension.
4422 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4423 NewProto->getReturnType());
4424 bool LooseCompatible = !MergedReturn.isNull();
4425 for (unsigned Idx = 0, End = Old->getNumParams();
4426 LooseCompatible && Idx != End; ++Idx) {
4427 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4428 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4429 if (Context.typesAreCompatible(T1: OldParm->getType(),
4430 T2: NewProto->getParamType(i: Idx))) {
4431 ArgTypes.push_back(Elt: NewParm->getType());
4432 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4433 T2: NewParm->getType(),
4434 /*CompareUnqualified=*/true)) {
4435 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4436 .PromotedType: NewProto->getParamType(i: Idx) };
4437 Warnings.push_back(Elt: Warn);
4438 ArgTypes.push_back(Elt: NewParm->getType());
4439 } else
4440 LooseCompatible = false;
4441 }
4442
4443 if (LooseCompatible) {
4444 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4445 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4446 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4447 << Warnings[Warn].PromotedType
4448 << Warnings[Warn].OldParm->getType();
4449 if (Warnings[Warn].OldParm->getLocation().isValid())
4450 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4451 DiagID: diag::note_previous_declaration);
4452 }
4453
4454 if (MergeTypeWithOld)
4455 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4456 EPI: OldProto->getExtProtoInfo()));
4457 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4458 }
4459
4460 // Fall through to diagnose conflicting types.
4461 }
4462
4463 // A function that has already been declared has been redeclared or
4464 // defined with a different type; show an appropriate diagnostic.
4465
4466 // If the previous declaration was an implicitly-generated builtin
4467 // declaration, then at the very least we should use a specialized note.
4468 unsigned BuiltinID;
4469 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4470 // If it's actually a library-defined builtin function like 'malloc'
4471 // or 'printf', just warn about the incompatible redeclaration.
4472 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4473 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4474 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4475 << Old << Old->getType();
4476 return false;
4477 }
4478
4479 PrevDiag = diag::note_previous_builtin_declaration;
4480 }
4481
4482 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4483 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4484 return true;
4485}
4486
4487bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4488 Scope *S, bool MergeTypeWithOld) {
4489 // Merge the attributes
4490 mergeDeclAttributes(New, Old);
4491
4492 // Merge "pure" flag.
4493 if (Old->isPureVirtual())
4494 New->setIsPureVirtual();
4495
4496 // Merge "used" flag.
4497 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4498 New->setIsUsed();
4499
4500 // Merge attributes from the parameters. These can mismatch with K&R
4501 // declarations.
4502 if (New->getNumParams() == Old->getNumParams())
4503 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4504 ParmVarDecl *NewParam = New->getParamDecl(i);
4505 ParmVarDecl *OldParam = Old->getParamDecl(i);
4506 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4507 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4508 }
4509
4510 if (getLangOpts().CPlusPlus)
4511 return MergeCXXFunctionDecl(New, Old, S);
4512
4513 // Merge the function types so the we get the composite types for the return
4514 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4515 // was visible.
4516 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4517 if (!Merged.isNull() && MergeTypeWithOld)
4518 New->setType(Merged);
4519
4520 return false;
4521}
4522
4523void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4524 ObjCMethodDecl *oldMethod) {
4525 // Merge the attributes, including deprecated/unavailable
4526 AvailabilityMergeKind MergeKind =
4527 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4528 ? (oldMethod->isOptional()
4529 ? AvailabilityMergeKind::OptionalProtocolImplementation
4530 : AvailabilityMergeKind::ProtocolImplementation)
4531 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4532 ? AvailabilityMergeKind::Redeclaration
4533 : AvailabilityMergeKind::Override;
4534
4535 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4536
4537 // Merge attributes from the parameters.
4538 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4539 oe = oldMethod->param_end();
4540 for (ObjCMethodDecl::param_iterator
4541 ni = newMethod->param_begin(), ne = newMethod->param_end();
4542 ni != ne && oi != oe; ++ni, ++oi)
4543 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4544
4545 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4546}
4547
4548static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4549 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4550
4551 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4552 ? diag::err_redefinition_different_type
4553 : diag::err_redeclaration_different_type)
4554 << New->getDeclName() << New->getType() << Old->getType();
4555
4556 diag::kind PrevDiag;
4557 SourceLocation OldLocation;
4558 std::tie(args&: PrevDiag, args&: OldLocation)
4559 = getNoteDiagForInvalidRedeclaration(Old, New);
4560 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4561 New->setInvalidDecl();
4562}
4563
4564void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4565 bool MergeTypeWithOld) {
4566 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4567 return;
4568
4569 QualType MergedT;
4570 if (getLangOpts().CPlusPlus) {
4571 if (New->getType()->isUndeducedType()) {
4572 // We don't know what the new type is until the initializer is attached.
4573 return;
4574 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4575 // These could still be something that needs exception specs checked.
4576 return MergeVarDeclExceptionSpecs(New, Old);
4577 }
4578 // C++ [basic.link]p10:
4579 // [...] the types specified by all declarations referring to a given
4580 // object or function shall be identical, except that declarations for an
4581 // array object can specify array types that differ by the presence or
4582 // absence of a major array bound (8.3.4).
4583 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4584 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4585 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4586
4587 // We are merging a variable declaration New into Old. If it has an array
4588 // bound, and that bound differs from Old's bound, we should diagnose the
4589 // mismatch.
4590 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4591 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4592 PrevVD = PrevVD->getPreviousDecl()) {
4593 QualType PrevVDTy = PrevVD->getType();
4594 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4595 continue;
4596
4597 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4598 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4599 }
4600 }
4601
4602 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4603 if (Context.hasSameType(T1: OldArray->getElementType(),
4604 T2: NewArray->getElementType()))
4605 MergedT = New->getType();
4606 }
4607 // FIXME: Check visibility. New is hidden but has a complete type. If New
4608 // has no array bound, it should not inherit one from Old, if Old is not
4609 // visible.
4610 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4611 if (Context.hasSameType(T1: OldArray->getElementType(),
4612 T2: NewArray->getElementType()))
4613 MergedT = Old->getType();
4614 }
4615 }
4616 else if (New->getType()->isObjCObjectPointerType() &&
4617 Old->getType()->isObjCObjectPointerType()) {
4618 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4619 Old->getType());
4620 }
4621 } else {
4622 // C 6.2.7p2:
4623 // All declarations that refer to the same object or function shall have
4624 // compatible type.
4625 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4626 }
4627 if (MergedT.isNull()) {
4628 // It's OK if we couldn't merge types if either type is dependent, for a
4629 // block-scope variable. In other cases (static data members of class
4630 // templates, variable templates, ...), we require the types to be
4631 // equivalent.
4632 // FIXME: The C++ standard doesn't say anything about this.
4633 if ((New->getType()->isDependentType() ||
4634 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4635 // If the old type was dependent, we can't merge with it, so the new type
4636 // becomes dependent for now. We'll reproduce the original type when we
4637 // instantiate the TypeSourceInfo for the variable.
4638 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4639 New->setType(Context.DependentTy);
4640 return;
4641 }
4642 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4643 }
4644
4645 // Don't actually update the type on the new declaration if the old
4646 // declaration was an extern declaration in a different scope.
4647 if (MergeTypeWithOld)
4648 New->setType(MergedT);
4649}
4650
4651static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4652 LookupResult &Previous) {
4653 // C11 6.2.7p4:
4654 // For an identifier with internal or external linkage declared
4655 // in a scope in which a prior declaration of that identifier is
4656 // visible, if the prior declaration specifies internal or
4657 // external linkage, the type of the identifier at the later
4658 // declaration becomes the composite type.
4659 //
4660 // If the variable isn't visible, we do not merge with its type.
4661 if (Previous.isShadowed())
4662 return false;
4663
4664 if (S.getLangOpts().CPlusPlus) {
4665 // C++11 [dcl.array]p3:
4666 // If there is a preceding declaration of the entity in the same
4667 // scope in which the bound was specified, an omitted array bound
4668 // is taken to be the same as in that earlier declaration.
4669 return NewVD->isPreviousDeclInSameBlockScope() ||
4670 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4671 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4672 } else {
4673 // If the old declaration was function-local, don't merge with its
4674 // type unless we're in the same function.
4675 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4676 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4677 }
4678}
4679
4680void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4681 // If the new decl is already invalid, don't do any other checking.
4682 if (New->isInvalidDecl())
4683 return;
4684
4685 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4686 return;
4687
4688 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4689
4690 // Verify the old decl was also a variable or variable template.
4691 VarDecl *Old = nullptr;
4692 VarTemplateDecl *OldTemplate = nullptr;
4693 if (Previous.isSingleResult()) {
4694 if (NewTemplate) {
4695 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4696 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4697
4698 if (auto *Shadow =
4699 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4700 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4701 return New->setInvalidDecl();
4702 } else {
4703 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4704
4705 if (auto *Shadow =
4706 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4707 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4708 return New->setInvalidDecl();
4709 }
4710 }
4711 if (!Old) {
4712 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4713 << New->getDeclName();
4714 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4715 New: New->getLocation());
4716 return New->setInvalidDecl();
4717 }
4718
4719 // If the old declaration was found in an inline namespace and the new
4720 // declaration was qualified, update the DeclContext to match.
4721 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4722
4723 // Ensure the template parameters are compatible.
4724 if (NewTemplate &&
4725 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4726 Old: OldTemplate->getTemplateParameters(),
4727 /*Complain=*/true, Kind: TPL_TemplateMatch))
4728 return New->setInvalidDecl();
4729
4730 // C++ [class.mem]p1:
4731 // A member shall not be declared twice in the member-specification [...]
4732 //
4733 // Here, we need only consider static data members.
4734 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4735 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4736 << New->getIdentifier();
4737 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4738 New->setInvalidDecl();
4739 }
4740
4741 mergeDeclAttributes(New, Old);
4742 // Warn if an already-defined variable is made a weak_import in a subsequent
4743 // declaration
4744 if (New->hasAttr<WeakImportAttr>())
4745 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4746 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4747 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4748 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4749 // Remove weak_import attribute on new declaration.
4750 New->dropAttr<WeakImportAttr>();
4751 break;
4752 }
4753 }
4754
4755 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4756 if (!Old->hasAttr<InternalLinkageAttr>()) {
4757 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4758 << ILA;
4759 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4760 New->dropAttr<InternalLinkageAttr>();
4761 }
4762
4763 // Merge the types.
4764 VarDecl *MostRecent = Old->getMostRecentDecl();
4765 if (MostRecent != Old) {
4766 MergeVarDeclTypes(New, Old: MostRecent,
4767 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4768 if (New->isInvalidDecl())
4769 return;
4770 }
4771
4772 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4773 if (New->isInvalidDecl())
4774 return;
4775
4776 diag::kind PrevDiag;
4777 SourceLocation OldLocation;
4778 std::tie(args&: PrevDiag, args&: OldLocation) =
4779 getNoteDiagForInvalidRedeclaration(Old, New);
4780
4781 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4782 if (New->getStorageClass() == SC_Static &&
4783 !New->isStaticDataMember() &&
4784 Old->hasExternalFormalLinkage()) {
4785 if (getLangOpts().MicrosoftExt) {
4786 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4787 << New->getDeclName();
4788 Diag(Loc: OldLocation, DiagID: PrevDiag);
4789 } else {
4790 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4791 << New->getDeclName();
4792 Diag(Loc: OldLocation, DiagID: PrevDiag);
4793 return New->setInvalidDecl();
4794 }
4795 }
4796 // C99 6.2.2p4:
4797 // For an identifier declared with the storage-class specifier
4798 // extern in a scope in which a prior declaration of that
4799 // identifier is visible,23) if the prior declaration specifies
4800 // internal or external linkage, the linkage of the identifier at
4801 // the later declaration is the same as the linkage specified at
4802 // the prior declaration. If no prior declaration is visible, or
4803 // if the prior declaration specifies no linkage, then the
4804 // identifier has external linkage.
4805 if (New->hasExternalStorage() && Old->hasLinkage())
4806 /* Okay */;
4807 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4808 !New->isStaticDataMember() &&
4809 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4810 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4811 Diag(Loc: OldLocation, DiagID: PrevDiag);
4812 return New->setInvalidDecl();
4813 }
4814
4815 // Check if extern is followed by non-extern and vice-versa.
4816 if (New->hasExternalStorage() &&
4817 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4818 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4819 Diag(Loc: OldLocation, DiagID: PrevDiag);
4820 return New->setInvalidDecl();
4821 }
4822 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4823 !New->hasExternalStorage()) {
4824 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4825 Diag(Loc: OldLocation, DiagID: PrevDiag);
4826 return New->setInvalidDecl();
4827 }
4828
4829 if (CheckRedeclarationInModule(New, Old))
4830 return;
4831
4832 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4833
4834 // FIXME: The test for external storage here seems wrong? We still
4835 // need to check for mismatches.
4836 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4837 // Don't complain about out-of-line definitions of static members.
4838 !(Old->getLexicalDeclContext()->isRecord() &&
4839 !New->getLexicalDeclContext()->isRecord())) {
4840 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4841 Diag(Loc: OldLocation, DiagID: PrevDiag);
4842 return New->setInvalidDecl();
4843 }
4844
4845 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4846 if (VarDecl *Def = Old->getDefinition()) {
4847 // C++1z [dcl.fcn.spec]p4:
4848 // If the definition of a variable appears in a translation unit before
4849 // its first declaration as inline, the program is ill-formed.
4850 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4851 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4852 }
4853 }
4854
4855 // If this redeclaration makes the variable inline, we may need to add it to
4856 // UndefinedButUsed.
4857 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4858 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4859 !Old->isInAnotherModuleUnit())
4860 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4861 y: SourceLocation()));
4862
4863 if (New->getTLSKind() != Old->getTLSKind()) {
4864 if (!Old->getTLSKind()) {
4865 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4866 Diag(Loc: OldLocation, DiagID: PrevDiag);
4867 } else if (!New->getTLSKind()) {
4868 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4869 Diag(Loc: OldLocation, DiagID: PrevDiag);
4870 } else {
4871 // Do not allow redeclaration to change the variable between requiring
4872 // static and dynamic initialization.
4873 // FIXME: GCC allows this, but uses the TLS keyword on the first
4874 // declaration to determine the kind. Do we need to be compatible here?
4875 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4876 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4877 Diag(Loc: OldLocation, DiagID: PrevDiag);
4878 }
4879 }
4880
4881 // C++ doesn't have tentative definitions, so go right ahead and check here.
4882 if (getLangOpts().CPlusPlus) {
4883 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4884 Old->getCanonicalDecl()->isConstexpr()) {
4885 // This definition won't be a definition any more once it's been merged.
4886 Diag(Loc: New->getLocation(),
4887 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4888 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4889 VarDecl *Def = Old->getDefinition();
4890 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4891 return;
4892 }
4893 } else {
4894 // C++ may not have a tentative definition rule, but it has a different
4895 // rule about what constitutes a definition in the first place. See
4896 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4897 // contains the extern specifier and doesn't have an initializer, it's fine
4898 // in C++.
4899 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4900 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4901 << New;
4902 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4903 }
4904 }
4905
4906 if (haveIncompatibleLanguageLinkages(Old, New)) {
4907 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4908 Diag(Loc: OldLocation, DiagID: PrevDiag);
4909 New->setInvalidDecl();
4910 return;
4911 }
4912
4913 // Merge "used" flag.
4914 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4915 New->setIsUsed();
4916
4917 // Keep a chain of previous declarations.
4918 New->setPreviousDecl(Old);
4919 if (NewTemplate)
4920 NewTemplate->setPreviousDecl(OldTemplate);
4921
4922 // Inherit access appropriately.
4923 New->setAccess(Old->getAccess());
4924 if (NewTemplate)
4925 NewTemplate->setAccess(New->getAccess());
4926
4927 if (Old->isInline())
4928 New->setImplicitlyInline();
4929}
4930
4931void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4932 SourceManager &SrcMgr = getSourceManager();
4933 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4934 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4935 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4936 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4937 auto &HSI = PP.getHeaderSearchInfo();
4938 StringRef HdrFilename =
4939 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4940
4941 auto noteFromModuleOrInclude = [&](Module *Mod,
4942 SourceLocation IncLoc) -> bool {
4943 // Redefinition errors with modules are common with non modular mapped
4944 // headers, example: a non-modular header H in module A that also gets
4945 // included directly in a TU. Pointing twice to the same header/definition
4946 // is confusing, try to get better diagnostics when modules is on.
4947 if (IncLoc.isValid()) {
4948 if (Mod) {
4949 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4950 << HdrFilename.str() << Mod->getFullModuleName();
4951 if (!Mod->DefinitionLoc.isInvalid())
4952 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4953 << Mod->getFullModuleName();
4954 } else {
4955 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4956 << HdrFilename.str();
4957 }
4958 return true;
4959 }
4960
4961 return false;
4962 };
4963
4964 // Is it the same file and same offset? Provide more information on why
4965 // this leads to a redefinition error.
4966 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4967 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4968 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4969 bool EmittedDiag =
4970 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4971 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4972
4973 // If the header has no guards, emit a note suggesting one.
4974 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
4975 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
4976
4977 if (EmittedDiag)
4978 return;
4979 }
4980
4981 // Redefinition coming from different files or couldn't do better above.
4982 if (Old->getLocation().isValid())
4983 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
4984}
4985
4986bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4987 if (!hasVisibleDefinition(D: Old) &&
4988 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4989 isa<VarTemplateSpecializationDecl>(Val: New) ||
4990 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4991 New->getDeclContext()->isDependentContext() ||
4992 New->hasAttr<SelectAnyAttr>())) {
4993 // The previous definition is hidden, and multiple definitions are
4994 // permitted (in separate TUs). Demote this to a declaration.
4995 New->demoteThisDefinitionToDeclaration();
4996
4997 // Make the canonical definition visible.
4998 if (auto *OldTD = Old->getDescribedVarTemplate())
4999 makeMergedDefinitionVisible(ND: OldTD);
5000 makeMergedDefinitionVisible(ND: Old);
5001 return false;
5002 } else {
5003 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5004 notePreviousDefinition(Old, New: New->getLocation());
5005 New->setInvalidDecl();
5006 return true;
5007 }
5008}
5009
5010Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5011 DeclSpec &DS,
5012 const ParsedAttributesView &DeclAttrs,
5013 RecordDecl *&AnonRecord) {
5014 return ParsedFreeStandingDeclSpec(
5015 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5016}
5017
5018// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5019// disambiguate entities defined in different scopes.
5020// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5021// compatibility.
5022// We will pick our mangling number depending on which version of MSVC is being
5023// targeted.
5024static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5025 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5026 ? S->getMSCurManglingNumber()
5027 : S->getMSLastManglingNumber();
5028}
5029
5030void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5031 if (!Context.getLangOpts().CPlusPlus)
5032 return;
5033
5034 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5035 // If this tag is the direct child of a class, number it if
5036 // it is anonymous.
5037 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5038 return;
5039 MangleNumberingContext &MCtx =
5040 Context.getManglingNumberContext(DC: Tag->getParent());
5041 Context.setManglingNumber(
5042 ND: Tag, Number: MCtx.getManglingNumber(
5043 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5044 return;
5045 }
5046
5047 // If this tag isn't a direct child of a class, number it if it is local.
5048 MangleNumberingContext *MCtx;
5049 Decl *ManglingContextDecl;
5050 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5051 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5052 if (MCtx) {
5053 Context.setManglingNumber(
5054 ND: Tag, Number: MCtx->getManglingNumber(
5055 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5056 }
5057}
5058
5059namespace {
5060struct NonCLikeKind {
5061 enum {
5062 None,
5063 BaseClass,
5064 DefaultMemberInit,
5065 Lambda,
5066 Friend,
5067 OtherMember,
5068 Invalid,
5069 } Kind = None;
5070 SourceRange Range;
5071
5072 explicit operator bool() { return Kind != None; }
5073};
5074}
5075
5076/// Determine whether a class is C-like, according to the rules of C++
5077/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5078static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5079 if (RD->isInvalidDecl())
5080 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5081
5082 // C++ [dcl.typedef]p9: [P1766R1]
5083 // An unnamed class with a typedef name for linkage purposes shall not
5084 //
5085 // -- have any base classes
5086 if (RD->getNumBases())
5087 return {.Kind: NonCLikeKind::BaseClass,
5088 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5089 RD->bases_end()[-1].getEndLoc())};
5090 bool Invalid = false;
5091 for (Decl *D : RD->decls()) {
5092 // Don't complain about things we already diagnosed.
5093 if (D->isInvalidDecl()) {
5094 Invalid = true;
5095 continue;
5096 }
5097
5098 // -- have any [...] default member initializers
5099 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5100 if (FD->hasInClassInitializer()) {
5101 auto *Init = FD->getInClassInitializer();
5102 return {.Kind: NonCLikeKind::DefaultMemberInit,
5103 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5104 }
5105 continue;
5106 }
5107
5108 // FIXME: We don't allow friend declarations. This violates the wording of
5109 // P1766, but not the intent.
5110 if (isa<FriendDecl>(Val: D))
5111 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5112
5113 // -- declare any members other than non-static data members, member
5114 // enumerations, or member classes,
5115 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5116 isa<EnumDecl>(Val: D))
5117 continue;
5118 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5119 if (!MemberRD) {
5120 if (D->isImplicit())
5121 continue;
5122 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5123 }
5124
5125 // -- contain a lambda-expression,
5126 if (MemberRD->isLambda())
5127 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5128
5129 // and all member classes shall also satisfy these requirements
5130 // (recursively).
5131 if (MemberRD->isThisDeclarationADefinition()) {
5132 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5133 return Kind;
5134 }
5135 }
5136
5137 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5138}
5139
5140void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5141 TypedefNameDecl *NewTD) {
5142 if (TagFromDeclSpec->isInvalidDecl())
5143 return;
5144
5145 // Do nothing if the tag already has a name for linkage purposes.
5146 if (TagFromDeclSpec->hasNameForLinkage())
5147 return;
5148
5149 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5150 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5151
5152 // The type must match the tag exactly; no qualifiers allowed.
5153 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5154 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5155 if (getLangOpts().CPlusPlus)
5156 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5157 return;
5158 }
5159
5160 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5161 // An unnamed class with a typedef name for linkage purposes shall [be
5162 // C-like].
5163 //
5164 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5165 // shouldn't happen, but there are constructs that the language rule doesn't
5166 // disallow for which we can't reasonably avoid computing linkage early.
5167 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5168 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5169 : NonCLikeKind();
5170 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5171 if (NonCLike || ChangesLinkage) {
5172 if (NonCLike.Kind == NonCLikeKind::Invalid)
5173 return;
5174
5175 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5176 if (ChangesLinkage) {
5177 // If the linkage changes, we can't accept this as an extension.
5178 if (NonCLike.Kind == NonCLikeKind::None)
5179 DiagID = diag::err_typedef_changes_linkage;
5180 else
5181 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5182 }
5183
5184 SourceLocation FixitLoc =
5185 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5186 llvm::SmallString<40> TextToInsert;
5187 TextToInsert += ' ';
5188 TextToInsert += NewTD->getIdentifier()->getName();
5189
5190 Diag(Loc: FixitLoc, DiagID)
5191 << isa<TypeAliasDecl>(Val: NewTD)
5192 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5193 if (NonCLike.Kind != NonCLikeKind::None) {
5194 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5195 << NonCLike.Kind - 1 << NonCLike.Range;
5196 }
5197 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5198 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5199
5200 if (ChangesLinkage)
5201 return;
5202 }
5203
5204 // Otherwise, set this as the anon-decl typedef for the tag.
5205 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5206
5207 // Now that we have a name for the tag, process API notes again.
5208 ProcessAPINotes(D: TagFromDeclSpec);
5209}
5210
5211static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5212 DeclSpec::TST T = DS.getTypeSpecType();
5213 switch (T) {
5214 case DeclSpec::TST_class:
5215 return 0;
5216 case DeclSpec::TST_struct:
5217 return 1;
5218 case DeclSpec::TST_interface:
5219 return 2;
5220 case DeclSpec::TST_union:
5221 return 3;
5222 case DeclSpec::TST_enum:
5223 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5224 if (ED->isScopedUsingClassTag())
5225 return 5;
5226 if (ED->isScoped())
5227 return 6;
5228 }
5229 return 4;
5230 default:
5231 llvm_unreachable("unexpected type specifier");
5232 }
5233}
5234
5235Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5236 DeclSpec &DS,
5237 const ParsedAttributesView &DeclAttrs,
5238 MultiTemplateParamsArg TemplateParams,
5239 bool IsExplicitInstantiation,
5240 RecordDecl *&AnonRecord,
5241 SourceLocation EllipsisLoc) {
5242 Decl *TagD = nullptr;
5243 TagDecl *Tag = nullptr;
5244 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5245 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5246 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5247 DS.getTypeSpecType() == DeclSpec::TST_union ||
5248 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5249 TagD = DS.getRepAsDecl();
5250
5251 if (!TagD) // We probably had an error
5252 return nullptr;
5253
5254 // Note that the above type specs guarantee that the
5255 // type rep is a Decl, whereas in many of the others
5256 // it's a Type.
5257 if (isa<TagDecl>(Val: TagD))
5258 Tag = cast<TagDecl>(Val: TagD);
5259 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5260 Tag = CTD->getTemplatedDecl();
5261 }
5262
5263 if (Tag) {
5264 handleTagNumbering(Tag, TagScope: S);
5265 Tag->setFreeStanding();
5266 if (Tag->isInvalidDecl())
5267 return Tag;
5268 }
5269
5270 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5271 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5272 // or incomplete types shall not be restrict-qualified."
5273 if (TypeQuals & DeclSpec::TQ_restrict)
5274 Diag(Loc: DS.getRestrictSpecLoc(),
5275 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5276 << DS.getSourceRange();
5277 }
5278
5279 if (DS.isInlineSpecified())
5280 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5281 << getLangOpts().CPlusPlus17;
5282
5283 if (DS.hasConstexprSpecifier()) {
5284 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5285 // and definitions of functions and variables.
5286 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5287 // the declaration of a function or function template
5288 if (Tag)
5289 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5290 << GetDiagnosticTypeSpecifierID(DS)
5291 << static_cast<int>(DS.getConstexprSpecifier());
5292 else if (getLangOpts().C23)
5293 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5294 else
5295 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5296 << static_cast<int>(DS.getConstexprSpecifier());
5297 // Don't emit warnings after this error.
5298 return TagD;
5299 }
5300
5301 DiagnoseFunctionSpecifiers(DS);
5302
5303 if (DS.isFriendSpecified()) {
5304 // If we're dealing with a decl but not a TagDecl, assume that
5305 // whatever routines created it handled the friendship aspect.
5306 if (TagD && !Tag)
5307 return nullptr;
5308 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5309 }
5310
5311 assert(EllipsisLoc.isInvalid() &&
5312 "Friend ellipsis but not friend-specified?");
5313
5314 // Track whether this decl-specifier declares anything.
5315 bool DeclaresAnything = true;
5316
5317 // Handle anonymous struct definitions.
5318 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5319 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5320 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5321 if (getLangOpts().CPlusPlus ||
5322 Record->getDeclContext()->isRecord()) {
5323 // If CurContext is a DeclContext that can contain statements,
5324 // RecursiveASTVisitor won't visit the decls that
5325 // BuildAnonymousStructOrUnion() will put into CurContext.
5326 // Also store them here so that they can be part of the
5327 // DeclStmt that gets created in this case.
5328 // FIXME: Also return the IndirectFieldDecls created by
5329 // BuildAnonymousStructOr union, for the same reason?
5330 if (CurContext->isFunctionOrMethod())
5331 AnonRecord = Record;
5332 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5333 Policy: Context.getPrintingPolicy());
5334 }
5335
5336 DeclaresAnything = false;
5337 }
5338 }
5339
5340 // C11 6.7.2.1p2:
5341 // A struct-declaration that does not declare an anonymous structure or
5342 // anonymous union shall contain a struct-declarator-list.
5343 //
5344 // This rule also existed in C89 and C99; the grammar for struct-declaration
5345 // did not permit a struct-declaration without a struct-declarator-list.
5346 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5347 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5348 // Check for Microsoft C extension: anonymous struct/union member.
5349 // Handle 2 kinds of anonymous struct/union:
5350 // struct STRUCT;
5351 // union UNION;
5352 // and
5353 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5354 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5355 if ((Tag && Tag->getDeclName()) ||
5356 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5357 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5358 : DS.getRepAsType().get()->getAsRecordDecl();
5359 if (Record && getLangOpts().MSAnonymousStructs) {
5360 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5361 << Record->isUnion() << DS.getSourceRange();
5362 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5363 }
5364
5365 DeclaresAnything = false;
5366 }
5367 }
5368
5369 // Skip all the checks below if we have a type error.
5370 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5371 (TagD && TagD->isInvalidDecl()))
5372 return TagD;
5373
5374 if (getLangOpts().CPlusPlus &&
5375 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5376 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5377 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5378 !Enum->isInvalidDecl())
5379 DeclaresAnything = false;
5380
5381 if (!DS.isMissingDeclaratorOk()) {
5382 // Customize diagnostic for a typedef missing a name.
5383 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5384 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5385 << DS.getSourceRange();
5386 else
5387 DeclaresAnything = false;
5388 }
5389
5390 if (DS.isModulePrivateSpecified() &&
5391 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5392 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5393 << Tag->getTagKind()
5394 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5395
5396 ActOnDocumentableDecl(D: TagD);
5397
5398 // C 6.7/2:
5399 // A declaration [...] shall declare at least a declarator [...], a tag,
5400 // or the members of an enumeration.
5401 // C++ [dcl.dcl]p3:
5402 // [If there are no declarators], and except for the declaration of an
5403 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5404 // names into the program, or shall redeclare a name introduced by a
5405 // previous declaration.
5406 if (!DeclaresAnything) {
5407 // In C, we allow this as a (popular) extension / bug. Don't bother
5408 // producing further diagnostics for redundant qualifiers after this.
5409 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5410 ? diag::err_no_declarators
5411 : diag::ext_no_declarators)
5412 << DS.getSourceRange();
5413 return TagD;
5414 }
5415
5416 // C++ [dcl.stc]p1:
5417 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5418 // init-declarator-list of the declaration shall not be empty.
5419 // C++ [dcl.fct.spec]p1:
5420 // If a cv-qualifier appears in a decl-specifier-seq, the
5421 // init-declarator-list of the declaration shall not be empty.
5422 //
5423 // Spurious qualifiers here appear to be valid in C.
5424 unsigned DiagID = diag::warn_standalone_specifier;
5425 if (getLangOpts().CPlusPlus)
5426 DiagID = diag::ext_standalone_specifier;
5427
5428 // Note that a linkage-specification sets a storage class, but
5429 // 'extern "C" struct foo;' is actually valid and not theoretically
5430 // useless.
5431 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5432 if (SCS == DeclSpec::SCS_mutable)
5433 // Since mutable is not a viable storage class specifier in C, there is
5434 // no reason to treat it as an extension. Instead, diagnose as an error.
5435 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5436 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5437 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5438 << DeclSpec::getSpecifierName(S: SCS);
5439 }
5440
5441 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5442 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5443 << DeclSpec::getSpecifierName(S: TSCS);
5444 if (DS.getTypeQualifiers()) {
5445 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5446 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5447 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5448 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5449 // Restrict is covered above.
5450 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5451 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5452 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5453 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5454 }
5455
5456 // Warn about ignored type attributes, for example:
5457 // __attribute__((aligned)) struct A;
5458 // Attributes should be placed after tag to apply to type declaration.
5459 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5460 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5461 if (TypeSpecType == DeclSpec::TST_class ||
5462 TypeSpecType == DeclSpec::TST_struct ||
5463 TypeSpecType == DeclSpec::TST_interface ||
5464 TypeSpecType == DeclSpec::TST_union ||
5465 TypeSpecType == DeclSpec::TST_enum) {
5466
5467 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5468 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5469 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5470 DiagnosticId = diag::warn_attribute_ignored;
5471 else if (AL.isRegularKeywordAttribute())
5472 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5473 else
5474 DiagnosticId = diag::warn_declspec_attribute_ignored;
5475 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5476 << AL << GetDiagnosticTypeSpecifierID(DS);
5477 };
5478
5479 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5480 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5481 }
5482 }
5483
5484 return TagD;
5485}
5486
5487/// We are trying to inject an anonymous member into the given scope;
5488/// check if there's an existing declaration that can't be overloaded.
5489///
5490/// \return true if this is a forbidden redeclaration
5491static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5492 DeclContext *Owner,
5493 DeclarationName Name,
5494 SourceLocation NameLoc, bool IsUnion,
5495 StorageClass SC) {
5496 LookupResult R(SemaRef, Name, NameLoc,
5497 Owner->isRecord() ? Sema::LookupMemberName
5498 : Sema::LookupOrdinaryName,
5499 RedeclarationKind::ForVisibleRedeclaration);
5500 if (!SemaRef.LookupName(R, S)) return false;
5501
5502 // Pick a representative declaration.
5503 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5504 assert(PrevDecl && "Expected a non-null Decl");
5505
5506 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5507 return false;
5508
5509 if (SC == StorageClass::SC_None &&
5510 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5511 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5512 if (!Owner->isRecord())
5513 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5514 return false;
5515 }
5516
5517 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5518 << IsUnion << Name;
5519 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5520
5521 return true;
5522}
5523
5524void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5525 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5526 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5527}
5528
5529void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5530 if (!getLangOpts().CPlusPlus)
5531 return;
5532
5533 // This function can be parsed before we have validated the
5534 // structure as an anonymous struct
5535 if (Record->isAnonymousStructOrUnion())
5536 return;
5537
5538 const NamedDecl *First = 0;
5539 for (const Decl *D : Record->decls()) {
5540 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5541 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5542 continue;
5543 if (!First)
5544 First = ND;
5545 else
5546 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5547 }
5548}
5549
5550/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5551/// anonymous struct or union AnonRecord into the owning context Owner
5552/// and scope S. This routine will be invoked just after we realize
5553/// that an unnamed union or struct is actually an anonymous union or
5554/// struct, e.g.,
5555///
5556/// @code
5557/// union {
5558/// int i;
5559/// float f;
5560/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5561/// // f into the surrounding scope.x
5562/// @endcode
5563///
5564/// This routine is recursive, injecting the names of nested anonymous
5565/// structs/unions into the owning context and scope as well.
5566static bool
5567InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5568 RecordDecl *AnonRecord, AccessSpecifier AS,
5569 StorageClass SC,
5570 SmallVectorImpl<NamedDecl *> &Chaining) {
5571 bool Invalid = false;
5572
5573 // Look every FieldDecl and IndirectFieldDecl with a name.
5574 for (auto *D : AnonRecord->decls()) {
5575 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5576 cast<NamedDecl>(Val: D)->getDeclName()) {
5577 ValueDecl *VD = cast<ValueDecl>(Val: D);
5578 // C++ [class.union]p2:
5579 // The names of the members of an anonymous union shall be
5580 // distinct from the names of any other entity in the
5581 // scope in which the anonymous union is declared.
5582
5583 bool FieldInvalid = CheckAnonMemberRedeclaration(
5584 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5585 IsUnion: AnonRecord->isUnion(), SC);
5586 if (FieldInvalid)
5587 Invalid = true;
5588
5589 // Inject the IndirectFieldDecl even if invalid, because later
5590 // diagnostics may depend on it being present, see findDefaultInitializer.
5591
5592 // C++ [class.union]p2:
5593 // For the purpose of name lookup, after the anonymous union
5594 // definition, the members of the anonymous union are
5595 // considered to have been defined in the scope in which the
5596 // anonymous union is declared.
5597 unsigned OldChainingSize = Chaining.size();
5598 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5599 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5600 else
5601 Chaining.push_back(Elt: VD);
5602
5603 assert(Chaining.size() >= 2);
5604 NamedDecl **NamedChain =
5605 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5606 for (unsigned i = 0; i < Chaining.size(); i++)
5607 NamedChain[i] = Chaining[i];
5608
5609 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5610 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5611 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5612
5613 for (const auto *Attr : VD->attrs())
5614 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5615
5616 IndirectField->setAccess(AS);
5617 IndirectField->setImplicit();
5618 IndirectField->setInvalidDecl(FieldInvalid);
5619 SemaRef.PushOnScopeChains(D: IndirectField, S);
5620
5621 // That includes picking up the appropriate access specifier.
5622 if (AS != AS_none)
5623 IndirectField->setAccess(AS);
5624
5625 Chaining.resize(N: OldChainingSize);
5626 }
5627 }
5628
5629 return Invalid;
5630}
5631
5632/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5633/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5634/// illegal input values are mapped to SC_None.
5635static StorageClass
5636StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5637 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5638 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5639 "Parser allowed 'typedef' as storage class VarDecl.");
5640 switch (StorageClassSpec) {
5641 case DeclSpec::SCS_unspecified: return SC_None;
5642 case DeclSpec::SCS_extern:
5643 if (DS.isExternInLinkageSpec())
5644 return SC_None;
5645 return SC_Extern;
5646 case DeclSpec::SCS_static: return SC_Static;
5647 case DeclSpec::SCS_auto: return SC_Auto;
5648 case DeclSpec::SCS_register: return SC_Register;
5649 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5650 // Illegal SCSs map to None: error reporting is up to the caller.
5651 case DeclSpec::SCS_mutable: // Fall through.
5652 case DeclSpec::SCS_typedef: return SC_None;
5653 }
5654 llvm_unreachable("unknown storage class specifier");
5655}
5656
5657static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5658 assert(Record->hasInClassInitializer());
5659
5660 for (const auto *I : Record->decls()) {
5661 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5662 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5663 FD = IFD->getAnonField();
5664 if (FD && FD->hasInClassInitializer())
5665 return FD->getLocation();
5666 }
5667
5668 llvm_unreachable("couldn't find in-class initializer");
5669}
5670
5671static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5672 SourceLocation DefaultInitLoc) {
5673 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5674 return;
5675
5676 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5677 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5678}
5679
5680static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5681 CXXRecordDecl *AnonUnion) {
5682 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5683 return;
5684
5685 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5686}
5687
5688Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5689 AccessSpecifier AS,
5690 RecordDecl *Record,
5691 const PrintingPolicy &Policy) {
5692 DeclContext *Owner = Record->getDeclContext();
5693
5694 // Diagnose whether this anonymous struct/union is an extension.
5695 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5696 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5697 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5698 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5699 else if (!Record->isUnion() && !getLangOpts().C11)
5700 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5701
5702 // C and C++ require different kinds of checks for anonymous
5703 // structs/unions.
5704 bool Invalid = false;
5705 if (getLangOpts().CPlusPlus) {
5706 const char *PrevSpec = nullptr;
5707 if (Record->isUnion()) {
5708 // C++ [class.union]p6:
5709 // C++17 [class.union.anon]p2:
5710 // Anonymous unions declared in a named namespace or in the
5711 // global namespace shall be declared static.
5712 unsigned DiagID;
5713 DeclContext *OwnerScope = Owner->getRedeclContext();
5714 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5715 (OwnerScope->isTranslationUnit() ||
5716 (OwnerScope->isNamespace() &&
5717 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5718 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5719 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5720
5721 // Recover by adding 'static'.
5722 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5723 PrevSpec, DiagID, Policy);
5724 }
5725 // C++ [class.union]p6:
5726 // A storage class is not allowed in a declaration of an
5727 // anonymous union in a class scope.
5728 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5729 isa<RecordDecl>(Val: Owner)) {
5730 Diag(Loc: DS.getStorageClassSpecLoc(),
5731 DiagID: diag::err_anonymous_union_with_storage_spec)
5732 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5733
5734 // Recover by removing the storage specifier.
5735 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5736 Loc: SourceLocation(),
5737 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5738 }
5739 }
5740
5741 // Ignore const/volatile/restrict qualifiers.
5742 if (DS.getTypeQualifiers()) {
5743 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5744 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5745 << Record->isUnion() << "const"
5746 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5747 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5748 Diag(Loc: DS.getVolatileSpecLoc(),
5749 DiagID: diag::ext_anonymous_struct_union_qualified)
5750 << Record->isUnion() << "volatile"
5751 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5752 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5753 Diag(Loc: DS.getRestrictSpecLoc(),
5754 DiagID: diag::ext_anonymous_struct_union_qualified)
5755 << Record->isUnion() << "restrict"
5756 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5757 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5758 Diag(Loc: DS.getAtomicSpecLoc(),
5759 DiagID: diag::ext_anonymous_struct_union_qualified)
5760 << Record->isUnion() << "_Atomic"
5761 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5762 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5763 Diag(Loc: DS.getUnalignedSpecLoc(),
5764 DiagID: diag::ext_anonymous_struct_union_qualified)
5765 << Record->isUnion() << "__unaligned"
5766 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5767
5768 DS.ClearTypeQualifiers();
5769 }
5770
5771 // C++ [class.union]p2:
5772 // The member-specification of an anonymous union shall only
5773 // define non-static data members. [Note: nested types and
5774 // functions cannot be declared within an anonymous union. ]
5775 for (auto *Mem : Record->decls()) {
5776 // Ignore invalid declarations; we already diagnosed them.
5777 if (Mem->isInvalidDecl())
5778 continue;
5779
5780 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5781 // C++ [class.union]p3:
5782 // An anonymous union shall not have private or protected
5783 // members (clause 11).
5784 assert(FD->getAccess() != AS_none);
5785 if (FD->getAccess() != AS_public) {
5786 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5787 << Record->isUnion() << (FD->getAccess() == AS_protected);
5788 Invalid = true;
5789 }
5790
5791 // C++ [class.union]p1
5792 // An object of a class with a non-trivial constructor, a non-trivial
5793 // copy constructor, a non-trivial destructor, or a non-trivial copy
5794 // assignment operator cannot be a member of a union, nor can an
5795 // array of such objects.
5796 if (CheckNontrivialField(FD))
5797 Invalid = true;
5798 } else if (Mem->isImplicit()) {
5799 // Any implicit members are fine.
5800 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5801 // This is a type that showed up in an
5802 // elaborated-type-specifier inside the anonymous struct or
5803 // union, but which actually declares a type outside of the
5804 // anonymous struct or union. It's okay.
5805 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5806 if (!MemRecord->isAnonymousStructOrUnion() &&
5807 MemRecord->getDeclName()) {
5808 // Visual C++ allows type definition in anonymous struct or union.
5809 if (getLangOpts().MicrosoftExt)
5810 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5811 << Record->isUnion();
5812 else {
5813 // This is a nested type declaration.
5814 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5815 << Record->isUnion();
5816 Invalid = true;
5817 }
5818 } else {
5819 // This is an anonymous type definition within another anonymous type.
5820 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5821 // not part of standard C++.
5822 Diag(Loc: MemRecord->getLocation(),
5823 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5824 << Record->isUnion();
5825 }
5826 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5827 // Any access specifier is fine.
5828 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5829 // In C++1z, static_assert declarations are also fine.
5830 } else {
5831 // We have something that isn't a non-static data
5832 // member. Complain about it.
5833 unsigned DK = diag::err_anonymous_record_bad_member;
5834 if (isa<TypeDecl>(Val: Mem))
5835 DK = diag::err_anonymous_record_with_type;
5836 else if (isa<FunctionDecl>(Val: Mem))
5837 DK = diag::err_anonymous_record_with_function;
5838 else if (isa<VarDecl>(Val: Mem))
5839 DK = diag::err_anonymous_record_with_static;
5840
5841 // Visual C++ allows type definition in anonymous struct or union.
5842 if (getLangOpts().MicrosoftExt &&
5843 DK == diag::err_anonymous_record_with_type)
5844 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5845 << Record->isUnion();
5846 else {
5847 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5848 Invalid = true;
5849 }
5850 }
5851 }
5852
5853 // C++11 [class.union]p8 (DR1460):
5854 // At most one variant member of a union may have a
5855 // brace-or-equal-initializer.
5856 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5857 Owner->isRecord())
5858 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5859 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5860 }
5861
5862 if (!Record->isUnion() && !Owner->isRecord()) {
5863 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5864 << getLangOpts().CPlusPlus;
5865 Invalid = true;
5866 }
5867
5868 // C++ [dcl.dcl]p3:
5869 // [If there are no declarators], and except for the declaration of an
5870 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5871 // names into the program
5872 // C++ [class.mem]p2:
5873 // each such member-declaration shall either declare at least one member
5874 // name of the class or declare at least one unnamed bit-field
5875 //
5876 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5877 if (getLangOpts().CPlusPlus && Record->field_empty())
5878 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5879
5880 // Mock up a declarator.
5881 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5882 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5883 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5884 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5885
5886 // Create a declaration for this anonymous struct/union.
5887 NamedDecl *Anon = nullptr;
5888 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5889 Anon = FieldDecl::Create(
5890 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5891 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5892 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5893 /*InitStyle=*/ICIS_NoInit);
5894 Anon->setAccess(AS);
5895 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5896
5897 if (getLangOpts().CPlusPlus)
5898 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5899 } else {
5900 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5901 if (SCSpec == DeclSpec::SCS_mutable) {
5902 // mutable can only appear on non-static class members, so it's always
5903 // an error here
5904 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5905 Invalid = true;
5906 SC = SC_None;
5907 }
5908
5909 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5910 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5911 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5912 if (Invalid)
5913 Anon->setInvalidDecl();
5914
5915 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5916
5917 // Default-initialize the implicit variable. This initialization will be
5918 // trivial in almost all cases, except if a union member has an in-class
5919 // initializer:
5920 // union { int n = 0; };
5921 ActOnUninitializedDecl(dcl: Anon);
5922 }
5923 Anon->setImplicit();
5924
5925 // Mark this as an anonymous struct/union type.
5926 Record->setAnonymousStructOrUnion(true);
5927
5928 // Add the anonymous struct/union object to the current
5929 // context. We'll be referencing this object when we refer to one of
5930 // its members.
5931 Owner->addDecl(D: Anon);
5932
5933 // Inject the members of the anonymous struct/union into the owning
5934 // context and into the identifier resolver chain for name lookup
5935 // purposes.
5936 SmallVector<NamedDecl*, 2> Chain;
5937 Chain.push_back(Elt: Anon);
5938
5939 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5940 Chaining&: Chain))
5941 Invalid = true;
5942
5943 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5944 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5945 MangleNumberingContext *MCtx;
5946 Decl *ManglingContextDecl;
5947 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5948 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5949 if (MCtx) {
5950 Context.setManglingNumber(
5951 ND: NewVD, Number: MCtx->getManglingNumber(
5952 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5953 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5954 }
5955 }
5956 }
5957
5958 if (Invalid)
5959 Anon->setInvalidDecl();
5960
5961 return Anon;
5962}
5963
5964Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5965 RecordDecl *Record) {
5966 assert(Record && "expected a record!");
5967
5968 // Mock up a declarator.
5969 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5970 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5971 assert(TInfo && "couldn't build declarator info for anonymous struct");
5972
5973 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5974 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
5975
5976 // Create a declaration for this anonymous struct.
5977 NamedDecl *Anon =
5978 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
5979 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
5980 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5981 /*InitStyle=*/ICIS_NoInit);
5982 Anon->setImplicit();
5983
5984 // Add the anonymous struct object to the current context.
5985 CurContext->addDecl(D: Anon);
5986
5987 // Inject the members of the anonymous struct into the current
5988 // context and into the identifier resolver chain for name lookup
5989 // purposes.
5990 SmallVector<NamedDecl*, 2> Chain;
5991 Chain.push_back(Elt: Anon);
5992
5993 RecordDecl *RecordDef = Record->getDefinition();
5994 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
5995 DiagID: diag::err_field_incomplete_or_sizeless) ||
5996 InjectAnonymousStructOrUnionMembers(
5997 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
5998 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
5999 Anon->setInvalidDecl();
6000 ParentDecl->setInvalidDecl();
6001 }
6002
6003 return Anon;
6004}
6005
6006DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6007 return GetNameFromUnqualifiedId(Name: D.getName());
6008}
6009
6010DeclarationNameInfo
6011Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6012 DeclarationNameInfo NameInfo;
6013 NameInfo.setLoc(Name.StartLocation);
6014
6015 switch (Name.getKind()) {
6016
6017 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6018 case UnqualifiedIdKind::IK_Identifier:
6019 NameInfo.setName(Name.Identifier);
6020 return NameInfo;
6021
6022 case UnqualifiedIdKind::IK_DeductionGuideName: {
6023 // C++ [temp.deduct.guide]p3:
6024 // The simple-template-id shall name a class template specialization.
6025 // The template-name shall be the same identifier as the template-name
6026 // of the simple-template-id.
6027 // These together intend to imply that the template-name shall name a
6028 // class template.
6029 // FIXME: template<typename T> struct X {};
6030 // template<typename T> using Y = X<T>;
6031 // Y(int) -> Y<int>;
6032 // satisfies these rules but does not name a class template.
6033 TemplateName TN = Name.TemplateName.get().get();
6034 auto *Template = TN.getAsTemplateDecl();
6035 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6036 Diag(Loc: Name.StartLocation,
6037 DiagID: diag::err_deduction_guide_name_not_class_template)
6038 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6039 if (Template)
6040 NoteTemplateLocation(Decl: *Template);
6041 return DeclarationNameInfo();
6042 }
6043
6044 NameInfo.setName(
6045 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6046 return NameInfo;
6047 }
6048
6049 case UnqualifiedIdKind::IK_OperatorFunctionId:
6050 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6051 Op: Name.OperatorFunctionId.Operator));
6052 NameInfo.setCXXOperatorNameRange(SourceRange(
6053 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6054 return NameInfo;
6055
6056 case UnqualifiedIdKind::IK_LiteralOperatorId:
6057 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6058 II: Name.Identifier));
6059 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6060 return NameInfo;
6061
6062 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6063 TypeSourceInfo *TInfo;
6064 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6065 if (Ty.isNull())
6066 return DeclarationNameInfo();
6067 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6068 Ty: Context.getCanonicalType(T: Ty)));
6069 NameInfo.setNamedTypeInfo(TInfo);
6070 return NameInfo;
6071 }
6072
6073 case UnqualifiedIdKind::IK_ConstructorName: {
6074 TypeSourceInfo *TInfo;
6075 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6076 if (Ty.isNull())
6077 return DeclarationNameInfo();
6078 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6079 Ty: Context.getCanonicalType(T: Ty)));
6080 NameInfo.setNamedTypeInfo(TInfo);
6081 return NameInfo;
6082 }
6083
6084 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6085 // In well-formed code, we can only have a constructor
6086 // template-id that refers to the current context, so go there
6087 // to find the actual type being constructed.
6088 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6089 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6090 return DeclarationNameInfo();
6091
6092 // Determine the type of the class being constructed.
6093 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6094
6095 // FIXME: Check two things: that the template-id names the same type as
6096 // CurClassType, and that the template-id does not occur when the name
6097 // was qualified.
6098
6099 NameInfo.setName(
6100 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6101 // FIXME: should we retrieve TypeSourceInfo?
6102 NameInfo.setNamedTypeInfo(nullptr);
6103 return NameInfo;
6104 }
6105
6106 case UnqualifiedIdKind::IK_DestructorName: {
6107 TypeSourceInfo *TInfo;
6108 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6109 if (Ty.isNull())
6110 return DeclarationNameInfo();
6111 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6112 Ty: Context.getCanonicalType(T: Ty)));
6113 NameInfo.setNamedTypeInfo(TInfo);
6114 return NameInfo;
6115 }
6116
6117 case UnqualifiedIdKind::IK_TemplateId: {
6118 TemplateName TName = Name.TemplateId->Template.get();
6119 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6120 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6121 }
6122
6123 } // switch (Name.getKind())
6124
6125 llvm_unreachable("Unknown name kind");
6126}
6127
6128static QualType getCoreType(QualType Ty) {
6129 do {
6130 if (Ty->isPointerOrReferenceType())
6131 Ty = Ty->getPointeeType();
6132 else if (Ty->isArrayType())
6133 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6134 else
6135 return Ty.withoutLocalFastQualifiers();
6136 } while (true);
6137}
6138
6139/// hasSimilarParameters - Determine whether the C++ functions Declaration
6140/// and Definition have "nearly" matching parameters. This heuristic is
6141/// used to improve diagnostics in the case where an out-of-line function
6142/// definition doesn't match any declaration within the class or namespace.
6143/// Also sets Params to the list of indices to the parameters that differ
6144/// between the declaration and the definition. If hasSimilarParameters
6145/// returns true and Params is empty, then all of the parameters match.
6146static bool hasSimilarParameters(ASTContext &Context,
6147 FunctionDecl *Declaration,
6148 FunctionDecl *Definition,
6149 SmallVectorImpl<unsigned> &Params) {
6150 Params.clear();
6151 if (Declaration->param_size() != Definition->param_size())
6152 return false;
6153 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6154 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6155 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6156
6157 // The parameter types are identical
6158 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6159 continue;
6160
6161 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6162 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6163 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6164 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6165
6166 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6167 (DeclTyName && DeclTyName == DefTyName))
6168 Params.push_back(Elt: Idx);
6169 else // The two parameters aren't even close
6170 return false;
6171 }
6172
6173 return true;
6174}
6175
6176/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6177/// declarator needs to be rebuilt in the current instantiation.
6178/// Any bits of declarator which appear before the name are valid for
6179/// consideration here. That's specifically the type in the decl spec
6180/// and the base type in any member-pointer chunks.
6181static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6182 DeclarationName Name) {
6183 // The types we specifically need to rebuild are:
6184 // - typenames, typeofs, and decltypes
6185 // - types which will become injected class names
6186 // Of course, we also need to rebuild any type referencing such a
6187 // type. It's safest to just say "dependent", but we call out a
6188 // few cases here.
6189
6190 DeclSpec &DS = D.getMutableDeclSpec();
6191 switch (DS.getTypeSpecType()) {
6192 case DeclSpec::TST_typename:
6193 case DeclSpec::TST_typeofType:
6194 case DeclSpec::TST_typeof_unqualType:
6195#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6196#include "clang/Basic/TransformTypeTraits.def"
6197 case DeclSpec::TST_atomic: {
6198 // Grab the type from the parser.
6199 TypeSourceInfo *TSI = nullptr;
6200 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6201 if (T.isNull() || !T->isInstantiationDependentType()) break;
6202
6203 // Make sure there's a type source info. This isn't really much
6204 // of a waste; most dependent types should have type source info
6205 // attached already.
6206 if (!TSI)
6207 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6208
6209 // Rebuild the type in the current instantiation.
6210 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6211 if (!TSI) return true;
6212
6213 // Store the new type back in the decl spec.
6214 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6215 DS.UpdateTypeRep(Rep: LocType);
6216 break;
6217 }
6218
6219 case DeclSpec::TST_decltype:
6220 case DeclSpec::TST_typeof_unqualExpr:
6221 case DeclSpec::TST_typeofExpr: {
6222 Expr *E = DS.getRepAsExpr();
6223 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6224 if (Result.isInvalid()) return true;
6225 DS.UpdateExprRep(Rep: Result.get());
6226 break;
6227 }
6228
6229 default:
6230 // Nothing to do for these decl specs.
6231 break;
6232 }
6233
6234 // It doesn't matter what order we do this in.
6235 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6236 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6237
6238 // The only type information in the declarator which can come
6239 // before the declaration name is the base type of a member
6240 // pointer.
6241 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6242 continue;
6243
6244 // Rebuild the scope specifier in-place.
6245 CXXScopeSpec &SS = Chunk.Mem.Scope();
6246 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6247 return true;
6248 }
6249
6250 return false;
6251}
6252
6253/// Returns true if the declaration is declared in a system header or from a
6254/// system macro.
6255static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6256 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6257 SM.isInSystemMacro(loc: D->getLocation());
6258}
6259
6260void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6261 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6262 // of system decl.
6263 if (D->getPreviousDecl() || D->isImplicit())
6264 return;
6265 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6266 if (Status != ReservedIdentifierStatus::NotReserved &&
6267 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6268 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6269 << D << static_cast<int>(Status);
6270 }
6271}
6272
6273Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6274 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6275
6276 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6277 // declaration only if the `bind_to_declaration` extension is set.
6278 SmallVector<FunctionDecl *, 4> Bases;
6279 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6280 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6281 TP: llvm::omp::TraitProperty::
6282 implementation_extension_bind_to_declaration))
6283 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6284 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6285
6286 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6287
6288 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6289 Dcl && Dcl->getDeclContext()->isFileContext())
6290 Dcl->setTopLevelDeclInObjCContainer();
6291
6292 if (!Bases.empty())
6293 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6294 Bases);
6295
6296 return Dcl;
6297}
6298
6299bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6300 DeclarationNameInfo NameInfo) {
6301 DeclarationName Name = NameInfo.getName();
6302
6303 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6304 while (Record && Record->isAnonymousStructOrUnion())
6305 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6306 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6307 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6308 return true;
6309 }
6310
6311 return false;
6312}
6313
6314bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6315 DeclarationName Name,
6316 SourceLocation Loc,
6317 TemplateIdAnnotation *TemplateId,
6318 bool IsMemberSpecialization) {
6319 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6320 "without nested-name-specifier");
6321 DeclContext *Cur = CurContext;
6322 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6323 Cur = Cur->getParent();
6324
6325 // If the user provided a superfluous scope specifier that refers back to the
6326 // class in which the entity is already declared, diagnose and ignore it.
6327 //
6328 // class X {
6329 // void X::f();
6330 // };
6331 //
6332 // Note, it was once ill-formed to give redundant qualification in all
6333 // contexts, but that rule was removed by DR482.
6334 if (Cur->Equals(DC)) {
6335 if (Cur->isRecord()) {
6336 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6337 : diag::err_member_extra_qualification)
6338 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6339 SS.clear();
6340 } else {
6341 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6342 }
6343 return false;
6344 }
6345
6346 // Check whether the qualifying scope encloses the scope of the original
6347 // declaration. For a template-id, we perform the checks in
6348 // CheckTemplateSpecializationScope.
6349 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6350 if (Cur->isRecord())
6351 Diag(Loc, DiagID: diag::err_member_qualification)
6352 << Name << SS.getRange();
6353 else if (isa<TranslationUnitDecl>(Val: DC))
6354 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6355 << Name << SS.getRange();
6356 else if (isa<FunctionDecl>(Val: Cur))
6357 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6358 << Name << SS.getRange();
6359 else if (isa<BlockDecl>(Val: Cur))
6360 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6361 << Name << SS.getRange();
6362 else if (isa<ExportDecl>(Val: Cur)) {
6363 if (!isa<NamespaceDecl>(Val: DC))
6364 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6365 << Name << SS.getRange();
6366 else
6367 // The cases that DC is not NamespaceDecl should be handled in
6368 // CheckRedeclarationExported.
6369 return false;
6370 } else
6371 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6372 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6373
6374 return true;
6375 }
6376
6377 if (Cur->isRecord()) {
6378 // Cannot qualify members within a class.
6379 Diag(Loc, DiagID: diag::err_member_qualification)
6380 << Name << SS.getRange();
6381 SS.clear();
6382
6383 // C++ constructors and destructors with incorrect scopes can break
6384 // our AST invariants by having the wrong underlying types. If
6385 // that's the case, then drop this declaration entirely.
6386 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6387 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6388 !Context.hasSameType(
6389 T1: Name.getCXXNameType(),
6390 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6391 return true;
6392
6393 return false;
6394 }
6395
6396 // C++23 [temp.names]p5:
6397 // The keyword template shall not appear immediately after a declarative
6398 // nested-name-specifier.
6399 //
6400 // First check the template-id (if any), and then check each component of the
6401 // nested-name-specifier in reverse order.
6402 //
6403 // FIXME: nested-name-specifiers in friend declarations are declarative,
6404 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6405 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6406 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6407 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6408
6409 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6410 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6411 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6412 SourceLocation TemplateKeywordLoc;
6413 switch (TL.getTypeLocClass()) {
6414 case TypeLoc::TemplateSpecialization: {
6415 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6416 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6417 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6418 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6419 << TST.getLocalSourceRange();
6420 break;
6421 }
6422 case TypeLoc::Decltype:
6423 case TypeLoc::PackIndexing: {
6424 const Type *T = TL.getTypePtr();
6425 // C++23 [expr.prim.id.qual]p2:
6426 // [...] A declarative nested-name-specifier shall not have a
6427 // computed-type-specifier.
6428 //
6429 // CWG2858 changed this from 'decltype-specifier' to
6430 // 'computed-type-specifier'.
6431 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6432 << T->isDecltypeType() << TL.getSourceRange();
6433 break;
6434 }
6435 case TypeLoc::DependentName:
6436 NextTL =
6437 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6438 break;
6439 default:
6440 break;
6441 }
6442 if (TemplateKeywordLoc.isValid())
6443 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6444 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6445 }
6446
6447 return false;
6448}
6449
6450NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6451 MultiTemplateParamsArg TemplateParamLists) {
6452 // TODO: consider using NameInfo for diagnostic.
6453 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6454 DeclarationName Name = NameInfo.getName();
6455
6456 // All of these full declarators require an identifier. If it doesn't have
6457 // one, the ParsedFreeStandingDeclSpec action should be used.
6458 if (D.isDecompositionDeclarator()) {
6459 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6460 } else if (!Name) {
6461 if (!D.isInvalidType()) // Reject this if we think it is valid.
6462 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6463 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6464 return nullptr;
6465 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6466 return nullptr;
6467
6468 DeclContext *DC = CurContext;
6469 if (D.getCXXScopeSpec().isInvalid())
6470 D.setInvalidType();
6471 else if (D.getCXXScopeSpec().isSet()) {
6472 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6473 UPPC: UPPC_DeclarationQualifier))
6474 return nullptr;
6475
6476 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6477 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6478 if (!DC || isa<EnumDecl>(Val: DC)) {
6479 // If we could not compute the declaration context, it's because the
6480 // declaration context is dependent but does not refer to a class,
6481 // class template, or class template partial specialization. Complain
6482 // and return early, to avoid the coming semantic disaster.
6483 Diag(Loc: D.getIdentifierLoc(),
6484 DiagID: diag::err_template_qualified_declarator_no_match)
6485 << D.getCXXScopeSpec().getScopeRep()
6486 << D.getCXXScopeSpec().getRange();
6487 return nullptr;
6488 }
6489 bool IsDependentContext = DC->isDependentContext();
6490
6491 if (!IsDependentContext &&
6492 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6493 return nullptr;
6494
6495 // If a class is incomplete, do not parse entities inside it.
6496 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6497 Diag(Loc: D.getIdentifierLoc(),
6498 DiagID: diag::err_member_def_undefined_record)
6499 << Name << DC << D.getCXXScopeSpec().getRange();
6500 return nullptr;
6501 }
6502 if (!D.getDeclSpec().isFriendSpecified()) {
6503 TemplateIdAnnotation *TemplateId =
6504 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6505 ? D.getName().TemplateId
6506 : nullptr;
6507 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6508 Loc: D.getIdentifierLoc(), TemplateId,
6509 /*IsMemberSpecialization=*/false)) {
6510 if (DC->isRecord())
6511 return nullptr;
6512
6513 D.setInvalidType();
6514 }
6515 }
6516
6517 // Check whether we need to rebuild the type of the given
6518 // declaration in the current instantiation.
6519 if (EnteringContext && IsDependentContext &&
6520 TemplateParamLists.size() != 0) {
6521 ContextRAII SavedContext(*this, DC);
6522 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6523 D.setInvalidType();
6524 }
6525 }
6526
6527 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6528 QualType R = TInfo->getType();
6529
6530 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6531 UPPC: UPPC_DeclarationType))
6532 D.setInvalidType();
6533
6534 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6535 forRedeclarationInCurContext());
6536
6537 // See if this is a redefinition of a variable in the same scope.
6538 if (!D.getCXXScopeSpec().isSet()) {
6539 bool IsLinkageLookup = false;
6540 bool CreateBuiltins = false;
6541
6542 // If the declaration we're planning to build will be a function
6543 // or object with linkage, then look for another declaration with
6544 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6545 //
6546 // If the declaration we're planning to build will be declared with
6547 // external linkage in the translation unit, create any builtin with
6548 // the same name.
6549 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6550 /* Do nothing*/;
6551 else if (CurContext->isFunctionOrMethod() &&
6552 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6553 R->isFunctionType())) {
6554 IsLinkageLookup = true;
6555 CreateBuiltins =
6556 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6557 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6558 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6559 CreateBuiltins = true;
6560
6561 if (IsLinkageLookup) {
6562 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6563 Previous.setRedeclarationKind(
6564 RedeclarationKind::ForExternalRedeclaration);
6565 }
6566
6567 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6568 } else { // Something like "int foo::x;"
6569 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6570
6571 // C++ [dcl.meaning]p1:
6572 // When the declarator-id is qualified, the declaration shall refer to a
6573 // previously declared member of the class or namespace to which the
6574 // qualifier refers (or, in the case of a namespace, of an element of the
6575 // inline namespace set of that namespace (7.3.1)) or to a specialization
6576 // thereof; [...]
6577 //
6578 // Note that we already checked the context above, and that we do not have
6579 // enough information to make sure that Previous contains the declaration
6580 // we want to match. For example, given:
6581 //
6582 // class X {
6583 // void f();
6584 // void f(float);
6585 // };
6586 //
6587 // void X::f(int) { } // ill-formed
6588 //
6589 // In this case, Previous will point to the overload set
6590 // containing the two f's declared in X, but neither of them
6591 // matches.
6592
6593 RemoveUsingDecls(R&: Previous);
6594 }
6595
6596 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6597 TPD && TPD->isTemplateParameter()) {
6598 // Older versions of clang allowed the names of function/variable templates
6599 // to shadow the names of their template parameters. For the compatibility
6600 // purposes we detect such cases and issue a default-to-error warning that
6601 // can be disabled with -Wno-strict-primary-template-shadow.
6602 if (!D.isInvalidType()) {
6603 bool AllowForCompatibility = false;
6604 if (Scope *DeclParent = S->getDeclParent();
6605 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6606 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6607 TemplateParamParent->isDeclScope(D: TPD);
6608 }
6609 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6610 SupportedForCompatibility: AllowForCompatibility);
6611 }
6612
6613 // Just pretend that we didn't see the previous declaration.
6614 Previous.clear();
6615 }
6616
6617 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6618 // Forget that the previous declaration is the injected-class-name.
6619 Previous.clear();
6620
6621 // In C++, the previous declaration we find might be a tag type
6622 // (class or enum). In this case, the new declaration will hide the
6623 // tag type. Note that this applies to functions, function templates, and
6624 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6625 if (Previous.isSingleTagDecl() &&
6626 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6627 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6628 Previous.clear();
6629
6630 // Check that there are no default arguments other than in the parameters
6631 // of a function declaration (C++ only).
6632 if (getLangOpts().CPlusPlus)
6633 CheckExtraCXXDefaultArguments(D);
6634
6635 /// Get the innermost enclosing declaration scope.
6636 S = S->getDeclParent();
6637
6638 NamedDecl *New;
6639
6640 bool AddToScope = true;
6641 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6642 if (TemplateParamLists.size()) {
6643 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6644 return nullptr;
6645 }
6646
6647 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6648 } else if (R->isFunctionType()) {
6649 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6650 TemplateParamLists,
6651 AddToScope);
6652 } else {
6653 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6654 AddToScope);
6655 }
6656
6657 if (!New)
6658 return nullptr;
6659
6660 warnOnCTypeHiddenInCPlusPlus(D: New);
6661
6662 // If this has an identifier and is not a function template specialization,
6663 // add it to the scope stack.
6664 if (New->getDeclName() && AddToScope)
6665 PushOnScopeChains(D: New, S);
6666
6667 if (OpenMP().isInOpenMPDeclareTargetContext())
6668 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6669
6670 return New;
6671}
6672
6673/// Helper method to turn variable array types into constant array
6674/// types in certain situations which would otherwise be errors (for
6675/// GCC compatibility).
6676static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6677 ASTContext &Context,
6678 bool &SizeIsNegative,
6679 llvm::APSInt &Oversized) {
6680 // This method tries to turn a variable array into a constant
6681 // array even when the size isn't an ICE. This is necessary
6682 // for compatibility with code that depends on gcc's buggy
6683 // constant expression folding, like struct {char x[(int)(char*)2];}
6684 SizeIsNegative = false;
6685 Oversized = 0;
6686
6687 if (T->isDependentType())
6688 return QualType();
6689
6690 QualifierCollector Qs;
6691 const Type *Ty = Qs.strip(type: T);
6692
6693 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6694 QualType Pointee = PTy->getPointeeType();
6695 QualType FixedType =
6696 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6697 Oversized);
6698 if (FixedType.isNull()) return FixedType;
6699 FixedType = Context.getPointerType(T: FixedType);
6700 return Qs.apply(Context, QT: FixedType);
6701 }
6702 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6703 QualType Inner = PTy->getInnerType();
6704 QualType FixedType =
6705 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6706 Oversized);
6707 if (FixedType.isNull()) return FixedType;
6708 FixedType = Context.getParenType(NamedType: FixedType);
6709 return Qs.apply(Context, QT: FixedType);
6710 }
6711
6712 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6713 if (!VLATy)
6714 return QualType();
6715
6716 QualType ElemTy = VLATy->getElementType();
6717 if (ElemTy->isVariablyModifiedType()) {
6718 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6719 SizeIsNegative, Oversized);
6720 if (ElemTy.isNull())
6721 return QualType();
6722 }
6723
6724 Expr::EvalResult Result;
6725 if (!VLATy->getSizeExpr() ||
6726 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6727 return QualType();
6728
6729 llvm::APSInt Res = Result.Val.getInt();
6730
6731 // Check whether the array size is negative.
6732 if (Res.isSigned() && Res.isNegative()) {
6733 SizeIsNegative = true;
6734 return QualType();
6735 }
6736
6737 // Check whether the array is too large to be addressed.
6738 unsigned ActiveSizeBits =
6739 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6740 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6741 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6742 : Res.getActiveBits();
6743 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6744 Oversized = std::move(Res);
6745 return QualType();
6746 }
6747
6748 QualType FoldedArrayType = Context.getConstantArrayType(
6749 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6750 return Qs.apply(Context, QT: FoldedArrayType);
6751}
6752
6753static void
6754FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6755 SrcTL = SrcTL.getUnqualifiedLoc();
6756 DstTL = DstTL.getUnqualifiedLoc();
6757 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6758 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6759 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6760 DstTL: DstPTL.getPointeeLoc());
6761 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6762 return;
6763 }
6764 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6765 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6766 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6767 DstTL: DstPTL.getInnerLoc());
6768 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6769 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6770 return;
6771 }
6772 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6773 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6774 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6775 TypeLoc DstElemTL = DstATL.getElementLoc();
6776 if (VariableArrayTypeLoc SrcElemATL =
6777 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6778 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6779 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6780 } else {
6781 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6782 }
6783 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6784 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6785 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6786}
6787
6788/// Helper method to turn variable array types into constant array
6789/// types in certain situations which would otherwise be errors (for
6790/// GCC compatibility).
6791static TypeSourceInfo*
6792TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6793 ASTContext &Context,
6794 bool &SizeIsNegative,
6795 llvm::APSInt &Oversized) {
6796 QualType FixedTy
6797 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6798 SizeIsNegative, Oversized);
6799 if (FixedTy.isNull())
6800 return nullptr;
6801 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6802 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6803 DstTL: FixedTInfo->getTypeLoc());
6804 return FixedTInfo;
6805}
6806
6807bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6808 QualType &T, SourceLocation Loc,
6809 unsigned FailedFoldDiagID) {
6810 bool SizeIsNegative;
6811 llvm::APSInt Oversized;
6812 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6813 TInfo, Context, SizeIsNegative, Oversized);
6814 if (FixedTInfo) {
6815 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6816 TInfo = FixedTInfo;
6817 T = FixedTInfo->getType();
6818 return true;
6819 }
6820
6821 if (SizeIsNegative)
6822 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6823 else if (Oversized.getBoolValue())
6824 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6825 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6826 /*UpperCase=*/false, /*InsertSeparators=*/true);
6827 else if (FailedFoldDiagID)
6828 Diag(Loc, DiagID: FailedFoldDiagID);
6829 return false;
6830}
6831
6832void
6833Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6834 if (!getLangOpts().CPlusPlus &&
6835 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6836 // Don't need to track declarations in the TU in C.
6837 return;
6838
6839 // Note that we have a locally-scoped external with this name.
6840 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6841}
6842
6843NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6844 // FIXME: We can have multiple results via __attribute__((overloadable)).
6845 auto Result = Context.getExternCContextDecl()->lookup(Name);
6846 return Result.empty() ? nullptr : *Result.begin();
6847}
6848
6849void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6850 // FIXME: We should probably indicate the identifier in question to avoid
6851 // confusion for constructs like "virtual int a(), b;"
6852 if (DS.isVirtualSpecified())
6853 Diag(Loc: DS.getVirtualSpecLoc(),
6854 DiagID: diag::err_virtual_non_function);
6855
6856 if (DS.hasExplicitSpecifier())
6857 Diag(Loc: DS.getExplicitSpecLoc(),
6858 DiagID: diag::err_explicit_non_function);
6859
6860 if (DS.isNoreturnSpecified())
6861 Diag(Loc: DS.getNoreturnSpecLoc(),
6862 DiagID: diag::err_noreturn_non_function);
6863}
6864
6865NamedDecl*
6866Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6867 TypeSourceInfo *TInfo, LookupResult &Previous) {
6868 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6869 if (D.getCXXScopeSpec().isSet()) {
6870 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6871 << D.getCXXScopeSpec().getRange();
6872 D.setInvalidType();
6873 // Pretend we didn't see the scope specifier.
6874 DC = CurContext;
6875 Previous.clear();
6876 }
6877
6878 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6879
6880 if (D.getDeclSpec().isInlineSpecified())
6881 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6882 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6883 ? diag::warn_ms_inline_non_function
6884 : diag::err_inline_non_function)
6885 << getLangOpts().CPlusPlus17;
6886 if (D.getDeclSpec().hasConstexprSpecifier())
6887 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6888 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6889
6890 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6891 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6892 Diag(Loc: D.getName().StartLocation,
6893 DiagID: diag::err_deduction_guide_invalid_specifier)
6894 << "typedef";
6895 else
6896 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6897 << D.getName().getSourceRange();
6898 return nullptr;
6899 }
6900
6901 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6902 if (!NewTD) return nullptr;
6903
6904 // Handle attributes prior to checking for duplicates in MergeVarDecl
6905 ProcessDeclAttributes(S, D: NewTD, PD: D);
6906
6907 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6908
6909 bool Redeclaration = D.isRedeclaration();
6910 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6911 D.setRedeclaration(Redeclaration);
6912 return ND;
6913}
6914
6915void
6916Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6917 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6918 // then it shall have block scope.
6919 // Note that variably modified types must be fixed before merging the decl so
6920 // that redeclarations will match.
6921 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6922 QualType T = TInfo->getType();
6923 if (T->isVariablyModifiedType()) {
6924 setFunctionHasBranchProtectedScope();
6925
6926 if (S->getFnParent() == nullptr) {
6927 bool SizeIsNegative;
6928 llvm::APSInt Oversized;
6929 TypeSourceInfo *FixedTInfo =
6930 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6931 SizeIsNegative,
6932 Oversized);
6933 if (FixedTInfo) {
6934 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6935 NewTD->setTypeSourceInfo(FixedTInfo);
6936 } else {
6937 if (SizeIsNegative)
6938 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6939 else if (T->isVariableArrayType())
6940 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6941 else if (Oversized.getBoolValue())
6942 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6943 << toString(I: Oversized, Radix: 10);
6944 else
6945 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6946 NewTD->setInvalidDecl();
6947 }
6948 }
6949 }
6950}
6951
6952NamedDecl*
6953Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6954 LookupResult &Previous, bool &Redeclaration) {
6955
6956 // Find the shadowed declaration before filtering for scope.
6957 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6958
6959 // Merge the decl with the existing one if appropriate. If the decl is
6960 // in an outer scope, it isn't the same thing.
6961 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6962 /*AllowInlineNamespace*/false);
6963 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6964 if (!Previous.empty()) {
6965 Redeclaration = true;
6966 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6967 } else {
6968 inferGslPointerAttribute(TD: NewTD);
6969 }
6970
6971 if (ShadowedDecl && !Redeclaration)
6972 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
6973
6974 // If this is the C FILE type, notify the AST context.
6975 if (IdentifierInfo *II = NewTD->getIdentifier())
6976 if (!NewTD->isInvalidDecl() &&
6977 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6978 switch (II->getNotableIdentifierID()) {
6979 case tok::NotableIdentifierKind::FILE:
6980 Context.setFILEDecl(NewTD);
6981 break;
6982 case tok::NotableIdentifierKind::jmp_buf:
6983 Context.setjmp_bufDecl(NewTD);
6984 break;
6985 case tok::NotableIdentifierKind::sigjmp_buf:
6986 Context.setsigjmp_bufDecl(NewTD);
6987 break;
6988 case tok::NotableIdentifierKind::ucontext_t:
6989 Context.setucontext_tDecl(NewTD);
6990 break;
6991 case tok::NotableIdentifierKind::float_t:
6992 case tok::NotableIdentifierKind::double_t:
6993 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
6994 break;
6995 default:
6996 break;
6997 }
6998 }
6999
7000 return NewTD;
7001}
7002
7003/// Determines whether the given declaration is an out-of-scope
7004/// previous declaration.
7005///
7006/// This routine should be invoked when name lookup has found a
7007/// previous declaration (PrevDecl) that is not in the scope where a
7008/// new declaration by the same name is being introduced. If the new
7009/// declaration occurs in a local scope, previous declarations with
7010/// linkage may still be considered previous declarations (C99
7011/// 6.2.2p4-5, C++ [basic.link]p6).
7012///
7013/// \param PrevDecl the previous declaration found by name
7014/// lookup
7015///
7016/// \param DC the context in which the new declaration is being
7017/// declared.
7018///
7019/// \returns true if PrevDecl is an out-of-scope previous declaration
7020/// for a new delcaration with the same name.
7021static bool
7022isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7023 ASTContext &Context) {
7024 if (!PrevDecl)
7025 return false;
7026
7027 if (!PrevDecl->hasLinkage())
7028 return false;
7029
7030 if (Context.getLangOpts().CPlusPlus) {
7031 // C++ [basic.link]p6:
7032 // If there is a visible declaration of an entity with linkage
7033 // having the same name and type, ignoring entities declared
7034 // outside the innermost enclosing namespace scope, the block
7035 // scope declaration declares that same entity and receives the
7036 // linkage of the previous declaration.
7037 DeclContext *OuterContext = DC->getRedeclContext();
7038 if (!OuterContext->isFunctionOrMethod())
7039 // This rule only applies to block-scope declarations.
7040 return false;
7041
7042 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7043 if (PrevOuterContext->isRecord())
7044 // We found a member function: ignore it.
7045 return false;
7046
7047 // Find the innermost enclosing namespace for the new and
7048 // previous declarations.
7049 OuterContext = OuterContext->getEnclosingNamespaceContext();
7050 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7051
7052 // The previous declaration is in a different namespace, so it
7053 // isn't the same function.
7054 if (!OuterContext->Equals(DC: PrevOuterContext))
7055 return false;
7056 }
7057
7058 return true;
7059}
7060
7061static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7062 CXXScopeSpec &SS = D.getCXXScopeSpec();
7063 if (!SS.isSet()) return;
7064 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7065}
7066
7067void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7068 QualType Type = Var->getType();
7069 if (Type.hasAddressSpace())
7070 return;
7071 if (Type->isDependentType())
7072 return;
7073 if (Type->isSamplerT() || Type->isVoidType())
7074 return;
7075 LangAS ImplAS = LangAS::opencl_private;
7076 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7077 // __opencl_c_program_scope_global_variables feature, the address space
7078 // for a variable at program scope or a static or extern variable inside
7079 // a function are inferred to be __global.
7080 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7081 Var->hasGlobalStorage())
7082 ImplAS = LangAS::opencl_global;
7083 // If the original type from a decayed type is an array type and that array
7084 // type has no address space yet, deduce it now.
7085 if (auto DT = dyn_cast<DecayedType>(Val&: Type)) {
7086 auto OrigTy = DT->getOriginalType();
7087 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7088 // Add the address space to the original array type and then propagate
7089 // that to the element type through `getAsArrayType`.
7090 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
7091 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
7092 // Re-generate the decayed type.
7093 Type = Context.getDecayedType(T: OrigTy);
7094 }
7095 }
7096 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
7097 // Apply any qualifiers (including address space) from the array type to
7098 // the element type. This implements C99 6.7.3p8: "If the specification of
7099 // an array type includes any type qualifiers, the element type is so
7100 // qualified, not the array type."
7101 if (Type->isArrayType())
7102 Type = QualType(Context.getAsArrayType(T: Type), 0);
7103 Var->setType(Type);
7104}
7105
7106static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7107 // 'weak' only applies to declarations with external linkage.
7108 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7109 if (!ND.isExternallyVisible()) {
7110 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7111 ND.dropAttr<WeakAttr>();
7112 }
7113 }
7114}
7115
7116static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7117 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7118 if (ND.isExternallyVisible()) {
7119 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7120 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7121 }
7122 }
7123}
7124
7125static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7126 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7127 if (VD->hasInit()) {
7128 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7129 assert(VD->isThisDeclarationADefinition() &&
7130 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7131 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7132 VD->dropAttr<AliasAttr>();
7133 }
7134 }
7135 }
7136}
7137
7138static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7139 // 'selectany' only applies to externally visible variable declarations.
7140 // It does not apply to functions.
7141 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7142 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7143 S.Diag(Loc: Attr->getLocation(),
7144 DiagID: diag::err_attribute_selectany_non_extern_data);
7145 ND.dropAttr<SelectAnyAttr>();
7146 }
7147 }
7148}
7149
7150static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7151 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7152 if (!ND.isExternallyVisible())
7153 S.Diag(Loc: Attr->getLocation(),
7154 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7155 }
7156}
7157
7158static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7159 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7160 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7161 bool IsAnonymousNS = false;
7162 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7163 if (VD) {
7164 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7165 while (NS && !IsAnonymousNS) {
7166 IsAnonymousNS = NS->isAnonymousNamespace();
7167 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7168 }
7169 }
7170 // dll attributes require external linkage. Static locals may have external
7171 // linkage but still cannot be explicitly imported or exported.
7172 // In Microsoft mode, a variable defined in anonymous namespace must have
7173 // external linkage in order to be exported.
7174 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7175 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7176 (!AnonNSInMicrosoftMode &&
7177 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7178 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7179 << &ND << Attr;
7180 ND.setInvalidDecl();
7181 }
7182 }
7183}
7184
7185static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7186 // Check the attributes on the function type and function params, if any.
7187 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7188 FD = FD->getMostRecentDecl();
7189 // Don't declare this variable in the second operand of the for-statement;
7190 // GCC miscompiles that by ending its lifetime before evaluating the
7191 // third operand. See gcc.gnu.org/PR86769.
7192 AttributedTypeLoc ATL;
7193 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7194 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7195 TL = ATL.getModifiedLoc()) {
7196 // The [[lifetimebound]] attribute can be applied to the implicit object
7197 // parameter of a non-static member function (other than a ctor or dtor)
7198 // by applying it to the function type.
7199 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7200 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7201 int NoImplicitObjectError = -1;
7202 if (!MD)
7203 NoImplicitObjectError = 0;
7204 else if (MD->isStatic())
7205 NoImplicitObjectError = 1;
7206 else if (MD->isExplicitObjectMemberFunction())
7207 NoImplicitObjectError = 2;
7208 if (NoImplicitObjectError != -1) {
7209 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7210 << NoImplicitObjectError << A->getRange();
7211 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7212 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7213 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7214 } else if (MD->getReturnType()->isVoidType()) {
7215 S.Diag(
7216 Loc: MD->getLocation(),
7217 DiagID: diag::
7218 err_lifetimebound_implicit_object_parameter_void_return_type);
7219 }
7220 }
7221 }
7222
7223 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7224 const ParmVarDecl *P = FD->getParamDecl(i: I);
7225
7226 // The [[lifetimebound]] attribute can be applied to a function parameter
7227 // only if the function returns a value.
7228 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7229 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7230 S.Diag(Loc: A->getLocation(),
7231 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7232 }
7233 }
7234 }
7235 }
7236}
7237
7238static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7239 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7240 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7241}
7242
7243static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7244 // Ensure that an auto decl is deduced otherwise the checks below might cache
7245 // the wrong linkage.
7246 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7247
7248 checkWeakAttr(S, ND);
7249 checkWeakRefAttr(S, ND);
7250 checkAliasAttr(S, ND);
7251 checkSelectAnyAttr(S, ND);
7252 checkHybridPatchableAttr(S, ND);
7253 checkInheritableAttr(S, ND);
7254 checkLifetimeBoundAttr(S, ND);
7255 checkModularFormatAttr(S, ND);
7256}
7257
7258static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7259 NamedDecl *NewDecl,
7260 bool IsSpecialization,
7261 bool IsDefinition) {
7262 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7263 return;
7264
7265 bool IsTemplate = false;
7266 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7267 OldDecl = OldTD->getTemplatedDecl();
7268 IsTemplate = true;
7269 if (!IsSpecialization)
7270 IsDefinition = false;
7271 }
7272 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7273 NewDecl = NewTD->getTemplatedDecl();
7274 IsTemplate = true;
7275 }
7276
7277 if (!OldDecl || !NewDecl)
7278 return;
7279
7280 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7281 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7282 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7283 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7284
7285 // dllimport and dllexport are inheritable attributes so we have to exclude
7286 // inherited attribute instances.
7287 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7288 (NewExportAttr && !NewExportAttr->isInherited());
7289
7290 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7291 // the only exception being explicit specializations.
7292 // Implicitly generated declarations are also excluded for now because there
7293 // is no other way to switch these to use dllimport or dllexport.
7294 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7295
7296 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7297 // Allow with a warning for free functions and global variables.
7298 bool JustWarn = false;
7299 if (!OldDecl->isCXXClassMember()) {
7300 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7301 if (VD && !VD->getDescribedVarTemplate())
7302 JustWarn = true;
7303 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7304 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7305 JustWarn = true;
7306 }
7307
7308 // We cannot change a declaration that's been used because IR has already
7309 // been emitted. Dllimported functions will still work though (modulo
7310 // address equality) as they can use the thunk.
7311 if (OldDecl->isUsed())
7312 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7313 JustWarn = false;
7314
7315 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7316 : diag::err_attribute_dll_redeclaration;
7317 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7318 << NewDecl
7319 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7320 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7321 if (!JustWarn) {
7322 NewDecl->setInvalidDecl();
7323 return;
7324 }
7325 }
7326
7327 // A redeclaration is not allowed to drop a dllimport attribute, the only
7328 // exceptions being inline function definitions (except for function
7329 // templates), local extern declarations, qualified friend declarations or
7330 // special MSVC extension: in the last case, the declaration is treated as if
7331 // it were marked dllexport.
7332 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7333 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7334 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7335 // Ignore static data because out-of-line definitions are diagnosed
7336 // separately.
7337 IsStaticDataMember = VD->isStaticDataMember();
7338 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7339 VarDecl::DeclarationOnly;
7340 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7341 IsInline = FD->isInlined();
7342 IsQualifiedFriend = FD->getQualifier() &&
7343 FD->getFriendObjectKind() == Decl::FOK_Declared;
7344 }
7345
7346 if (OldImportAttr && !HasNewAttr &&
7347 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7348 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7349 if (IsMicrosoftABI && IsDefinition) {
7350 if (IsSpecialization) {
7351 S.Diag(
7352 Loc: NewDecl->getLocation(),
7353 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7354 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7355 NewDecl->dropAttr<DLLImportAttr>();
7356 } else {
7357 S.Diag(Loc: NewDecl->getLocation(),
7358 DiagID: diag::warn_redeclaration_without_import_attribute)
7359 << NewDecl;
7360 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7361 NewDecl->dropAttr<DLLImportAttr>();
7362 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7363 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7364 }
7365 } else if (IsMicrosoftABI && IsSpecialization) {
7366 assert(!IsDefinition);
7367 // MSVC allows this. Keep the inherited attribute.
7368 } else {
7369 S.Diag(Loc: NewDecl->getLocation(),
7370 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7371 << NewDecl << OldImportAttr;
7372 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7373 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7374 OldDecl->dropAttr<DLLImportAttr>();
7375 NewDecl->dropAttr<DLLImportAttr>();
7376 }
7377 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7378 // In MinGW, seeing a function declared inline drops the dllimport
7379 // attribute.
7380 OldDecl->dropAttr<DLLImportAttr>();
7381 NewDecl->dropAttr<DLLImportAttr>();
7382 S.Diag(Loc: NewDecl->getLocation(),
7383 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7384 << NewDecl << OldImportAttr;
7385 }
7386
7387 // A specialization of a class template member function is processed here
7388 // since it's a redeclaration. If the parent class is dllexport, the
7389 // specialization inherits that attribute. This doesn't happen automatically
7390 // since the parent class isn't instantiated until later.
7391 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7392 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7393 !NewImportAttr && !NewExportAttr) {
7394 if (const DLLExportAttr *ParentExportAttr =
7395 MD->getParent()->getAttr<DLLExportAttr>()) {
7396 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7397 NewAttr->setInherited(true);
7398 NewDecl->addAttr(A: NewAttr);
7399 }
7400 }
7401 }
7402}
7403
7404/// Given that we are within the definition of the given function,
7405/// will that definition behave like C99's 'inline', where the
7406/// definition is discarded except for optimization purposes?
7407static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7408 // Try to avoid calling GetGVALinkageForFunction.
7409
7410 // All cases of this require the 'inline' keyword.
7411 if (!FD->isInlined()) return false;
7412
7413 // This is only possible in C++ with the gnu_inline attribute.
7414 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7415 return false;
7416
7417 // Okay, go ahead and call the relatively-more-expensive function.
7418 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7419}
7420
7421/// Determine whether a variable is extern "C" prior to attaching
7422/// an initializer. We can't just call isExternC() here, because that
7423/// will also compute and cache whether the declaration is externally
7424/// visible, which might change when we attach the initializer.
7425///
7426/// This can only be used if the declaration is known to not be a
7427/// redeclaration of an internal linkage declaration.
7428///
7429/// For instance:
7430///
7431/// auto x = []{};
7432///
7433/// Attaching the initializer here makes this declaration not externally
7434/// visible, because its type has internal linkage.
7435///
7436/// FIXME: This is a hack.
7437template<typename T>
7438static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7439 if (S.getLangOpts().CPlusPlus) {
7440 // In C++, the overloadable attribute negates the effects of extern "C".
7441 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7442 return false;
7443
7444 // So do CUDA's host/device attributes.
7445 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7446 D->template hasAttr<CUDAHostAttr>()))
7447 return false;
7448 }
7449 return D->isExternC();
7450}
7451
7452static bool shouldConsiderLinkage(const VarDecl *VD) {
7453 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7454 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7455 isa<OMPDeclareMapperDecl>(Val: DC))
7456 return VD->hasExternalStorage();
7457 if (DC->isFileContext())
7458 return true;
7459 if (DC->isRecord())
7460 return false;
7461 if (DC->getDeclKind() == Decl::HLSLBuffer)
7462 return false;
7463
7464 if (isa<RequiresExprBodyDecl>(Val: DC))
7465 return false;
7466 llvm_unreachable("Unexpected context");
7467}
7468
7469static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7470 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7471 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7472 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7473 return true;
7474 if (DC->isRecord())
7475 return false;
7476 llvm_unreachable("Unexpected context");
7477}
7478
7479static bool hasParsedAttr(Scope *S, const Declarator &PD,
7480 ParsedAttr::Kind Kind) {
7481 // Check decl attributes on the DeclSpec.
7482 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7483 return true;
7484
7485 // Walk the declarator structure, checking decl attributes that were in a type
7486 // position to the decl itself.
7487 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7488 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7489 return true;
7490 }
7491
7492 // Finally, check attributes on the decl itself.
7493 return PD.getAttributes().hasAttribute(K: Kind) ||
7494 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7495}
7496
7497bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7498 if (!DC->isFunctionOrMethod())
7499 return false;
7500
7501 // If this is a local extern function or variable declared within a function
7502 // template, don't add it into the enclosing namespace scope until it is
7503 // instantiated; it might have a dependent type right now.
7504 if (DC->isDependentContext())
7505 return true;
7506
7507 // C++11 [basic.link]p7:
7508 // When a block scope declaration of an entity with linkage is not found to
7509 // refer to some other declaration, then that entity is a member of the
7510 // innermost enclosing namespace.
7511 //
7512 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7513 // semantically-enclosing namespace, not a lexically-enclosing one.
7514 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7515 DC = DC->getParent();
7516 return true;
7517}
7518
7519/// Returns true if given declaration has external C language linkage.
7520static bool isDeclExternC(const Decl *D) {
7521 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7522 return FD->isExternC();
7523 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7524 return VD->isExternC();
7525
7526 llvm_unreachable("Unknown type of decl!");
7527}
7528
7529/// Returns true if there hasn't been any invalid type diagnosed.
7530static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7531 DeclContext *DC = NewVD->getDeclContext();
7532 QualType R = NewVD->getType();
7533
7534 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7535 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7536 // argument.
7537 if (R->isImageType() || R->isPipeType()) {
7538 Se.Diag(Loc: NewVD->getLocation(),
7539 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7540 << R;
7541 NewVD->setInvalidDecl();
7542 return false;
7543 }
7544
7545 // OpenCL v1.2 s6.9.r:
7546 // The event type cannot be used to declare a program scope variable.
7547 // OpenCL v2.0 s6.9.q:
7548 // The clk_event_t and reserve_id_t types cannot be declared in program
7549 // scope.
7550 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7551 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7552 Se.Diag(Loc: NewVD->getLocation(),
7553 DiagID: diag::err_invalid_type_for_program_scope_var)
7554 << R;
7555 NewVD->setInvalidDecl();
7556 return false;
7557 }
7558 }
7559
7560 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7561 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7562 LO: Se.getLangOpts())) {
7563 QualType NR = R.getCanonicalType();
7564 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7565 NR->isReferenceType()) {
7566 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7567 NR->isFunctionReferenceType()) {
7568 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7569 << NR->isReferenceType();
7570 NewVD->setInvalidDecl();
7571 return false;
7572 }
7573 NR = NR->getPointeeType();
7574 }
7575 }
7576
7577 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7578 LO: Se.getLangOpts())) {
7579 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7580 // half array type (unless the cl_khr_fp16 extension is enabled).
7581 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7582 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7583 NewVD->setInvalidDecl();
7584 return false;
7585 }
7586 }
7587
7588 // OpenCL v1.2 s6.9.r:
7589 // The event type cannot be used with the __local, __constant and __global
7590 // address space qualifiers.
7591 if (R->isEventT()) {
7592 if (R.getAddressSpace() != LangAS::opencl_private) {
7593 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7594 NewVD->setInvalidDecl();
7595 return false;
7596 }
7597 }
7598
7599 if (R->isSamplerT()) {
7600 // OpenCL v1.2 s6.9.b p4:
7601 // The sampler type cannot be used with the __local and __global address
7602 // space qualifiers.
7603 if (R.getAddressSpace() == LangAS::opencl_local ||
7604 R.getAddressSpace() == LangAS::opencl_global) {
7605 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7606 NewVD->setInvalidDecl();
7607 }
7608
7609 // OpenCL v1.2 s6.12.14.1:
7610 // A global sampler must be declared with either the constant address
7611 // space qualifier or with the const qualifier.
7612 if (DC->isTranslationUnit() &&
7613 !(R.getAddressSpace() == LangAS::opencl_constant ||
7614 R.isConstQualified())) {
7615 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7616 NewVD->setInvalidDecl();
7617 }
7618 if (NewVD->isInvalidDecl())
7619 return false;
7620 }
7621
7622 return true;
7623}
7624
7625template <typename AttrTy>
7626static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7627 const TypedefNameDecl *TND = TT->getDecl();
7628 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7629 AttrTy *Clone = Attribute->clone(S.Context);
7630 Clone->setInherited(true);
7631 D->addAttr(A: Clone);
7632 }
7633}
7634
7635// This function emits warning and a corresponding note based on the
7636// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7637// declarations of an annotated type must be const qualified.
7638static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7639 QualType VarType = VD->getType().getCanonicalType();
7640
7641 // Ignore local declarations (for now) and those with const qualification.
7642 // TODO: Local variables should not be allowed if their type declaration has
7643 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7644 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7645 return;
7646
7647 if (VarType->isArrayType()) {
7648 // Retrieve element type for array declarations.
7649 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7650 }
7651
7652 const RecordDecl *RD = VarType->getAsRecordDecl();
7653
7654 // Check if the record declaration is present and if it has any attributes.
7655 if (RD == nullptr)
7656 return;
7657
7658 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7659 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7660 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7661 return;
7662 }
7663}
7664
7665void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7666 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7667 "NewD is not a function or variable");
7668
7669 if (PendingExportedNames.empty())
7670 return;
7671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7672 if (getLangOpts().CPlusPlus && !FD->isExternC())
7673 return;
7674 }
7675 IdentifierInfo *IdentName = NewD->getIdentifier();
7676 if (IdentName == nullptr)
7677 return;
7678 auto PendingName = PendingExportedNames.find(Val: IdentName);
7679 if (PendingName != PendingExportedNames.end()) {
7680 auto &Label = PendingName->second;
7681 if (!Label.Used) {
7682 Label.Used = true;
7683 if (NewD->hasExternalFormalLinkage())
7684 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7685 else
7686 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7687 }
7688 }
7689}
7690
7691// Checks if VD is declared at global scope or with C language linkage.
7692static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7693 return Name.getAsIdentifierInfo() &&
7694 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7695 !VD->getDescribedVarTemplate() &&
7696 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7697 VD->isExternC());
7698}
7699
7700void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7701 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7702
7703 // Quickly return if the function does not have an `asm` attribute.
7704 if (E == nullptr)
7705 return;
7706
7707 // The parser guarantees this is a string.
7708 StringLiteral *SE = cast<StringLiteral>(Val: E);
7709 StringRef Label = SE->getString();
7710 QualType R = TInfo->getType();
7711 if (S->getFnParent() != nullptr) {
7712 switch (SC) {
7713 case SC_None:
7714 case SC_Auto:
7715 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7716 break;
7717 case SC_Register:
7718 // Local Named register
7719 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7720 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7721 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7722 break;
7723 case SC_Static:
7724 case SC_Extern:
7725 case SC_PrivateExtern:
7726 break;
7727 }
7728 } else if (SC == SC_Register) {
7729 // Global Named register
7730 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7731 const auto &TI = Context.getTargetInfo();
7732 bool HasSizeMismatch;
7733
7734 if (!TI.isValidGCCRegisterName(Name: Label))
7735 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7736 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7737 HasSizeMismatch))
7738 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7739 else if (HasSizeMismatch)
7740 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7741 }
7742
7743 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7744 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7745 DiagID: diag::err_asm_unsupported_register_type)
7746 << TInfo->getTypeLoc().getSourceRange();
7747 NewVD->setInvalidDecl(true);
7748 }
7749 }
7750}
7751
7752NamedDecl *Sema::ActOnVariableDeclarator(
7753 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7754 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7755 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7756 QualType R = TInfo->getType();
7757 DeclarationName Name = GetNameForDeclarator(D).getName();
7758
7759 IdentifierInfo *II = Name.getAsIdentifierInfo();
7760 bool IsPlaceholderVariable = false;
7761
7762 if (D.isDecompositionDeclarator()) {
7763 // Take the name of the first declarator as our name for diagnostic
7764 // purposes.
7765 auto &Decomp = D.getDecompositionDeclarator();
7766 if (!Decomp.bindings().empty()) {
7767 II = Decomp.bindings()[0].Name;
7768 Name = II;
7769 }
7770 } else if (!II) {
7771 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7772 return nullptr;
7773 }
7774
7775
7776 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7777 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7778 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7779 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7780
7781 IsPlaceholderVariable = true;
7782
7783 if (!Previous.empty()) {
7784 NamedDecl *PrevDecl = *Previous.begin();
7785 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7786 DC: DC->getRedeclContext());
7787 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7788 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7789 if (IsPlaceholderVariable)
7790 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7791 }
7792 }
7793 }
7794
7795 // dllimport globals without explicit storage class are treated as extern. We
7796 // have to change the storage class this early to get the right DeclContext.
7797 if (SC == SC_None && !DC->isRecord() &&
7798 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7799 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7800 SC = SC_Extern;
7801
7802 DeclContext *OriginalDC = DC;
7803 bool IsLocalExternDecl = SC == SC_Extern &&
7804 adjustContextForLocalExternDecl(DC);
7805
7806 if (SCSpec == DeclSpec::SCS_mutable) {
7807 // mutable can only appear on non-static class members, so it's always
7808 // an error here
7809 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7810 D.setInvalidType();
7811 SC = SC_None;
7812 }
7813
7814 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7815 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7816 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7817 // In C++11, the 'register' storage class specifier is deprecated.
7818 // Suppress the warning in system macros, it's used in macros in some
7819 // popular C system headers, such as in glibc's htonl() macro.
7820 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7821 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7822 : diag::warn_deprecated_register)
7823 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7824 }
7825
7826 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7827
7828 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7829 // C99 6.9p2: The storage-class specifiers auto and register shall not
7830 // appear in the declaration specifiers in an external declaration.
7831 // Global Register+Asm is a GNU extension we support.
7832 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7833 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7834 D.setInvalidType();
7835 }
7836 }
7837
7838 // If this variable has a VLA type and an initializer, try to
7839 // fold to a constant-sized type. This is otherwise invalid.
7840 if (D.hasInitializer() && R->isVariableArrayType())
7841 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7842 /*DiagID=*/FailedFoldDiagID: 0);
7843
7844 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7845 const AutoType *AT = TL.getTypePtr();
7846 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7847 }
7848
7849 bool IsMemberSpecialization = false;
7850 bool IsVariableTemplateSpecialization = false;
7851 bool IsPartialSpecialization = false;
7852 bool IsVariableTemplate = false;
7853 VarDecl *NewVD = nullptr;
7854 VarTemplateDecl *NewTemplate = nullptr;
7855 TemplateParameterList *TemplateParams = nullptr;
7856 if (!getLangOpts().CPlusPlus) {
7857 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7858 Id: II, T: R, TInfo, S: SC);
7859
7860 if (R->getContainedDeducedType())
7861 ParsingInitForAutoVars.insert(Ptr: NewVD);
7862
7863 if (D.isInvalidType())
7864 NewVD->setInvalidDecl();
7865
7866 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7867 NewVD->hasLocalStorage())
7868 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7869 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7870 } else {
7871 bool Invalid = false;
7872 // Match up the template parameter lists with the scope specifier, then
7873 // determine whether we have a template or a template specialization.
7874 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7875 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7876 SS: D.getCXXScopeSpec(),
7877 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7878 ? D.getName().TemplateId
7879 : nullptr,
7880 ParamLists: TemplateParamLists,
7881 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7882
7883 if (TemplateParams) {
7884 if (DC->isDependentContext()) {
7885 ContextRAII SavedContext(*this, DC);
7886 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7887 Invalid = true;
7888 }
7889
7890 if (!TemplateParams->size() &&
7891 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7892 // There is an extraneous 'template<>' for this variable. Complain
7893 // about it, but allow the declaration of the variable.
7894 Diag(Loc: TemplateParams->getTemplateLoc(),
7895 DiagID: diag::err_template_variable_noparams)
7896 << II
7897 << SourceRange(TemplateParams->getTemplateLoc(),
7898 TemplateParams->getRAngleLoc());
7899 TemplateParams = nullptr;
7900 } else {
7901 // Check that we can declare a template here.
7902 if (CheckTemplateDeclScope(S, TemplateParams))
7903 return nullptr;
7904
7905 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7906 // This is an explicit specialization or a partial specialization.
7907 IsVariableTemplateSpecialization = true;
7908 IsPartialSpecialization = TemplateParams->size() > 0;
7909 } else { // if (TemplateParams->size() > 0)
7910 // This is a template declaration.
7911 IsVariableTemplate = true;
7912
7913 // Only C++1y supports variable templates (N3651).
7914 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7915 }
7916 }
7917 } else {
7918 // Check that we can declare a member specialization here.
7919 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7920 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7921 return nullptr;
7922 assert((Invalid ||
7923 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7924 "should have a 'template<>' for this decl");
7925 }
7926
7927 bool IsExplicitSpecialization =
7928 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7929
7930 // C++ [temp.expl.spec]p2:
7931 // The declaration in an explicit-specialization shall not be an
7932 // export-declaration. An explicit specialization shall not use a
7933 // storage-class-specifier other than thread_local.
7934 //
7935 // We use the storage-class-specifier from DeclSpec because we may have
7936 // added implicit 'extern' for declarations with __declspec(dllimport)!
7937 if (SCSpec != DeclSpec::SCS_unspecified &&
7938 (IsExplicitSpecialization || IsMemberSpecialization)) {
7939 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7940 DiagID: diag::ext_explicit_specialization_storage_class)
7941 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7942 }
7943
7944 if (CurContext->isRecord()) {
7945 if (SC == SC_Static) {
7946 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7947 // Walk up the enclosing DeclContexts to check for any that are
7948 // incompatible with static data members.
7949 const DeclContext *FunctionOrMethod = nullptr;
7950 const CXXRecordDecl *AnonStruct = nullptr;
7951 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7952 if (Ctxt->isFunctionOrMethod()) {
7953 FunctionOrMethod = Ctxt;
7954 break;
7955 }
7956 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7957 if (ParentDecl && !ParentDecl->getDeclName()) {
7958 AnonStruct = ParentDecl;
7959 break;
7960 }
7961 }
7962 if (FunctionOrMethod) {
7963 // C++ [class.static.data]p5: A local class shall not have static
7964 // data members.
7965 Diag(Loc: D.getIdentifierLoc(),
7966 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7967 << Name << RD->getDeclName() << RD->getTagKind();
7968 Invalid = true;
7969 RD->setInvalidDecl();
7970 } else if (AnonStruct) {
7971 // C++ [class.static.data]p4: Unnamed classes and classes contained
7972 // directly or indirectly within unnamed classes shall not contain
7973 // static data members.
7974 Diag(Loc: D.getIdentifierLoc(),
7975 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7976 << Name << AnonStruct->getTagKind();
7977 Invalid = true;
7978 } else if (RD->isUnion()) {
7979 // C++98 [class.union]p1: If a union contains a static data member,
7980 // the program is ill-formed. C++11 drops this restriction.
7981 DiagCompat(Loc: D.getIdentifierLoc(),
7982 CompatDiagId: diag_compat::static_data_member_in_union)
7983 << Name;
7984 }
7985 }
7986 } else if (IsVariableTemplate || IsPartialSpecialization) {
7987 // There is no such thing as a member field template.
7988 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7989 << II << TemplateParams->getSourceRange();
7990 // Recover by pretending this is a static data member template.
7991 SC = SC_Static;
7992 }
7993 } else if (DC->isRecord()) {
7994 // This is an out-of-line definition of a static data member.
7995 switch (SC) {
7996 case SC_None:
7997 break;
7998 case SC_Static:
7999 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8000 DiagID: diag::err_static_out_of_line)
8001 << FixItHint::CreateRemoval(
8002 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8003 break;
8004 case SC_Auto:
8005 case SC_Register:
8006 case SC_Extern:
8007 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8008 // to names of variables declared in a block or to function parameters.
8009 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8010 // of class members
8011
8012 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8013 DiagID: diag::err_storage_class_for_static_member)
8014 << FixItHint::CreateRemoval(
8015 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8016 break;
8017 case SC_PrivateExtern:
8018 llvm_unreachable("C storage class in c++!");
8019 }
8020 }
8021
8022 if (IsVariableTemplateSpecialization) {
8023 SourceLocation TemplateKWLoc =
8024 TemplateParamLists.size() > 0
8025 ? TemplateParamLists[0]->getTemplateLoc()
8026 : SourceLocation();
8027 DeclResult Res = ActOnVarTemplateSpecialization(
8028 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8029 IsPartialSpecialization);
8030 if (Res.isInvalid())
8031 return nullptr;
8032 NewVD = cast<VarDecl>(Val: Res.get());
8033 AddToScope = false;
8034 } else if (D.isDecompositionDeclarator()) {
8035 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8036 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
8037 Bindings);
8038 } else
8039 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8040 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8041
8042 // If this is supposed to be a variable template, create it as such.
8043 if (IsVariableTemplate) {
8044 NewTemplate =
8045 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8046 Params: TemplateParams, Decl: NewVD);
8047 NewVD->setDescribedVarTemplate(NewTemplate);
8048 }
8049
8050 // If this decl has an auto type in need of deduction, make a note of the
8051 // Decl so we can diagnose uses of it in its own initializer.
8052 if (R->getContainedDeducedType())
8053 ParsingInitForAutoVars.insert(Ptr: NewVD);
8054
8055 if (D.isInvalidType() || Invalid) {
8056 NewVD->setInvalidDecl();
8057 if (NewTemplate)
8058 NewTemplate->setInvalidDecl();
8059 }
8060
8061 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8062
8063 // If we have any template parameter lists that don't directly belong to
8064 // the variable (matching the scope specifier), store them.
8065 // An explicit variable template specialization does not own any template
8066 // parameter lists.
8067 unsigned VDTemplateParamLists =
8068 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8069 if (TemplateParamLists.size() > VDTemplateParamLists)
8070 NewVD->setTemplateParameterListsInfo(
8071 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8072 }
8073
8074 if (D.getDeclSpec().isInlineSpecified()) {
8075 if (!getLangOpts().CPlusPlus) {
8076 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8077 << 0;
8078 } else if (CurContext->isFunctionOrMethod()) {
8079 // 'inline' is not allowed on block scope variable declaration.
8080 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8081 DiagID: diag::err_inline_declaration_block_scope) << Name
8082 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8083 } else {
8084 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8085 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8086 : diag::compat_pre_cxx17_inline_variable);
8087 NewVD->setInlineSpecified();
8088 }
8089 }
8090
8091 // Set the lexical context. If the declarator has a C++ scope specifier, the
8092 // lexical context will be different from the semantic context.
8093 NewVD->setLexicalDeclContext(CurContext);
8094 if (NewTemplate)
8095 NewTemplate->setLexicalDeclContext(CurContext);
8096
8097 if (IsLocalExternDecl) {
8098 if (D.isDecompositionDeclarator())
8099 for (auto *B : Bindings)
8100 B->setLocalExternDecl();
8101 else
8102 NewVD->setLocalExternDecl();
8103 }
8104
8105 bool EmitTLSUnsupportedError = false;
8106 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8107 // C++11 [dcl.stc]p4:
8108 // When thread_local is applied to a variable of block scope the
8109 // storage-class-specifier static is implied if it does not appear
8110 // explicitly.
8111 // Core issue: 'static' is not implied if the variable is declared
8112 // 'extern'.
8113 if (NewVD->hasLocalStorage() &&
8114 (SCSpec != DeclSpec::SCS_unspecified ||
8115 TSCS != DeclSpec::TSCS_thread_local ||
8116 !DC->isFunctionOrMethod()))
8117 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8118 DiagID: diag::err_thread_non_global)
8119 << DeclSpec::getSpecifierName(S: TSCS);
8120 else if (!Context.getTargetInfo().isTLSSupported()) {
8121 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8122 // Postpone error emission until we've collected attributes required to
8123 // figure out whether it's a host or device variable and whether the
8124 // error should be ignored.
8125 EmitTLSUnsupportedError = true;
8126 // We still need to mark the variable as TLS so it shows up in AST with
8127 // proper storage class for other tools to use even if we're not going
8128 // to emit any code for it.
8129 NewVD->setTSCSpec(TSCS);
8130 } else
8131 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8132 DiagID: diag::err_thread_unsupported);
8133 } else
8134 NewVD->setTSCSpec(TSCS);
8135 }
8136
8137 switch (D.getDeclSpec().getConstexprSpecifier()) {
8138 case ConstexprSpecKind::Unspecified:
8139 break;
8140
8141 case ConstexprSpecKind::Consteval:
8142 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8143 DiagID: diag::err_constexpr_wrong_decl_kind)
8144 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8145 [[fallthrough]];
8146
8147 case ConstexprSpecKind::Constexpr:
8148 NewVD->setConstexpr(true);
8149 // C++1z [dcl.spec.constexpr]p1:
8150 // A static data member declared with the constexpr specifier is
8151 // implicitly an inline variable.
8152 if (NewVD->isStaticDataMember() &&
8153 (getLangOpts().CPlusPlus17 ||
8154 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8155 NewVD->setImplicitlyInline();
8156 break;
8157
8158 case ConstexprSpecKind::Constinit:
8159 if (!NewVD->hasGlobalStorage())
8160 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8161 DiagID: diag::err_constinit_local_variable);
8162 else
8163 NewVD->addAttr(
8164 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8165 S: ConstInitAttr::Keyword_constinit));
8166 break;
8167 }
8168
8169 // C99 6.7.4p3
8170 // An inline definition of a function with external linkage shall
8171 // not contain a definition of a modifiable object with static or
8172 // thread storage duration...
8173 // We only apply this when the function is required to be defined
8174 // elsewhere, i.e. when the function is not 'extern inline'. Note
8175 // that a local variable with thread storage duration still has to
8176 // be marked 'static'. Also note that it's possible to get these
8177 // semantics in C++ using __attribute__((gnu_inline)).
8178 if (SC == SC_Static && S->getFnParent() != nullptr &&
8179 !NewVD->getType().isConstQualified()) {
8180 FunctionDecl *CurFD = getCurFunctionDecl();
8181 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8182 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8183 DiagID: diag::warn_static_local_in_extern_inline);
8184 MaybeSuggestAddingStaticToDecl(D: CurFD);
8185 }
8186 }
8187
8188 if (D.getDeclSpec().isModulePrivateSpecified()) {
8189 if (IsVariableTemplateSpecialization)
8190 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8191 << (IsPartialSpecialization ? 1 : 0)
8192 << FixItHint::CreateRemoval(
8193 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8194 else if (IsMemberSpecialization)
8195 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8196 << 2
8197 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8198 else if (NewVD->hasLocalStorage())
8199 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8200 << 0 << NewVD
8201 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8202 << FixItHint::CreateRemoval(
8203 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8204 else {
8205 NewVD->setModulePrivate();
8206 if (NewTemplate)
8207 NewTemplate->setModulePrivate();
8208 for (auto *B : Bindings)
8209 B->setModulePrivate();
8210 }
8211 }
8212
8213 if (getLangOpts().OpenCL) {
8214 deduceOpenCLAddressSpace(Var: NewVD);
8215
8216 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8217 if (TSC != TSCS_unspecified) {
8218 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8219 DiagID: diag::err_opencl_unknown_type_specifier)
8220 << getLangOpts().getOpenCLVersionString()
8221 << DeclSpec::getSpecifierName(S: TSC) << 1;
8222 NewVD->setInvalidDecl();
8223 }
8224 }
8225
8226 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8227 // address space if the table has local storage (semantic checks elsewhere
8228 // will produce an error anyway).
8229 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8230 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8231 !NewVD->hasLocalStorage()) {
8232 QualType Type = Context.getAddrSpaceQualType(
8233 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8234 NewVD->setType(Type);
8235 }
8236 }
8237
8238 if (Expr *E = D.getAsmLabel()) {
8239 // The parser guarantees this is a string.
8240 StringLiteral *SE = cast<StringLiteral>(Val: E);
8241 StringRef Label = SE->getString();
8242
8243 // Insert the asm attribute.
8244 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8245 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8246 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8247 ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier());
8248 if (I != ExtnameUndeclaredIdentifiers.end()) {
8249 if (isDeclExternC(D: NewVD)) {
8250 NewVD->addAttr(A: I->second);
8251 ExtnameUndeclaredIdentifiers.erase(I);
8252 } else
8253 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8254 << /*Variable*/ 1 << NewVD;
8255 }
8256 }
8257
8258 // Handle attributes prior to checking for duplicates in MergeVarDecl
8259 ProcessDeclAttributes(S, D: NewVD, PD: D);
8260
8261 if (getLangOpts().HLSL)
8262 HLSL().ActOnVariableDeclarator(VD: NewVD);
8263
8264 if (getLangOpts().OpenACC)
8265 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8266
8267 // FIXME: This is probably the wrong location to be doing this and we should
8268 // probably be doing this for more attributes (especially for function
8269 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8270 // the code to copy attributes would be generated by TableGen.
8271 if (R->isFunctionPointerType())
8272 if (const auto *TT = R->getAs<TypedefType>())
8273 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8274
8275 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8276 if (EmitTLSUnsupportedError &&
8277 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8278 (getLangOpts().OpenMPIsTargetDevice &&
8279 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8280 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8281 DiagID: diag::err_thread_unsupported);
8282
8283 if (EmitTLSUnsupportedError &&
8284 (LangOpts.SYCLIsDevice ||
8285 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8286 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8287 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8288 // storage [duration]."
8289 if (SC == SC_None && S->getFnParent() != nullptr &&
8290 (NewVD->hasAttr<CUDASharedAttr>() ||
8291 NewVD->hasAttr<CUDAConstantAttr>())) {
8292 NewVD->setStorageClass(SC_Static);
8293 }
8294 }
8295
8296 // Ensure that dllimport globals without explicit storage class are treated as
8297 // extern. The storage class is set above using parsed attributes. Now we can
8298 // check the VarDecl itself.
8299 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8300 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8301 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8302
8303 // In auto-retain/release, infer strong retension for variables of
8304 // retainable type.
8305 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8306 NewVD->setInvalidDecl();
8307
8308 // Check the ASM label here, as we need to know all other attributes of the
8309 // Decl first. Otherwise, we can't know if the asm label refers to the
8310 // host or device in a CUDA context. The device has other registers than
8311 // host and we must know where the function will be placed.
8312 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8313
8314 // Find the shadowed declaration before filtering for scope.
8315 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8316 ? getShadowedDeclaration(D: NewVD, R: Previous)
8317 : nullptr;
8318
8319 // Don't consider existing declarations that are in a different
8320 // scope and are out-of-semantic-context declarations (if the new
8321 // declaration has linkage).
8322 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8323 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8324 IsMemberSpecialization ||
8325 IsVariableTemplateSpecialization);
8326
8327 // Check whether the previous declaration is in the same block scope. This
8328 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8329 if (getLangOpts().CPlusPlus &&
8330 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8331 NewVD->setPreviousDeclInSameBlockScope(
8332 Previous.isSingleResult() && !Previous.isShadowed() &&
8333 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8334
8335 if (!getLangOpts().CPlusPlus) {
8336 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8337 } else {
8338 // If this is an explicit specialization of a static data member, check it.
8339 if (IsMemberSpecialization && !IsVariableTemplate &&
8340 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8341 CheckMemberSpecialization(Member: NewVD, Previous))
8342 NewVD->setInvalidDecl();
8343
8344 // Merge the decl with the existing one if appropriate.
8345 if (!Previous.empty()) {
8346 if (Previous.isSingleResult() &&
8347 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8348 D.getCXXScopeSpec().isSet()) {
8349 // The user tried to define a non-static data member
8350 // out-of-line (C++ [dcl.meaning]p1).
8351 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8352 << D.getCXXScopeSpec().getRange();
8353 Previous.clear();
8354 NewVD->setInvalidDecl();
8355 }
8356 } else if (D.getCXXScopeSpec().isSet() &&
8357 !IsVariableTemplateSpecialization) {
8358 // No previous declaration in the qualifying scope.
8359 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8360 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8361 << D.getCXXScopeSpec().getRange();
8362 NewVD->setInvalidDecl();
8363 }
8364
8365 if (!IsPlaceholderVariable)
8366 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8367
8368 // CheckVariableDeclaration will set NewVD as invalid if something is in
8369 // error like WebAssembly tables being declared as arrays with a non-zero
8370 // size, but then parsing continues and emits further errors on that line.
8371 // To avoid that we check here if it happened and return nullptr.
8372 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8373 return nullptr;
8374
8375 if (NewTemplate) {
8376 VarTemplateDecl *PrevVarTemplate =
8377 NewVD->getPreviousDecl()
8378 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8379 : nullptr;
8380
8381 // Check the template parameter list of this declaration, possibly
8382 // merging in the template parameter list from the previous variable
8383 // template declaration.
8384 if (CheckTemplateParameterList(
8385 NewParams: TemplateParams,
8386 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8387 : nullptr,
8388 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8389 DC->isDependentContext())
8390 ? TPC_ClassTemplateMember
8391 : TPC_Other))
8392 NewVD->setInvalidDecl();
8393
8394 // If we are providing an explicit specialization of a static variable
8395 // template, make a note of that.
8396 if (PrevVarTemplate &&
8397 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8398 PrevVarTemplate->setMemberSpecialization();
8399 }
8400 }
8401
8402 // Diagnose shadowed variables iff this isn't a redeclaration.
8403 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8404 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8405
8406 ProcessPragmaWeak(S, D: NewVD);
8407 ProcessPragmaExport(NewD: NewVD);
8408
8409 // If this is the first declaration of an extern C variable, update
8410 // the map of such variables.
8411 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8412 isIncompleteDeclExternC(S&: *this, D: NewVD))
8413 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8414
8415 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8416 MangleNumberingContext *MCtx;
8417 Decl *ManglingContextDecl;
8418 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8419 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8420 if (MCtx) {
8421 Context.setManglingNumber(
8422 ND: NewVD, Number: MCtx->getManglingNumber(
8423 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8424 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8425 }
8426 }
8427
8428 // Special handling of variable named 'main'.
8429 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8430 // C++ [basic.start.main]p3:
8431 // A program that declares
8432 // - a variable main at global scope, or
8433 // - an entity named main with C language linkage (in any namespace)
8434 // is ill-formed
8435 if (getLangOpts().CPlusPlus)
8436 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8437 << NewVD->isExternC();
8438
8439 // In C, and external-linkage variable named main results in undefined
8440 // behavior.
8441 else if (NewVD->hasExternalFormalLinkage())
8442 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8443 }
8444
8445 if (D.isRedeclaration() && !Previous.empty()) {
8446 NamedDecl *Prev = Previous.getRepresentativeDecl();
8447 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8448 IsDefinition: D.isFunctionDefinition());
8449 }
8450
8451 if (NewTemplate) {
8452 if (NewVD->isInvalidDecl())
8453 NewTemplate->setInvalidDecl();
8454 ActOnDocumentableDecl(D: NewTemplate);
8455 return NewTemplate;
8456 }
8457
8458 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8459 CompleteMemberSpecialization(Member: NewVD, Previous);
8460
8461 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8462
8463 return NewVD;
8464}
8465
8466/// Enum describing the %select options in diag::warn_decl_shadow.
8467enum ShadowedDeclKind {
8468 SDK_Local,
8469 SDK_Global,
8470 SDK_StaticMember,
8471 SDK_Field,
8472 SDK_Typedef,
8473 SDK_Using,
8474 SDK_StructuredBinding
8475};
8476
8477/// Determine what kind of declaration we're shadowing.
8478static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8479 const DeclContext *OldDC) {
8480 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8481 return SDK_Using;
8482 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8483 return SDK_Typedef;
8484 else if (isa<BindingDecl>(Val: ShadowedDecl))
8485 return SDK_StructuredBinding;
8486 else if (isa<RecordDecl>(Val: OldDC))
8487 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8488
8489 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8490}
8491
8492/// Return the location of the capture if the given lambda captures the given
8493/// variable \p VD, or an invalid source location otherwise.
8494static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8495 const ValueDecl *VD) {
8496 for (const Capture &Capture : LSI->Captures) {
8497 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8498 return Capture.getLocation();
8499 }
8500 return SourceLocation();
8501}
8502
8503static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8504 const LookupResult &R) {
8505 // Only diagnose if we're shadowing an unambiguous field or variable.
8506 if (R.getResultKind() != LookupResultKind::Found)
8507 return false;
8508
8509 // Return false if warning is ignored.
8510 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8511}
8512
8513NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8514 const LookupResult &R) {
8515 if (!shouldWarnIfShadowedDecl(Diags, R))
8516 return nullptr;
8517
8518 // Don't diagnose declarations at file scope.
8519 if (D->hasGlobalStorage() && !D->isStaticLocal())
8520 return nullptr;
8521
8522 NamedDecl *ShadowedDecl = R.getFoundDecl();
8523 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8524 : nullptr;
8525}
8526
8527NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8528 const LookupResult &R) {
8529 // Don't warn if typedef declaration is part of a class
8530 if (D->getDeclContext()->isRecord())
8531 return nullptr;
8532
8533 if (!shouldWarnIfShadowedDecl(Diags, R))
8534 return nullptr;
8535
8536 NamedDecl *ShadowedDecl = R.getFoundDecl();
8537 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8538}
8539
8540NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8541 const LookupResult &R) {
8542 if (!shouldWarnIfShadowedDecl(Diags, R))
8543 return nullptr;
8544
8545 NamedDecl *ShadowedDecl = R.getFoundDecl();
8546 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8547 : nullptr;
8548}
8549
8550void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8551 const LookupResult &R) {
8552 DeclContext *NewDC = D->getDeclContext();
8553
8554 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8555 if (const auto *MD =
8556 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8557 // Fields aren't shadowed in C++ static members or in member functions
8558 // with an explicit object parameter.
8559 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8560 return;
8561 }
8562 // Fields shadowed by constructor parameters are a special case. Usually
8563 // the constructor initializes the field with the parameter.
8564 if (isa<CXXConstructorDecl>(Val: NewDC))
8565 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8566 // Remember that this was shadowed so we can either warn about its
8567 // modification or its existence depending on warning settings.
8568 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8569 return;
8570 }
8571 }
8572
8573 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8574 if (shadowedVar->isExternC()) {
8575 // For shadowing external vars, make sure that we point to the global
8576 // declaration, not a locally scoped extern declaration.
8577 for (auto *I : shadowedVar->redecls())
8578 if (I->isFileVarDecl()) {
8579 ShadowedDecl = I;
8580 break;
8581 }
8582 }
8583
8584 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8585
8586 unsigned WarningDiag = diag::warn_decl_shadow;
8587 SourceLocation CaptureLoc;
8588 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8589 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8590 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8591 // Handle both VarDecl and BindingDecl in lambda contexts
8592 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8593 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8594 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8595 if (RD->getLambdaCaptureDefault() == LCD_None) {
8596 // Try to avoid warnings for lambdas with an explicit capture
8597 // list. Warn only when the lambda captures the shadowed decl
8598 // explicitly.
8599 CaptureLoc = getCaptureLocation(LSI, VD);
8600 if (CaptureLoc.isInvalid())
8601 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8602 } else {
8603 // Remember that this was shadowed so we can avoid the warning if
8604 // the shadowed decl isn't captured and the warning settings allow
8605 // it.
8606 cast<LambdaScopeInfo>(Val: getCurFunction())
8607 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8608 return;
8609 }
8610 }
8611 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8612 // If lambda can capture this, then emit default shadowing warning,
8613 // Otherwise it is not really a shadowing case since field is not
8614 // available in lambda's body.
8615 // At this point we don't know that lambda can capture this, so
8616 // remember that this was shadowed and delay until we know.
8617 cast<LambdaScopeInfo>(Val: getCurFunction())
8618 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8619 return;
8620 }
8621 }
8622 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8623 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8624 bool HasLocalStorage = false;
8625 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8626 HasLocalStorage = VD->hasLocalStorage();
8627 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8628 HasLocalStorage =
8629 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8630
8631 if (HasLocalStorage) {
8632 // A variable can't shadow a local variable or binding in an enclosing
8633 // scope, if they are separated by a non-capturing declaration
8634 // context.
8635 for (DeclContext *ParentDC = NewDC;
8636 ParentDC && !ParentDC->Equals(DC: OldDC);
8637 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8638 // Only block literals, captured statements, and lambda expressions
8639 // can capture; other scopes don't.
8640 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8641 !isLambdaCallOperator(DC: ParentDC))
8642 return;
8643 }
8644 }
8645 }
8646 }
8647 }
8648
8649 // Never warn about shadowing a placeholder variable.
8650 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8651 return;
8652
8653 // Only warn about certain kinds of shadowing for class members.
8654 if (NewDC) {
8655 // In particular, don't warn about shadowing non-class members.
8656 if (NewDC->isRecord() && !OldDC->isRecord())
8657 return;
8658
8659 // Skip shadowing check if we're in a class scope, dealing with an enum
8660 // constant in a different context.
8661 DeclContext *ReDC = NewDC->getRedeclContext();
8662 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8663 return;
8664
8665 // TODO: should we warn about static data members shadowing
8666 // static data members from base classes?
8667
8668 // TODO: don't diagnose for inaccessible shadowed members.
8669 // This is hard to do perfectly because we might friend the
8670 // shadowing context, but that's just a false negative.
8671 }
8672
8673 DeclarationName Name = R.getLookupName();
8674
8675 // Emit warning and note.
8676 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8677 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8678 if (!CaptureLoc.isInvalid())
8679 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8680 << Name << /*explicitly*/ 1;
8681 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8682}
8683
8684void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8685 for (const auto &Shadow : LSI->ShadowingDecls) {
8686 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8687 // Try to avoid the warning when the shadowed decl isn't captured.
8688 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8689 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8690 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8691 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8692 Diag(Loc: Shadow.VD->getLocation(),
8693 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8694 : diag::warn_decl_shadow)
8695 << Shadow.VD->getDeclName()
8696 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8697 if (CaptureLoc.isValid())
8698 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8699 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8700 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8701 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8702 Diag(Loc: Shadow.VD->getLocation(),
8703 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8704 : diag::warn_decl_shadow_uncaptured_local)
8705 << Shadow.VD->getDeclName()
8706 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8707 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8708 }
8709 }
8710}
8711
8712void Sema::CheckShadow(Scope *S, VarDecl *D) {
8713 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8714 return;
8715
8716 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8717 Sema::LookupOrdinaryName,
8718 RedeclarationKind::ForVisibleRedeclaration);
8719 LookupName(R, S);
8720 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8721 CheckShadow(D, ShadowedDecl, R);
8722}
8723
8724/// Check if 'E', which is an expression that is about to be modified, refers
8725/// to a constructor parameter that shadows a field.
8726void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8727 // Quickly ignore expressions that can't be shadowing ctor parameters.
8728 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8729 return;
8730 E = E->IgnoreParenImpCasts();
8731 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8732 if (!DRE)
8733 return;
8734 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8735 auto I = ShadowingDecls.find(Val: D);
8736 if (I == ShadowingDecls.end())
8737 return;
8738 const NamedDecl *ShadowedDecl = I->second;
8739 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8740 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8741 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8742 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8743
8744 // Avoid issuing multiple warnings about the same decl.
8745 ShadowingDecls.erase(I);
8746}
8747
8748/// Check for conflict between this global or extern "C" declaration and
8749/// previous global or extern "C" declarations. This is only used in C++.
8750template<typename T>
8751static bool checkGlobalOrExternCConflict(
8752 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8753 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8754 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8755
8756 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8757 // The common case: this global doesn't conflict with any extern "C"
8758 // declaration.
8759 return false;
8760 }
8761
8762 if (Prev) {
8763 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8764 // Both the old and new declarations have C language linkage. This is a
8765 // redeclaration.
8766 Previous.clear();
8767 Previous.addDecl(D: Prev);
8768 return true;
8769 }
8770
8771 // This is a global, non-extern "C" declaration, and there is a previous
8772 // non-global extern "C" declaration. Diagnose if this is a variable
8773 // declaration.
8774 if (!isa<VarDecl>(ND))
8775 return false;
8776 } else {
8777 // The declaration is extern "C". Check for any declaration in the
8778 // translation unit which might conflict.
8779 if (IsGlobal) {
8780 // We have already performed the lookup into the translation unit.
8781 IsGlobal = false;
8782 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8783 I != E; ++I) {
8784 if (isa<VarDecl>(Val: *I)) {
8785 Prev = *I;
8786 break;
8787 }
8788 }
8789 } else {
8790 DeclContext::lookup_result R =
8791 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8792 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8793 I != E; ++I) {
8794 if (isa<VarDecl>(Val: *I)) {
8795 Prev = *I;
8796 break;
8797 }
8798 // FIXME: If we have any other entity with this name in global scope,
8799 // the declaration is ill-formed, but that is a defect: it breaks the
8800 // 'stat' hack, for instance. Only variables can have mangled name
8801 // clashes with extern "C" declarations, so only they deserve a
8802 // diagnostic.
8803 }
8804 }
8805
8806 if (!Prev)
8807 return false;
8808 }
8809
8810 // Use the first declaration's location to ensure we point at something which
8811 // is lexically inside an extern "C" linkage-spec.
8812 assert(Prev && "should have found a previous declaration to diagnose");
8813 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8814 Prev = FD->getFirstDecl();
8815 else
8816 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8817
8818 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8819 << IsGlobal << ND;
8820 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8821 << IsGlobal;
8822 return false;
8823}
8824
8825/// Apply special rules for handling extern "C" declarations. Returns \c true
8826/// if we have found that this is a redeclaration of some prior entity.
8827///
8828/// Per C++ [dcl.link]p6:
8829/// Two declarations [for a function or variable] with C language linkage
8830/// with the same name that appear in different scopes refer to the same
8831/// [entity]. An entity with C language linkage shall not be declared with
8832/// the same name as an entity in global scope.
8833template<typename T>
8834static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8835 LookupResult &Previous) {
8836 if (!S.getLangOpts().CPlusPlus) {
8837 // In C, when declaring a global variable, look for a corresponding 'extern'
8838 // variable declared in function scope. We don't need this in C++, because
8839 // we find local extern decls in the surrounding file-scope DeclContext.
8840 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8841 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8842 Previous.clear();
8843 Previous.addDecl(D: Prev);
8844 return true;
8845 }
8846 }
8847 return false;
8848 }
8849
8850 // A declaration in the translation unit can conflict with an extern "C"
8851 // declaration.
8852 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8853 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8854
8855 // An extern "C" declaration can conflict with a declaration in the
8856 // translation unit or can be a redeclaration of an extern "C" declaration
8857 // in another scope.
8858 if (isIncompleteDeclExternC(S,ND))
8859 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8860
8861 // Neither global nor extern "C": nothing to do.
8862 return false;
8863}
8864
8865static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8866 QualType T) {
8867 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8868 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8869 // any of its members, even recursively, shall not have an atomic type, or a
8870 // variably modified type, or a type that is volatile or restrict qualified.
8871 if (CanonT->isVariablyModifiedType()) {
8872 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8873 return true;
8874 }
8875
8876 // Arrays are qualified by their element type, so get the base type (this
8877 // works on non-arrays as well).
8878 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8879
8880 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8881 CanonT.isRestrictQualified()) {
8882 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8883 return true;
8884 }
8885
8886 if (CanonT->isRecordType()) {
8887 const RecordDecl *RD = CanonT->getAsRecordDecl();
8888 if (!RD->isInvalidDecl() &&
8889 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8890 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8891 }))
8892 return true;
8893 }
8894
8895 return false;
8896}
8897
8898void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8899 // If the decl is already known invalid, don't check it.
8900 if (NewVD->isInvalidDecl())
8901 return;
8902
8903 QualType T = NewVD->getType();
8904
8905 // Defer checking an 'auto' type until its initializer is attached.
8906 if (T->isUndeducedType())
8907 return;
8908
8909 if (NewVD->hasAttrs())
8910 CheckAlignasUnderalignment(D: NewVD);
8911
8912 if (T->isObjCObjectType()) {
8913 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8914 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8915 T = Context.getObjCObjectPointerType(OIT: T);
8916 NewVD->setType(T);
8917 }
8918
8919 // Emit an error if an address space was applied to decl with local storage.
8920 // This includes arrays of objects with address space qualifiers, but not
8921 // automatic variables that point to other address spaces.
8922 // ISO/IEC TR 18037 S5.1.2
8923 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8924 T.getAddressSpace() != LangAS::Default) {
8925 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8926 NewVD->setInvalidDecl();
8927 return;
8928 }
8929
8930 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8931 // scope.
8932 if (getLangOpts().OpenCLVersion == 120 &&
8933 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8934 LO: getLangOpts()) &&
8935 NewVD->isStaticLocal()) {
8936 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8937 NewVD->setInvalidDecl();
8938 return;
8939 }
8940
8941 if (getLangOpts().OpenCL) {
8942 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8943 return;
8944
8945 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8946 if (NewVD->hasAttr<BlocksAttr>()) {
8947 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8948 return;
8949 }
8950
8951 if (T->isBlockPointerType()) {
8952 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8953 // can't use 'extern' storage class.
8954 if (!T.isConstQualified()) {
8955 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8956 << 0 /*const*/;
8957 NewVD->setInvalidDecl();
8958 return;
8959 }
8960 if (NewVD->hasExternalStorage()) {
8961 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8962 NewVD->setInvalidDecl();
8963 return;
8964 }
8965 }
8966
8967 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8968 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8969 NewVD->hasExternalStorage()) {
8970 if (!T->isSamplerT() && !T->isDependentType() &&
8971 !(T.getAddressSpace() == LangAS::opencl_constant ||
8972 (T.getAddressSpace() == LangAS::opencl_global &&
8973 getOpenCLOptions().areProgramScopeVariablesSupported(
8974 Opts: getLangOpts())))) {
8975 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8976 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8977 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8978 << Scope << "global or constant";
8979 else
8980 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8981 << Scope << "constant";
8982 NewVD->setInvalidDecl();
8983 return;
8984 }
8985 } else {
8986 if (T.getAddressSpace() == LangAS::opencl_global) {
8987 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8988 << 1 /*is any function*/ << "global";
8989 NewVD->setInvalidDecl();
8990 return;
8991 }
8992 // When this extension is enabled, 'local' variables are permitted in
8993 // non-kernel functions and within nested scopes of kernel functions,
8994 // bypassing standard OpenCL address space restrictions.
8995 bool AllowFunctionScopeLocalVariables =
8996 T.getAddressSpace() == LangAS::opencl_local &&
8997 getOpenCLOptions().isAvailableOption(
8998 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
8999 if (AllowFunctionScopeLocalVariables) {
9000 // Direct pass: No further diagnostics needed for this specific case.
9001 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9002 T.getAddressSpace() == LangAS::opencl_local) {
9003 FunctionDecl *FD = getCurFunctionDecl();
9004 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9005 // in functions.
9006 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9007 if (T.getAddressSpace() == LangAS::opencl_constant)
9008 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9009 << 0 /*non-kernel only*/ << "constant";
9010 else
9011 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9012 << 0 /*non-kernel only*/ << "local";
9013 NewVD->setInvalidDecl();
9014 return;
9015 }
9016 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9017 // in the outermost scope of a kernel function.
9018 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9019 if (!getCurScope()->isFunctionScope()) {
9020 if (T.getAddressSpace() == LangAS::opencl_constant)
9021 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9022 << "constant";
9023 else
9024 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9025 << "local";
9026 NewVD->setInvalidDecl();
9027 return;
9028 }
9029 }
9030 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9031 // If we are parsing a template we didn't deduce an addr
9032 // space yet.
9033 T.getAddressSpace() != LangAS::Default) {
9034 // Do not allow other address spaces on automatic variable.
9035 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9036 NewVD->setInvalidDecl();
9037 return;
9038 }
9039 }
9040 }
9041
9042 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9043 && !NewVD->hasAttr<BlocksAttr>()) {
9044 if (getLangOpts().getGC() != LangOptions::NonGC)
9045 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9046 else {
9047 assert(!getLangOpts().ObjCAutoRefCount);
9048 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9049 }
9050 }
9051
9052 // WebAssembly tables must be static with a zero length and can't be
9053 // declared within functions.
9054 if (T->isWebAssemblyTableType()) {
9055 if (getCurScope()->getParent()) { // Parent is null at top-level
9056 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9057 NewVD->setInvalidDecl();
9058 return;
9059 }
9060 if (NewVD->getStorageClass() != SC_Static) {
9061 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9062 NewVD->setInvalidDecl();
9063 return;
9064 }
9065 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9066 if (!ATy || ATy->getZExtSize() != 0) {
9067 Diag(Loc: NewVD->getLocation(),
9068 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9069 NewVD->setInvalidDecl();
9070 return;
9071 }
9072 }
9073
9074 // zero sized static arrays are not allowed in HIP device functions
9075 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9076 if (FunctionDecl *FD = getCurFunctionDecl();
9077 FD &&
9078 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9079 if (const ConstantArrayType *ArrayT =
9080 getASTContext().getAsConstantArrayType(T);
9081 ArrayT && ArrayT->isZeroSize()) {
9082 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9083 }
9084 }
9085 }
9086
9087 bool isVM = T->isVariablyModifiedType();
9088 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9089 NewVD->hasAttr<BlocksAttr>())
9090 setFunctionHasBranchProtectedScope();
9091
9092 if ((isVM && NewVD->hasLinkage()) ||
9093 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9094 bool SizeIsNegative;
9095 llvm::APSInt Oversized;
9096 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9097 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9098 QualType FixedT;
9099 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9100 FixedT = FixedTInfo->getType();
9101 else if (FixedTInfo) {
9102 // Type and type-as-written are canonically different. We need to fix up
9103 // both types separately.
9104 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9105 Oversized);
9106 }
9107 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9108 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9109 // FIXME: This won't give the correct result for
9110 // int a[10][n];
9111 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9112
9113 if (NewVD->isFileVarDecl())
9114 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9115 << SizeRange;
9116 else if (NewVD->isStaticLocal())
9117 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9118 << SizeRange;
9119 else
9120 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9121 << SizeRange;
9122 NewVD->setInvalidDecl();
9123 return;
9124 }
9125
9126 if (!FixedTInfo) {
9127 if (NewVD->isFileVarDecl())
9128 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9129 else
9130 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9131 NewVD->setInvalidDecl();
9132 return;
9133 }
9134
9135 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9136 NewVD->setType(FixedT);
9137 NewVD->setTypeSourceInfo(FixedTInfo);
9138 }
9139
9140 if (T->isVoidType()) {
9141 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9142 // of objects and functions.
9143 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9144 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9145 << T;
9146 NewVD->setInvalidDecl();
9147 return;
9148 }
9149 }
9150
9151 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9152 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal);
9153 NewVD->setInvalidDecl();
9154 return;
9155 }
9156
9157 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9158 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9159 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9160 NewVD->setInvalidDecl();
9161 return;
9162 }
9163
9164 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9165 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm);
9166 NewVD->setInvalidDecl();
9167 return;
9168 }
9169
9170 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9171 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9172 NewVD->setInvalidDecl();
9173 return;
9174 }
9175
9176 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9177 !T->isDependentType() &&
9178 RequireLiteralType(Loc: NewVD->getLocation(), T,
9179 DiagID: diag::err_constexpr_var_non_literal)) {
9180 NewVD->setInvalidDecl();
9181 return;
9182 }
9183
9184 // PPC MMA non-pointer types are not allowed as non-local variable types.
9185 if (Context.getTargetInfo().getTriple().isPPC64() &&
9186 !NewVD->isLocalVarDecl() &&
9187 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9188 NewVD->setInvalidDecl();
9189 return;
9190 }
9191
9192 // Check that SVE types are only used in functions with SVE available.
9193 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9194 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9195 llvm::StringMap<bool> CallerFeatureMap;
9196 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9197 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9198 FeatureMap: CallerFeatureMap)) {
9199 NewVD->setInvalidDecl();
9200 return;
9201 }
9202 }
9203
9204 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9205 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9206 llvm::StringMap<bool> CallerFeatureMap;
9207 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9208 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9209 FeatureMap: CallerFeatureMap);
9210 }
9211
9212 if (T.hasAddressSpace() &&
9213 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9214 NewVD->setInvalidDecl();
9215 return;
9216 }
9217}
9218
9219bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9220 CheckVariableDeclarationType(NewVD);
9221
9222 // If the decl is already known invalid, don't check it.
9223 if (NewVD->isInvalidDecl())
9224 return false;
9225
9226 // If we did not find anything by this name, look for a non-visible
9227 // extern "C" declaration with the same name.
9228 if (Previous.empty() &&
9229 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9230 Previous.setShadowed();
9231
9232 if (!Previous.empty()) {
9233 MergeVarDecl(New: NewVD, Previous);
9234 return true;
9235 }
9236 return false;
9237}
9238
9239bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9240 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9241
9242 // Look for methods in base classes that this method might override.
9243 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9244 /*DetectVirtual=*/false);
9245 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9246 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9247 DeclarationName Name = MD->getDeclName();
9248
9249 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9250 // We really want to find the base class destructor here.
9251 Name = Context.DeclarationNames.getCXXDestructorName(
9252 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9253 }
9254
9255 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9256 CXXMethodDecl *BaseMD =
9257 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9258 if (!BaseMD || !BaseMD->isVirtual() ||
9259 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9260 /*ConsiderCudaAttrs=*/true))
9261 continue;
9262 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9263 continue;
9264 if (Overridden.insert(Ptr: BaseMD).second) {
9265 MD->addOverriddenMethod(MD: BaseMD);
9266 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9267 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9268 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9269 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9270 }
9271
9272 // A method can only override one function from each base class. We
9273 // don't track indirectly overridden methods from bases of bases.
9274 return true;
9275 }
9276
9277 return false;
9278 };
9279
9280 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9281 return !Overridden.empty();
9282}
9283
9284namespace {
9285 // Struct for holding all of the extra arguments needed by
9286 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9287 struct ActOnFDArgs {
9288 Scope *S;
9289 Declarator &D;
9290 MultiTemplateParamsArg TemplateParamLists;
9291 bool AddToScope;
9292 };
9293} // end anonymous namespace
9294
9295namespace {
9296
9297// Callback to only accept typo corrections that have a non-zero edit distance.
9298// Also only accept corrections that have the same parent decl.
9299class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9300 public:
9301 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9302 CXXRecordDecl *Parent)
9303 : Context(Context), OriginalFD(TypoFD),
9304 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9305
9306 bool ValidateCandidate(const TypoCorrection &candidate) override {
9307 if (candidate.getEditDistance() == 0)
9308 return false;
9309
9310 SmallVector<unsigned, 1> MismatchedParams;
9311 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9312 CDeclEnd = candidate.end();
9313 CDecl != CDeclEnd; ++CDecl) {
9314 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9315
9316 if (FD && !FD->hasBody() &&
9317 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9318 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9319 CXXRecordDecl *Parent = MD->getParent();
9320 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9321 return true;
9322 } else if (!ExpectedParent) {
9323 return true;
9324 }
9325 }
9326 }
9327
9328 return false;
9329 }
9330
9331 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9332 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9333 }
9334
9335 private:
9336 ASTContext &Context;
9337 FunctionDecl *OriginalFD;
9338 CXXRecordDecl *ExpectedParent;
9339};
9340
9341} // end anonymous namespace
9342
9343void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9344 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9345}
9346
9347/// Generate diagnostics for an invalid function redeclaration.
9348///
9349/// This routine handles generating the diagnostic messages for an invalid
9350/// function redeclaration, including finding possible similar declarations
9351/// or performing typo correction if there are no previous declarations with
9352/// the same name.
9353///
9354/// Returns a NamedDecl iff typo correction was performed and substituting in
9355/// the new declaration name does not cause new errors.
9356static NamedDecl *DiagnoseInvalidRedeclaration(
9357 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9358 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9359 DeclarationName Name = NewFD->getDeclName();
9360 DeclContext *NewDC = NewFD->getDeclContext();
9361 SmallVector<unsigned, 1> MismatchedParams;
9362 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9363 TypoCorrection Correction;
9364 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9365 unsigned DiagMsg =
9366 IsLocalFriend ? diag::err_no_matching_local_friend :
9367 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9368 diag::err_member_decl_does_not_match;
9369 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9370 IsLocalFriend ? Sema::LookupLocalFriendName
9371 : Sema::LookupOrdinaryName,
9372 RedeclarationKind::ForVisibleRedeclaration);
9373
9374 NewFD->setInvalidDecl();
9375 if (IsLocalFriend)
9376 SemaRef.LookupName(R&: Prev, S);
9377 else
9378 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9379 assert(!Prev.isAmbiguous() &&
9380 "Cannot have an ambiguity in previous-declaration lookup");
9381 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9382 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9383 MD ? MD->getParent() : nullptr);
9384 if (!Prev.empty()) {
9385 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9386 Func != FuncEnd; ++Func) {
9387 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9388 if (FD &&
9389 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9390 // Add 1 to the index so that 0 can mean the mismatch didn't
9391 // involve a parameter
9392 unsigned ParamNum =
9393 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9394 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9395 }
9396 }
9397 // If the qualified name lookup yielded nothing, try typo correction
9398 } else if ((Correction = SemaRef.CorrectTypo(
9399 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9400 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9401 Mode: CorrectTypoKind::ErrorRecovery,
9402 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9403 // Set up everything for the call to ActOnFunctionDeclarator
9404 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9405 IdLoc: ExtraArgs.D.getIdentifierLoc());
9406 Previous.clear();
9407 Previous.setLookupName(Correction.getCorrection());
9408 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9409 CDeclEnd = Correction.end();
9410 CDecl != CDeclEnd; ++CDecl) {
9411 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9412 if (FD && !FD->hasBody() &&
9413 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9414 Previous.addDecl(D: FD);
9415 }
9416 }
9417 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9418
9419 NamedDecl *Result;
9420 // Retry building the function declaration with the new previous
9421 // declarations, and with errors suppressed.
9422 {
9423 // Trap errors.
9424 Sema::SFINAETrap Trap(SemaRef);
9425
9426 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9427 // pieces need to verify the typo-corrected C++ declaration and hopefully
9428 // eliminate the need for the parameter pack ExtraArgs.
9429 Result = SemaRef.ActOnFunctionDeclarator(
9430 S: ExtraArgs.S, D&: ExtraArgs.D,
9431 DC: Correction.getCorrectionDecl()->getDeclContext(),
9432 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9433 AddToScope&: ExtraArgs.AddToScope);
9434
9435 if (Trap.hasErrorOccurred())
9436 Result = nullptr;
9437 }
9438
9439 if (Result) {
9440 // Determine which correction we picked.
9441 Decl *Canonical = Result->getCanonicalDecl();
9442 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9443 I != E; ++I)
9444 if ((*I)->getCanonicalDecl() == Canonical)
9445 Correction.setCorrectionDecl(*I);
9446
9447 // Let Sema know about the correction.
9448 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9449 SemaRef.diagnoseTypo(
9450 Correction,
9451 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9452 ? diag::err_no_matching_local_friend_suggest
9453 : diag::err_member_decl_does_not_match_suggest)
9454 << Name << NewDC << IsDefinition);
9455 return Result;
9456 }
9457
9458 // Pretend the typo correction never occurred
9459 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9460 IdLoc: ExtraArgs.D.getIdentifierLoc());
9461 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9462 Previous.clear();
9463 Previous.setLookupName(Name);
9464 }
9465
9466 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9467 << Name << NewDC << IsDefinition << NewFD->getLocation();
9468
9469 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9470 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9471 CXXRecordDecl *RD = NewMD->getParent();
9472 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9473 << RD->getName() << RD->getLocation();
9474 }
9475
9476 bool NewFDisConst = NewMD && NewMD->isConst();
9477
9478 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9479 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9480 NearMatch != NearMatchEnd; ++NearMatch) {
9481 FunctionDecl *FD = NearMatch->first;
9482 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9483 bool FDisConst = MD && MD->isConst();
9484 bool IsMember = MD || !IsLocalFriend;
9485
9486 // FIXME: These notes are poorly worded for the local friend case.
9487 if (unsigned Idx = NearMatch->second) {
9488 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9489 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9490 if (Loc.isInvalid()) Loc = FD->getLocation();
9491 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9492 : diag::note_local_decl_close_param_match)
9493 << Idx << FDParam->getType()
9494 << NewFD->getParamDecl(i: Idx - 1)->getType();
9495 } else if (FDisConst != NewFDisConst) {
9496 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9497 DiagID: diag::note_member_def_close_const_match)
9498 << NewFDisConst << FD->getSourceRange().getEnd();
9499 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9500 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9501 Code: " const");
9502 else if (FTI.hasMethodTypeQualifiers() &&
9503 FTI.getConstQualifierLoc().isValid())
9504 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9505 } else {
9506 SemaRef.Diag(Loc: FD->getLocation(),
9507 DiagID: IsMember ? diag::note_member_def_close_match
9508 : diag::note_local_decl_close_match);
9509 }
9510 }
9511 return nullptr;
9512}
9513
9514static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9515 switch (D.getDeclSpec().getStorageClassSpec()) {
9516 default: llvm_unreachable("Unknown storage class!");
9517 case DeclSpec::SCS_auto:
9518 case DeclSpec::SCS_register:
9519 case DeclSpec::SCS_mutable:
9520 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9521 DiagID: diag::err_typecheck_sclass_func);
9522 D.getMutableDeclSpec().ClearStorageClassSpecs();
9523 D.setInvalidType();
9524 break;
9525 case DeclSpec::SCS_unspecified: break;
9526 case DeclSpec::SCS_extern:
9527 if (D.getDeclSpec().isExternInLinkageSpec())
9528 return SC_None;
9529 return SC_Extern;
9530 case DeclSpec::SCS_static: {
9531 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9532 // C99 6.7.1p5:
9533 // The declaration of an identifier for a function that has
9534 // block scope shall have no explicit storage-class specifier
9535 // other than extern
9536 // See also (C++ [dcl.stc]p4).
9537 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9538 DiagID: diag::err_static_block_func);
9539 break;
9540 } else
9541 return SC_Static;
9542 }
9543 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9544 }
9545
9546 // No explicit storage class has already been returned
9547 return SC_None;
9548}
9549
9550static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9551 DeclContext *DC, QualType &R,
9552 TypeSourceInfo *TInfo,
9553 StorageClass SC,
9554 bool &IsVirtualOkay) {
9555 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9556 DeclarationName Name = NameInfo.getName();
9557
9558 FunctionDecl *NewFD = nullptr;
9559 bool isInline = D.getDeclSpec().isInlineSpecified();
9560
9561 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9562 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9563 (SemaRef.getLangOpts().C23 &&
9564 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9565
9566 if (SemaRef.getLangOpts().C23)
9567 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9568 DiagID: diag::err_c23_constexpr_not_variable);
9569 else
9570 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9571 DiagID: diag::err_constexpr_wrong_decl_kind)
9572 << static_cast<int>(ConstexprKind);
9573 ConstexprKind = ConstexprSpecKind::Unspecified;
9574 D.getMutableDeclSpec().ClearConstexprSpec();
9575 }
9576
9577 if (!SemaRef.getLangOpts().CPlusPlus) {
9578 // Determine whether the function was written with a prototype. This is
9579 // true when:
9580 // - there is a prototype in the declarator, or
9581 // - the type R of the function is some kind of typedef or other non-
9582 // attributed reference to a type name (which eventually refers to a
9583 // function type). Note, we can't always look at the adjusted type to
9584 // check this case because attributes may cause a non-function
9585 // declarator to still have a function type. e.g.,
9586 // typedef void func(int a);
9587 // __attribute__((noreturn)) func other_func; // This has a prototype
9588 bool HasPrototype =
9589 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9590 (D.getDeclSpec().isTypeRep() &&
9591 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9592 ->isFunctionProtoType()) ||
9593 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9594 assert(
9595 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9596 "Strict prototypes are required");
9597
9598 NewFD = FunctionDecl::Create(
9599 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9600 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9601 ConstexprKind: ConstexprSpecKind::Unspecified,
9602 /*TrailingRequiresClause=*/{});
9603 if (D.isInvalidType())
9604 NewFD->setInvalidDecl();
9605
9606 return NewFD;
9607 }
9608
9609 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9610 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9611
9612 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9613
9614 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9615 // This is a C++ constructor declaration.
9616 assert(DC->isRecord() &&
9617 "Constructors can only be declared in a member context");
9618
9619 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9620 return CXXConstructorDecl::Create(
9621 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9622 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9623 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9624 Inherited: InheritedConstructor(), TrailingRequiresClause);
9625
9626 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9627 // This is a C++ destructor declaration.
9628 if (DC->isRecord()) {
9629 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9630 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9631 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9632 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9633 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9634 /*isImplicitlyDeclared=*/false, ConstexprKind,
9635 TrailingRequiresClause);
9636 // User defined destructors start as not selected if the class definition is still
9637 // not done.
9638 if (Record->isBeingDefined())
9639 NewDD->setIneligibleOrNotSelected(true);
9640
9641 // If the destructor needs an implicit exception specification, set it
9642 // now. FIXME: It'd be nice to be able to create the right type to start
9643 // with, but the type needs to reference the destructor declaration.
9644 if (SemaRef.getLangOpts().CPlusPlus11)
9645 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9646
9647 IsVirtualOkay = true;
9648 return NewDD;
9649
9650 } else {
9651 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9652 D.setInvalidType();
9653
9654 // Create a FunctionDecl to satisfy the function definition parsing
9655 // code path.
9656 return FunctionDecl::Create(
9657 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9658 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9659 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9660 }
9661
9662 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9663 if (!DC->isRecord()) {
9664 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9665 DiagID: diag::err_conv_function_not_member);
9666 return nullptr;
9667 }
9668
9669 SemaRef.CheckConversionDeclarator(D, R, SC);
9670 if (D.isInvalidType())
9671 return nullptr;
9672
9673 IsVirtualOkay = true;
9674 return CXXConversionDecl::Create(
9675 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9676 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9677 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9678 TrailingRequiresClause);
9679
9680 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9681 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9682 return nullptr;
9683 return CXXDeductionGuideDecl::Create(
9684 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9685 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9686 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9687 } else if (DC->isRecord()) {
9688 // If the name of the function is the same as the name of the record,
9689 // then this must be an invalid constructor that has a return type.
9690 // (The parser checks for a return type and makes the declarator a
9691 // constructor if it has no return type).
9692 if (Name.getAsIdentifierInfo() &&
9693 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9694 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9695 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9696 << SourceRange(D.getIdentifierLoc());
9697 return nullptr;
9698 }
9699
9700 // This is a C++ method declaration.
9701 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9702 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9703 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9704 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9705 IsVirtualOkay = !Ret->isStatic();
9706 return Ret;
9707 } else {
9708 bool isFriend =
9709 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9710 if (!isFriend && SemaRef.CurContext->isRecord())
9711 return nullptr;
9712
9713 // Determine whether the function was written with a
9714 // prototype. This true when:
9715 // - we're in C++ (where every function has a prototype),
9716 return FunctionDecl::Create(
9717 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9718 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9719 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9720 }
9721}
9722
9723enum OpenCLParamType {
9724 ValidKernelParam,
9725 PtrPtrKernelParam,
9726 PtrKernelParam,
9727 InvalidAddrSpacePtrKernelParam,
9728 InvalidKernelParam,
9729 RecordKernelParam
9730};
9731
9732static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9733 // Size dependent types are just typedefs to normal integer types
9734 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9735 // integers other than by their names.
9736 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9737
9738 // Remove typedefs one by one until we reach a typedef
9739 // for a size dependent type.
9740 QualType DesugaredTy = Ty;
9741 do {
9742 ArrayRef<StringRef> Names(SizeTypeNames);
9743 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9744 if (Names.end() != Match)
9745 return true;
9746
9747 Ty = DesugaredTy;
9748 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9749 } while (DesugaredTy != Ty);
9750
9751 return false;
9752}
9753
9754static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9755 if (PT->isDependentType())
9756 return InvalidKernelParam;
9757
9758 if (PT->isPointerOrReferenceType()) {
9759 QualType PointeeType = PT->getPointeeType();
9760 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9761 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9762 PointeeType.getAddressSpace() == LangAS::Default)
9763 return InvalidAddrSpacePtrKernelParam;
9764
9765 if (PointeeType->isPointerType()) {
9766 // This is a pointer to pointer parameter.
9767 // Recursively check inner type.
9768 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9769 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9770 ParamKind == InvalidKernelParam)
9771 return ParamKind;
9772
9773 // OpenCL v3.0 s6.11.a:
9774 // A restriction to pass pointers to pointers only applies to OpenCL C
9775 // v1.2 or below.
9776 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9777 return ValidKernelParam;
9778
9779 return PtrPtrKernelParam;
9780 }
9781
9782 // C++ for OpenCL v1.0 s2.4:
9783 // Moreover the types used in parameters of the kernel functions must be:
9784 // Standard layout types for pointer parameters. The same applies to
9785 // reference if an implementation supports them in kernel parameters.
9786 if (S.getLangOpts().OpenCLCPlusPlus &&
9787 !S.getOpenCLOptions().isAvailableOption(
9788 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9789 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9790 bool IsStandardLayoutType = true;
9791 if (CXXRec) {
9792 // If template type is not ODR-used its definition is only available
9793 // in the template definition not its instantiation.
9794 // FIXME: This logic doesn't work for types that depend on template
9795 // parameter (PR58590).
9796 if (!CXXRec->hasDefinition())
9797 CXXRec = CXXRec->getTemplateInstantiationPattern();
9798 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9799 IsStandardLayoutType = false;
9800 }
9801 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9802 !IsStandardLayoutType)
9803 return InvalidKernelParam;
9804 }
9805
9806 // OpenCL v1.2 s6.9.p:
9807 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9808 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9809 return ValidKernelParam;
9810
9811 return PtrKernelParam;
9812 }
9813
9814 // OpenCL v1.2 s6.9.k:
9815 // Arguments to kernel functions in a program cannot be declared with the
9816 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9817 // uintptr_t or a struct and/or union that contain fields declared to be one
9818 // of these built-in scalar types.
9819 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9820 return InvalidKernelParam;
9821
9822 if (PT->isImageType())
9823 return PtrKernelParam;
9824
9825 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9826 return InvalidKernelParam;
9827
9828 // OpenCL extension spec v1.2 s9.5:
9829 // This extension adds support for half scalar and vector types as built-in
9830 // types that can be used for arithmetic operations, conversions etc.
9831 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9832 PT->isHalfType())
9833 return InvalidKernelParam;
9834
9835 // Look into an array argument to check if it has a forbidden type.
9836 if (PT->isArrayType()) {
9837 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9838 // Call ourself to check an underlying type of an array. Since the
9839 // getPointeeOrArrayElementType returns an innermost type which is not an
9840 // array, this recursive call only happens once.
9841 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9842 }
9843
9844 // C++ for OpenCL v1.0 s2.4:
9845 // Moreover the types used in parameters of the kernel functions must be:
9846 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9847 // types) for parameters passed by value;
9848 if (S.getLangOpts().OpenCLCPlusPlus &&
9849 !S.getOpenCLOptions().isAvailableOption(
9850 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9851 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9852 return InvalidKernelParam;
9853
9854 if (PT->isRecordType())
9855 return RecordKernelParam;
9856
9857 return ValidKernelParam;
9858}
9859
9860static void checkIsValidOpenCLKernelParameter(
9861 Sema &S,
9862 Declarator &D,
9863 ParmVarDecl *Param,
9864 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9865 QualType PT = Param->getType();
9866
9867 // Cache the valid types we encounter to avoid rechecking structs that are
9868 // used again
9869 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9870 return;
9871
9872 switch (getOpenCLKernelParameterType(S, PT)) {
9873 case PtrPtrKernelParam:
9874 // OpenCL v3.0 s6.11.a:
9875 // A kernel function argument cannot be declared as a pointer to a pointer
9876 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9877 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9878 D.setInvalidType();
9879 return;
9880
9881 case InvalidAddrSpacePtrKernelParam:
9882 // OpenCL v1.0 s6.5:
9883 // __kernel function arguments declared to be a pointer of a type can point
9884 // to one of the following address spaces only : __global, __local or
9885 // __constant.
9886 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9887 D.setInvalidType();
9888 return;
9889
9890 // OpenCL v1.2 s6.9.k:
9891 // Arguments to kernel functions in a program cannot be declared with the
9892 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9893 // uintptr_t or a struct and/or union that contain fields declared to be
9894 // one of these built-in scalar types.
9895
9896 case InvalidKernelParam:
9897 // OpenCL v1.2 s6.8 n:
9898 // A kernel function argument cannot be declared
9899 // of event_t type.
9900 // Do not diagnose half type since it is diagnosed as invalid argument
9901 // type for any function elsewhere.
9902 if (!PT->isHalfType()) {
9903 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9904
9905 // Explain what typedefs are involved.
9906 const TypedefType *Typedef = nullptr;
9907 while ((Typedef = PT->getAs<TypedefType>())) {
9908 SourceLocation Loc = Typedef->getDecl()->getLocation();
9909 // SourceLocation may be invalid for a built-in type.
9910 if (Loc.isValid())
9911 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9912 PT = Typedef->desugar();
9913 }
9914 }
9915
9916 D.setInvalidType();
9917 return;
9918
9919 case PtrKernelParam:
9920 case ValidKernelParam:
9921 ValidTypes.insert(Ptr: PT.getTypePtr());
9922 return;
9923
9924 case RecordKernelParam:
9925 break;
9926 }
9927
9928 // Track nested structs we will inspect
9929 SmallVector<const Decl *, 4> VisitStack;
9930
9931 // Track where we are in the nested structs. Items will migrate from
9932 // VisitStack to HistoryStack as we do the DFS for bad field.
9933 SmallVector<const FieldDecl *, 4> HistoryStack;
9934 HistoryStack.push_back(Elt: nullptr);
9935
9936 // At this point we already handled everything except of a RecordType.
9937 assert(PT->isRecordType() && "Unexpected type.");
9938 const auto *PD = PT->castAsRecordDecl();
9939 VisitStack.push_back(Elt: PD);
9940 assert(VisitStack.back() && "First decl null?");
9941
9942 do {
9943 const Decl *Next = VisitStack.pop_back_val();
9944 if (!Next) {
9945 assert(!HistoryStack.empty());
9946 // Found a marker, we have gone up a level
9947 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9948 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9949
9950 continue;
9951 }
9952
9953 // Adds everything except the original parameter declaration (which is not a
9954 // field itself) to the history stack.
9955 const RecordDecl *RD;
9956 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9957 HistoryStack.push_back(Elt: Field);
9958
9959 QualType FieldTy = Field->getType();
9960 // Other field types (known to be valid or invalid) are handled while we
9961 // walk around RecordDecl::fields().
9962 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9963 "Unexpected type.");
9964 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9965
9966 RD = FieldRecTy->castAsRecordDecl();
9967 } else {
9968 RD = cast<RecordDecl>(Val: Next);
9969 }
9970
9971 // Add a null marker so we know when we've gone back up a level
9972 VisitStack.push_back(Elt: nullptr);
9973
9974 for (const auto *FD : RD->fields()) {
9975 QualType QT = FD->getType();
9976
9977 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9978 continue;
9979
9980 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9981 if (ParamType == ValidKernelParam)
9982 continue;
9983
9984 if (ParamType == RecordKernelParam) {
9985 VisitStack.push_back(Elt: FD);
9986 continue;
9987 }
9988
9989 // OpenCL v1.2 s6.9.p:
9990 // Arguments to kernel functions that are declared to be a struct or union
9991 // do not allow OpenCL objects to be passed as elements of the struct or
9992 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9993 // of SVM.
9994 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9995 ParamType == InvalidAddrSpacePtrKernelParam) {
9996 S.Diag(Loc: Param->getLocation(),
9997 DiagID: diag::err_record_with_pointers_kernel_param)
9998 << PT->isUnionType()
9999 << PT;
10000 } else {
10001 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10002 }
10003
10004 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10005 << PD->getDeclName();
10006
10007 // We have an error, now let's go back up through history and show where
10008 // the offending field came from
10009 for (ArrayRef<const FieldDecl *>::const_iterator
10010 I = HistoryStack.begin() + 1,
10011 E = HistoryStack.end();
10012 I != E; ++I) {
10013 const FieldDecl *OuterField = *I;
10014 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10015 << OuterField->getType();
10016 }
10017
10018 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10019 << QT->isPointerType()
10020 << QT;
10021 D.setInvalidType();
10022 return;
10023 }
10024 } while (!VisitStack.empty());
10025}
10026
10027/// Find the DeclContext in which a tag is implicitly declared if we see an
10028/// elaborated type specifier in the specified context, and lookup finds
10029/// nothing.
10030static DeclContext *getTagInjectionContext(DeclContext *DC) {
10031 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10032 DC = DC->getParent();
10033 return DC;
10034}
10035
10036/// Find the Scope in which a tag is implicitly declared if we see an
10037/// elaborated type specifier in the specified context, and lookup finds
10038/// nothing.
10039static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10040 while (S->isClassScope() ||
10041 (LangOpts.CPlusPlus &&
10042 S->isFunctionPrototypeScope()) ||
10043 ((S->getFlags() & Scope::DeclScope) == 0) ||
10044 (S->getEntity() && S->getEntity()->isTransparentContext()))
10045 S = S->getParent();
10046 return S;
10047}
10048
10049/// Determine whether a declaration matches a known function in namespace std.
10050static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10051 unsigned BuiltinID) {
10052 switch (BuiltinID) {
10053 case Builtin::BI__GetExceptionInfo:
10054 // No type checking whatsoever.
10055 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10056
10057 case Builtin::BIaddressof:
10058 case Builtin::BI__addressof:
10059 case Builtin::BIforward:
10060 case Builtin::BIforward_like:
10061 case Builtin::BImove:
10062 case Builtin::BImove_if_noexcept:
10063 case Builtin::BIas_const: {
10064 // Ensure that we don't treat the algorithm
10065 // OutputIt std::move(InputIt, InputIt, OutputIt)
10066 // as the builtin std::move.
10067 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10068 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10069 }
10070
10071 default:
10072 return false;
10073 }
10074}
10075
10076NamedDecl*
10077Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10078 TypeSourceInfo *TInfo, LookupResult &Previous,
10079 MultiTemplateParamsArg TemplateParamListsRef,
10080 bool &AddToScope) {
10081 QualType R = TInfo->getType();
10082
10083 assert(R->isFunctionType());
10084 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10085 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10086
10087 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10088 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10089 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10090 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10091 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10092 TemplateParamLists.back() = Invented;
10093 else
10094 TemplateParamLists.push_back(Elt: Invented);
10095 }
10096
10097 // TODO: consider using NameInfo for diagnostic.
10098 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10099 DeclarationName Name = NameInfo.getName();
10100 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10101
10102 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10103 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10104 DiagID: diag::err_invalid_thread)
10105 << DeclSpec::getSpecifierName(S: TSCS);
10106
10107 if (D.isFirstDeclarationOfMember())
10108 adjustMemberFunctionCC(
10109 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10110 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10111
10112 bool isFriend = false;
10113 FunctionTemplateDecl *FunctionTemplate = nullptr;
10114 bool isMemberSpecialization = false;
10115 bool isFunctionTemplateSpecialization = false;
10116
10117 bool HasExplicitTemplateArgs = false;
10118 TemplateArgumentListInfo TemplateArgs;
10119
10120 bool isVirtualOkay = false;
10121
10122 DeclContext *OriginalDC = DC;
10123 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10124
10125 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10126 IsVirtualOkay&: isVirtualOkay);
10127 if (!NewFD) return nullptr;
10128
10129 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10130 NewFD->setTopLevelDeclInObjCContainer();
10131
10132 // Set the lexical context. If this is a function-scope declaration, or has a
10133 // C++ scope specifier, or is the object of a friend declaration, the lexical
10134 // context will be different from the semantic context.
10135 NewFD->setLexicalDeclContext(CurContext);
10136
10137 if (IsLocalExternDecl)
10138 NewFD->setLocalExternDecl();
10139
10140 if (getLangOpts().CPlusPlus) {
10141 // The rules for implicit inlines changed in C++20 for methods and friends
10142 // with an in-class definition (when such a definition is not attached to
10143 // the global module). This does not affect declarations that are already
10144 // inline (whether explicitly or implicitly by being declared constexpr,
10145 // consteval, etc).
10146 // FIXME: We need a better way to separate C++ standard and clang modules.
10147 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10148 !NewFD->getOwningModule() ||
10149 NewFD->isFromGlobalModule() ||
10150 NewFD->getOwningModule()->isHeaderLikeModule();
10151 bool isInline = D.getDeclSpec().isInlineSpecified();
10152 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10153 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10154 isFriend = D.getDeclSpec().isFriendSpecified();
10155 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10156 // Pre-C++20 [class.friend]p5
10157 // A function can be defined in a friend declaration of a
10158 // class . . . . Such a function is implicitly inline.
10159 // Post C++20 [class.friend]p7
10160 // Such a function is implicitly an inline function if it is attached
10161 // to the global module.
10162 NewFD->setImplicitlyInline();
10163 }
10164
10165 // If this is a method defined in an __interface, and is not a constructor
10166 // or an overloaded operator, then set the pure flag (isVirtual will already
10167 // return true).
10168 if (const CXXRecordDecl *Parent =
10169 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10170 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10171 NewFD->setIsPureVirtual(true);
10172
10173 // C++ [class.union]p2
10174 // A union can have member functions, but not virtual functions.
10175 if (isVirtual && Parent->isUnion()) {
10176 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10177 NewFD->setInvalidDecl();
10178 }
10179 if ((Parent->isClass() || Parent->isStruct()) &&
10180 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10181 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10182 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10183 if (auto *Def = Parent->getDefinition())
10184 Def->setInitMethod(true);
10185 }
10186 }
10187
10188 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10189 isMemberSpecialization = false;
10190 isFunctionTemplateSpecialization = false;
10191 if (D.isInvalidType())
10192 NewFD->setInvalidDecl();
10193
10194 // Match up the template parameter lists with the scope specifier, then
10195 // determine whether we have a template or a template specialization.
10196 bool Invalid = false;
10197 TemplateIdAnnotation *TemplateId =
10198 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10199 ? D.getName().TemplateId
10200 : nullptr;
10201 TemplateParameterList *TemplateParams =
10202 MatchTemplateParametersToScopeSpecifier(
10203 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10204 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10205 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10206 if (TemplateParams) {
10207 // Check that we can declare a template here.
10208 if (CheckTemplateDeclScope(S, TemplateParams))
10209 NewFD->setInvalidDecl();
10210
10211 if (TemplateParams->size() > 0) {
10212 // This is a function template
10213
10214 // A destructor cannot be a template.
10215 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10216 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10217 NewFD->setInvalidDecl();
10218 // Function template with explicit template arguments.
10219 } else if (TemplateId) {
10220 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10221 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10222 NewFD->setInvalidDecl();
10223 }
10224
10225 // If we're adding a template to a dependent context, we may need to
10226 // rebuilding some of the types used within the template parameter list,
10227 // now that we know what the current instantiation is.
10228 if (DC->isDependentContext()) {
10229 ContextRAII SavedContext(*this, DC);
10230 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10231 Invalid = true;
10232 }
10233
10234 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10235 L: NewFD->getLocation(),
10236 Name, Params: TemplateParams,
10237 Decl: NewFD);
10238 FunctionTemplate->setLexicalDeclContext(CurContext);
10239 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10240
10241 // For source fidelity, store the other template param lists.
10242 if (TemplateParamLists.size() > 1) {
10243 NewFD->setTemplateParameterListsInfo(Context,
10244 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10245 .drop_back(N: 1));
10246 }
10247 } else {
10248 // This is a function template specialization.
10249 isFunctionTemplateSpecialization = true;
10250 // For source fidelity, store all the template param lists.
10251 if (TemplateParamLists.size() > 0)
10252 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10253
10254 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10255 if (isFriend) {
10256 // We want to remove the "template<>", found here.
10257 SourceRange RemoveRange = TemplateParams->getSourceRange();
10258
10259 // If we remove the template<> and the name is not a
10260 // template-id, we're actually silently creating a problem:
10261 // the friend declaration will refer to an untemplated decl,
10262 // and clearly the user wants a template specialization. So
10263 // we need to insert '<>' after the name.
10264 SourceLocation InsertLoc;
10265 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10266 InsertLoc = D.getName().getSourceRange().getEnd();
10267 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10268 }
10269
10270 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10271 << Name << RemoveRange
10272 << FixItHint::CreateRemoval(RemoveRange)
10273 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10274 Invalid = true;
10275
10276 // Recover by faking up an empty template argument list.
10277 HasExplicitTemplateArgs = true;
10278 TemplateArgs.setLAngleLoc(InsertLoc);
10279 TemplateArgs.setRAngleLoc(InsertLoc);
10280 }
10281 }
10282 } else {
10283 // Check that we can declare a template here.
10284 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10285 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10286 NewFD->setInvalidDecl();
10287
10288 // All template param lists were matched against the scope specifier:
10289 // this is NOT (an explicit specialization of) a template.
10290 if (TemplateParamLists.size() > 0)
10291 // For source fidelity, store all the template param lists.
10292 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10293
10294 // "friend void foo<>(int);" is an implicit specialization decl.
10295 if (isFriend && TemplateId)
10296 isFunctionTemplateSpecialization = true;
10297 }
10298
10299 // If this is a function template specialization and the unqualified-id of
10300 // the declarator-id is a template-id, convert the template argument list
10301 // into our AST format and check for unexpanded packs.
10302 if (isFunctionTemplateSpecialization && TemplateId) {
10303 HasExplicitTemplateArgs = true;
10304
10305 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10306 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10307 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10308 TemplateId->NumArgs);
10309 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10310
10311 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10312 // declaration of a function template partial specialization? Should we
10313 // consider the unexpanded pack context to be a partial specialization?
10314 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10315 if (DiagnoseUnexpandedParameterPack(
10316 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10317 : UPPC_ExplicitSpecialization))
10318 NewFD->setInvalidDecl();
10319 }
10320 }
10321
10322 if (Invalid) {
10323 NewFD->setInvalidDecl();
10324 if (FunctionTemplate)
10325 FunctionTemplate->setInvalidDecl();
10326 }
10327
10328 // C++ [dcl.fct.spec]p5:
10329 // The virtual specifier shall only be used in declarations of
10330 // nonstatic class member functions that appear within a
10331 // member-specification of a class declaration; see 10.3.
10332 //
10333 if (isVirtual && !NewFD->isInvalidDecl()) {
10334 if (!isVirtualOkay) {
10335 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10336 DiagID: diag::err_virtual_non_function);
10337 } else if (!CurContext->isRecord()) {
10338 // 'virtual' was specified outside of the class.
10339 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10340 DiagID: diag::err_virtual_out_of_class)
10341 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10342 } else if (NewFD->getDescribedFunctionTemplate()) {
10343 // C++ [temp.mem]p3:
10344 // A member function template shall not be virtual.
10345 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10346 DiagID: diag::err_virtual_member_function_template)
10347 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10348 } else {
10349 // Okay: Add virtual to the method.
10350 NewFD->setVirtualAsWritten(true);
10351 }
10352
10353 if (getLangOpts().CPlusPlus14 &&
10354 NewFD->getReturnType()->isUndeducedType())
10355 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10356 }
10357
10358 // C++ [dcl.fct.spec]p3:
10359 // The inline specifier shall not appear on a block scope function
10360 // declaration.
10361 if (isInline && !NewFD->isInvalidDecl()) {
10362 if (CurContext->isFunctionOrMethod()) {
10363 // 'inline' is not allowed on block scope function declaration.
10364 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10365 DiagID: diag::err_inline_declaration_block_scope) << Name
10366 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10367 }
10368 }
10369
10370 // C++ [dcl.fct.spec]p6:
10371 // The explicit specifier shall be used only in the declaration of a
10372 // constructor or conversion function within its class definition;
10373 // see 12.3.1 and 12.3.2.
10374 if (hasExplicit && !NewFD->isInvalidDecl() &&
10375 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10376 if (!CurContext->isRecord()) {
10377 // 'explicit' was specified outside of the class.
10378 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10379 DiagID: diag::err_explicit_out_of_class)
10380 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10381 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10382 !isa<CXXConversionDecl>(Val: NewFD)) {
10383 // 'explicit' was specified on a function that wasn't a constructor
10384 // or conversion function.
10385 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10386 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10387 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10388 }
10389 }
10390
10391 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10392 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10393 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10394 // are implicitly inline.
10395 NewFD->setImplicitlyInline();
10396
10397 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10398 // be either constructors or to return a literal type. Therefore,
10399 // destructors cannot be declared constexpr.
10400 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10401 (!getLangOpts().CPlusPlus20 ||
10402 ConstexprKind == ConstexprSpecKind::Consteval)) {
10403 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10404 << static_cast<int>(ConstexprKind);
10405 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10406 ? ConstexprSpecKind::Unspecified
10407 : ConstexprSpecKind::Constexpr);
10408 }
10409 // C++20 [dcl.constexpr]p2: An allocation function, or a
10410 // deallocation function shall not be declared with the consteval
10411 // specifier.
10412 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10413 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10414 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10415 DiagID: diag::err_invalid_consteval_decl_kind)
10416 << NewFD;
10417 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10418 }
10419 }
10420
10421 // If __module_private__ was specified, mark the function accordingly.
10422 if (D.getDeclSpec().isModulePrivateSpecified()) {
10423 if (isFunctionTemplateSpecialization) {
10424 SourceLocation ModulePrivateLoc
10425 = D.getDeclSpec().getModulePrivateSpecLoc();
10426 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10427 << 0
10428 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10429 } else {
10430 NewFD->setModulePrivate();
10431 if (FunctionTemplate)
10432 FunctionTemplate->setModulePrivate();
10433 }
10434 }
10435
10436 if (isFriend) {
10437 if (FunctionTemplate) {
10438 FunctionTemplate->setObjectOfFriendDecl();
10439 FunctionTemplate->setAccess(AS_public);
10440 }
10441 NewFD->setObjectOfFriendDecl();
10442 NewFD->setAccess(AS_public);
10443 }
10444
10445 // If a function is defined as defaulted or deleted, mark it as such now.
10446 // We'll do the relevant checks on defaulted / deleted functions later.
10447 switch (D.getFunctionDefinitionKind()) {
10448 case FunctionDefinitionKind::Declaration:
10449 case FunctionDefinitionKind::Definition:
10450 break;
10451
10452 case FunctionDefinitionKind::Defaulted:
10453 NewFD->setDefaulted();
10454 break;
10455
10456 case FunctionDefinitionKind::Deleted:
10457 NewFD->setDeletedAsWritten();
10458 break;
10459 }
10460
10461 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10462 D.isFunctionDefinition()) {
10463 // Pre C++20 [class.mfct]p2:
10464 // A member function may be defined (8.4) in its class definition, in
10465 // which case it is an inline member function (7.1.2)
10466 // Post C++20 [class.mfct]p1:
10467 // If a member function is attached to the global module and is defined
10468 // in its class definition, it is inline.
10469 NewFD->setImplicitlyInline();
10470 }
10471
10472 if (!isFriend && SC != SC_None) {
10473 // C++ [temp.expl.spec]p2:
10474 // The declaration in an explicit-specialization shall not be an
10475 // export-declaration. An explicit specialization shall not use a
10476 // storage-class-specifier other than thread_local.
10477 //
10478 // We diagnose friend declarations with storage-class-specifiers
10479 // elsewhere.
10480 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10481 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10482 DiagID: diag::ext_explicit_specialization_storage_class)
10483 << FixItHint::CreateRemoval(
10484 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10485 }
10486
10487 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10488 assert(isa<CXXMethodDecl>(NewFD) &&
10489 "Out-of-line member function should be a CXXMethodDecl");
10490 // C++ [class.static]p1:
10491 // A data or function member of a class may be declared static
10492 // in a class definition, in which case it is a static member of
10493 // the class.
10494
10495 // Complain about the 'static' specifier if it's on an out-of-line
10496 // member function definition.
10497
10498 // MSVC permits the use of a 'static' storage specifier on an
10499 // out-of-line member function template declaration and class member
10500 // template declaration (MSVC versions before 2015), warn about this.
10501 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10502 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10503 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10504 (getLangOpts().MSVCCompat &&
10505 NewFD->getDescribedFunctionTemplate()))
10506 ? diag::ext_static_out_of_line
10507 : diag::err_static_out_of_line)
10508 << FixItHint::CreateRemoval(
10509 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10510 }
10511 }
10512
10513 // C++11 [except.spec]p15:
10514 // A deallocation function with no exception-specification is treated
10515 // as if it were specified with noexcept(true).
10516 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10517 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10518 !FPT->hasExceptionSpec())
10519 NewFD->setType(Context.getFunctionType(
10520 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10521 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10522
10523 // C++20 [dcl.inline]/7
10524 // If an inline function or variable that is attached to a named module
10525 // is declared in a definition domain, it shall be defined in that
10526 // domain.
10527 // So, if the current declaration does not have a definition, we must
10528 // check at the end of the TU (or when the PMF starts) to see that we
10529 // have a definition at that point.
10530 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10531 NewFD->isInNamedModule()) {
10532 PendingInlineFuncDecls.insert(Ptr: NewFD);
10533 }
10534 }
10535
10536 // Filter out previous declarations that don't match the scope.
10537 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10538 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10539 isMemberSpecialization ||
10540 isFunctionTemplateSpecialization);
10541
10542 // Handle GNU asm-label extension (encoded as an attribute).
10543 if (Expr *E = D.getAsmLabel()) {
10544 // The parser guarantees this is a string.
10545 StringLiteral *SE = cast<StringLiteral>(Val: E);
10546 NewFD->addAttr(
10547 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10548 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10549 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10550 ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier());
10551 if (I != ExtnameUndeclaredIdentifiers.end()) {
10552 if (isDeclExternC(D: NewFD)) {
10553 NewFD->addAttr(A: I->second);
10554 ExtnameUndeclaredIdentifiers.erase(I);
10555 } else
10556 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10557 << /*Variable*/0 << NewFD;
10558 }
10559 }
10560
10561 // Copy the parameter declarations from the declarator D to the function
10562 // declaration NewFD, if they are available. First scavenge them into Params.
10563 SmallVector<ParmVarDecl*, 16> Params;
10564 unsigned FTIIdx;
10565 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10566 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10567
10568 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10569 // function that takes no arguments, not a function that takes a
10570 // single void argument.
10571 // We let through "const void" here because Sema::GetTypeForDeclarator
10572 // already checks for that case.
10573 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10574 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10575 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10576 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10577 Param->setDeclContext(NewFD);
10578 Params.push_back(Elt: Param);
10579
10580 if (Param->isInvalidDecl())
10581 NewFD->setInvalidDecl();
10582 }
10583 }
10584
10585 if (!getLangOpts().CPlusPlus) {
10586 // In C, find all the tag declarations from the prototype and move them
10587 // into the function DeclContext. Remove them from the surrounding tag
10588 // injection context of the function, which is typically but not always
10589 // the TU.
10590 DeclContext *PrototypeTagContext =
10591 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10592 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10593 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10594
10595 // We don't want to reparent enumerators. Look at their parent enum
10596 // instead.
10597 if (!TD) {
10598 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10599 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10600 }
10601 if (!TD)
10602 continue;
10603 DeclContext *TagDC = TD->getLexicalDeclContext();
10604 if (!TagDC->containsDecl(D: TD))
10605 continue;
10606 TagDC->removeDecl(D: TD);
10607 TD->setDeclContext(NewFD);
10608 NewFD->addDecl(D: TD);
10609
10610 // Preserve the lexical DeclContext if it is not the surrounding tag
10611 // injection context of the FD. In this example, the semantic context of
10612 // E will be f and the lexical context will be S, while both the
10613 // semantic and lexical contexts of S will be f:
10614 // void f(struct S { enum E { a } f; } s);
10615 if (TagDC != PrototypeTagContext)
10616 TD->setLexicalDeclContext(TagDC);
10617 }
10618 }
10619 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10620 // When we're declaring a function with a typedef, typeof, etc as in the
10621 // following example, we'll need to synthesize (unnamed)
10622 // parameters for use in the declaration.
10623 //
10624 // @code
10625 // typedef void fn(int);
10626 // fn f;
10627 // @endcode
10628
10629 // Synthesize a parameter for each argument type.
10630 for (const auto &AI : FT->param_types()) {
10631 ParmVarDecl *Param =
10632 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10633 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10634 Params.push_back(Elt: Param);
10635 }
10636 } else {
10637 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10638 "Should not need args for typedef of non-prototype fn");
10639 }
10640
10641 // Finally, we know we have the right number of parameters, install them.
10642 NewFD->setParams(Params);
10643
10644 // If this declarator is a declaration and not a definition, its parameters
10645 // will not be pushed onto a scope chain. That means we will not issue any
10646 // reserved identifier warnings for the declaration, but we will for the
10647 // definition. Handle those here.
10648 if (!D.isFunctionDefinition()) {
10649 for (const ParmVarDecl *PVD : Params)
10650 warnOnReservedIdentifier(D: PVD);
10651 }
10652
10653 if (D.getDeclSpec().isNoreturnSpecified())
10654 NewFD->addAttr(
10655 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10656
10657 // Functions returning a variably modified type violate C99 6.7.5.2p2
10658 // because all functions have linkage.
10659 if (!NewFD->isInvalidDecl() &&
10660 NewFD->getReturnType()->isVariablyModifiedType()) {
10661 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10662 NewFD->setInvalidDecl();
10663 }
10664
10665 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10666 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10667 !NewFD->hasAttr<SectionAttr>())
10668 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10669 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10670 Range: PragmaClangTextSection.PragmaLocation));
10671
10672 // Apply an implicit SectionAttr if #pragma code_seg is active.
10673 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10674 !NewFD->hasAttr<SectionAttr>()) {
10675 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10676 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10677 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10678 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10679 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10680 ASTContext::PSF_Read,
10681 TheDecl: NewFD))
10682 NewFD->dropAttr<SectionAttr>();
10683 }
10684
10685 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10686 // active.
10687 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10688 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10689 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10690 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10691
10692 // Apply an implicit CodeSegAttr from class declspec or
10693 // apply an implicit SectionAttr from #pragma code_seg if active.
10694 if (!NewFD->hasAttr<CodeSegAttr>()) {
10695 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10696 IsDefinition: D.isFunctionDefinition())) {
10697 NewFD->addAttr(A: SAttr);
10698 }
10699 }
10700
10701 // Handle attributes.
10702 ProcessDeclAttributes(S, D: NewFD, PD: D);
10703 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10704 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10705 !NewTVA->isDefaultVersion() &&
10706 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10707 // Don't add to scope fmv functions declarations if fmv disabled
10708 AddToScope = false;
10709 return NewFD;
10710 }
10711
10712 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10713 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10714 // type.
10715 //
10716 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10717 // type declaration will generate a compilation error.
10718 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10719 if (AddressSpace != LangAS::Default) {
10720 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10721 NewFD->setInvalidDecl();
10722 }
10723 }
10724
10725 if (!getLangOpts().CPlusPlus) {
10726 // Perform semantic checking on the function declaration.
10727 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10728 CheckMain(FD: NewFD, D: D.getDeclSpec());
10729
10730 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10731 CheckMSVCRTEntryPoint(FD: NewFD);
10732
10733 if (!NewFD->isInvalidDecl())
10734 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10735 IsMemberSpecialization: isMemberSpecialization,
10736 DeclIsDefn: D.isFunctionDefinition()));
10737 else if (!Previous.empty())
10738 // Recover gracefully from an invalid redeclaration.
10739 D.setRedeclaration(true);
10740 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10741 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10742 "previous declaration set still overloaded");
10743
10744 // Diagnose no-prototype function declarations with calling conventions that
10745 // don't support variadic calls. Only do this in C and do it after merging
10746 // possibly prototyped redeclarations.
10747 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10748 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10749 CallingConv CC = FT->getExtInfo().getCC();
10750 if (!supportsVariadicCall(CC)) {
10751 // Windows system headers sometimes accidentally use stdcall without
10752 // (void) parameters, so we relax this to a warning.
10753 int DiagID =
10754 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10755 Diag(Loc: NewFD->getLocation(), DiagID)
10756 << FunctionType::getNameForCallConv(CC);
10757 }
10758 }
10759
10760 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10761 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10762 checkNonTrivialCUnion(
10763 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10764 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10765 } else {
10766 // C++11 [replacement.functions]p3:
10767 // The program's definitions shall not be specified as inline.
10768 //
10769 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10770 //
10771 // Suppress the diagnostic if the function is __attribute__((used)), since
10772 // that forces an external definition to be emitted.
10773 if (D.getDeclSpec().isInlineSpecified() &&
10774 NewFD->isReplaceableGlobalAllocationFunction() &&
10775 !NewFD->hasAttr<UsedAttr>())
10776 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10777 DiagID: diag::ext_operator_new_delete_declared_inline)
10778 << NewFD->getDeclName();
10779
10780 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10781 // C++20 [dcl.decl.general]p4:
10782 // The optional requires-clause in an init-declarator or
10783 // member-declarator shall be present only if the declarator declares a
10784 // templated function.
10785 //
10786 // C++20 [temp.pre]p8:
10787 // An entity is templated if it is
10788 // - a template,
10789 // - an entity defined or created in a templated entity,
10790 // - a member of a templated entity,
10791 // - an enumerator for an enumeration that is a templated entity, or
10792 // - the closure type of a lambda-expression appearing in the
10793 // declaration of a templated entity.
10794 //
10795 // [Note 6: A local class, a local or block variable, or a friend
10796 // function defined in a templated entity is a templated entity.
10797 // — end note]
10798 //
10799 // A templated function is a function template or a function that is
10800 // templated. A templated class is a class template or a class that is
10801 // templated. A templated variable is a variable template or a variable
10802 // that is templated.
10803 if (!FunctionTemplate) {
10804 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10805 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10806 // An explicit specialization shall not have a trailing
10807 // requires-clause unless it declares a function template.
10808 //
10809 // Since a friend function template specialization cannot be
10810 // definition, and since a non-template friend declaration with a
10811 // trailing requires-clause must be a definition, we diagnose
10812 // friend function template specializations with trailing
10813 // requires-clauses on the same path as explicit specializations
10814 // even though they aren't necessarily prohibited by the same
10815 // language rule.
10816 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10817 << isFriend;
10818 } else if (isFriend && NewFD->isTemplated() &&
10819 !D.isFunctionDefinition()) {
10820 // C++ [temp.friend]p9:
10821 // A non-template friend declaration with a requires-clause shall be
10822 // a definition.
10823 Diag(Loc: NewFD->getBeginLoc(),
10824 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10825 NewFD->setInvalidDecl();
10826 } else if (!NewFD->isTemplated() ||
10827 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10828 Diag(Loc: TRC->getBeginLoc(),
10829 DiagID: diag::err_constrained_non_templated_function);
10830 }
10831 }
10832 }
10833
10834 // We do not add HD attributes to specializations here because
10835 // they may have different constexpr-ness compared to their
10836 // templates and, after maybeAddHostDeviceAttrs() is applied,
10837 // may end up with different effective targets. Instead, a
10838 // specialization inherits its target attributes from its template
10839 // in the CheckFunctionTemplateSpecialization() call below.
10840 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10841 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10842
10843 // Handle explicit specializations of function templates
10844 // and friend function declarations with an explicit
10845 // template argument list.
10846 if (isFunctionTemplateSpecialization) {
10847 bool isDependentSpecialization = false;
10848 if (isFriend) {
10849 // For friend function specializations, this is a dependent
10850 // specialization if its semantic context is dependent, its
10851 // type is dependent, or if its template-id is dependent.
10852 isDependentSpecialization =
10853 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10854 (HasExplicitTemplateArgs &&
10855 TemplateSpecializationType::
10856 anyInstantiationDependentTemplateArguments(
10857 Args: TemplateArgs.arguments()));
10858 assert((!isDependentSpecialization ||
10859 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10860 "dependent friend function specialization without template "
10861 "args");
10862 } else {
10863 // For class-scope explicit specializations of function templates,
10864 // if the lexical context is dependent, then the specialization
10865 // is dependent.
10866 isDependentSpecialization =
10867 CurContext->isRecord() && CurContext->isDependentContext();
10868 }
10869
10870 TemplateArgumentListInfo *ExplicitTemplateArgs =
10871 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10872 if (isDependentSpecialization) {
10873 // If it's a dependent specialization, it may not be possible
10874 // to determine the primary template (for explicit specializations)
10875 // or befriended declaration (for friends) until the enclosing
10876 // template is instantiated. In such cases, we store the declarations
10877 // found by name lookup and defer resolution until instantiation.
10878 if (CheckDependentFunctionTemplateSpecialization(
10879 FD: NewFD, ExplicitTemplateArgs, Previous))
10880 NewFD->setInvalidDecl();
10881 } else if (!NewFD->isInvalidDecl()) {
10882 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10883 Previous))
10884 NewFD->setInvalidDecl();
10885 }
10886 } else if (isMemberSpecialization && !FunctionTemplate) {
10887 if (CheckMemberSpecialization(Member: NewFD, Previous))
10888 NewFD->setInvalidDecl();
10889 }
10890
10891 // Perform semantic checking on the function declaration.
10892 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10893 CheckMain(FD: NewFD, D: D.getDeclSpec());
10894
10895 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10896 CheckMSVCRTEntryPoint(FD: NewFD);
10897
10898 if (!NewFD->isInvalidDecl())
10899 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10900 IsMemberSpecialization: isMemberSpecialization,
10901 DeclIsDefn: D.isFunctionDefinition()));
10902 else if (!Previous.empty())
10903 // Recover gracefully from an invalid redeclaration.
10904 D.setRedeclaration(true);
10905
10906 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10907 !D.isRedeclaration() ||
10908 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10909 "previous declaration set still overloaded");
10910
10911 NamedDecl *PrincipalDecl = (FunctionTemplate
10912 ? cast<NamedDecl>(Val: FunctionTemplate)
10913 : NewFD);
10914
10915 if (isFriend && NewFD->getPreviousDecl()) {
10916 AccessSpecifier Access = AS_public;
10917 if (!NewFD->isInvalidDecl())
10918 Access = NewFD->getPreviousDecl()->getAccess();
10919
10920 NewFD->setAccess(Access);
10921 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10922 }
10923
10924 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10925 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10926 PrincipalDecl->setNonMemberOperator();
10927
10928 // If we have a function template, check the template parameter
10929 // list. This will check and merge default template arguments.
10930 if (FunctionTemplate) {
10931 FunctionTemplateDecl *PrevTemplate =
10932 FunctionTemplate->getPreviousDecl();
10933 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10934 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10935 : nullptr,
10936 TPC: D.getDeclSpec().isFriendSpecified()
10937 ? (D.isFunctionDefinition()
10938 ? TPC_FriendFunctionTemplateDefinition
10939 : TPC_FriendFunctionTemplate)
10940 : (D.getCXXScopeSpec().isSet() &&
10941 DC && DC->isRecord() &&
10942 DC->isDependentContext())
10943 ? TPC_ClassTemplateMember
10944 : TPC_FunctionTemplate);
10945 }
10946
10947 if (NewFD->isInvalidDecl()) {
10948 // Ignore all the rest of this.
10949 } else if (!D.isRedeclaration()) {
10950 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10951 .AddToScope: AddToScope };
10952 // Fake up an access specifier if it's supposed to be a class member.
10953 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10954 NewFD->setAccess(AS_public);
10955
10956 // Qualified decls generally require a previous declaration.
10957 if (D.getCXXScopeSpec().isSet()) {
10958 // ...with the major exception of templated-scope or
10959 // dependent-scope friend declarations.
10960
10961 // TODO: we currently also suppress this check in dependent
10962 // contexts because (1) the parameter depth will be off when
10963 // matching friend templates and (2) we might actually be
10964 // selecting a friend based on a dependent factor. But there
10965 // are situations where these conditions don't apply and we
10966 // can actually do this check immediately.
10967 //
10968 // Unless the scope is dependent, it's always an error if qualified
10969 // redeclaration lookup found nothing at all. Diagnose that now;
10970 // nothing will diagnose that error later.
10971 if (isFriend &&
10972 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10973 (!Previous.empty() && CurContext->isDependentContext()))) {
10974 // ignore these
10975 } else if (NewFD->isCPUDispatchMultiVersion() ||
10976 NewFD->isCPUSpecificMultiVersion()) {
10977 // ignore this, we allow the redeclaration behavior here to create new
10978 // versions of the function.
10979 } else {
10980 // The user tried to provide an out-of-line definition for a
10981 // function that is a member of a class or namespace, but there
10982 // was no such member function declared (C++ [class.mfct]p2,
10983 // C++ [namespace.memdef]p2). For example:
10984 //
10985 // class X {
10986 // void f() const;
10987 // };
10988 //
10989 // void X::f() { } // ill-formed
10990 //
10991 // Complain about this problem, and attempt to suggest close
10992 // matches (e.g., those that differ only in cv-qualifiers and
10993 // whether the parameter types are references).
10994
10995 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10996 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10997 AddToScope = ExtraArgs.AddToScope;
10998 return Result;
10999 }
11000 }
11001
11002 // Unqualified local friend declarations are required to resolve
11003 // to something.
11004 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11005 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11006 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11007 AddToScope = ExtraArgs.AddToScope;
11008 return Result;
11009 }
11010 }
11011 } else if (!D.isFunctionDefinition() &&
11012 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11013 !isFriend && !isFunctionTemplateSpecialization &&
11014 !isMemberSpecialization) {
11015 // An out-of-line member function declaration must also be a
11016 // definition (C++ [class.mfct]p2).
11017 // Note that this is not the case for explicit specializations of
11018 // function templates or member functions of class templates, per
11019 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11020 // extension for compatibility with old SWIG code which likes to
11021 // generate them.
11022 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11023 << D.getCXXScopeSpec().getRange();
11024 }
11025 }
11026
11027 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11028 // Any top level function could potentially be specified as an entry.
11029 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11030 HLSL().ActOnTopLevelFunction(FD: NewFD);
11031
11032 if (NewFD->hasAttr<HLSLShaderAttr>())
11033 HLSL().CheckEntryPoint(FD: NewFD);
11034 }
11035
11036 // If this is the first declaration of a library builtin function, add
11037 // attributes as appropriate.
11038 if (!D.isRedeclaration()) {
11039 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11040 if (unsigned BuiltinID = II->getBuiltinID()) {
11041 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11042 if (!InStdNamespace &&
11043 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11044 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11045 // Validate the type matches unless this builtin is specified as
11046 // matching regardless of its declared type.
11047 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11048 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11049 } else {
11050 ASTContext::GetBuiltinTypeError Error;
11051 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11052 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11053
11054 if (!Error && !BuiltinType.isNull() &&
11055 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11056 T: NewFD->getType(), U: BuiltinType))
11057 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11058 }
11059 }
11060 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11061 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11062 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11063 }
11064 }
11065 }
11066 }
11067
11068 ProcessPragmaWeak(S, D: NewFD);
11069 ProcessPragmaExport(NewD: NewFD);
11070 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11071
11072 AddKnownFunctionAttributes(FD: NewFD);
11073
11074 if (NewFD->hasAttr<OverloadableAttr>() &&
11075 !NewFD->getType()->getAs<FunctionProtoType>()) {
11076 Diag(Loc: NewFD->getLocation(),
11077 DiagID: diag::err_attribute_overloadable_no_prototype)
11078 << NewFD;
11079 NewFD->dropAttr<OverloadableAttr>();
11080 }
11081
11082 // If there's a #pragma GCC visibility in scope, and this isn't a class
11083 // member, set the visibility of this function.
11084 if (!DC->isRecord() && NewFD->isExternallyVisible())
11085 AddPushedVisibilityAttribute(RD: NewFD);
11086
11087 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11088 // marking the function.
11089 ObjC().AddCFAuditedAttribute(D: NewFD);
11090
11091 // If this is a function definition, check if we have to apply any
11092 // attributes (i.e. optnone and no_builtin) due to a pragma.
11093 if (D.isFunctionDefinition()) {
11094 AddRangeBasedOptnone(FD: NewFD);
11095 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11096 AddSectionMSAllocText(FD: NewFD);
11097 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11098 }
11099
11100 // If this is the first declaration of an extern C variable, update
11101 // the map of such variables.
11102 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11103 isIncompleteDeclExternC(S&: *this, D: NewFD))
11104 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11105
11106 // Set this FunctionDecl's range up to the right paren.
11107 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11108
11109 if (D.isRedeclaration() && !Previous.empty()) {
11110 NamedDecl *Prev = Previous.getRepresentativeDecl();
11111 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11112 IsSpecialization: isMemberSpecialization ||
11113 isFunctionTemplateSpecialization,
11114 IsDefinition: D.isFunctionDefinition());
11115 }
11116
11117 if (getLangOpts().CUDA) {
11118 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11119 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11120 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11121 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11122 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11123 << CUDA().getConfigureFuncName();
11124 Context.setcudaConfigureCallDecl(NewFD);
11125 }
11126 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11127 !NewFD->isInvalidDecl() &&
11128 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11129 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11130 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11131 << CUDA().getConfigureFuncName();
11132 Context.setcudaGetParameterBufferDecl(NewFD);
11133 }
11134 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11135 !NewFD->isInvalidDecl() &&
11136 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11137 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11138 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11139 << CUDA().getConfigureFuncName();
11140 Context.setcudaLaunchDeviceDecl(NewFD);
11141 }
11142 }
11143 }
11144
11145 MarkUnusedFileScopedDecl(D: NewFD);
11146
11147 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11148 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11149 if (SC == SC_Static) {
11150 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11151 D.setInvalidType();
11152 }
11153
11154 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11155 if (!NewFD->getReturnType()->isVoidType()) {
11156 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11157 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11158 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11159 : FixItHint());
11160 D.setInvalidType();
11161 }
11162
11163 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11164 for (auto *Param : NewFD->parameters())
11165 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11166
11167 if (getLangOpts().OpenCLCPlusPlus) {
11168 if (DC->isRecord()) {
11169 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11170 D.setInvalidType();
11171 }
11172 if (FunctionTemplate) {
11173 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11174 D.setInvalidType();
11175 }
11176 }
11177 }
11178
11179 if (getLangOpts().CPlusPlus) {
11180 // Precalculate whether this is a friend function template with a constraint
11181 // that depends on an enclosing template, per [temp.friend]p9.
11182 if (isFriend && FunctionTemplate &&
11183 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11184 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11185
11186 // C++ [temp.friend]p9:
11187 // A friend function template with a constraint that depends on a
11188 // template parameter from an enclosing template shall be a definition.
11189 if (!D.isFunctionDefinition()) {
11190 Diag(Loc: NewFD->getBeginLoc(),
11191 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11192 NewFD->setInvalidDecl();
11193 }
11194 }
11195
11196 if (FunctionTemplate) {
11197 if (NewFD->isInvalidDecl())
11198 FunctionTemplate->setInvalidDecl();
11199 return FunctionTemplate;
11200 }
11201
11202 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11203 CompleteMemberSpecialization(Member: NewFD, Previous);
11204 }
11205
11206 for (const ParmVarDecl *Param : NewFD->parameters()) {
11207 QualType PT = Param->getType();
11208
11209 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11210 // types.
11211 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11212 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11213 QualType ElemTy = PipeTy->getElementType();
11214 if (ElemTy->isPointerOrReferenceType()) {
11215 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11216 D.setInvalidType();
11217 }
11218 }
11219 }
11220 // WebAssembly tables can't be used as function parameters.
11221 if (Context.getTargetInfo().getTriple().isWasm()) {
11222 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11223 Diag(Loc: Param->getTypeSpecStartLoc(),
11224 DiagID: diag::err_wasm_table_as_function_parameter);
11225 D.setInvalidType();
11226 }
11227 }
11228 }
11229
11230 // Diagnose availability attributes. Availability cannot be used on functions
11231 // that are run during load/unload.
11232 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11233 if (NewFD->hasAttr<ConstructorAttr>()) {
11234 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11235 << 1;
11236 NewFD->dropAttr<AvailabilityAttr>();
11237 }
11238 if (NewFD->hasAttr<DestructorAttr>()) {
11239 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11240 << 2;
11241 NewFD->dropAttr<AvailabilityAttr>();
11242 }
11243 }
11244
11245 // Diagnose no_builtin attribute on function declaration that are not a
11246 // definition.
11247 // FIXME: We should really be doing this in
11248 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11249 // the FunctionDecl and at this point of the code
11250 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11251 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11252 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11253 switch (D.getFunctionDefinitionKind()) {
11254 case FunctionDefinitionKind::Defaulted:
11255 case FunctionDefinitionKind::Deleted:
11256 Diag(Loc: NBA->getLocation(),
11257 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11258 << NBA->getSpelling();
11259 break;
11260 case FunctionDefinitionKind::Declaration:
11261 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11262 << NBA->getSpelling();
11263 break;
11264 case FunctionDefinitionKind::Definition:
11265 break;
11266 }
11267
11268 // Similar to no_builtin logic above, at this point of the code
11269 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11270 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11271 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11272 !NewFD->isInvalidDecl() &&
11273 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11274 ExternalDeclarations.push_back(Elt: NewFD);
11275
11276 // Used for a warning on the 'next' declaration when used with a
11277 // `routine(name)`.
11278 if (getLangOpts().OpenACC)
11279 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11280
11281 return NewFD;
11282}
11283
11284/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11285/// when __declspec(code_seg) "is applied to a class, all member functions of
11286/// the class and nested classes -- this includes compiler-generated special
11287/// member functions -- are put in the specified segment."
11288/// The actual behavior is a little more complicated. The Microsoft compiler
11289/// won't check outer classes if there is an active value from #pragma code_seg.
11290/// The CodeSeg is always applied from the direct parent but only from outer
11291/// classes when the #pragma code_seg stack is empty. See:
11292/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11293/// available since MS has removed the page.
11294static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11295 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11296 if (!Method)
11297 return nullptr;
11298 const CXXRecordDecl *Parent = Method->getParent();
11299 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11300 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11301 NewAttr->setImplicit(true);
11302 return NewAttr;
11303 }
11304
11305 // The Microsoft compiler won't check outer classes for the CodeSeg
11306 // when the #pragma code_seg stack is active.
11307 if (S.CodeSegStack.CurrentValue)
11308 return nullptr;
11309
11310 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11311 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11312 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11313 NewAttr->setImplicit(true);
11314 return NewAttr;
11315 }
11316 }
11317 return nullptr;
11318}
11319
11320Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11321 bool IsDefinition) {
11322 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11323 return A;
11324 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11325 CodeSegStack.CurrentValue)
11326 return SectionAttr::CreateImplicit(
11327 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11328 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11329 return nullptr;
11330}
11331
11332bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11333 QualType NewT, QualType OldT) {
11334 if (!NewD->getLexicalDeclContext()->isDependentContext())
11335 return true;
11336
11337 // For dependently-typed local extern declarations and friends, we can't
11338 // perform a correct type check in general until instantiation:
11339 //
11340 // int f();
11341 // template<typename T> void g() { T f(); }
11342 //
11343 // (valid if g() is only instantiated with T = int).
11344 if (NewT->isDependentType() &&
11345 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11346 return false;
11347
11348 // Similarly, if the previous declaration was a dependent local extern
11349 // declaration, we don't really know its type yet.
11350 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11351 return false;
11352
11353 return true;
11354}
11355
11356bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11357 if (!D->getLexicalDeclContext()->isDependentContext())
11358 return true;
11359
11360 // Don't chain dependent friend function definitions until instantiation, to
11361 // permit cases like
11362 //
11363 // void func();
11364 // template<typename T> class C1 { friend void func() {} };
11365 // template<typename T> class C2 { friend void func() {} };
11366 //
11367 // ... which is valid if only one of C1 and C2 is ever instantiated.
11368 //
11369 // FIXME: This need only apply to function definitions. For now, we proxy
11370 // this by checking for a file-scope function. We do not want this to apply
11371 // to friend declarations nominating member functions, because that gets in
11372 // the way of access checks.
11373 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11374 return false;
11375
11376 auto *VD = dyn_cast<ValueDecl>(Val: D);
11377 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11378 return !VD || !PrevVD ||
11379 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11380 OldT: PrevVD->getType());
11381}
11382
11383/// Check the target or target_version attribute of the function for
11384/// MultiVersion validity.
11385///
11386/// Returns true if there was an error, false otherwise.
11387static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11388 const auto *TA = FD->getAttr<TargetAttr>();
11389 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11390
11391 assert((TA || TVA) && "Expecting target or target_version attribute");
11392
11393 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11394 enum ErrType { Feature = 0, Architecture = 1 };
11395
11396 if (TA) {
11397 ParsedTargetAttr ParseInfo =
11398 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11399 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11400 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11401 << Architecture << ParseInfo.CPU;
11402 return true;
11403 }
11404 for (const auto &Feat : ParseInfo.Features) {
11405 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11406 if (Feat[0] == '-') {
11407 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11408 << Feature << ("no-" + BareFeat).str();
11409 return true;
11410 }
11411
11412 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11413 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11414 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11415 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11416 << Feature << BareFeat;
11417 return true;
11418 }
11419 }
11420 }
11421
11422 if (TVA) {
11423 llvm::SmallVector<StringRef, 8> Feats;
11424 ParsedTargetAttr ParseInfo;
11425 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11426 ParseInfo =
11427 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11428 for (auto &Feat : ParseInfo.Features)
11429 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11430 } else {
11431 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11432 TVA->getFeatures(Out&: Feats);
11433 }
11434 for (const auto &Feat : Feats) {
11435 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11436 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11437 << Feature << Feat;
11438 return true;
11439 }
11440 }
11441 }
11442 return false;
11443}
11444
11445// Provide a white-list of attributes that are allowed to be combined with
11446// multiversion functions.
11447static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11448 MultiVersionKind MVKind) {
11449 // Note: this list/diagnosis must match the list in
11450 // checkMultiversionAttributesAllSame.
11451 switch (Kind) {
11452 default:
11453 return false;
11454 case attr::ArmLocallyStreaming:
11455 return MVKind == MultiVersionKind::TargetVersion ||
11456 MVKind == MultiVersionKind::TargetClones;
11457 case attr::Used:
11458 return MVKind == MultiVersionKind::Target;
11459 case attr::NonNull:
11460 case attr::NoThrow:
11461 return true;
11462 }
11463}
11464
11465static bool checkNonMultiVersionCompatAttributes(Sema &S,
11466 const FunctionDecl *FD,
11467 const FunctionDecl *CausedFD,
11468 MultiVersionKind MVKind) {
11469 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11470 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11471 << static_cast<unsigned>(MVKind) << A;
11472 if (CausedFD)
11473 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11474 return true;
11475 };
11476
11477 for (const Attr *A : FD->attrs()) {
11478 switch (A->getKind()) {
11479 case attr::CPUDispatch:
11480 case attr::CPUSpecific:
11481 if (MVKind != MultiVersionKind::CPUDispatch &&
11482 MVKind != MultiVersionKind::CPUSpecific)
11483 return Diagnose(S, A);
11484 break;
11485 case attr::Target:
11486 if (MVKind != MultiVersionKind::Target)
11487 return Diagnose(S, A);
11488 break;
11489 case attr::TargetVersion:
11490 if (MVKind != MultiVersionKind::TargetVersion &&
11491 MVKind != MultiVersionKind::TargetClones)
11492 return Diagnose(S, A);
11493 break;
11494 case attr::TargetClones:
11495 if (MVKind != MultiVersionKind::TargetClones &&
11496 MVKind != MultiVersionKind::TargetVersion)
11497 return Diagnose(S, A);
11498 break;
11499 default:
11500 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11501 return Diagnose(S, A);
11502 break;
11503 }
11504 }
11505 return false;
11506}
11507
11508bool Sema::areMultiversionVariantFunctionsCompatible(
11509 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11510 const PartialDiagnostic &NoProtoDiagID,
11511 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11512 const PartialDiagnosticAt &NoSupportDiagIDAt,
11513 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11514 bool ConstexprSupported, bool CLinkageMayDiffer) {
11515 enum DoesntSupport {
11516 FuncTemplates = 0,
11517 VirtFuncs = 1,
11518 DeducedReturn = 2,
11519 Constructors = 3,
11520 Destructors = 4,
11521 DeletedFuncs = 5,
11522 DefaultedFuncs = 6,
11523 ConstexprFuncs = 7,
11524 ConstevalFuncs = 8,
11525 Lambda = 9,
11526 };
11527 enum Different {
11528 CallingConv = 0,
11529 ReturnType = 1,
11530 ConstexprSpec = 2,
11531 InlineSpec = 3,
11532 Linkage = 4,
11533 LanguageLinkage = 5,
11534 };
11535
11536 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11537 !OldFD->getType()->getAs<FunctionProtoType>()) {
11538 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11539 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11540 return true;
11541 }
11542
11543 if (NoProtoDiagID.getDiagID() != 0 &&
11544 !NewFD->getType()->getAs<FunctionProtoType>())
11545 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11546
11547 if (!TemplatesSupported &&
11548 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11549 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11550 << FuncTemplates;
11551
11552 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11553 if (NewCXXFD->isVirtual())
11554 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11555 << VirtFuncs;
11556
11557 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11558 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11559 << Constructors;
11560
11561 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11562 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11563 << Destructors;
11564 }
11565
11566 if (NewFD->isDeleted())
11567 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11568 << DeletedFuncs;
11569
11570 if (NewFD->isDefaulted())
11571 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11572 << DefaultedFuncs;
11573
11574 if (!ConstexprSupported && NewFD->isConstexpr())
11575 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11576 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11577
11578 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11579 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11580 QualType NewReturnType = NewType->getReturnType();
11581
11582 if (NewReturnType->isUndeducedType())
11583 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11584 << DeducedReturn;
11585
11586 // Ensure the return type is identical.
11587 if (OldFD) {
11588 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11589 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11590 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11591 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11592
11593 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11594 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11595
11596 bool ArmStreamingCCMismatched = false;
11597 if (OldFPT && NewFPT) {
11598 unsigned Diff =
11599 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11600 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11601 // cannot be mixed.
11602 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11603 FunctionType::SME_PStateSMCompatibleMask))
11604 ArmStreamingCCMismatched = true;
11605 }
11606
11607 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11608 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11609
11610 QualType OldReturnType = OldType->getReturnType();
11611
11612 if (OldReturnType != NewReturnType)
11613 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11614
11615 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11616 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11617
11618 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11619 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11620
11621 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11622 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11623
11624 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11625 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11626
11627 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11628 NewLoc: NewFD->getLocation()))
11629 return true;
11630 }
11631 return false;
11632}
11633
11634static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11635 const FunctionDecl *NewFD,
11636 bool CausesMV,
11637 MultiVersionKind MVKind) {
11638 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11639 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11640 if (OldFD)
11641 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11642 return true;
11643 }
11644
11645 bool IsCPUSpecificCPUDispatchMVKind =
11646 MVKind == MultiVersionKind::CPUDispatch ||
11647 MVKind == MultiVersionKind::CPUSpecific;
11648
11649 if (CausesMV && OldFD &&
11650 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11651 return true;
11652
11653 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11654 return true;
11655
11656 // Only allow transition to MultiVersion if it hasn't been used.
11657 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11658 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11659 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11660 return true;
11661 }
11662
11663 return S.areMultiversionVariantFunctionsCompatible(
11664 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11665 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11666 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11667 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11668 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11669 << static_cast<unsigned>(MVKind)),
11670 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11671 S.PDiag(DiagID: diag::err_multiversion_diff)),
11672 /*TemplatesSupported=*/false,
11673 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11674 /*CLinkageMayDiffer=*/false);
11675}
11676
11677/// Check the validity of a multiversion function declaration that is the
11678/// first of its kind. Also sets the multiversion'ness' of the function itself.
11679///
11680/// This sets NewFD->isInvalidDecl() to true if there was an error.
11681///
11682/// Returns true if there was an error, false otherwise.
11683static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11684 MultiVersionKind MVKind = FD->getMultiVersionKind();
11685 assert(MVKind != MultiVersionKind::None &&
11686 "Function lacks multiversion attribute");
11687 const auto *TA = FD->getAttr<TargetAttr>();
11688 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11689 // The target attribute only causes MV if this declaration is the default,
11690 // otherwise it is treated as a normal function.
11691 if (TA && !TA->isDefaultVersion())
11692 return false;
11693
11694 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11695 FD->setInvalidDecl();
11696 return true;
11697 }
11698
11699 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11700 FD->setInvalidDecl();
11701 return true;
11702 }
11703
11704 FD->setIsMultiVersion();
11705 return false;
11706}
11707
11708static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11709 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11710 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11711 return true;
11712 }
11713
11714 return false;
11715}
11716
11717static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11718 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11719 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11720 return;
11721
11722 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11723 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11724
11725 if (MVKindTo == MultiVersionKind::None &&
11726 (MVKindFrom == MultiVersionKind::TargetVersion ||
11727 MVKindFrom == MultiVersionKind::TargetClones))
11728 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11729 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11730}
11731
11732static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11733 FunctionDecl *NewFD,
11734 bool &Redeclaration,
11735 NamedDecl *&OldDecl,
11736 LookupResult &Previous) {
11737 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11738
11739 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11740 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11741 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11742 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11743
11744 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11745
11746 // The definitions should be allowed in any order. If we have discovered
11747 // a new target version and the preceeding was the default, then add the
11748 // corresponding attribute to it.
11749 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11750
11751 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11752 // to change, this is a simple redeclaration.
11753 if (NewTA && !NewTA->isDefaultVersion() &&
11754 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11755 return false;
11756
11757 // Otherwise, this decl causes MultiVersioning.
11758 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11759 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11760 : MultiVersionKind::Target)) {
11761 NewFD->setInvalidDecl();
11762 return true;
11763 }
11764
11765 if (CheckMultiVersionValue(S, FD: NewFD)) {
11766 NewFD->setInvalidDecl();
11767 return true;
11768 }
11769
11770 // If this is 'default', permit the forward declaration.
11771 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11772 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11773 Redeclaration = true;
11774 OldDecl = OldFD;
11775 OldFD->setIsMultiVersion();
11776 NewFD->setIsMultiVersion();
11777 return false;
11778 }
11779
11780 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11781 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11782 NewFD->setInvalidDecl();
11783 return true;
11784 }
11785
11786 if (NewTA) {
11787 ParsedTargetAttr OldParsed =
11788 S.getASTContext().getTargetInfo().parseTargetAttr(
11789 Str: OldTA->getFeaturesStr());
11790 llvm::sort(C&: OldParsed.Features);
11791 ParsedTargetAttr NewParsed =
11792 S.getASTContext().getTargetInfo().parseTargetAttr(
11793 Str: NewTA->getFeaturesStr());
11794 // Sort order doesn't matter, it just needs to be consistent.
11795 llvm::sort(C&: NewParsed.Features);
11796 if (OldParsed == NewParsed) {
11797 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11798 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11799 NewFD->setInvalidDecl();
11800 return true;
11801 }
11802 }
11803
11804 for (const auto *FD : OldFD->redecls()) {
11805 const auto *CurTA = FD->getAttr<TargetAttr>();
11806 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11807 // We allow forward declarations before ANY multiversioning attributes, but
11808 // nothing after the fact.
11809 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11810 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11811 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11812 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11813 << (NewTA ? 0 : 2);
11814 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11815 NewFD->setInvalidDecl();
11816 return true;
11817 }
11818 }
11819
11820 OldFD->setIsMultiVersion();
11821 NewFD->setIsMultiVersion();
11822 Redeclaration = false;
11823 OldDecl = nullptr;
11824 Previous.clear();
11825 return false;
11826}
11827
11828static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11829 MultiVersionKind OldKind = Old->getMultiVersionKind();
11830 MultiVersionKind NewKind = New->getMultiVersionKind();
11831
11832 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11833 NewKind == MultiVersionKind::None)
11834 return true;
11835
11836 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11837 switch (OldKind) {
11838 case MultiVersionKind::TargetVersion:
11839 return NewKind == MultiVersionKind::TargetClones;
11840 case MultiVersionKind::TargetClones:
11841 return NewKind == MultiVersionKind::TargetVersion;
11842 default:
11843 return false;
11844 }
11845 } else {
11846 switch (OldKind) {
11847 case MultiVersionKind::CPUDispatch:
11848 return NewKind == MultiVersionKind::CPUSpecific;
11849 case MultiVersionKind::CPUSpecific:
11850 return NewKind == MultiVersionKind::CPUDispatch;
11851 default:
11852 return false;
11853 }
11854 }
11855}
11856
11857/// Check the validity of a new function declaration being added to an existing
11858/// multiversioned declaration collection.
11859static bool CheckMultiVersionAdditionalDecl(
11860 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11861 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11862 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11863 LookupResult &Previous) {
11864
11865 // Disallow mixing of multiversioning types.
11866 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11867 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11868 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11869 NewFD->setInvalidDecl();
11870 return true;
11871 }
11872
11873 // Add the default target_version attribute if it's missing.
11874 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11875 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11876
11877 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11878 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11879 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11880 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11881
11882 ParsedTargetAttr NewParsed;
11883 if (NewTA) {
11884 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11885 Str: NewTA->getFeaturesStr());
11886 llvm::sort(C&: NewParsed.Features);
11887 }
11888 llvm::SmallVector<StringRef, 8> NewFeats;
11889 if (NewTVA) {
11890 NewTVA->getFeatures(Out&: NewFeats);
11891 llvm::sort(C&: NewFeats);
11892 }
11893
11894 bool UseMemberUsingDeclRules =
11895 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11896
11897 bool MayNeedOverloadableChecks =
11898 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11899
11900 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11901 // of a previous member of the MultiVersion set.
11902 for (NamedDecl *ND : Previous) {
11903 FunctionDecl *CurFD = ND->getAsFunction();
11904 if (!CurFD || CurFD->isInvalidDecl())
11905 continue;
11906 if (MayNeedOverloadableChecks &&
11907 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11908 continue;
11909
11910 switch (NewMVKind) {
11911 case MultiVersionKind::None:
11912 assert(OldMVKind == MultiVersionKind::TargetClones &&
11913 "Only target_clones can be omitted in subsequent declarations");
11914 break;
11915 case MultiVersionKind::Target: {
11916 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11917 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11918 NewFD->setIsMultiVersion();
11919 Redeclaration = true;
11920 OldDecl = ND;
11921 return false;
11922 }
11923
11924 ParsedTargetAttr CurParsed =
11925 S.getASTContext().getTargetInfo().parseTargetAttr(
11926 Str: CurTA->getFeaturesStr());
11927 llvm::sort(C&: CurParsed.Features);
11928 if (CurParsed == NewParsed) {
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 break;
11935 }
11936 case MultiVersionKind::TargetVersion: {
11937 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11938 if (CurTVA->getName() == NewTVA->getName()) {
11939 NewFD->setIsMultiVersion();
11940 Redeclaration = true;
11941 OldDecl = ND;
11942 return false;
11943 }
11944 llvm::SmallVector<StringRef, 8> CurFeats;
11945 CurTVA->getFeatures(Out&: CurFeats);
11946 llvm::sort(C&: CurFeats);
11947
11948 if (CurFeats == NewFeats) {
11949 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11950 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11951 NewFD->setInvalidDecl();
11952 return true;
11953 }
11954 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11955 // Default
11956 if (NewFeats.empty())
11957 break;
11958
11959 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11960 llvm::SmallVector<StringRef, 8> CurFeats;
11961 CurClones->getFeatures(Out&: CurFeats, Index: I);
11962 llvm::sort(C&: CurFeats);
11963
11964 if (CurFeats == NewFeats) {
11965 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11966 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11967 NewFD->setInvalidDecl();
11968 return true;
11969 }
11970 }
11971 }
11972 break;
11973 }
11974 case MultiVersionKind::TargetClones: {
11975 assert(NewClones && "MultiVersionKind does not match attribute type");
11976 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11977 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11978 !std::equal(first1: CurClones->featuresStrs_begin(),
11979 last1: CurClones->featuresStrs_end(),
11980 first2: NewClones->featuresStrs_begin())) {
11981 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11982 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11983 NewFD->setInvalidDecl();
11984 return true;
11985 }
11986 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11987 llvm::SmallVector<StringRef, 8> CurFeats;
11988 CurTVA->getFeatures(Out&: CurFeats);
11989 llvm::sort(C&: CurFeats);
11990
11991 // Default
11992 if (CurFeats.empty())
11993 break;
11994
11995 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11996 NewFeats.clear();
11997 NewClones->getFeatures(Out&: NewFeats, Index: I);
11998 llvm::sort(C&: NewFeats);
11999
12000 if (CurFeats == NewFeats) {
12001 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12002 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12003 NewFD->setInvalidDecl();
12004 return true;
12005 }
12006 }
12007 break;
12008 }
12009 Redeclaration = true;
12010 OldDecl = CurFD;
12011 NewFD->setIsMultiVersion();
12012 return false;
12013 }
12014 case MultiVersionKind::CPUSpecific:
12015 case MultiVersionKind::CPUDispatch: {
12016 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12017 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12018 // Handle CPUDispatch/CPUSpecific versions.
12019 // Only 1 CPUDispatch function is allowed, this will make it go through
12020 // the redeclaration errors.
12021 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12022 CurFD->hasAttr<CPUDispatchAttr>()) {
12023 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12024 std::equal(
12025 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12026 first2: NewCPUDisp->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 // If the declarations don't match, this is an error condition.
12037 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12038 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12039 NewFD->setInvalidDecl();
12040 return true;
12041 }
12042 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12043 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12044 std::equal(
12045 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12046 first2: NewCPUSpec->cpus_begin(),
12047 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12048 return Cur->getName() == New->getName();
12049 })) {
12050 NewFD->setIsMultiVersion();
12051 Redeclaration = true;
12052 OldDecl = ND;
12053 return false;
12054 }
12055
12056 // Only 1 version of CPUSpecific is allowed for each CPU.
12057 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12058 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12059 if (CurII == NewII) {
12060 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12061 << NewII;
12062 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12063 NewFD->setInvalidDecl();
12064 return true;
12065 }
12066 }
12067 }
12068 }
12069 break;
12070 }
12071 }
12072 }
12073
12074 // Redeclarations of a target_clones function may omit the attribute, in which
12075 // case it will be inherited during declaration merging.
12076 if (NewMVKind == MultiVersionKind::None &&
12077 OldMVKind == MultiVersionKind::TargetClones) {
12078 NewFD->setIsMultiVersion();
12079 Redeclaration = true;
12080 OldDecl = OldFD;
12081 return false;
12082 }
12083
12084 // Else, this is simply a non-redecl case. Checking the 'value' is only
12085 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12086 // handled in the attribute adding step.
12087 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12088 NewFD->setInvalidDecl();
12089 return true;
12090 }
12091
12092 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12093 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12094 NewFD->setInvalidDecl();
12095 return true;
12096 }
12097
12098 // Permit forward declarations in the case where these two are compatible.
12099 if (!OldFD->isMultiVersion()) {
12100 OldFD->setIsMultiVersion();
12101 NewFD->setIsMultiVersion();
12102 Redeclaration = true;
12103 OldDecl = OldFD;
12104 return false;
12105 }
12106
12107 NewFD->setIsMultiVersion();
12108 Redeclaration = false;
12109 OldDecl = nullptr;
12110 Previous.clear();
12111 return false;
12112}
12113
12114/// Check the validity of a mulitversion function declaration.
12115/// Also sets the multiversion'ness' of the function itself.
12116///
12117/// This sets NewFD->isInvalidDecl() to true if there was an error.
12118///
12119/// Returns true if there was an error, false otherwise.
12120static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12121 bool &Redeclaration, NamedDecl *&OldDecl,
12122 LookupResult &Previous) {
12123 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12124
12125 // Check if FMV is disabled.
12126 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12127 return false;
12128
12129 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12130 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12131 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12132 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12133 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12134 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12135
12136 // Main isn't allowed to become a multiversion function, however it IS
12137 // permitted to have 'main' be marked with the 'target' optimization hint,
12138 // for 'target_version' only default is allowed.
12139 if (NewFD->isMain()) {
12140 if (MVKind != MultiVersionKind::None &&
12141 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12142 !(MVKind == MultiVersionKind::TargetVersion &&
12143 NewTVA->isDefaultVersion())) {
12144 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12145 NewFD->setInvalidDecl();
12146 return true;
12147 }
12148 return false;
12149 }
12150
12151 // Target attribute on AArch64 is not used for multiversioning
12152 if (NewTA && TI.getTriple().isAArch64())
12153 return false;
12154
12155 // Target attribute on RISCV is not used for multiversioning
12156 if (NewTA && TI.getTriple().isRISCV())
12157 return false;
12158
12159 if (!OldDecl || !OldDecl->getAsFunction() ||
12160 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12161 DC: NewFD->getDeclContext()->getRedeclContext())) {
12162 // If there's no previous declaration, AND this isn't attempting to cause
12163 // multiversioning, this isn't an error condition.
12164 if (MVKind == MultiVersionKind::None)
12165 return false;
12166 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12167 }
12168
12169 FunctionDecl *OldFD = OldDecl->getAsFunction();
12170
12171 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12172 return false;
12173
12174 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12175 // for target_clones and target_version.
12176 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12177 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12178 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12179 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12180 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12181 NewFD->setInvalidDecl();
12182 return true;
12183 }
12184
12185 if (!OldFD->isMultiVersion()) {
12186 switch (MVKind) {
12187 case MultiVersionKind::Target:
12188 case MultiVersionKind::TargetVersion:
12189 return CheckDeclarationCausesMultiVersioning(
12190 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12191 case MultiVersionKind::TargetClones:
12192 if (OldFD->isUsed(CheckUsedAttr: false)) {
12193 NewFD->setInvalidDecl();
12194 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12195 }
12196 OldFD->setIsMultiVersion();
12197 break;
12198
12199 case MultiVersionKind::CPUDispatch:
12200 case MultiVersionKind::CPUSpecific:
12201 case MultiVersionKind::None:
12202 break;
12203 }
12204 }
12205
12206 // At this point, we have a multiversion function decl (in OldFD) AND an
12207 // appropriate attribute in the current function decl (unless it's allowed to
12208 // omit the attribute). Resolve that these are still compatible with previous
12209 // declarations.
12210 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12211 NewCPUSpec, NewClones, Redeclaration,
12212 OldDecl, Previous);
12213}
12214
12215static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12216 bool IsPure = NewFD->hasAttr<PureAttr>();
12217 bool IsConst = NewFD->hasAttr<ConstAttr>();
12218
12219 // If there are no pure or const attributes, there's nothing to check.
12220 if (!IsPure && !IsConst)
12221 return;
12222
12223 // If the function is marked both pure and const, we retain the const
12224 // attribute because it makes stronger guarantees than the pure attribute, and
12225 // we drop the pure attribute explicitly to prevent later confusion about
12226 // semantics.
12227 if (IsPure && IsConst) {
12228 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12229 NewFD->dropAttrs<PureAttr>();
12230 }
12231
12232 // Constructors and destructors are functions which return void, so are
12233 // handled here as well.
12234 if (NewFD->getReturnType()->isVoidType()) {
12235 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12236 << IsConst;
12237 NewFD->dropAttrs<PureAttr, ConstAttr>();
12238 }
12239}
12240
12241bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12242 LookupResult &Previous,
12243 bool IsMemberSpecialization,
12244 bool DeclIsDefn) {
12245 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12246 "Variably modified return types are not handled here");
12247
12248 // Determine whether the type of this function should be merged with
12249 // a previous visible declaration. This never happens for functions in C++,
12250 // and always happens in C if the previous declaration was visible.
12251 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12252 !Previous.isShadowed();
12253
12254 bool Redeclaration = false;
12255 NamedDecl *OldDecl = nullptr;
12256 bool MayNeedOverloadableChecks = false;
12257
12258 inferLifetimeCaptureByAttribute(FD: NewFD);
12259 // Merge or overload the declaration with an existing declaration of
12260 // the same name, if appropriate.
12261 if (!Previous.empty()) {
12262 // Determine whether NewFD is an overload of PrevDecl or
12263 // a declaration that requires merging. If it's an overload,
12264 // there's no more work to do here; we'll just add the new
12265 // function to the scope.
12266 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12267 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12268 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12269 Redeclaration = true;
12270 OldDecl = Candidate;
12271 }
12272 } else {
12273 MayNeedOverloadableChecks = true;
12274 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12275 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12276 case OverloadKind::Match:
12277 Redeclaration = true;
12278 break;
12279
12280 case OverloadKind::NonFunction:
12281 Redeclaration = true;
12282 break;
12283
12284 case OverloadKind::Overload:
12285 Redeclaration = false;
12286 break;
12287 }
12288 }
12289 }
12290
12291 // Check for a previous extern "C" declaration with this name.
12292 if (!Redeclaration &&
12293 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12294 if (!Previous.empty()) {
12295 // This is an extern "C" declaration with the same name as a previous
12296 // declaration, and thus redeclares that entity...
12297 Redeclaration = true;
12298 OldDecl = Previous.getFoundDecl();
12299 MergeTypeWithPrevious = false;
12300
12301 // ... except in the presence of __attribute__((overloadable)).
12302 if (OldDecl->hasAttr<OverloadableAttr>() ||
12303 NewFD->hasAttr<OverloadableAttr>()) {
12304 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12305 MayNeedOverloadableChecks = true;
12306 Redeclaration = false;
12307 OldDecl = nullptr;
12308 }
12309 }
12310 }
12311 }
12312
12313 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12314 return Redeclaration;
12315
12316 // PPC MMA non-pointer types are not allowed as function return types.
12317 if (Context.getTargetInfo().getTriple().isPPC64() &&
12318 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12319 NewFD->setInvalidDecl();
12320 }
12321
12322 CheckConstPureAttributesUsage(S&: *this, NewFD);
12323
12324 // C++ [dcl.spec.auto.general]p12:
12325 // Return type deduction for a templated function with a placeholder in its
12326 // declared type occurs when the definition is instantiated even if the
12327 // function body contains a return statement with a non-type-dependent
12328 // operand.
12329 //
12330 // C++ [temp.dep.expr]p3:
12331 // An id-expression is type-dependent if it is a template-id that is not a
12332 // concept-id and is dependent; or if its terminal name is:
12333 // - [...]
12334 // - associated by name lookup with one or more declarations of member
12335 // functions of a class that is the current instantiation declared with a
12336 // return type that contains a placeholder type,
12337 // - [...]
12338 //
12339 // If this is a templated function with a placeholder in its return type,
12340 // make the placeholder type dependent since it won't be deduced until the
12341 // definition is instantiated. We do this here because it needs to happen
12342 // for implicitly instantiated member functions/member function templates.
12343 if (getLangOpts().CPlusPlus14 &&
12344 (NewFD->isDependentContext() &&
12345 NewFD->getReturnType()->isUndeducedType())) {
12346 const FunctionProtoType *FPT =
12347 NewFD->getType()->castAs<FunctionProtoType>();
12348 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12349 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12350 EPI: FPT->getExtProtoInfo()));
12351 }
12352
12353 // C++11 [dcl.constexpr]p8:
12354 // A constexpr specifier for a non-static member function that is not
12355 // a constructor declares that member function to be const.
12356 //
12357 // This needs to be delayed until we know whether this is an out-of-line
12358 // definition of a static member function.
12359 //
12360 // This rule is not present in C++1y, so we produce a backwards
12361 // compatibility warning whenever it happens in C++11.
12362 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12363 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12364 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12365 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12366 CXXMethodDecl *OldMD = nullptr;
12367 if (OldDecl)
12368 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12369 if (!OldMD || !OldMD->isStatic()) {
12370 const FunctionProtoType *FPT =
12371 MD->getType()->castAs<FunctionProtoType>();
12372 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12373 EPI.TypeQuals.addConst();
12374 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12375 Args: FPT->getParamTypes(), EPI));
12376
12377 // Warn that we did this, if we're not performing template instantiation.
12378 // In that case, we'll have warned already when the template was defined.
12379 if (!inTemplateInstantiation()) {
12380 SourceLocation AddConstLoc;
12381 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12382 .IgnoreParens().getAs<FunctionTypeLoc>())
12383 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12384
12385 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12386 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12387 }
12388 }
12389 }
12390
12391 if (Redeclaration) {
12392 // NewFD and OldDecl represent declarations that need to be
12393 // merged.
12394 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12395 NewDeclIsDefn: DeclIsDefn)) {
12396 NewFD->setInvalidDecl();
12397 return Redeclaration;
12398 }
12399
12400 Previous.clear();
12401 Previous.addDecl(D: OldDecl);
12402
12403 if (FunctionTemplateDecl *OldTemplateDecl =
12404 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12405 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12406 FunctionTemplateDecl *NewTemplateDecl
12407 = NewFD->getDescribedFunctionTemplate();
12408 assert(NewTemplateDecl && "Template/non-template mismatch");
12409
12410 // The call to MergeFunctionDecl above may have created some state in
12411 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12412 // can add it as a redeclaration.
12413 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12414
12415 NewFD->setPreviousDeclaration(OldFD);
12416 if (NewFD->isCXXClassMember()) {
12417 NewFD->setAccess(OldTemplateDecl->getAccess());
12418 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12419 }
12420
12421 // If this is an explicit specialization of a member that is a function
12422 // template, mark it as a member specialization.
12423 if (IsMemberSpecialization &&
12424 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12425 NewTemplateDecl->setMemberSpecialization();
12426 assert(OldTemplateDecl->isMemberSpecialization());
12427 // Explicit specializations of a member template do not inherit deleted
12428 // status from the parent member template that they are specializing.
12429 if (OldFD->isDeleted()) {
12430 // FIXME: This assert will not hold in the presence of modules.
12431 assert(OldFD->getCanonicalDecl() == OldFD);
12432 // FIXME: We need an update record for this AST mutation.
12433 OldFD->setDeletedAsWritten(D: false);
12434 }
12435 }
12436
12437 } else {
12438 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12439 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12440 // This needs to happen first so that 'inline' propagates.
12441 NewFD->setPreviousDeclaration(OldFD);
12442 if (NewFD->isCXXClassMember())
12443 NewFD->setAccess(OldFD->getAccess());
12444 }
12445 }
12446 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12447 !NewFD->getAttr<OverloadableAttr>()) {
12448 assert((Previous.empty() ||
12449 llvm::any_of(Previous,
12450 [](const NamedDecl *ND) {
12451 return ND->hasAttr<OverloadableAttr>();
12452 })) &&
12453 "Non-redecls shouldn't happen without overloadable present");
12454
12455 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12456 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12457 return FD && !FD->hasAttr<OverloadableAttr>();
12458 });
12459
12460 if (OtherUnmarkedIter != Previous.end()) {
12461 Diag(Loc: NewFD->getLocation(),
12462 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12463 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12464 DiagID: diag::note_attribute_overloadable_prev_overload)
12465 << false;
12466
12467 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12468 }
12469 }
12470
12471 if (LangOpts.OpenMP)
12472 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12473
12474 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12475 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12476
12477 if (NewFD->hasAttr<SYCLExternalAttr>())
12478 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12479
12480 // Semantic checking for this function declaration (in isolation).
12481
12482 if (getLangOpts().CPlusPlus) {
12483 // C++-specific checks.
12484 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12485 CheckConstructor(Constructor);
12486 } else if (CXXDestructorDecl *Destructor =
12487 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12488 // We check here for invalid destructor names.
12489 // If we have a friend destructor declaration that is dependent, we can't
12490 // diagnose right away because cases like this are still valid:
12491 // template <class T> struct A { friend T::X::~Y(); };
12492 // struct B { struct Y { ~Y(); }; using X = Y; };
12493 // template struct A<B>;
12494 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12495 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12496 CanQualType ClassType =
12497 Context.getCanonicalTagType(TD: Destructor->getParent());
12498
12499 DeclarationName Name =
12500 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12501 if (NewFD->getDeclName() != Name) {
12502 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12503 NewFD->setInvalidDecl();
12504 return Redeclaration;
12505 }
12506 }
12507 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12508 if (auto *TD = Guide->getDescribedFunctionTemplate())
12509 CheckDeductionGuideTemplate(TD);
12510
12511 // A deduction guide is not on the list of entities that can be
12512 // explicitly specialized.
12513 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12514 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12515 << /*explicit specialization*/ 1;
12516 }
12517
12518 // Find any virtual functions that this function overrides.
12519 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12520 if (!Method->isFunctionTemplateSpecialization() &&
12521 !Method->getDescribedFunctionTemplate() &&
12522 Method->isCanonicalDecl()) {
12523 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12524 }
12525 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12526 // C++2a [class.virtual]p6
12527 // A virtual method shall not have a requires-clause.
12528 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12529 DiagID: diag::err_constrained_virtual_method);
12530
12531 if (Method->isStatic())
12532 checkThisInStaticMemberFunctionType(Method);
12533 }
12534
12535 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12536 ActOnConversionDeclarator(Conversion);
12537
12538 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12539 if (NewFD->isOverloadedOperator() &&
12540 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12541 NewFD->setInvalidDecl();
12542 return Redeclaration;
12543 }
12544
12545 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12546 if (NewFD->getLiteralIdentifier() &&
12547 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12548 NewFD->setInvalidDecl();
12549 return Redeclaration;
12550 }
12551
12552 // In C++, check default arguments now that we have merged decls. Unless
12553 // the lexical context is the class, because in this case this is done
12554 // during delayed parsing anyway.
12555 if (!CurContext->isRecord())
12556 CheckCXXDefaultArguments(FD: NewFD);
12557
12558 // If this function is declared as being extern "C", then check to see if
12559 // the function returns a UDT (class, struct, or union type) that is not C
12560 // compatible, and if it does, warn the user.
12561 // But, issue any diagnostic on the first declaration only.
12562 if (Previous.empty() && NewFD->isExternC()) {
12563 QualType R = NewFD->getReturnType();
12564 if (R->isIncompleteType() && !R->isVoidType())
12565 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12566 << NewFD << R;
12567 else if (!R.isPODType(Context) && !R->isVoidType() &&
12568 !R->isObjCObjectPointerType())
12569 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12570 }
12571
12572 // C++1z [dcl.fct]p6:
12573 // [...] whether the function has a non-throwing exception-specification
12574 // [is] part of the function type
12575 //
12576 // This results in an ABI break between C++14 and C++17 for functions whose
12577 // declared type includes an exception-specification in a parameter or
12578 // return type. (Exception specifications on the function itself are OK in
12579 // most cases, and exception specifications are not permitted in most other
12580 // contexts where they could make it into a mangling.)
12581 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12582 auto HasNoexcept = [&](QualType T) -> bool {
12583 // Strip off declarator chunks that could be between us and a function
12584 // type. We don't need to look far, exception specifications are very
12585 // restricted prior to C++17.
12586 if (auto *RT = T->getAs<ReferenceType>())
12587 T = RT->getPointeeType();
12588 else if (T->isAnyPointerType())
12589 T = T->getPointeeType();
12590 else if (auto *MPT = T->getAs<MemberPointerType>())
12591 T = MPT->getPointeeType();
12592 if (auto *FPT = T->getAs<FunctionProtoType>())
12593 if (FPT->isNothrow())
12594 return true;
12595 return false;
12596 };
12597
12598 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12599 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12600 for (QualType T : FPT->param_types())
12601 AnyNoexcept |= HasNoexcept(T);
12602 if (AnyNoexcept)
12603 Diag(Loc: NewFD->getLocation(),
12604 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12605 << NewFD;
12606 }
12607
12608 if (!Redeclaration && LangOpts.CUDA) {
12609 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12610 for (auto *Parm : NewFD->parameters()) {
12611 if (!Parm->getType()->isDependentType() &&
12612 Parm->hasAttr<CUDAGridConstantAttr>() &&
12613 !(IsKernel && Parm->getType().isConstQualified()))
12614 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12615 DiagID: diag::err_cuda_grid_constant_not_allowed);
12616 }
12617 CUDA().checkTargetOverload(NewFD, Previous);
12618 }
12619 }
12620
12621 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12622 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12623
12624 return Redeclaration;
12625}
12626
12627void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12628 // [basic.start.main]p3
12629 // The main function shall not be declared with C linkage-specification.
12630 if (FD->isExternCContext())
12631 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12632
12633 // C++11 [basic.start.main]p3:
12634 // A program that [...] declares main to be inline, static or
12635 // constexpr is ill-formed.
12636 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12637 // appear in a declaration of main.
12638 // static main is not an error under C99, but we should warn about it.
12639 // We accept _Noreturn main as an extension.
12640 if (FD->getStorageClass() == SC_Static)
12641 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12642 ? diag::err_static_main : diag::warn_static_main)
12643 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12644 if (FD->isInlineSpecified())
12645 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12646 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12647 if (DS.isNoreturnSpecified()) {
12648 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12649 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12650 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12651 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12652 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12653 }
12654 if (FD->isConstexpr()) {
12655 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12656 << FD->isConsteval()
12657 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12658 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12659 }
12660
12661 if (getLangOpts().OpenCL) {
12662 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12663 << FD->hasAttr<DeviceKernelAttr>();
12664 FD->setInvalidDecl();
12665 return;
12666 }
12667
12668 if (FD->hasAttr<SYCLExternalAttr>()) {
12669 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12670 << FD->getAttr<SYCLExternalAttr>();
12671 FD->setInvalidDecl();
12672 return;
12673 }
12674
12675 // Functions named main in hlsl are default entries, but don't have specific
12676 // signatures they are required to conform to.
12677 if (getLangOpts().HLSL)
12678 return;
12679
12680 QualType T = FD->getType();
12681 assert(T->isFunctionType() && "function decl is not of function type");
12682 const FunctionType* FT = T->castAs<FunctionType>();
12683
12684 // Set default calling convention for main()
12685 if (FT->getCallConv() != CC_C) {
12686 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12687 FD->setType(QualType(FT, 0));
12688 T = Context.getCanonicalType(T: FD->getType());
12689 }
12690
12691 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12692 // In C with GNU extensions we allow main() to have non-integer return
12693 // type, but we should warn about the extension, and we disable the
12694 // implicit-return-zero rule.
12695
12696 // GCC in C mode accepts qualified 'int'.
12697 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12698 FD->setHasImplicitReturnZero(true);
12699 else {
12700 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12701 SourceRange RTRange = FD->getReturnTypeSourceRange();
12702 if (RTRange.isValid())
12703 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12704 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12705 }
12706 } else {
12707 // In C and C++, main magically returns 0 if you fall off the end;
12708 // set the flag which tells us that.
12709 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12710
12711 // All the standards say that main() should return 'int'.
12712 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12713 FD->setHasImplicitReturnZero(true);
12714 else {
12715 // Otherwise, this is just a flat-out error.
12716 SourceRange RTRange = FD->getReturnTypeSourceRange();
12717 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12718 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12719 : FixItHint());
12720 FD->setInvalidDecl(true);
12721 }
12722
12723 // [basic.start.main]p3:
12724 // A program that declares a function main that belongs to the global scope
12725 // and is attached to a named module is ill-formed.
12726 if (FD->isInNamedModule()) {
12727 const SourceLocation start = FD->getTypeSpecStartLoc();
12728 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12729 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12730 }
12731 }
12732
12733 // Treat protoless main() as nullary.
12734 if (isa<FunctionNoProtoType>(Val: FT)) return;
12735
12736 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12737 unsigned nparams = FTP->getNumParams();
12738 assert(FD->getNumParams() == nparams);
12739
12740 bool HasExtraParameters = (nparams > 3);
12741
12742 if (FTP->isVariadic()) {
12743 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12744 // FIXME: if we had information about the location of the ellipsis, we
12745 // could add a FixIt hint to remove it as a parameter.
12746 }
12747
12748 // Darwin passes an undocumented fourth argument of type char**. If
12749 // other platforms start sprouting these, the logic below will start
12750 // getting shifty.
12751 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12752 HasExtraParameters = false;
12753
12754 if (HasExtraParameters) {
12755 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12756 FD->setInvalidDecl(true);
12757 nparams = 3;
12758 }
12759
12760 // FIXME: a lot of the following diagnostics would be improved
12761 // if we had some location information about types.
12762
12763 QualType CharPP =
12764 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12765 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12766
12767 for (unsigned i = 0; i < nparams; ++i) {
12768 QualType AT = FTP->getParamType(i);
12769
12770 bool mismatch = true;
12771
12772 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12773 mismatch = false;
12774 else if (Expected[i] == CharPP) {
12775 // As an extension, the following forms are okay:
12776 // char const **
12777 // char const * const *
12778 // char * const *
12779
12780 QualifierCollector qs;
12781 const PointerType* PT;
12782 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12783 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12784 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12785 T2: Context.CharTy)) {
12786 qs.removeConst();
12787 mismatch = !qs.empty();
12788 }
12789 }
12790
12791 if (mismatch) {
12792 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12793 // TODO: suggest replacing given type with expected type
12794 FD->setInvalidDecl(true);
12795 }
12796 }
12797
12798 if (nparams == 1 && !FD->isInvalidDecl()) {
12799 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12800 }
12801
12802 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12803 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12804 FD->setInvalidDecl();
12805 }
12806}
12807
12808static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12809
12810 // Default calling convention for main and wmain is __cdecl
12811 if (FD->getName() == "main" || FD->getName() == "wmain")
12812 return false;
12813
12814 // Default calling convention for MinGW and Cygwin is __cdecl
12815 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12816 if (T.isOSCygMing())
12817 return false;
12818
12819 // Default calling convention for WinMain, wWinMain and DllMain
12820 // is __stdcall on 32 bit Windows
12821 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12822 return true;
12823
12824 return false;
12825}
12826
12827void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12828 QualType T = FD->getType();
12829 assert(T->isFunctionType() && "function decl is not of function type");
12830 const FunctionType *FT = T->castAs<FunctionType>();
12831
12832 // Set an implicit return of 'zero' if the function can return some integral,
12833 // enumeration, pointer or nullptr type.
12834 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12835 FT->getReturnType()->isAnyPointerType() ||
12836 FT->getReturnType()->isNullPtrType())
12837 // DllMain is exempt because a return value of zero means it failed.
12838 if (FD->getName() != "DllMain")
12839 FD->setHasImplicitReturnZero(true);
12840
12841 // Explicitly specified calling conventions are applied to MSVC entry points
12842 if (!hasExplicitCallingConv(T)) {
12843 if (isDefaultStdCall(FD, S&: *this)) {
12844 if (FT->getCallConv() != CC_X86StdCall) {
12845 FT = Context.adjustFunctionType(
12846 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12847 FD->setType(QualType(FT, 0));
12848 }
12849 } else if (FT->getCallConv() != CC_C) {
12850 FT = Context.adjustFunctionType(Fn: FT,
12851 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12852 FD->setType(QualType(FT, 0));
12853 }
12854 }
12855
12856 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12857 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12858 FD->setInvalidDecl();
12859 }
12860}
12861
12862bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12863 // FIXME: Need strict checking. In C89, we need to check for
12864 // any assignment, increment, decrement, function-calls, or
12865 // commas outside of a sizeof. In C99, it's the same list,
12866 // except that the aforementioned are allowed in unevaluated
12867 // expressions. Everything else falls under the
12868 // "may accept other forms of constant expressions" exception.
12869 //
12870 // Regular C++ code will not end up here (exceptions: language extensions,
12871 // OpenCL C++ etc), so the constant expression rules there don't matter.
12872 if (Init->isValueDependent()) {
12873 assert(Init->containsErrors() &&
12874 "Dependent code should only occur in error-recovery path.");
12875 return true;
12876 }
12877 const Expr *Culprit;
12878 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12879 return false;
12880 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12881 return true;
12882}
12883
12884namespace {
12885 // Visits an initialization expression to see if OrigDecl is evaluated in
12886 // its own initialization and throws a warning if it does.
12887 class SelfReferenceChecker
12888 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12889 Sema &S;
12890 Decl *OrigDecl;
12891 bool isRecordType;
12892 bool isPODType;
12893 bool isReferenceType;
12894 bool isInCXXOperatorCall;
12895
12896 bool isInitList;
12897 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12898
12899 public:
12900 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12901
12902 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12903 S(S), OrigDecl(OrigDecl) {
12904 isPODType = false;
12905 isRecordType = false;
12906 isReferenceType = false;
12907 isInCXXOperatorCall = false;
12908 isInitList = false;
12909 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12910 isPODType = VD->getType().isPODType(Context: S.Context);
12911 isRecordType = VD->getType()->isRecordType();
12912 isReferenceType = VD->getType()->isReferenceType();
12913 }
12914 }
12915
12916 // For most expressions, just call the visitor. For initializer lists,
12917 // track the index of the field being initialized since fields are
12918 // initialized in order allowing use of previously initialized fields.
12919 void CheckExpr(Expr *E) {
12920 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12921 if (!InitList) {
12922 Visit(S: E);
12923 return;
12924 }
12925
12926 // Track and increment the index here.
12927 isInitList = true;
12928 InitFieldIndex.push_back(Elt: 0);
12929 for (auto *Child : InitList->children()) {
12930 CheckExpr(E: cast<Expr>(Val: Child));
12931 ++InitFieldIndex.back();
12932 }
12933 InitFieldIndex.pop_back();
12934 }
12935
12936 // Returns true if MemberExpr is checked and no further checking is needed.
12937 // Returns false if additional checking is required.
12938 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12939 llvm::SmallVector<FieldDecl*, 4> Fields;
12940 Expr *Base = E;
12941 bool ReferenceField = false;
12942
12943 // Get the field members used.
12944 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12945 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12946 if (!FD)
12947 return false;
12948 Fields.push_back(Elt: FD);
12949 if (FD->getType()->isReferenceType())
12950 ReferenceField = true;
12951 Base = ME->getBase()->IgnoreParenImpCasts();
12952 }
12953
12954 // Keep checking only if the base Decl is the same.
12955 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12956 if (!DRE || DRE->getDecl() != OrigDecl)
12957 return false;
12958
12959 // A reference field can be bound to an unininitialized field.
12960 if (CheckReference && !ReferenceField)
12961 return true;
12962
12963 // Convert FieldDecls to their index number.
12964 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12965 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12966 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12967
12968 // See if a warning is needed by checking the first difference in index
12969 // numbers. If field being used has index less than the field being
12970 // initialized, then the use is safe.
12971 for (auto UsedIter = UsedFieldIndex.begin(),
12972 UsedEnd = UsedFieldIndex.end(),
12973 OrigIter = InitFieldIndex.begin(),
12974 OrigEnd = InitFieldIndex.end();
12975 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12976 if (*UsedIter < *OrigIter)
12977 return true;
12978 if (*UsedIter > *OrigIter)
12979 break;
12980 }
12981
12982 // TODO: Add a different warning which will print the field names.
12983 HandleDeclRefExpr(DRE);
12984 return true;
12985 }
12986
12987 // For most expressions, the cast is directly above the DeclRefExpr.
12988 // For conditional operators, the cast can be outside the conditional
12989 // operator if both expressions are DeclRefExpr's.
12990 void HandleValue(Expr *E) {
12991 E = E->IgnoreParens();
12992 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12993 HandleDeclRefExpr(DRE);
12994 return;
12995 }
12996
12997 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12998 Visit(S: CO->getCond());
12999 HandleValue(E: CO->getTrueExpr());
13000 HandleValue(E: CO->getFalseExpr());
13001 return;
13002 }
13003
13004 if (BinaryConditionalOperator *BCO =
13005 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13006 Visit(S: BCO->getCond());
13007 HandleValue(E: BCO->getFalseExpr());
13008 return;
13009 }
13010
13011 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13012 if (Expr *SE = OVE->getSourceExpr())
13013 HandleValue(E: SE);
13014 return;
13015 }
13016
13017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13018 if (BO->getOpcode() == BO_Comma) {
13019 Visit(S: BO->getLHS());
13020 HandleValue(E: BO->getRHS());
13021 return;
13022 }
13023 }
13024
13025 if (isa<MemberExpr>(Val: E)) {
13026 if (isInitList) {
13027 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13028 CheckReference: false /*CheckReference*/))
13029 return;
13030 }
13031
13032 Expr *Base = E->IgnoreParenImpCasts();
13033 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13034 // Check for static member variables and don't warn on them.
13035 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13036 return;
13037 Base = ME->getBase()->IgnoreParenImpCasts();
13038 }
13039 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13040 HandleDeclRefExpr(DRE);
13041 return;
13042 }
13043
13044 Visit(S: E);
13045 }
13046
13047 // Reference types not handled in HandleValue are handled here since all
13048 // uses of references are bad, not just r-value uses.
13049 void VisitDeclRefExpr(DeclRefExpr *E) {
13050 if (isReferenceType)
13051 HandleDeclRefExpr(DRE: E);
13052 }
13053
13054 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13055 if (E->getCastKind() == CK_LValueToRValue) {
13056 HandleValue(E: E->getSubExpr());
13057 return;
13058 }
13059
13060 Inherited::VisitImplicitCastExpr(S: E);
13061 }
13062
13063 void VisitMemberExpr(MemberExpr *E) {
13064 if (isInitList) {
13065 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13066 return;
13067 }
13068
13069 // Don't warn on arrays since they can be treated as pointers.
13070 if (E->getType()->canDecayToPointerType()) return;
13071
13072 // Warn when a non-static method call is followed by non-static member
13073 // field accesses, which is followed by a DeclRefExpr.
13074 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13075 bool Warn = (MD && !MD->isStatic());
13076 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13077 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13078 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13079 Warn = false;
13080 Base = ME->getBase()->IgnoreParenImpCasts();
13081 }
13082
13083 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13084 if (Warn)
13085 HandleDeclRefExpr(DRE);
13086 return;
13087 }
13088
13089 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13090 // Visit that expression.
13091 Visit(S: Base);
13092 }
13093
13094 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13095 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13096 Expr *Callee = E->getCallee();
13097
13098 if (isa<UnresolvedLookupExpr>(Val: Callee))
13099 return Inherited::VisitCXXOperatorCallExpr(S: E);
13100
13101 Visit(S: Callee);
13102 for (auto Arg: E->arguments())
13103 HandleValue(E: Arg->IgnoreParenImpCasts());
13104 }
13105
13106 void VisitLambdaExpr(LambdaExpr *E) {
13107 if (!isInCXXOperatorCall) {
13108 Inherited::VisitLambdaExpr(LE: E);
13109 return;
13110 }
13111
13112 for (Expr *Init : E->capture_inits())
13113 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13114 HandleDeclRefExpr(DRE);
13115 else if (Init)
13116 Visit(S: Init);
13117 }
13118
13119 void VisitUnaryOperator(UnaryOperator *E) {
13120 // For POD record types, addresses of its own members are well-defined.
13121 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13122 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13123 if (!isPODType)
13124 HandleValue(E: E->getSubExpr());
13125 return;
13126 }
13127
13128 if (E->isIncrementDecrementOp()) {
13129 HandleValue(E: E->getSubExpr());
13130 return;
13131 }
13132
13133 Inherited::VisitUnaryOperator(S: E);
13134 }
13135
13136 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13137
13138 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13139 if (E->getConstructor()->isCopyConstructor()) {
13140 Expr *ArgExpr = E->getArg(Arg: 0);
13141 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13142 if (ILE->getNumInits() == 1)
13143 ArgExpr = ILE->getInit(Init: 0);
13144 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13145 if (ICE->getCastKind() == CK_NoOp)
13146 ArgExpr = ICE->getSubExpr();
13147 HandleValue(E: ArgExpr);
13148 return;
13149 }
13150 Inherited::VisitCXXConstructExpr(S: E);
13151 }
13152
13153 void VisitCallExpr(CallExpr *E) {
13154 // Treat std::move as a use.
13155 if (E->isCallToStdMove()) {
13156 HandleValue(E: E->getArg(Arg: 0));
13157 return;
13158 }
13159
13160 Inherited::VisitCallExpr(CE: E);
13161 }
13162
13163 void VisitBinaryOperator(BinaryOperator *E) {
13164 if (E->isCompoundAssignmentOp()) {
13165 HandleValue(E: E->getLHS());
13166 Visit(S: E->getRHS());
13167 return;
13168 }
13169
13170 Inherited::VisitBinaryOperator(S: E);
13171 }
13172
13173 // A custom visitor for BinaryConditionalOperator is needed because the
13174 // regular visitor would check the condition and true expression separately
13175 // but both point to the same place giving duplicate diagnostics.
13176 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13177 Visit(S: E->getCond());
13178 Visit(S: E->getFalseExpr());
13179 }
13180
13181 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13182 Decl* ReferenceDecl = DRE->getDecl();
13183 if (OrigDecl != ReferenceDecl) return;
13184 unsigned diag;
13185 if (isReferenceType) {
13186 diag = diag::warn_uninit_self_reference_in_reference_init;
13187 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13188 diag = diag::warn_static_self_reference_in_init;
13189 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13190 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13191 DRE->getDecl()->getType()->isRecordType()) {
13192 diag = diag::warn_uninit_self_reference_in_init;
13193 } else {
13194 // Local variables will be handled by the CFG analysis.
13195 return;
13196 }
13197
13198 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13199 PD: S.PDiag(DiagID: diag)
13200 << DRE->getDecl() << OrigDecl->getLocation()
13201 << DRE->getSourceRange());
13202 }
13203 };
13204
13205 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13206 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13207 bool DirectInit) {
13208 // Parameters arguments are occassionially constructed with itself,
13209 // for instance, in recursive functions. Skip them.
13210 if (isa<ParmVarDecl>(Val: OrigDecl))
13211 return;
13212
13213 // Skip checking for file-scope constexpr variables - constant evaluation
13214 // will produce appropriate errors without needing runtime diagnostics.
13215 // Local constexpr should still emit runtime warnings.
13216 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13217 VD && VD->isConstexpr() && VD->isFileVarDecl())
13218 return;
13219
13220 E = E->IgnoreParens();
13221
13222 // Skip checking T a = a where T is not a record or reference type.
13223 // Doing so is a way to silence uninitialized warnings.
13224 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13225 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13226 if (ICE->getCastKind() == CK_LValueToRValue)
13227 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13228 if (DRE->getDecl() == OrigDecl)
13229 return;
13230
13231 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13232 }
13233} // end anonymous namespace
13234
13235namespace {
13236 // Simple wrapper to add the name of a variable or (if no variable is
13237 // available) a DeclarationName into a diagnostic.
13238 struct VarDeclOrName {
13239 VarDecl *VDecl;
13240 DeclarationName Name;
13241
13242 friend const Sema::SemaDiagnosticBuilder &
13243 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13244 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13245 }
13246 };
13247} // end anonymous namespace
13248
13249QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13250 DeclarationName Name, QualType Type,
13251 TypeSourceInfo *TSI,
13252 SourceRange Range, bool DirectInit,
13253 Expr *Init) {
13254 bool IsInitCapture = !VDecl;
13255 assert((!VDecl || !VDecl->isInitCapture()) &&
13256 "init captures are expected to be deduced prior to initialization");
13257
13258 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13259
13260 DeducedType *Deduced = Type->getContainedDeducedType();
13261 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13262
13263 // Diagnose auto array declarations in C23, unless it's a supported extension.
13264 if (getLangOpts().C23 && Type->isArrayType() &&
13265 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13266 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13267 << (int)Deduced->getContainedAutoType()->getKeyword()
13268 << /*in array decl*/ 23 << Range;
13269 return QualType();
13270 }
13271
13272 // C++11 [dcl.spec.auto]p3
13273 if (!Init) {
13274 assert(VDecl && "no init for init capture deduction?");
13275
13276 // Except for class argument deduction, and then for an initializing
13277 // declaration only, i.e. no static at class scope or extern.
13278 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13279 VDecl->hasExternalStorage() ||
13280 VDecl->isStaticDataMember()) {
13281 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13282 << VDecl->getDeclName() << Type;
13283 return QualType();
13284 }
13285 }
13286
13287 ArrayRef<Expr*> DeduceInits;
13288 if (Init)
13289 DeduceInits = Init;
13290
13291 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13292 if (DirectInit && PL)
13293 DeduceInits = PL->exprs();
13294
13295 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13296 assert(VDecl && "non-auto type for init capture deduction?");
13297 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13298 InitializationKind Kind = InitializationKind::CreateForInit(
13299 Loc: VDecl->getLocation(), DirectInit, Init);
13300 // FIXME: Initialization should not be taking a mutable list of inits.
13301 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13302 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13303 Init: InitsCopy);
13304 }
13305
13306 if (DirectInit) {
13307 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13308 DeduceInits = IL->inits();
13309 }
13310
13311 // Deduction only works if we have exactly one source expression.
13312 if (DeduceInits.empty()) {
13313 // It isn't possible to write this directly, but it is possible to
13314 // end up in this situation with "auto x(some_pack...);"
13315 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13316 ? diag::err_init_capture_no_expression
13317 : diag::err_auto_var_init_no_expression)
13318 << VN << Type << Range;
13319 return QualType();
13320 }
13321
13322 if (DeduceInits.size() > 1) {
13323 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13324 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13325 : diag::err_auto_var_init_multiple_expressions)
13326 << VN << Type << Range;
13327 return QualType();
13328 }
13329
13330 Expr *DeduceInit = DeduceInits[0];
13331 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13332 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13333 ? diag::err_init_capture_paren_braces
13334 : diag::err_auto_var_init_paren_braces)
13335 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13336 return QualType();
13337 }
13338
13339 // Expressions default to 'id' when we're in a debugger.
13340 bool DefaultedAnyToId = false;
13341 if (getLangOpts().DebuggerCastResultToId &&
13342 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13343 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13344 if (Result.isInvalid()) {
13345 return QualType();
13346 }
13347 Init = Result.get();
13348 DefaultedAnyToId = true;
13349 }
13350
13351 // C++ [dcl.decomp]p1:
13352 // If the assignment-expression [...] has array type A and no ref-qualifier
13353 // is present, e has type cv A
13354 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13355 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13356 DeduceInit->getType()->isConstantArrayType())
13357 return Context.getQualifiedType(T: DeduceInit->getType(),
13358 Qs: Type.getQualifiers());
13359
13360 QualType DeducedType;
13361 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13362 TemplateDeductionResult Result =
13363 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13364 if (Result != TemplateDeductionResult::Success &&
13365 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13366 if (!IsInitCapture)
13367 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13368 else if (isa<InitListExpr>(Val: Init))
13369 Diag(Loc: Range.getBegin(),
13370 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13371 << VN
13372 << (DeduceInit->getType().isNull() ? TSI->getType()
13373 : DeduceInit->getType())
13374 << DeduceInit->getSourceRange();
13375 else
13376 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13377 << VN << TSI->getType()
13378 << (DeduceInit->getType().isNull() ? TSI->getType()
13379 : DeduceInit->getType())
13380 << DeduceInit->getSourceRange();
13381 }
13382
13383 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13384 // 'id' instead of a specific object type prevents most of our usual
13385 // checks.
13386 // We only want to warn outside of template instantiations, though:
13387 // inside a template, the 'id' could have come from a parameter.
13388 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13389 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13390 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13391 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13392 }
13393
13394 return DeducedType;
13395}
13396
13397bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13398 Expr *Init) {
13399 assert(!Init || !Init->containsErrors());
13400 QualType DeducedType = deduceVarTypeFromInitializer(
13401 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13402 Range: VDecl->getSourceRange(), DirectInit, Init);
13403 if (DeducedType.isNull()) {
13404 VDecl->setInvalidDecl();
13405 return true;
13406 }
13407
13408 VDecl->setType(DeducedType);
13409 assert(VDecl->isLinkageValid());
13410
13411 // In ARC, infer lifetime.
13412 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13413 VDecl->setInvalidDecl();
13414
13415 if (getLangOpts().OpenCL)
13416 deduceOpenCLAddressSpace(Var: VDecl);
13417
13418 if (getLangOpts().HLSL)
13419 HLSL().deduceAddressSpace(Decl: VDecl);
13420
13421 // If this is a redeclaration, check that the type we just deduced matches
13422 // the previously declared type.
13423 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13424 // We never need to merge the type, because we cannot form an incomplete
13425 // array of auto, nor deduce such a type.
13426 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13427 }
13428
13429 // Check the deduced type is valid for a variable declaration.
13430 CheckVariableDeclarationType(NewVD: VDecl);
13431 return VDecl->isInvalidDecl();
13432}
13433
13434void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13435 SourceLocation Loc) {
13436 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13437 Init = EWC->getSubExpr();
13438
13439 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13440 Init = CE->getSubExpr();
13441
13442 QualType InitType = Init->getType();
13443 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13444 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13445 "shouldn't be called if type doesn't have a non-trivial C struct");
13446 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13447 for (auto *I : ILE->inits()) {
13448 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13449 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13450 continue;
13451 SourceLocation SL = I->getExprLoc();
13452 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13453 }
13454 return;
13455 }
13456
13457 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13458 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13459 checkNonTrivialCUnion(QT: InitType, Loc,
13460 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13461 NonTrivialKind: NTCUK_Init);
13462 } else {
13463 // Assume all other explicit initializers involving copying some existing
13464 // object.
13465 // TODO: ignore any explicit initializers where we can guarantee
13466 // copy-elision.
13467 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13468 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13469 NonTrivialKind: NTCUK_Copy);
13470 }
13471}
13472
13473namespace {
13474
13475bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13476 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13477 // in the source code or implicitly by the compiler if it is in a union
13478 // defined in a system header and has non-trivial ObjC ownership
13479 // qualifications. We don't want those fields to participate in determining
13480 // whether the containing union is non-trivial.
13481 return FD->hasAttr<UnavailableAttr>();
13482}
13483
13484struct DiagNonTrivalCUnionDefaultInitializeVisitor
13485 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13486 void> {
13487 using Super =
13488 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13489 void>;
13490
13491 DiagNonTrivalCUnionDefaultInitializeVisitor(
13492 QualType OrigTy, SourceLocation OrigLoc,
13493 NonTrivialCUnionContext UseContext, Sema &S)
13494 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13495
13496 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13497 const FieldDecl *FD, bool InNonTrivialUnion) {
13498 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13499 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13500 Args&: InNonTrivialUnion);
13501 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13502 }
13503
13504 void visitARCStrong(QualType QT, const FieldDecl *FD,
13505 bool InNonTrivialUnion) {
13506 if (InNonTrivialUnion)
13507 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13508 << 1 << 0 << QT << FD->getName();
13509 }
13510
13511 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13512 if (InNonTrivialUnion)
13513 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13514 << 1 << 0 << QT << FD->getName();
13515 }
13516
13517 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13518 const auto *RD = QT->castAsRecordDecl();
13519 if (RD->isUnion()) {
13520 if (OrigLoc.isValid()) {
13521 bool IsUnion = false;
13522 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13523 IsUnion = OrigRD->isUnion();
13524 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13525 << 0 << OrigTy << IsUnion << UseContext;
13526 // Reset OrigLoc so that this diagnostic is emitted only once.
13527 OrigLoc = SourceLocation();
13528 }
13529 InNonTrivialUnion = true;
13530 }
13531
13532 if (InNonTrivialUnion)
13533 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13534 << 0 << 0 << QT.getUnqualifiedType() << "";
13535
13536 for (const FieldDecl *FD : RD->fields())
13537 if (!shouldIgnoreForRecordTriviality(FD))
13538 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13539 }
13540
13541 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13542
13543 // The non-trivial C union type or the struct/union type that contains a
13544 // non-trivial C union.
13545 QualType OrigTy;
13546 SourceLocation OrigLoc;
13547 NonTrivialCUnionContext UseContext;
13548 Sema &S;
13549};
13550
13551struct DiagNonTrivalCUnionDestructedTypeVisitor
13552 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13553 using Super =
13554 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13555
13556 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13557 SourceLocation OrigLoc,
13558 NonTrivialCUnionContext UseContext,
13559 Sema &S)
13560 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13561
13562 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13563 const FieldDecl *FD, bool InNonTrivialUnion) {
13564 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13565 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13566 Args&: InNonTrivialUnion);
13567 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13568 }
13569
13570 void visitARCStrong(QualType QT, const FieldDecl *FD,
13571 bool InNonTrivialUnion) {
13572 if (InNonTrivialUnion)
13573 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13574 << 1 << 1 << QT << FD->getName();
13575 }
13576
13577 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13578 if (InNonTrivialUnion)
13579 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13580 << 1 << 1 << QT << FD->getName();
13581 }
13582
13583 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13584 const auto *RD = QT->castAsRecordDecl();
13585 if (RD->isUnion()) {
13586 if (OrigLoc.isValid()) {
13587 bool IsUnion = false;
13588 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13589 IsUnion = OrigRD->isUnion();
13590 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13591 << 1 << OrigTy << IsUnion << UseContext;
13592 // Reset OrigLoc so that this diagnostic is emitted only once.
13593 OrigLoc = SourceLocation();
13594 }
13595 InNonTrivialUnion = true;
13596 }
13597
13598 if (InNonTrivialUnion)
13599 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13600 << 0 << 1 << QT.getUnqualifiedType() << "";
13601
13602 for (const FieldDecl *FD : RD->fields())
13603 if (!shouldIgnoreForRecordTriviality(FD))
13604 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13605 }
13606
13607 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13608 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13609 bool InNonTrivialUnion) {}
13610
13611 // The non-trivial C union type or the struct/union type that contains a
13612 // non-trivial C union.
13613 QualType OrigTy;
13614 SourceLocation OrigLoc;
13615 NonTrivialCUnionContext UseContext;
13616 Sema &S;
13617};
13618
13619struct DiagNonTrivalCUnionCopyVisitor
13620 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13621 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13622
13623 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13624 NonTrivialCUnionContext UseContext, Sema &S)
13625 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13626
13627 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13628 const FieldDecl *FD, bool InNonTrivialUnion) {
13629 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13630 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13631 Args&: InNonTrivialUnion);
13632 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13633 }
13634
13635 void visitARCStrong(QualType QT, const FieldDecl *FD,
13636 bool InNonTrivialUnion) {
13637 if (InNonTrivialUnion)
13638 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13639 << 1 << 2 << QT << FD->getName();
13640 }
13641
13642 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13643 if (InNonTrivialUnion)
13644 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13645 << 1 << 2 << QT << FD->getName();
13646 }
13647
13648 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13649 const auto *RD = QT->castAsRecordDecl();
13650 if (RD->isUnion()) {
13651 if (OrigLoc.isValid()) {
13652 bool IsUnion = false;
13653 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13654 IsUnion = OrigRD->isUnion();
13655 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13656 << 2 << OrigTy << IsUnion << UseContext;
13657 // Reset OrigLoc so that this diagnostic is emitted only once.
13658 OrigLoc = SourceLocation();
13659 }
13660 InNonTrivialUnion = true;
13661 }
13662
13663 if (InNonTrivialUnion)
13664 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13665 << 0 << 2 << QT.getUnqualifiedType() << "";
13666
13667 for (const FieldDecl *FD : RD->fields())
13668 if (!shouldIgnoreForRecordTriviality(FD))
13669 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13670 }
13671
13672 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13673 if (InNonTrivialUnion)
13674 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13675 << 1 << 2 << QT << FD->getName();
13676 }
13677
13678 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13679 const FieldDecl *FD, bool InNonTrivialUnion) {}
13680 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13681 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13682 bool InNonTrivialUnion) {}
13683
13684 // The non-trivial C union type or the struct/union type that contains a
13685 // non-trivial C union.
13686 QualType OrigTy;
13687 SourceLocation OrigLoc;
13688 NonTrivialCUnionContext UseContext;
13689 Sema &S;
13690};
13691
13692} // namespace
13693
13694void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13695 NonTrivialCUnionContext UseContext,
13696 unsigned NonTrivialKind) {
13697 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13698 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13699 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13700 "shouldn't be called if type doesn't have a non-trivial C union");
13701
13702 if ((NonTrivialKind & NTCUK_Init) &&
13703 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13704 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13705 .visit(FT: QT, Args: nullptr, Args: false);
13706 if ((NonTrivialKind & NTCUK_Destruct) &&
13707 QT.hasNonTrivialToPrimitiveDestructCUnion())
13708 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13709 .visit(FT: QT, Args: nullptr, Args: false);
13710 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13711 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13712 .visit(FT: QT, Args: nullptr, Args: false);
13713}
13714
13715bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13716 const VarDecl *Dcl) {
13717 if (!getLangOpts().CPlusPlus)
13718 return false;
13719
13720 // We only need to warn if the definition is in a header file, so wait to
13721 // diagnose until we've seen the definition.
13722 if (!Dcl->isThisDeclarationADefinition())
13723 return false;
13724
13725 // If an object is defined in a source file, its definition can't get
13726 // duplicated since it will never appear in more than one TU.
13727 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13728 return false;
13729
13730 // If the variable we're looking at is a static local, then we actually care
13731 // about the properties of the function containing it.
13732 const ValueDecl *Target = Dcl;
13733 // VarDecls and FunctionDecls have different functions for checking
13734 // inline-ness, and whether they were originally templated, so we have to
13735 // call the appropriate functions manually.
13736 bool TargetIsInline = Dcl->isInline();
13737 bool TargetWasTemplated =
13738 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13739
13740 // Update the Target and TargetIsInline property if necessary
13741 if (Dcl->isStaticLocal()) {
13742 const DeclContext *Ctx = Dcl->getDeclContext();
13743 if (!Ctx)
13744 return false;
13745
13746 const FunctionDecl *FunDcl =
13747 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13748 if (!FunDcl)
13749 return false;
13750
13751 Target = FunDcl;
13752 // IsInlined() checks for the C++ inline property
13753 TargetIsInline = FunDcl->isInlined();
13754 TargetWasTemplated =
13755 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13756 }
13757
13758 // Non-inline functions/variables can only legally appear in one TU
13759 // unless they were part of a template. Unfortunately, making complex
13760 // template instantiations visible is infeasible in practice, since
13761 // everything the template depends on also has to be visible. To avoid
13762 // giving impractical-to-fix warnings, don't warn if we're inside
13763 // something that was templated, even on inline stuff.
13764 if (!TargetIsInline || TargetWasTemplated)
13765 return false;
13766
13767 // If the object isn't hidden, the dynamic linker will prevent duplication.
13768 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13769
13770 // The target is "hidden" (from the dynamic linker) if:
13771 // 1. On posix, it has hidden visibility, or
13772 // 2. On windows, it has no import/export annotation, and neither does the
13773 // class which directly contains it.
13774 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13775 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13776 return false;
13777
13778 // If the variable isn't directly annotated, check to see if it's a member
13779 // of an annotated class.
13780 const CXXRecordDecl *Ctx =
13781 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13782 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13783 return false;
13784
13785 } else if (Lnk.getVisibility() != HiddenVisibility) {
13786 // Posix case
13787 return false;
13788 }
13789
13790 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13791 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13792 return false;
13793
13794 return true;
13795}
13796
13797// Determine whether the object seems mutable for the purpose of diagnosing
13798// possible unique object duplication, i.e. non-const-qualified, and
13799// not an always-constant type like a function.
13800// Not perfect: doesn't account for mutable members, for example, or
13801// elements of container types.
13802// For nested pointers, any individual level being non-const is sufficient.
13803static bool looksMutable(QualType T, const ASTContext &Ctx) {
13804 T = T.getNonReferenceType();
13805 if (T->isFunctionType())
13806 return false;
13807 if (!T.isConstant(Ctx))
13808 return true;
13809 if (T->isPointerType())
13810 return looksMutable(T: T->getPointeeType(), Ctx);
13811 return false;
13812}
13813
13814void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13815 // If this object has external linkage and hidden visibility, it might be
13816 // duplicated when built into a shared library, which causes problems if it's
13817 // mutable (since the copies won't be in sync) or its initialization has side
13818 // effects (since it will run once per copy instead of once globally).
13819
13820 // Don't diagnose if we're inside a template, because it's not practical to
13821 // fix the warning in most cases.
13822 if (!VD->isTemplated() &&
13823 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13824
13825 QualType Type = VD->getType();
13826 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13827 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13828 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13829 }
13830
13831 // To keep false positives low, only warn if we're certain that the
13832 // initializer has side effects. Don't warn on operator new, since a mutable
13833 // pointer will trigger the previous warning, and an immutable pointer
13834 // getting duplicated just results in a little extra memory usage.
13835 const Expr *Init = VD->getAnyInitializer();
13836 if (Init &&
13837 Init->HasSideEffects(Ctx: VD->getASTContext(),
13838 /*IncludePossibleEffects=*/false) &&
13839 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13840 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13841 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13842 }
13843 }
13844}
13845
13846void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13847 llvm::scope_exit ResetDeclForInitializer([this]() {
13848 if (!this->ExprEvalContexts.empty())
13849 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13850 });
13851
13852 // If there is no declaration, there was an error parsing it. Just ignore
13853 // the initializer.
13854 if (!RealDecl) {
13855 return;
13856 }
13857
13858 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13859 if (!Method->isInvalidDecl()) {
13860 // Pure-specifiers are handled in ActOnPureSpecifier.
13861 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13862 << Method->getDeclName() << Init->getSourceRange();
13863 Method->setInvalidDecl();
13864 }
13865 return;
13866 }
13867
13868 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13869 if (!VDecl) {
13870 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13871 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13872 RealDecl->setInvalidDecl();
13873 return;
13874 }
13875
13876 if (VDecl->isInvalidDecl()) {
13877 ExprResult Recovery =
13878 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13879 if (Expr *E = Recovery.get())
13880 VDecl->setInit(E);
13881 return;
13882 }
13883
13884 // WebAssembly tables can't be used to initialise a variable.
13885 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13886 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13887 VDecl->setInvalidDecl();
13888 return;
13889 }
13890
13891 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13892 if (VDecl->getType()->isUndeducedType()) {
13893 if (Init->containsErrors()) {
13894 // Invalidate the decl as we don't know the type for recovery-expr yet.
13895 RealDecl->setInvalidDecl();
13896 VDecl->setInit(Init);
13897 return;
13898 }
13899
13900 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
13901 assert(VDecl->isInvalidDecl() &&
13902 "decl should be invalidated when deduce fails");
13903 if (auto *RecoveryExpr =
13904 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
13905 .get())
13906 VDecl->setInit(RecoveryExpr);
13907 return;
13908 }
13909 }
13910
13911 this->CheckAttributesOnDeducedType(D: RealDecl);
13912
13913 // we don't initialize groupshared variables so warn and return
13914 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
13915 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
13916 return;
13917 }
13918
13919 // dllimport cannot be used on variable definitions.
13920 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13921 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13922 VDecl->setInvalidDecl();
13923 return;
13924 }
13925
13926 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13927 // the identifier has external or internal linkage, the declaration shall
13928 // have no initializer for the identifier.
13929 // C++14 [dcl.init]p5 is the same restriction for C++.
13930 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13931 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
13932 VDecl->setInvalidDecl();
13933 return;
13934 }
13935
13936 if (!VDecl->getType()->isDependentType()) {
13937 // A definition must end up with a complete type, which means it must be
13938 // complete with the restriction that an array type might be completed by
13939 // the initializer; note that later code assumes this restriction.
13940 QualType BaseDeclType = VDecl->getType();
13941 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13942 BaseDeclType = Array->getElementType();
13943 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
13944 DiagID: diag::err_typecheck_decl_incomplete_type)) {
13945 RealDecl->setInvalidDecl();
13946 return;
13947 }
13948
13949 // The variable can not have an abstract class type.
13950 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
13951 DiagID: diag::err_abstract_type_in_decl,
13952 Args: AbstractVariableType))
13953 VDecl->setInvalidDecl();
13954 }
13955
13956 // C++ [module.import/6]
13957 // ...
13958 // A header unit shall not contain a definition of a non-inline function or
13959 // variable whose name has external linkage.
13960 //
13961 // We choose to allow weak & selectany definitions, as they are common in
13962 // headers, and have semantics similar to inline definitions which are allowed
13963 // in header units.
13964 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13965 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13966 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13967 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
13968 !VDecl->getInstantiatedFromStaticDataMember() &&
13969 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13970 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
13971 VDecl->setInvalidDecl();
13972 }
13973
13974 // If adding the initializer will turn this declaration into a definition,
13975 // and we already have a definition for this variable, diagnose or otherwise
13976 // handle the situation.
13977 if (VarDecl *Def = VDecl->getDefinition())
13978 if (Def != VDecl &&
13979 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13980 !VDecl->isThisDeclarationADemotedDefinition() &&
13981 checkVarDeclRedefinition(Old: Def, New: VDecl))
13982 return;
13983
13984 if (getLangOpts().CPlusPlus) {
13985 // C++ [class.static.data]p4
13986 // If a static data member is of const integral or const
13987 // enumeration type, its declaration in the class definition can
13988 // specify a constant-initializer which shall be an integral
13989 // constant expression (5.19). In that case, the member can appear
13990 // in integral constant expressions. The member shall still be
13991 // defined in a namespace scope if it is used in the program and the
13992 // namespace scope definition shall not contain an initializer.
13993 //
13994 // We already performed a redefinition check above, but for static
13995 // data members we also need to check whether there was an in-class
13996 // declaration with an initializer.
13997 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13998 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
13999 << VDecl->getDeclName();
14000 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14001 DiagID: diag::note_previous_initializer)
14002 << 0;
14003 return;
14004 }
14005
14006 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14007 VDecl->setInvalidDecl();
14008 return;
14009 }
14010 }
14011
14012 // If the variable has an initializer and local storage, check whether
14013 // anything jumps over the initialization.
14014 if (VDecl->hasLocalStorage())
14015 setFunctionHasBranchProtectedScope();
14016
14017 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14018 // a kernel function cannot be initialized."
14019 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14020 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14021 VDecl->setInvalidDecl();
14022 return;
14023 }
14024
14025 // The LoaderUninitialized attribute acts as a definition (of undef).
14026 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14027 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14028 VDecl->setInvalidDecl();
14029 return;
14030 }
14031
14032 if (getLangOpts().HLSL)
14033 if (!HLSL().handleInitialization(VDecl, Init))
14034 return;
14035
14036 // Get the decls type and save a reference for later, since
14037 // CheckInitializerTypes may change it.
14038 QualType DclT = VDecl->getType(), SavT = DclT;
14039
14040 // Expressions default to 'id' when we're in a debugger
14041 // and we are assigning it to a variable of Objective-C pointer type.
14042 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14043 Init->getType() == Context.UnknownAnyTy) {
14044 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14045 if (!Result.isUsable()) {
14046 VDecl->setInvalidDecl();
14047 return;
14048 }
14049 Init = Result.get();
14050 }
14051
14052 // Perform the initialization.
14053 bool InitializedFromParenListExpr = false;
14054 bool IsParenListInit = false;
14055 if (!VDecl->isInvalidDecl()) {
14056 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14057 InitializationKind Kind = InitializationKind::CreateForInit(
14058 Loc: VDecl->getLocation(), DirectInit, Init);
14059
14060 MultiExprArg Args = Init;
14061 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14062 Args =
14063 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14064 InitializedFromParenListExpr = true;
14065 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14066 Args = CXXDirectInit->getInitExprs();
14067 InitializedFromParenListExpr = true;
14068 }
14069
14070 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14071 /*TopLevelOfInitList=*/false,
14072 /*TreatUnavailableAsInvalid=*/false);
14073 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14074 if (!Result.isUsable()) {
14075 // If the provided initializer fails to initialize the var decl,
14076 // we attach a recovery expr for better recovery.
14077 auto RecoveryExpr =
14078 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14079 if (RecoveryExpr.get())
14080 VDecl->setInit(RecoveryExpr.get());
14081 // In general, for error recovery purposes, the initializer doesn't play
14082 // part in the valid bit of the declaration. There are a few exceptions:
14083 // 1) if the var decl has a deduced auto type, and the type cannot be
14084 // deduced by an invalid initializer;
14085 // 2) if the var decl is a decomposition decl with a non-deduced type,
14086 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14087 // Case 1) was already handled elsewhere.
14088 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14089 VDecl->setInvalidDecl();
14090 return;
14091 }
14092
14093 Init = Result.getAs<Expr>();
14094 IsParenListInit = !InitSeq.steps().empty() &&
14095 InitSeq.step_begin()->Kind ==
14096 InitializationSequence::SK_ParenthesizedListInit;
14097 QualType VDeclType = VDecl->getType();
14098 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14099 !VDeclType->isDependentType() &&
14100 Context.getAsIncompleteArrayType(T: VDeclType) &&
14101 Context.getAsIncompleteArrayType(T: Init->getType())) {
14102 // Bail out if it is not possible to deduce array size from the
14103 // initializer.
14104 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14105 << VDeclType;
14106 VDecl->setInvalidDecl();
14107 return;
14108 }
14109 }
14110
14111 // Check for self-references within variable initializers.
14112 // Variables declared within a function/method body (except for references)
14113 // are handled by a dataflow analysis.
14114 // This is undefined behavior in C++, but valid in C.
14115 if (getLangOpts().CPlusPlus)
14116 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14117 VDecl->getType()->isReferenceType())
14118 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14119
14120 // If the type changed, it means we had an incomplete type that was
14121 // completed by the initializer. For example:
14122 // int ary[] = { 1, 3, 5 };
14123 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14124 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14125 VDecl->setType(DclT);
14126
14127 if (!VDecl->isInvalidDecl()) {
14128 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14129
14130 if (VDecl->hasAttr<BlocksAttr>())
14131 ObjC().checkRetainCycles(Var: VDecl, Init);
14132
14133 // It is safe to assign a weak reference into a strong variable.
14134 // Although this code can still have problems:
14135 // id x = self.weakProp;
14136 // id y = self.weakProp;
14137 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14138 // paths through the function. This should be revisited if
14139 // -Wrepeated-use-of-weak is made flow-sensitive.
14140 if (FunctionScopeInfo *FSI = getCurFunction())
14141 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14142 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14143 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14144 Loc: Init->getBeginLoc()))
14145 FSI->markSafeWeakUse(E: Init);
14146 }
14147
14148 // The initialization is usually a full-expression.
14149 //
14150 // FIXME: If this is a braced initialization of an aggregate, it is not
14151 // an expression, and each individual field initializer is a separate
14152 // full-expression. For instance, in:
14153 //
14154 // struct Temp { ~Temp(); };
14155 // struct S { S(Temp); };
14156 // struct T { S a, b; } t = { Temp(), Temp() }
14157 //
14158 // we should destroy the first Temp before constructing the second.
14159
14160 // Set context flag for OverflowBehaviorType initialization analysis
14161 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14162 true);
14163 ExprResult Result =
14164 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14165 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14166 if (!Result.isUsable()) {
14167 VDecl->setInvalidDecl();
14168 return;
14169 }
14170 Init = Result.get();
14171
14172 // Attach the initializer to the decl.
14173 VDecl->setInit(Init);
14174
14175 if (VDecl->isLocalVarDecl()) {
14176 // Don't check the initializer if the declaration is malformed.
14177 if (VDecl->isInvalidDecl()) {
14178 // do nothing
14179
14180 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14181 // This is true even in C++ for OpenCL.
14182 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14183 CheckForConstantInitializer(Init);
14184
14185 // Otherwise, C++ does not restrict the initializer.
14186 } else if (getLangOpts().CPlusPlus) {
14187 // do nothing
14188
14189 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14190 // static storage duration shall be constant expressions or string literals.
14191 } else if (VDecl->getStorageClass() == SC_Static) {
14192 // Avoid evaluating the initializer twice for constexpr variables. It will
14193 // be evaluated later.
14194 if (!VDecl->isConstexpr())
14195 CheckForConstantInitializer(Init);
14196
14197 // C89 is stricter than C99 for aggregate initializers.
14198 // C89 6.5.7p3: All the expressions [...] in an initializer list
14199 // for an object that has aggregate or union type shall be
14200 // constant expressions.
14201 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14202 isa<InitListExpr>(Val: Init)) {
14203 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14204 }
14205
14206 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14207 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14208 if (VDecl->hasLocalStorage())
14209 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14210 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14211 VDecl->getLexicalDeclContext()->isRecord()) {
14212 // This is an in-class initialization for a static data member, e.g.,
14213 //
14214 // struct S {
14215 // static const int value = 17;
14216 // };
14217
14218 // C++ [class.mem]p4:
14219 // A member-declarator can contain a constant-initializer only
14220 // if it declares a static member (9.4) of const integral or
14221 // const enumeration type, see 9.4.2.
14222 //
14223 // C++11 [class.static.data]p3:
14224 // If a non-volatile non-inline const static data member is of integral
14225 // or enumeration type, its declaration in the class definition can
14226 // specify a brace-or-equal-initializer in which every initializer-clause
14227 // that is an assignment-expression is a constant expression. A static
14228 // data member of literal type can be declared in the class definition
14229 // with the constexpr specifier; if so, its declaration shall specify a
14230 // brace-or-equal-initializer in which every initializer-clause that is
14231 // an assignment-expression is a constant expression.
14232
14233 // Do nothing on dependent types.
14234 if (DclT->isDependentType()) {
14235
14236 // Allow any 'static constexpr' members, whether or not they are of literal
14237 // type. We separately check that every constexpr variable is of literal
14238 // type.
14239 } else if (VDecl->isConstexpr()) {
14240
14241 // Require constness.
14242 } else if (!DclT.isConstQualified()) {
14243 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14244 << Init->getSourceRange();
14245 VDecl->setInvalidDecl();
14246
14247 // We allow integer constant expressions in all cases.
14248 } else if (DclT->isIntegralOrEnumerationType()) {
14249 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14250 // In C++11, a non-constexpr const static data member with an
14251 // in-class initializer cannot be volatile.
14252 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14253
14254 // We allow foldable floating-point constants as an extension.
14255 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14256 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14257 // it anyway and provide a fixit to add the 'constexpr'.
14258 if (getLangOpts().CPlusPlus11) {
14259 Diag(Loc: VDecl->getLocation(),
14260 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14261 << DclT << Init->getSourceRange();
14262 Diag(Loc: VDecl->getBeginLoc(),
14263 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14264 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14265 } else {
14266 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14267 << DclT << Init->getSourceRange();
14268
14269 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14270 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14271 << Init->getSourceRange();
14272 VDecl->setInvalidDecl();
14273 }
14274 }
14275
14276 // Suggest adding 'constexpr' in C++11 for literal types.
14277 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14278 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14279 << DclT << Init->getSourceRange()
14280 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14281 VDecl->setConstexpr(true);
14282
14283 } else {
14284 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14285 << DclT << Init->getSourceRange();
14286 VDecl->setInvalidDecl();
14287 }
14288 } else if (VDecl->isFileVarDecl()) {
14289 // In C, extern is typically used to avoid tentative definitions when
14290 // declaring variables in headers, but adding an initializer makes it a
14291 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14292 // In C++, extern is often used to give implicitly static const variables
14293 // external linkage, so don't warn in that case. If selectany is present,
14294 // this might be header code intended for C and C++ inclusion, so apply the
14295 // C++ rules.
14296 if (VDecl->getStorageClass() == SC_Extern &&
14297 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14298 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14299 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14300 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14301 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14302
14303 // In Microsoft C++ mode, a const variable defined in namespace scope has
14304 // external linkage by default if the variable is declared with
14305 // __declspec(dllexport).
14306 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14307 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14308 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14309 VDecl->setStorageClass(SC_Extern);
14310
14311 // C99 6.7.8p4. All file scoped initializers need to be constant.
14312 // Avoid duplicate diagnostics for constexpr variables.
14313 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14314 !VDecl->isConstexpr())
14315 CheckForConstantInitializer(Init);
14316 }
14317
14318 QualType InitType = Init->getType();
14319 if (!InitType.isNull() &&
14320 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14321 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14322 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14323
14324 // We will represent direct-initialization similarly to copy-initialization:
14325 // int x(1); -as-> int x = 1;
14326 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14327 //
14328 // Clients that want to distinguish between the two forms, can check for
14329 // direct initializer using VarDecl::getInitStyle().
14330 // A major benefit is that clients that don't particularly care about which
14331 // exactly form was it (like the CodeGen) can handle both cases without
14332 // special case code.
14333
14334 // C++ 8.5p11:
14335 // The form of initialization (using parentheses or '=') matters
14336 // when the entity being initialized has class type.
14337 if (InitializedFromParenListExpr) {
14338 assert(DirectInit && "Call-style initializer must be direct init.");
14339 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14340 : VarDecl::CallInit);
14341 } else if (DirectInit) {
14342 // This must be list-initialization. No other way is direct-initialization.
14343 VDecl->setInitStyle(VarDecl::ListInit);
14344 }
14345
14346 if (LangOpts.OpenMP &&
14347 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14348 VDecl->isFileVarDecl())
14349 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14350 CheckCompleteVariableDeclaration(VD: VDecl);
14351
14352 if (LangOpts.OpenACC && !InitType.isNull())
14353 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14354}
14355
14356void Sema::ActOnInitializerError(Decl *D) {
14357 // Our main concern here is re-establishing invariants like "a
14358 // variable's type is either dependent or complete".
14359 if (!D || D->isInvalidDecl()) return;
14360
14361 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14362 if (!VD) return;
14363
14364 // Bindings are not usable if we can't make sense of the initializer.
14365 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14366 for (auto *BD : DD->bindings())
14367 BD->setInvalidDecl();
14368
14369 // Auto types are meaningless if we can't make sense of the initializer.
14370 if (VD->getType()->isUndeducedType()) {
14371 D->setInvalidDecl();
14372 return;
14373 }
14374
14375 QualType Ty = VD->getType();
14376 if (Ty->isDependentType()) return;
14377
14378 // Require a complete type.
14379 if (RequireCompleteType(Loc: VD->getLocation(),
14380 T: Context.getBaseElementType(QT: Ty),
14381 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14382 VD->setInvalidDecl();
14383 return;
14384 }
14385
14386 // Require a non-abstract type.
14387 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14388 DiagID: diag::err_abstract_type_in_decl,
14389 Args: AbstractVariableType)) {
14390 VD->setInvalidDecl();
14391 return;
14392 }
14393
14394 // Don't bother complaining about constructors or destructors,
14395 // though.
14396}
14397
14398void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14399 // If there is no declaration, there was an error parsing it. Just ignore it.
14400 if (!RealDecl)
14401 return;
14402
14403 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14404 QualType Type = Var->getType();
14405
14406 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14407 if (isa<DecompositionDecl>(Val: RealDecl)) {
14408 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14409 Var->setInvalidDecl();
14410 return;
14411 }
14412
14413 if (Type->isUndeducedType() &&
14414 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14415 return;
14416
14417 this->CheckAttributesOnDeducedType(D: RealDecl);
14418
14419 // C++11 [class.static.data]p3: A static data member can be declared with
14420 // the constexpr specifier; if so, its declaration shall specify
14421 // a brace-or-equal-initializer.
14422 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14423 // the definition of a variable [...] or the declaration of a static data
14424 // member.
14425 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14426 !Var->isThisDeclarationADemotedDefinition()) {
14427 if (Var->isStaticDataMember()) {
14428 // C++1z removes the relevant rule; the in-class declaration is always
14429 // a definition there.
14430 if (!getLangOpts().CPlusPlus17 &&
14431 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14432 Diag(Loc: Var->getLocation(),
14433 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14434 << Var;
14435 Var->setInvalidDecl();
14436 return;
14437 }
14438 } else {
14439 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14440 Var->setInvalidDecl();
14441 return;
14442 }
14443 }
14444
14445 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14446 // be initialized.
14447 if (!Var->isInvalidDecl() &&
14448 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14449 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14450 bool HasConstExprDefaultConstructor = false;
14451 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14452 for (auto *Ctor : RD->ctors()) {
14453 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14454 Ctor->getMethodQualifiers().getAddressSpace() ==
14455 LangAS::opencl_constant) {
14456 HasConstExprDefaultConstructor = true;
14457 }
14458 }
14459 }
14460 if (!HasConstExprDefaultConstructor) {
14461 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14462 Var->setInvalidDecl();
14463 return;
14464 }
14465 }
14466
14467 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14468 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14469 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14470 Var->setInvalidDecl();
14471 return;
14472 }
14473
14474 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14475 if (Var->getStorageClass() == SC_Extern) {
14476 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14477 << Var;
14478 Var->setInvalidDecl();
14479 return;
14480 }
14481 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14482 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14483 Var->setInvalidDecl();
14484 return;
14485 }
14486 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14487 if (!RD->hasTrivialDefaultConstructor()) {
14488 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14489 Var->setInvalidDecl();
14490 return;
14491 }
14492 }
14493 // The declaration is uninitialized, no need for further checks.
14494 return;
14495 }
14496
14497 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14498 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14499 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14500 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14501 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14502 NonTrivialKind: NTCUK_Init);
14503
14504 switch (DefKind) {
14505 case VarDecl::Definition:
14506 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14507 break;
14508
14509 // We have an out-of-line definition of a static data member
14510 // that has an in-class initializer, so we type-check this like
14511 // a declaration.
14512 //
14513 [[fallthrough]];
14514
14515 case VarDecl::DeclarationOnly:
14516 // It's only a declaration.
14517
14518 // Block scope. C99 6.7p7: If an identifier for an object is
14519 // declared with no linkage (C99 6.2.2p6), the type for the
14520 // object shall be complete.
14521 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14522 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14523 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14524 DiagID: diag::err_typecheck_decl_incomplete_type))
14525 Var->setInvalidDecl();
14526
14527 // Make sure that the type is not abstract.
14528 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14529 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14530 DiagID: diag::err_abstract_type_in_decl,
14531 Args: AbstractVariableType))
14532 Var->setInvalidDecl();
14533 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14534 Var->getStorageClass() == SC_PrivateExtern) {
14535 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14536 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14537 }
14538
14539 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14540 !Var->isInvalidDecl())
14541 ExternalDeclarations.push_back(Elt: Var);
14542
14543 return;
14544
14545 case VarDecl::TentativeDefinition:
14546 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14547 // object that has file scope without an initializer, and without a
14548 // storage-class specifier or with the storage-class specifier "static",
14549 // constitutes a tentative definition. Note: A tentative definition with
14550 // external linkage is valid (C99 6.2.2p5).
14551 if (!Var->isInvalidDecl()) {
14552 if (const IncompleteArrayType *ArrayT
14553 = Context.getAsIncompleteArrayType(T: Type)) {
14554 if (RequireCompleteSizedType(
14555 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14556 DiagID: diag::err_array_incomplete_or_sizeless_type))
14557 Var->setInvalidDecl();
14558 }
14559 if (Var->getStorageClass() == SC_Static) {
14560 // C99 6.9.2p3: If the declaration of an identifier for an object is
14561 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14562 // declared type shall not be an incomplete type.
14563 // NOTE: code such as the following
14564 // static struct s;
14565 // struct s { int a; };
14566 // is accepted by gcc. Hence here we issue a warning instead of
14567 // an error and we do not invalidate the static declaration.
14568 // NOTE: to avoid multiple warnings, only check the first declaration.
14569 if (Var->isFirstDecl())
14570 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14571 DiagID: diag::ext_typecheck_decl_incomplete_type,
14572 Args: Type->isArrayType());
14573 }
14574 }
14575
14576 // Record the tentative definition; we're done.
14577 if (!Var->isInvalidDecl())
14578 TentativeDefinitions.push_back(LocalValue: Var);
14579 return;
14580 }
14581
14582 // Provide a specific diagnostic for uninitialized variable definitions
14583 // with incomplete array type, unless it is a global unbounded HLSL resource
14584 // array.
14585 if (Type->isIncompleteArrayType() &&
14586 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14587 Type->isHLSLResourceRecordArray())) {
14588 if (Var->isConstexpr())
14589 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14590 << Var;
14591 else
14592 Diag(Loc: Var->getLocation(),
14593 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14594 Var->setInvalidDecl();
14595 return;
14596 }
14597
14598 // Provide a specific diagnostic for uninitialized variable
14599 // definitions with reference type.
14600 if (Type->isReferenceType()) {
14601 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14602 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14603 return;
14604 }
14605
14606 // Do not attempt to type-check the default initializer for a
14607 // variable with dependent type.
14608 if (Type->isDependentType())
14609 return;
14610
14611 if (Var->isInvalidDecl())
14612 return;
14613
14614 if (!Var->hasAttr<AliasAttr>()) {
14615 if (RequireCompleteType(Loc: Var->getLocation(),
14616 T: Context.getBaseElementType(QT: Type),
14617 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14618 Var->setInvalidDecl();
14619 return;
14620 }
14621 } else {
14622 return;
14623 }
14624
14625 // The variable can not have an abstract class type.
14626 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14627 DiagID: diag::err_abstract_type_in_decl,
14628 Args: AbstractVariableType)) {
14629 Var->setInvalidDecl();
14630 return;
14631 }
14632
14633 // In C, if the definition is const-qualified and has no initializer, it
14634 // is left uninitialized unless it has static or thread storage duration.
14635 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14636 unsigned DiagID = diag::warn_default_init_const_unsafe;
14637 if (Var->getStorageDuration() == SD_Static ||
14638 Var->getStorageDuration() == SD_Thread)
14639 DiagID = diag::warn_default_init_const;
14640
14641 bool EmitCppCompat = !Diags.isIgnored(
14642 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14643 Loc: Var->getLocation());
14644
14645 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14646 }
14647
14648 // Check for jumps past the implicit initializer. C++0x
14649 // clarifies that this applies to a "variable with automatic
14650 // storage duration", not a "local variable".
14651 // C++11 [stmt.dcl]p3
14652 // A program that jumps from a point where a variable with automatic
14653 // storage duration is not in scope to a point where it is in scope is
14654 // ill-formed unless the variable has scalar type, class type with a
14655 // trivial default constructor and a trivial destructor, a cv-qualified
14656 // version of one of these types, or an array of one of the preceding
14657 // types and is declared without an initializer.
14658 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14659 if (const auto *CXXRecord =
14660 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14661 // Mark the function (if we're in one) for further checking even if the
14662 // looser rules of C++11 do not require such checks, so that we can
14663 // diagnose incompatibilities with C++98.
14664 if (!CXXRecord->isPOD())
14665 setFunctionHasBranchProtectedScope();
14666 }
14667 }
14668 // In OpenCL, we can't initialize objects in the __local address space,
14669 // even implicitly, so don't synthesize an implicit initializer.
14670 if (getLangOpts().OpenCL &&
14671 Var->getType().getAddressSpace() == LangAS::opencl_local)
14672 return;
14673
14674 // Handle HLSL uninitialized decls
14675 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14676 return;
14677
14678 // HLSL input & push-constant variables are expected to be externally
14679 // initialized, even when marked `static`.
14680 if (getLangOpts().HLSL &&
14681 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14682 return;
14683
14684 // C++03 [dcl.init]p9:
14685 // If no initializer is specified for an object, and the
14686 // object is of (possibly cv-qualified) non-POD class type (or
14687 // array thereof), the object shall be default-initialized; if
14688 // the object is of const-qualified type, the underlying class
14689 // type shall have a user-declared default
14690 // constructor. Otherwise, if no initializer is specified for
14691 // a non- static object, the object and its subobjects, if
14692 // any, have an indeterminate initial value); if the object
14693 // or any of its subobjects are of const-qualified type, the
14694 // program is ill-formed.
14695 // C++0x [dcl.init]p11:
14696 // If no initializer is specified for an object, the object is
14697 // default-initialized; [...].
14698 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14699 InitializationKind Kind
14700 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14701
14702 InitializationSequence InitSeq(*this, Entity, Kind, {});
14703 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14704
14705 if (Init.get()) {
14706 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14707 // This is important for template substitution.
14708 Var->setInitStyle(VarDecl::CallInit);
14709 } else if (Init.isInvalid()) {
14710 // If default-init fails, attach a recovery-expr initializer to track
14711 // that initialization was attempted and failed.
14712 auto RecoveryExpr =
14713 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14714 if (RecoveryExpr.get())
14715 Var->setInit(RecoveryExpr.get());
14716 }
14717
14718 CheckCompleteVariableDeclaration(VD: Var);
14719 }
14720}
14721
14722void Sema::ActOnCXXForRangeDecl(Decl *D) {
14723 // If there is no declaration, there was an error parsing it. Ignore it.
14724 if (!D)
14725 return;
14726
14727 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14728 if (!VD) {
14729 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14730 D->setInvalidDecl();
14731 return;
14732 }
14733
14734 VD->setCXXForRangeDecl(true);
14735
14736 // for-range-declaration cannot be given a storage class specifier.
14737 int Error = -1;
14738 switch (VD->getStorageClass()) {
14739 case SC_None:
14740 break;
14741 case SC_Extern:
14742 Error = 0;
14743 break;
14744 case SC_Static:
14745 Error = 1;
14746 break;
14747 case SC_PrivateExtern:
14748 Error = 2;
14749 break;
14750 case SC_Auto:
14751 Error = 3;
14752 break;
14753 case SC_Register:
14754 Error = 4;
14755 break;
14756 }
14757
14758 // for-range-declaration cannot be given a storage class specifier con't.
14759 switch (VD->getTSCSpec()) {
14760 case TSCS_thread_local:
14761 Error = 6;
14762 break;
14763 case TSCS___thread:
14764 case TSCS__Thread_local:
14765 case TSCS_unspecified:
14766 break;
14767 }
14768
14769 if (Error != -1) {
14770 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14771 << VD << Error;
14772 D->setInvalidDecl();
14773 }
14774}
14775
14776StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14777 IdentifierInfo *Ident,
14778 ParsedAttributes &Attrs) {
14779 // C++1y [stmt.iter]p1:
14780 // A range-based for statement of the form
14781 // for ( for-range-identifier : for-range-initializer ) statement
14782 // is equivalent to
14783 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14784 DeclSpec DS(Attrs.getPool().getFactory());
14785
14786 const char *PrevSpec;
14787 unsigned DiagID;
14788 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14789 Policy: getPrintingPolicy());
14790
14791 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14792 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14793 D.takeAttributesAppending(attrs&: Attrs);
14794
14795 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14796 EndLoc: IdentLoc);
14797 Decl *Var = ActOnDeclarator(S, D);
14798 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14799 FinalizeDeclaration(D: Var);
14800 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14801 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14802 : IdentLoc);
14803}
14804
14805void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
14806 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
14807 return;
14808 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
14809 QualType MethodType = MD->getType();
14810 QualType AttributedType =
14811 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
14812 TypeLocBuilder TLB;
14813 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14814 TLB.pushFullCopy(L: TSI->getTypeLoc());
14815 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
14816 TyLoc.setAttr(Attr);
14817 MD->setType(AttributedType);
14818 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
14819}
14820
14821void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14822 if (var->isInvalidDecl()) return;
14823
14824 CUDA().MaybeAddConstantAttr(VD: var);
14825
14826 if (getLangOpts().OpenCL) {
14827 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14828 // initialiser
14829 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14830 !var->hasInit()) {
14831 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14832 << 1 /*Init*/;
14833 var->setInvalidDecl();
14834 return;
14835 }
14836 }
14837
14838 // In Objective-C, don't allow jumps past the implicit initialization of a
14839 // local retaining variable.
14840 if (getLangOpts().ObjC &&
14841 var->hasLocalStorage()) {
14842 switch (var->getType().getObjCLifetime()) {
14843 case Qualifiers::OCL_None:
14844 case Qualifiers::OCL_ExplicitNone:
14845 case Qualifiers::OCL_Autoreleasing:
14846 break;
14847
14848 case Qualifiers::OCL_Weak:
14849 case Qualifiers::OCL_Strong:
14850 setFunctionHasBranchProtectedScope();
14851 break;
14852 }
14853 }
14854
14855 if (var->hasLocalStorage() &&
14856 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14857 setFunctionHasBranchProtectedScope();
14858
14859 // Warn about externally-visible variables being defined without a
14860 // prior declaration. We only want to do this for global
14861 // declarations, but we also specifically need to avoid doing it for
14862 // class members because the linkage of an anonymous class can
14863 // change if it's later given a typedef name.
14864 if (var->isThisDeclarationADefinition() &&
14865 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14866 var->isExternallyVisible() && var->hasLinkage() &&
14867 !var->isInline() && !var->getDescribedVarTemplate() &&
14868 var->getStorageClass() != SC_Register &&
14869 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14870 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14871 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14872 Loc: var->getLocation())) {
14873 // Find a previous declaration that's not a definition.
14874 VarDecl *prev = var->getPreviousDecl();
14875 while (prev && prev->isThisDeclarationADefinition())
14876 prev = prev->getPreviousDecl();
14877
14878 if (!prev) {
14879 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14880 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14881 << /* variable */ 0;
14882 }
14883 }
14884
14885 // Cache the result of checking for constant initialization.
14886 std::optional<bool> CacheHasConstInit;
14887 const Expr *CacheCulprit = nullptr;
14888 auto checkConstInit = [&]() mutable {
14889 const Expr *Init = var->getInit();
14890 if (Init->isInstantiationDependent())
14891 return true;
14892
14893 if (!CacheHasConstInit)
14894 CacheHasConstInit = var->getInit()->isConstantInitializer(
14895 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14896 return *CacheHasConstInit;
14897 };
14898
14899 if (var->getTLSKind() == VarDecl::TLS_Static) {
14900 if (var->getType().isDestructedType()) {
14901 // GNU C++98 edits for __thread, [basic.start.term]p3:
14902 // The type of an object with thread storage duration shall not
14903 // have a non-trivial destructor.
14904 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14905 if (getLangOpts().CPlusPlus11)
14906 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14907 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14908 if (!checkConstInit()) {
14909 // GNU C++98 edits for __thread, [basic.start.init]p4:
14910 // An object of thread storage duration shall not require dynamic
14911 // initialization.
14912 // FIXME: Need strict checking here.
14913 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14914 << CacheCulprit->getSourceRange();
14915 if (getLangOpts().CPlusPlus11)
14916 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14917 }
14918 }
14919 }
14920
14921
14922 if (!var->getType()->isStructureType() && var->hasInit() &&
14923 isa<InitListExpr>(Val: var->getInit())) {
14924 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14925 unsigned NumInits = ILE->getNumInits();
14926 if (NumInits > 2)
14927 for (unsigned I = 0; I < NumInits; ++I) {
14928 const auto *Init = ILE->getInit(Init: I);
14929 if (!Init)
14930 break;
14931 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14932 if (!SL)
14933 break;
14934
14935 unsigned NumConcat = SL->getNumConcatenated();
14936 // Diagnose missing comma in string array initialization.
14937 // Do not warn when all the elements in the initializer are concatenated
14938 // together. Do not warn for macros too.
14939 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14940 bool OnlyOneMissingComma = true;
14941 for (unsigned J = I + 1; J < NumInits; ++J) {
14942 const auto *Init = ILE->getInit(Init: J);
14943 if (!Init)
14944 break;
14945 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14946 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14947 OnlyOneMissingComma = false;
14948 break;
14949 }
14950 }
14951
14952 if (OnlyOneMissingComma) {
14953 SmallVector<FixItHint, 1> Hints;
14954 for (unsigned i = 0; i < NumConcat - 1; ++i)
14955 Hints.push_back(Elt: FixItHint::CreateInsertion(
14956 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14957
14958 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
14959 DiagID: diag::warn_concatenated_literal_array_init)
14960 << Hints;
14961 Diag(Loc: SL->getBeginLoc(),
14962 DiagID: diag::note_concatenated_string_literal_silence);
14963 }
14964 // In any case, stop now.
14965 break;
14966 }
14967 }
14968 }
14969
14970
14971 QualType type = var->getType();
14972
14973 if (var->hasAttr<BlocksAttr>())
14974 getCurFunction()->addByrefBlockVar(VD: var);
14975
14976 Expr *Init = var->getInit();
14977 bool GlobalStorage = var->hasGlobalStorage();
14978 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14979 QualType baseType = Context.getBaseElementType(QT: type);
14980 bool HasConstInit = true;
14981
14982 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14983 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14984 << var;
14985
14986 // Check whether the initializer is sufficiently constant.
14987 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14988 !type->isDependentType() && Init && !Init->isValueDependent() &&
14989 (GlobalStorage || var->isConstexpr() ||
14990 var->mightBeUsableInConstantExpressions(C: Context))) {
14991 // If this variable might have a constant initializer or might be usable in
14992 // constant expressions, check whether or not it actually is now. We can't
14993 // do this lazily, because the result might depend on things that change
14994 // later, such as which constexpr functions happen to be defined.
14995 SmallVector<PartialDiagnosticAt, 8> Notes;
14996 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14997 // Prior to C++11, in contexts where a constant initializer is required,
14998 // the set of valid constant initializers is described by syntactic rules
14999 // in [expr.const]p2-6.
15000 // FIXME: Stricter checking for these rules would be useful for constinit /
15001 // -Wglobal-constructors.
15002 HasConstInit = checkConstInit();
15003
15004 // Compute and cache the constant value, and remember that we have a
15005 // constant initializer.
15006 if (HasConstInit) {
15007 if (var->isStaticDataMember() && !var->isInline() &&
15008 var->getLexicalDeclContext()->isRecord() &&
15009 type->isIntegralOrEnumerationType()) {
15010 // In C++98, in-class initialization for a static data member must
15011 // be an integer constant expression.
15012 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15013 Diag(Loc: Init->getExprLoc(),
15014 DiagID: diag::ext_in_class_initializer_non_constant)
15015 << Init->getSourceRange();
15016 }
15017 }
15018 (void)var->checkForConstantInitialization(Notes);
15019 Notes.clear();
15020 } else if (CacheCulprit) {
15021 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15022 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15023 Notes.back().second << CacheCulprit->getSourceRange();
15024 }
15025 } else {
15026 // Evaluate the initializer to see if it's a constant initializer.
15027 HasConstInit = var->checkForConstantInitialization(Notes);
15028 }
15029
15030 if (HasConstInit) {
15031 // FIXME: Consider replacing the initializer with a ConstantExpr.
15032 } else if (var->isConstexpr()) {
15033 SourceLocation DiagLoc = var->getLocation();
15034 // If the note doesn't add any useful information other than a source
15035 // location, fold it into the primary diagnostic.
15036 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15037 diag::note_invalid_subexpr_in_const_expr) {
15038 DiagLoc = Notes[0].first;
15039 Notes.clear();
15040 }
15041 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15042 << var << Init->getSourceRange();
15043 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15044 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15045 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15046 auto *Attr = var->getAttr<ConstInitAttr>();
15047 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15048 << Init->getSourceRange();
15049 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15050 << Attr->getRange() << Attr->isConstinit();
15051 for (auto &it : Notes)
15052 Diag(Loc: it.first, PD: it.second);
15053 } else if (var->isStaticDataMember() && !var->isInline() &&
15054 var->getLexicalDeclContext()->isRecord()) {
15055 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15056 << Init->getSourceRange();
15057 for (auto &it : Notes)
15058 Diag(Loc: it.first, PD: it.second);
15059 var->setInvalidDecl();
15060 } else if (IsGlobal &&
15061 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15062 Loc: var->getLocation())) {
15063 // Warn about globals which don't have a constant initializer. Don't
15064 // warn about globals with a non-trivial destructor because we already
15065 // warned about them.
15066 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15067 if (!(RD && !RD->hasTrivialDestructor())) {
15068 // checkConstInit() here permits trivial default initialization even in
15069 // C++11 onwards, where such an initializer is not a constant initializer
15070 // but nonetheless doesn't require a global constructor.
15071 if (!checkConstInit())
15072 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15073 << Init->getSourceRange();
15074 }
15075 }
15076 }
15077
15078 // Apply section attributes and pragmas to global variables.
15079 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15080 !inTemplateInstantiation()) {
15081 PragmaStack<StringLiteral *> *Stack = nullptr;
15082 int SectionFlags = ASTContext::PSF_Read;
15083 bool MSVCEnv =
15084 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15085 std::optional<QualType::NonConstantStorageReason> Reason;
15086 if (HasConstInit &&
15087 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15088 Stack = &ConstSegStack;
15089 } else {
15090 SectionFlags |= ASTContext::PSF_Write;
15091 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15092 }
15093 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15094 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15095 SectionFlags |= ASTContext::PSF_Implicit;
15096 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15097 } else if (Stack->CurrentValue) {
15098 if (Stack != &ConstSegStack && MSVCEnv &&
15099 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15100 var->getType().isConstQualified()) {
15101 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15102 NonConstNonReferenceType) &&
15103 "This case should've already been handled elsewhere");
15104 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15105 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15106 ? QualType::NonConstantStorageReason::NonTrivialCtor
15107 : *Reason);
15108 }
15109 SectionFlags |= ASTContext::PSF_Implicit;
15110 auto SectionName = Stack->CurrentValue->getString();
15111 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15112 Range: Stack->CurrentPragmaLocation,
15113 S: SectionAttr::Declspec_allocate));
15114 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15115 var->dropAttr<SectionAttr>();
15116 }
15117
15118 // Apply the init_seg attribute if this has an initializer. If the
15119 // initializer turns out to not be dynamic, we'll end up ignoring this
15120 // attribute.
15121 if (CurInitSeg && var->getInit())
15122 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15123 Range: CurInitSegLoc));
15124 }
15125
15126 // All the following checks are C++ only.
15127 if (!getLangOpts().CPlusPlus) {
15128 // If this variable must be emitted, add it as an initializer for the
15129 // current module.
15130 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15131 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15132 return;
15133 }
15134
15135 DiagnoseUniqueObjectDuplication(VD: var);
15136
15137 // Require the destructor.
15138 if (!type->isDependentType())
15139 if (auto *RD = baseType->getAsCXXRecordDecl())
15140 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15141
15142 // If this variable must be emitted, add it as an initializer for the current
15143 // module.
15144 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty() &&
15145 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15146 // For named modules, we may only emit non discardable variables.
15147 !isDiscardableGVALinkage(L: Context.GetGVALinkageForVariable(VD: var))))
15148 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15149
15150 // Build the bindings if this is a structured binding declaration.
15151 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15152 CheckCompleteDecompositionDeclaration(DD);
15153}
15154
15155void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15156 assert(VD->isStaticLocal());
15157
15158 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15159
15160 // Find outermost function when VD is in lambda function.
15161 while (FD && !getDLLAttr(D: FD) &&
15162 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15163 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15164 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15165 }
15166
15167 if (!FD)
15168 return;
15169
15170 // Static locals inherit dll attributes from their function.
15171 if (Attr *A = getDLLAttr(D: FD)) {
15172 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15173 NewAttr->setInherited(true);
15174 VD->addAttr(A: NewAttr);
15175 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15176 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15177 NewAttr->setInherited(true);
15178 VD->addAttr(A: NewAttr);
15179
15180 // Export this function to enforce exporting this static variable even
15181 // if it is not used in this compilation unit.
15182 if (!FD->hasAttr<DLLExportAttr>())
15183 FD->addAttr(A: NewAttr);
15184
15185 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15186 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15187 NewAttr->setInherited(true);
15188 VD->addAttr(A: NewAttr);
15189 }
15190}
15191
15192void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15193 assert(VD->getTLSKind());
15194
15195 // Perform TLS alignment check here after attributes attached to the variable
15196 // which may affect the alignment have been processed. Only perform the check
15197 // if the target has a maximum TLS alignment (zero means no constraints).
15198 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15199 // Protect the check so that it's not performed on dependent types and
15200 // dependent alignments (we can't determine the alignment in that case).
15201 if (!VD->hasDependentAlignment()) {
15202 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15203 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15204 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15205 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15206 << (unsigned)MaxAlignChars.getQuantity();
15207 }
15208 }
15209 }
15210}
15211
15212void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15213 // Note that we are no longer parsing the initializer for this declaration.
15214 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15215
15216 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15217 if (!VD)
15218 return;
15219
15220 // Emit any deferred warnings for the variable's initializer, even if the
15221 // variable is invalid
15222 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15223
15224 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15225 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15226 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15227 if (PragmaClangBSSSection.Valid)
15228 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15229 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15230 Range: PragmaClangBSSSection.PragmaLocation));
15231 if (PragmaClangDataSection.Valid)
15232 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15233 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15234 Range: PragmaClangDataSection.PragmaLocation));
15235 if (PragmaClangRodataSection.Valid)
15236 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15237 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15238 Range: PragmaClangRodataSection.PragmaLocation));
15239 if (PragmaClangRelroSection.Valid)
15240 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15241 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15242 Range: PragmaClangRelroSection.PragmaLocation));
15243 }
15244
15245 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15246 for (auto *BD : DD->bindings()) {
15247 FinalizeDeclaration(ThisDecl: BD);
15248 }
15249 }
15250
15251 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15252 K: BuiltinCountedByRefKind::Initializer);
15253
15254 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15255
15256 if (VD->isStaticLocal())
15257 CheckStaticLocalForDllExport(VD);
15258
15259 if (VD->getTLSKind())
15260 CheckThreadLocalForLargeAlignment(VD);
15261
15262 // Perform check for initializers of device-side global variables.
15263 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15264 // 7.5). We must also apply the same checks to all __shared__
15265 // variables whether they are local or not. CUDA also allows
15266 // constant initializers for __constant__ and __device__ variables.
15267 if (getLangOpts().CUDA)
15268 CUDA().checkAllowedInitializer(VD);
15269
15270 // Grab the dllimport or dllexport attribute off of the VarDecl.
15271 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15272
15273 // Imported static data members cannot be defined out-of-line.
15274 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15275 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15276 VD->isThisDeclarationADefinition()) {
15277 // We allow definitions of dllimport class template static data members
15278 // with a warning.
15279 CXXRecordDecl *Context =
15280 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15281 bool IsClassTemplateMember =
15282 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15283 Context->getDescribedClassTemplate();
15284
15285 Diag(Loc: VD->getLocation(),
15286 DiagID: IsClassTemplateMember
15287 ? diag::warn_attribute_dllimport_static_field_definition
15288 : diag::err_attribute_dllimport_static_field_definition);
15289 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15290 if (!IsClassTemplateMember)
15291 VD->setInvalidDecl();
15292 }
15293 }
15294
15295 // dllimport/dllexport variables cannot be thread local, their TLS index
15296 // isn't exported with the variable.
15297 if (DLLAttr && VD->getTLSKind()) {
15298 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15299 if (F && getDLLAttr(D: F)) {
15300 assert(VD->isStaticLocal());
15301 // But if this is a static local in a dlimport/dllexport function, the
15302 // function will never be inlined, which means the var would never be
15303 // imported, so having it marked import/export is safe.
15304 } else {
15305 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15306 << DLLAttr;
15307 VD->setInvalidDecl();
15308 }
15309 }
15310
15311 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15312 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15313 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15314 << Attr;
15315 VD->dropAttr<UsedAttr>();
15316 }
15317 }
15318 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15319 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15320 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15321 << Attr;
15322 VD->dropAttr<RetainAttr>();
15323 }
15324 }
15325
15326 const DeclContext *DC = VD->getDeclContext();
15327 // If there's a #pragma GCC visibility in scope, and this isn't a class
15328 // member, set the visibility of this variable.
15329 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15330 AddPushedVisibilityAttribute(RD: VD);
15331
15332 // FIXME: Warn on unused var template partial specializations.
15333 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15334 MarkUnusedFileScopedDecl(D: VD);
15335
15336 // Now we have parsed the initializer and can update the table of magic
15337 // tag values.
15338 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15339 !VD->getType()->isIntegralOrEnumerationType())
15340 return;
15341
15342 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15343 const Expr *MagicValueExpr = VD->getInit();
15344 if (!MagicValueExpr) {
15345 continue;
15346 }
15347 std::optional<llvm::APSInt> MagicValueInt;
15348 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15349 Diag(Loc: I->getRange().getBegin(),
15350 DiagID: diag::err_type_tag_for_datatype_not_ice)
15351 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15352 continue;
15353 }
15354 if (MagicValueInt->getActiveBits() > 64) {
15355 Diag(Loc: I->getRange().getBegin(),
15356 DiagID: diag::err_type_tag_for_datatype_too_large)
15357 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15358 continue;
15359 }
15360 uint64_t MagicValue = MagicValueInt->getZExtValue();
15361 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15362 MagicValue,
15363 Type: I->getMatchingCType(),
15364 LayoutCompatible: I->getLayoutCompatible(),
15365 MustBeNull: I->getMustBeNull());
15366 }
15367}
15368
15369static bool hasDeducedAuto(DeclaratorDecl *DD) {
15370 auto *VD = dyn_cast<VarDecl>(Val: DD);
15371 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15372}
15373
15374Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15375 ArrayRef<Decl *> Group) {
15376 SmallVector<Decl*, 8> Decls;
15377
15378 if (DS.isTypeSpecOwned())
15379 Decls.push_back(Elt: DS.getRepAsDecl());
15380
15381 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15382 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15383 bool DiagnosedMultipleDecomps = false;
15384 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15385 bool DiagnosedNonDeducedAuto = false;
15386
15387 for (Decl *D : Group) {
15388 if (!D)
15389 continue;
15390 // Check if the Decl has been declared in '#pragma omp declare target'
15391 // directive and has static storage duration.
15392 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15393 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15394 VD->hasGlobalStorage())
15395 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15396 // For declarators, there are some additional syntactic-ish checks we need
15397 // to perform.
15398 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15399 if (!FirstDeclaratorInGroup)
15400 FirstDeclaratorInGroup = DD;
15401 if (!FirstDecompDeclaratorInGroup)
15402 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15403 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15404 !hasDeducedAuto(DD))
15405 FirstNonDeducedAutoInGroup = DD;
15406
15407 if (FirstDeclaratorInGroup != DD) {
15408 // A decomposition declaration cannot be combined with any other
15409 // declaration in the same group.
15410 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15411 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15412 DiagID: diag::err_decomp_decl_not_alone)
15413 << FirstDeclaratorInGroup->getSourceRange()
15414 << DD->getSourceRange();
15415 DiagnosedMultipleDecomps = true;
15416 }
15417
15418 // A declarator that uses 'auto' in any way other than to declare a
15419 // variable with a deduced type cannot be combined with any other
15420 // declarator in the same group.
15421 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15422 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15423 DiagID: diag::err_auto_non_deduced_not_alone)
15424 << FirstNonDeducedAutoInGroup->getType()
15425 ->hasAutoForTrailingReturnType()
15426 << FirstDeclaratorInGroup->getSourceRange()
15427 << DD->getSourceRange();
15428 DiagnosedNonDeducedAuto = true;
15429 }
15430 }
15431 }
15432
15433 Decls.push_back(Elt: D);
15434 }
15435
15436 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15437 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15438 handleTagNumbering(Tag, TagScope: S);
15439 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15440 getLangOpts().CPlusPlus)
15441 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15442 }
15443 }
15444
15445 return BuildDeclaratorGroup(Group: Decls);
15446}
15447
15448Sema::DeclGroupPtrTy
15449Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15450 // C++14 [dcl.spec.auto]p7: (DR1347)
15451 // If the type that replaces the placeholder type is not the same in each
15452 // deduction, the program is ill-formed.
15453 if (Group.size() > 1) {
15454 QualType Deduced;
15455 VarDecl *DeducedDecl = nullptr;
15456 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15457 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15458 if (!D || D->isInvalidDecl())
15459 break;
15460 DeducedType *DT = D->getType()->getContainedDeducedType();
15461 if (!DT || DT->getDeducedType().isNull())
15462 continue;
15463 if (Deduced.isNull()) {
15464 Deduced = DT->getDeducedType();
15465 DeducedDecl = D;
15466 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15467 auto *AT = dyn_cast<AutoType>(Val: DT);
15468 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15469 DiagID: diag::err_auto_different_deductions)
15470 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15471 << DeducedDecl->getDeclName() << DT->getDeducedType()
15472 << D->getDeclName();
15473 if (DeducedDecl->hasInit())
15474 Dia << DeducedDecl->getInit()->getSourceRange();
15475 if (D->getInit())
15476 Dia << D->getInit()->getSourceRange();
15477 D->setInvalidDecl();
15478 break;
15479 }
15480 }
15481 }
15482
15483 ActOnDocumentableDecls(Group);
15484
15485 return DeclGroupPtrTy::make(
15486 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15487}
15488
15489void Sema::ActOnDocumentableDecl(Decl *D) {
15490 ActOnDocumentableDecls(Group: D);
15491}
15492
15493void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15494 // Don't parse the comment if Doxygen diagnostics are ignored.
15495 if (Group.empty() || !Group[0])
15496 return;
15497
15498 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15499 Loc: Group[0]->getLocation()) &&
15500 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15501 Loc: Group[0]->getLocation()))
15502 return;
15503
15504 if (Group.size() >= 2) {
15505 // This is a decl group. Normally it will contain only declarations
15506 // produced from declarator list. But in case we have any definitions or
15507 // additional declaration references:
15508 // 'typedef struct S {} S;'
15509 // 'typedef struct S *S;'
15510 // 'struct S *pS;'
15511 // FinalizeDeclaratorGroup adds these as separate declarations.
15512 Decl *MaybeTagDecl = Group[0];
15513 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15514 Group = Group.slice(N: 1);
15515 }
15516 }
15517
15518 // FIXME: We assume every Decl in the group is in the same file.
15519 // This is false when preprocessor constructs the group from decls in
15520 // different files (e. g. macros or #include).
15521 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15522}
15523
15524void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15525 // Check that there are no default arguments inside the type of this
15526 // parameter.
15527 if (getLangOpts().CPlusPlus)
15528 CheckExtraCXXDefaultArguments(D);
15529
15530 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15531 if (D.getCXXScopeSpec().isSet()) {
15532 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15533 << D.getCXXScopeSpec().getRange();
15534 }
15535
15536 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15537 // simple identifier except [...irrelevant cases...].
15538 switch (D.getName().getKind()) {
15539 case UnqualifiedIdKind::IK_Identifier:
15540 break;
15541
15542 case UnqualifiedIdKind::IK_OperatorFunctionId:
15543 case UnqualifiedIdKind::IK_ConversionFunctionId:
15544 case UnqualifiedIdKind::IK_LiteralOperatorId:
15545 case UnqualifiedIdKind::IK_ConstructorName:
15546 case UnqualifiedIdKind::IK_DestructorName:
15547 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15548 case UnqualifiedIdKind::IK_DeductionGuideName:
15549 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15550 << GetNameForDeclarator(D).getName();
15551 break;
15552
15553 case UnqualifiedIdKind::IK_TemplateId:
15554 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15555 // GetNameForDeclarator would not produce a useful name in this case.
15556 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15557 break;
15558 }
15559}
15560
15561void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15562 // This only matters in C.
15563 if (getLangOpts().CPlusPlus)
15564 return;
15565
15566 // This only matters if the declaration has a type.
15567 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15568 if (!VD)
15569 return;
15570
15571 // Get the type, this only matters for tag types.
15572 QualType QT = VD->getType();
15573 const auto *TD = QT->getAsTagDecl();
15574 if (!TD)
15575 return;
15576
15577 // Check if the tag declaration is lexically declared somewhere different
15578 // from the lexical declaration of the given object, then it will be hidden
15579 // in C++ and we should warn on it.
15580 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15581 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15582 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15583 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15584 }
15585}
15586
15587static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15588 SourceLocation ExplicitThisLoc) {
15589 if (!ExplicitThisLoc.isValid())
15590 return;
15591 assert(S.getLangOpts().CPlusPlus &&
15592 "explicit parameter in non-cplusplus mode");
15593 if (!S.getLangOpts().CPlusPlus23)
15594 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15595 << P->getSourceRange();
15596
15597 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15598 // parameter pack.
15599 if (P->isParameterPack()) {
15600 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15601 << P->getSourceRange();
15602 return;
15603 }
15604 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15605 if (LambdaScopeInfo *LSI = S.getCurLambda())
15606 LSI->ExplicitObjectParameter = P;
15607}
15608
15609Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15610 SourceLocation ExplicitThisLoc) {
15611 const DeclSpec &DS = D.getDeclSpec();
15612
15613 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15614 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15615 // except for the special case of a single unnamed parameter of type void
15616 // with no storage class specifier, no type qualifier, and no following
15617 // ellipsis terminator.
15618 // Clang applies the C2y rules for 'register void' in all C language modes,
15619 // same as GCC, because it's questionable what that could possibly mean.
15620
15621 // C++03 [dcl.stc]p2 also permits 'auto'.
15622 StorageClass SC = SC_None;
15623 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15624 SC = SC_Register;
15625 // In C++11, the 'register' storage class specifier is deprecated.
15626 // In C++17, it is not allowed, but we tolerate it as an extension.
15627 if (getLangOpts().CPlusPlus11) {
15628 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15629 ? diag::ext_register_storage_class
15630 : diag::warn_deprecated_register)
15631 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15632 } else if (!getLangOpts().CPlusPlus &&
15633 DS.getTypeSpecType() == DeclSpec::TST_void &&
15634 D.getNumTypeObjects() == 0) {
15635 Diag(Loc: DS.getStorageClassSpecLoc(),
15636 DiagID: diag::err_invalid_storage_class_in_func_decl)
15637 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15638 D.getMutableDeclSpec().ClearStorageClassSpecs();
15639 }
15640 } else if (getLangOpts().CPlusPlus &&
15641 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15642 SC = SC_Auto;
15643 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15644 Diag(Loc: DS.getStorageClassSpecLoc(),
15645 DiagID: diag::err_invalid_storage_class_in_func_decl);
15646 D.getMutableDeclSpec().ClearStorageClassSpecs();
15647 }
15648
15649 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15650 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15651 << DeclSpec::getSpecifierName(S: TSCS);
15652 if (DS.isInlineSpecified())
15653 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15654 << getLangOpts().CPlusPlus17;
15655 if (DS.hasConstexprSpecifier())
15656 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15657 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15658
15659 DiagnoseFunctionSpecifiers(DS);
15660
15661 CheckFunctionOrTemplateParamDeclarator(S, D);
15662
15663 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15664 QualType parmDeclType = TInfo->getType();
15665
15666 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15667 const IdentifierInfo *II = D.getIdentifier();
15668 if (II) {
15669 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15670 RedeclarationKind::ForVisibleRedeclaration);
15671 LookupName(R, S);
15672 if (!R.empty()) {
15673 NamedDecl *PrevDecl = *R.begin();
15674 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15675 // Maybe we will complain about the shadowed template parameter.
15676 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15677 // Just pretend that we didn't see the previous declaration.
15678 PrevDecl = nullptr;
15679 }
15680 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15681 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15682 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15683 // Recover by removing the name
15684 II = nullptr;
15685 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15686 D.setInvalidType(true);
15687 }
15688 }
15689 }
15690
15691 // Incomplete resource arrays are not allowed as function parameters in HLSL
15692 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15693 parmDeclType->isHLSLResourceRecordArray()) {
15694 Diag(Loc: D.getIdentifierLoc(),
15695 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15696 D.setInvalidType(true);
15697 }
15698
15699 // Temporarily put parameter variables in the translation unit, not
15700 // the enclosing context. This prevents them from accidentally
15701 // looking like class members in C++.
15702 ParmVarDecl *New =
15703 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15704 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15705
15706 if (D.isInvalidType())
15707 New->setInvalidDecl();
15708
15709 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15710
15711 assert(S->isFunctionPrototypeScope());
15712 assert(S->getFunctionPrototypeDepth() >= 1);
15713 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15714 parameterIndex: S->getNextFunctionPrototypeIndex());
15715
15716 warnOnCTypeHiddenInCPlusPlus(D: New);
15717
15718 // Add the parameter declaration into this scope.
15719 S->AddDecl(D: New);
15720 if (II)
15721 IdResolver.AddDecl(D: New);
15722
15723 ProcessDeclAttributes(S, D: New, PD: D);
15724
15725 if (D.getDeclSpec().isModulePrivateSpecified())
15726 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15727 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15728 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15729
15730 if (New->hasAttr<BlocksAttr>()) {
15731 Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal);
15732 }
15733
15734 if (getLangOpts().OpenCL)
15735 deduceOpenCLAddressSpace(Var: New);
15736
15737 return New;
15738}
15739
15740ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15741 SourceLocation Loc,
15742 QualType T) {
15743 /* FIXME: setting StartLoc == Loc.
15744 Would it be worth to modify callers so as to provide proper source
15745 location for the unnamed parameters, embedding the parameter's type? */
15746 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15747 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15748 S: SC_None, DefArg: nullptr);
15749 Param->setImplicit();
15750 return Param;
15751}
15752
15753void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15754 // Don't diagnose unused-parameter errors in template instantiations; we
15755 // will already have done so in the template itself.
15756 if (inTemplateInstantiation())
15757 return;
15758
15759 for (const ParmVarDecl *Parameter : Parameters) {
15760 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15761 !Parameter->hasAttr<UnusedAttr>() &&
15762 !Parameter->getIdentifier()->isPlaceholder()) {
15763 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15764 << Parameter->getDeclName();
15765 }
15766 }
15767}
15768
15769void Sema::DiagnoseSizeOfParametersAndReturnValue(
15770 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15771 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15772 return;
15773
15774 // Warn if the return value is pass-by-value and larger than the specified
15775 // threshold.
15776 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15777 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15778 if (Size > LangOpts.NumLargeByValueCopy)
15779 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15780 }
15781
15782 // Warn if any parameter is pass-by-value and larger than the specified
15783 // threshold.
15784 for (const ParmVarDecl *Parameter : Parameters) {
15785 QualType T = Parameter->getType();
15786 if (T->isDependentType() || !T.isPODType(Context))
15787 continue;
15788 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15789 if (Size > LangOpts.NumLargeByValueCopy)
15790 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15791 << Parameter << Size;
15792 }
15793}
15794
15795ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15796 SourceLocation NameLoc,
15797 const IdentifierInfo *Name, QualType T,
15798 TypeSourceInfo *TSInfo, StorageClass SC) {
15799 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15800 if (getLangOpts().ObjCAutoRefCount &&
15801 T.getObjCLifetime() == Qualifiers::OCL_None &&
15802 T->isObjCLifetimeType()) {
15803
15804 Qualifiers::ObjCLifetime lifetime;
15805
15806 // Special cases for arrays:
15807 // - if it's const, use __unsafe_unretained
15808 // - otherwise, it's an error
15809 if (T->isArrayType()) {
15810 if (!T.isConstQualified()) {
15811 if (DelayedDiagnostics.shouldDelayDiagnostics())
15812 DelayedDiagnostics.add(
15813 diag: sema::DelayedDiagnostic::makeForbiddenType(
15814 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15815 else
15816 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15817 << TSInfo->getTypeLoc().getSourceRange();
15818 }
15819 lifetime = Qualifiers::OCL_ExplicitNone;
15820 } else {
15821 lifetime = T->getObjCARCImplicitLifetime();
15822 }
15823 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15824 }
15825
15826 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15827 T: Context.getAdjustedParameterType(T),
15828 TInfo: TSInfo, S: SC, DefArg: nullptr);
15829
15830 // Make a note if we created a new pack in the scope of a lambda, so that
15831 // we know that references to that pack must also be expanded within the
15832 // lambda scope.
15833 if (New->isParameterPack())
15834 if (auto *CSI = getEnclosingLambdaOrBlock())
15835 CSI->LocalPacks.push_back(Elt: New);
15836
15837 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15838 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15839 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15840 UseContext: NonTrivialCUnionContext::FunctionParam,
15841 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15842
15843 // Parameter declarators cannot be interface types. All ObjC objects are
15844 // passed by reference.
15845 if (T->isObjCObjectType()) {
15846 SourceLocation TypeEndLoc =
15847 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15848 Diag(Loc: NameLoc,
15849 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15850 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15851 T = Context.getObjCObjectPointerType(OIT: T);
15852 New->setType(T);
15853 }
15854
15855 // __ptrauth is forbidden on parameters.
15856 if (T.getPointerAuth()) {
15857 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15858 New->setInvalidDecl();
15859 }
15860
15861 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15862 // duration shall not be qualified by an address-space qualifier."
15863 // Since all parameters have automatic store duration, they can not have
15864 // an address space.
15865 if (T.getAddressSpace() != LangAS::Default &&
15866 // OpenCL allows function arguments declared to be an array of a type
15867 // to be qualified with an address space.
15868 !(getLangOpts().OpenCL &&
15869 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15870 // WebAssembly allows reference types as parameters. Funcref in particular
15871 // lives in a different address space.
15872 !(T->isFunctionPointerType() &&
15873 T.getAddressSpace() == LangAS::wasm_funcref) &&
15874 // HLSL allows function arguments to be qualified with an address space
15875 // if the groupshared annotation is used.
15876 !(getLangOpts().HLSL &&
15877 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
15878 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15879 New->setInvalidDecl();
15880 }
15881
15882 // PPC MMA non-pointer types are not allowed as function argument types.
15883 if (Context.getTargetInfo().getTriple().isPPC64() &&
15884 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15885 New->setInvalidDecl();
15886 }
15887
15888 return New;
15889}
15890
15891void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15892 SourceLocation LocAfterDecls) {
15893 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15894
15895 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15896 // in the declaration list shall have at least one declarator, those
15897 // declarators shall only declare identifiers from the identifier list, and
15898 // every identifier in the identifier list shall be declared.
15899 //
15900 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15901 // identifiers it names shall be declared in the declaration list."
15902 //
15903 // This is why we only diagnose in C99 and later. Note, the other conditions
15904 // listed are checked elsewhere.
15905 if (!FTI.hasPrototype) {
15906 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15907 --i;
15908 if (FTI.Params[i].Param == nullptr) {
15909 if (getLangOpts().C99) {
15910 SmallString<256> Code;
15911 llvm::raw_svector_ostream(Code)
15912 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15913 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
15914 << FTI.Params[i].Ident
15915 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
15916 }
15917
15918 // Implicitly declare the argument as type 'int' for lack of a better
15919 // type.
15920 AttributeFactory attrs;
15921 DeclSpec DS(attrs);
15922 const char* PrevSpec; // unused
15923 unsigned DiagID; // unused
15924 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15925 DiagID, Policy: Context.getPrintingPolicy());
15926 // Use the identifier location for the type source range.
15927 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15928 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15929 Declarator ParamD(DS, ParsedAttributesView::none(),
15930 DeclaratorContext::KNRTypeList);
15931 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15932 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15933 }
15934 }
15935 }
15936}
15937
15938Decl *
15939Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15940 MultiTemplateParamsArg TemplateParameterLists,
15941 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15942 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15943 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15944 Scope *ParentScope = FnBodyScope->getParent();
15945
15946 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15947 // we define a non-templated function definition, we will create a declaration
15948 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15949 // The base function declaration will have the equivalent of an `omp declare
15950 // variant` annotation which specifies the mangled definition as a
15951 // specialization function under the OpenMP context defined as part of the
15952 // `omp begin declare variant`.
15953 SmallVector<FunctionDecl *, 4> Bases;
15954 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15955 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15956 S: ParentScope, D, TemplateParameterLists, Bases);
15957
15958 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15959 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15960 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15961
15962 if (!Bases.empty())
15963 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15964 Bases);
15965
15966 return Dcl;
15967}
15968
15969void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15970 Consumer.HandleInlineFunctionDefinition(D);
15971}
15972
15973static bool FindPossiblePrototype(const FunctionDecl *FD,
15974 const FunctionDecl *&PossiblePrototype) {
15975 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15976 Prev = Prev->getPreviousDecl()) {
15977 // Ignore any declarations that occur in function or method
15978 // scope, because they aren't visible from the header.
15979 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15980 continue;
15981
15982 PossiblePrototype = Prev;
15983 return Prev->getType()->isFunctionProtoType();
15984 }
15985 return false;
15986}
15987
15988static bool
15989ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15990 const FunctionDecl *&PossiblePrototype) {
15991 // Don't warn about invalid declarations.
15992 if (FD->isInvalidDecl())
15993 return false;
15994
15995 // Or declarations that aren't global.
15996 if (!FD->isGlobal())
15997 return false;
15998
15999 // Don't warn about C++ member functions.
16000 if (isa<CXXMethodDecl>(Val: FD))
16001 return false;
16002
16003 // Don't warn about 'main'.
16004 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16005 if (IdentifierInfo *II = FD->getIdentifier())
16006 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16007 return false;
16008
16009 if (FD->isMSVCRTEntryPoint())
16010 return false;
16011
16012 // Don't warn about inline functions.
16013 if (FD->isInlined())
16014 return false;
16015
16016 // Don't warn about function templates.
16017 if (FD->getDescribedFunctionTemplate())
16018 return false;
16019
16020 // Don't warn about function template specializations.
16021 if (FD->isFunctionTemplateSpecialization())
16022 return false;
16023
16024 // Don't warn for OpenCL kernels.
16025 if (FD->hasAttr<DeviceKernelAttr>())
16026 return false;
16027
16028 // Don't warn on explicitly deleted functions.
16029 if (FD->isDeleted())
16030 return false;
16031
16032 // Don't warn on implicitly local functions (such as having local-typed
16033 // parameters).
16034 if (!FD->isExternallyVisible())
16035 return false;
16036
16037 // If we were able to find a potential prototype, don't warn.
16038 if (FindPossiblePrototype(FD, PossiblePrototype))
16039 return false;
16040
16041 return true;
16042}
16043
16044void
16045Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16046 const FunctionDecl *EffectiveDefinition,
16047 SkipBodyInfo *SkipBody) {
16048 const FunctionDecl *Definition = EffectiveDefinition;
16049 if (!Definition &&
16050 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16051 return;
16052
16053 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16054 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16055 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16056 // A merged copy of the same function, instantiated as a member of
16057 // the same class, is OK.
16058 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16059 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16060 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16061 return;
16062 }
16063 }
16064 }
16065
16066 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16067 return;
16068
16069 // Don't emit an error when this is redefinition of a typo-corrected
16070 // definition.
16071 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16072 return;
16073
16074 bool DefinitionVisible = false;
16075 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16076 (Definition->getFormalLinkage() == Linkage::Internal ||
16077 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16078 Definition->getNumTemplateParameterLists())) {
16079 SkipBody->ShouldSkip = true;
16080 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16081 if (!DefinitionVisible) {
16082 if (auto *TD = Definition->getDescribedFunctionTemplate())
16083 makeMergedDefinitionVisible(ND: TD);
16084 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16085 }
16086 return;
16087 }
16088
16089 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16090 Definition->getStorageClass() == SC_Extern)
16091 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16092 << FD << getLangOpts().CPlusPlus;
16093 else
16094 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16095
16096 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16097 FD->setInvalidDecl();
16098}
16099
16100LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16101 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16102
16103 LambdaScopeInfo *LSI = PushLambdaScope();
16104 LSI->CallOperator = CallOperator;
16105 LSI->Lambda = LambdaClass;
16106 LSI->ReturnType = CallOperator->getReturnType();
16107 // When this function is called in situation where the context of the call
16108 // operator is not entered, we set AfterParameterList to false, so that
16109 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16110 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16111 // where we would set the CurContext to the lambda operator before
16112 // substituting into it. In this case the flag needs to be true such that
16113 // tryCaptureVariable can correctly handle potential captures thereof.
16114 LSI->AfterParameterList = CurContext == CallOperator;
16115
16116 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16117 // used at the point of dealing with potential captures.
16118 //
16119 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16120 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16121 // associated. (Technically, we could recover that list from their
16122 // instantiation patterns, but for now, the GLTemplateParameterList seems
16123 // unnecessary in these cases.)
16124 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16125 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16126 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16127
16128 if (LCD == LCD_None)
16129 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16130 else if (LCD == LCD_ByCopy)
16131 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16132 else if (LCD == LCD_ByRef)
16133 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16134 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16135
16136 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16137 LSI->Mutable = !CallOperator->isConst();
16138 if (CallOperator->isExplicitObjectMemberFunction())
16139 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16140
16141 // Add the captures to the LSI so they can be noted as already
16142 // captured within tryCaptureVar.
16143 auto I = LambdaClass->field_begin();
16144 for (const auto &C : LambdaClass->captures()) {
16145 if (C.capturesVariable()) {
16146 ValueDecl *VD = C.getCapturedVar();
16147 if (VD->isInitCapture())
16148 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16149 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16150 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16151 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16152 /*EllipsisLoc*/C.isPackExpansion()
16153 ? C.getEllipsisLoc() : SourceLocation(),
16154 CaptureType: I->getType(), /*Invalid*/false);
16155
16156 } else if (C.capturesThis()) {
16157 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16158 ByCopy: C.getCaptureKind() == LCK_StarThis);
16159 } else {
16160 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16161 CaptureType: I->getType());
16162 }
16163 ++I;
16164 }
16165 return LSI;
16166}
16167
16168Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16169 SkipBodyInfo *SkipBody,
16170 FnBodyKind BodyKind) {
16171 if (!D) {
16172 // Parsing the function declaration failed in some way. Push on a fake scope
16173 // anyway so we can try to parse the function body.
16174 PushFunctionScope();
16175 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16176 return D;
16177 }
16178
16179 FunctionDecl *FD = nullptr;
16180
16181 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16182 FD = FunTmpl->getTemplatedDecl();
16183 else
16184 FD = cast<FunctionDecl>(Val: D);
16185
16186 // Do not push if it is a lambda because one is already pushed when building
16187 // the lambda in ActOnStartOfLambdaDefinition().
16188 if (!isLambdaCallOperator(DC: FD))
16189 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16190 FD);
16191
16192 // Check for defining attributes before the check for redefinition.
16193 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16194 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16195 FD->dropAttr<AliasAttr>();
16196 FD->setInvalidDecl();
16197 }
16198 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16199 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16200 FD->dropAttr<IFuncAttr>();
16201 FD->setInvalidDecl();
16202 }
16203 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16204 if (Context.getTargetInfo().getTriple().isAArch64() &&
16205 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16206 !Attr->isDefaultVersion()) {
16207 // If function multi versioning disabled skip parsing function body
16208 // defined with non-default target_version attribute
16209 if (SkipBody)
16210 SkipBody->ShouldSkip = true;
16211 return nullptr;
16212 }
16213 }
16214
16215 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16216 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16217 Ctor->isDefaultConstructor() &&
16218 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16219 // If this is an MS ABI dllexport default constructor, instantiate any
16220 // default arguments.
16221 InstantiateDefaultCtorDefaultArgs(Ctor);
16222 }
16223 }
16224
16225 // See if this is a redefinition. If 'will have body' (or similar) is already
16226 // set, then these checks were already performed when it was set.
16227 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16228 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16229 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16230
16231 // If we're skipping the body, we're done. Don't enter the scope.
16232 if (SkipBody && SkipBody->ShouldSkip)
16233 return D;
16234 }
16235
16236 // Mark this function as "will have a body eventually". This lets users to
16237 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16238 // this function.
16239 FD->setWillHaveBody();
16240
16241 // If we are instantiating a generic lambda call operator, push
16242 // a LambdaScopeInfo onto the function stack. But use the information
16243 // that's already been calculated (ActOnLambdaExpr) to prime the current
16244 // LambdaScopeInfo.
16245 // When the template operator is being specialized, the LambdaScopeInfo,
16246 // has to be properly restored so that tryCaptureVariable doesn't try
16247 // and capture any new variables. In addition when calculating potential
16248 // captures during transformation of nested lambdas, it is necessary to
16249 // have the LSI properly restored.
16250 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16251 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16252 // instantiated, explicitly specialized.
16253 if (FD->getTemplateSpecializationInfo()
16254 ->isExplicitInstantiationOrSpecialization()) {
16255 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec);
16256 FD->setInvalidDecl();
16257 PushFunctionScope();
16258 } else {
16259 assert(inTemplateInstantiation() &&
16260 "There should be an active template instantiation on the stack "
16261 "when instantiating a generic lambda!");
16262 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16263 }
16264 } else {
16265 // Enter a new function scope
16266 PushFunctionScope();
16267 }
16268
16269 // Builtin functions cannot be defined.
16270 if (unsigned BuiltinID = FD->getBuiltinID()) {
16271 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16272 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16273 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16274 FD->setInvalidDecl();
16275 }
16276 }
16277
16278 // The return type of a function definition must be complete (C99 6.9.1p3).
16279 // C++23 [dcl.fct.def.general]/p2
16280 // The type of [...] the return for a function definition
16281 // shall not be a (possibly cv-qualified) class type that is incomplete
16282 // or abstract within the function body unless the function is deleted.
16283 QualType ResultType = FD->getReturnType();
16284 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16285 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16286 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16287 DiagID: diag::err_func_def_incomplete_result) ||
16288 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16289 DiagID: diag::err_abstract_type_in_decl,
16290 Args: AbstractReturnType)))
16291 FD->setInvalidDecl();
16292
16293 if (FnBodyScope)
16294 PushDeclContext(S: FnBodyScope, DC: FD);
16295
16296 // Check the validity of our function parameters
16297 if (BodyKind != FnBodyKind::Delete)
16298 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16299 /*CheckParameterNames=*/true);
16300
16301 // Add non-parameter declarations already in the function to the current
16302 // scope.
16303 if (FnBodyScope) {
16304 for (Decl *NPD : FD->decls()) {
16305 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16306 if (!NonParmDecl)
16307 continue;
16308 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16309 "parameters should not be in newly created FD yet");
16310
16311 // If the decl has a name, make it accessible in the current scope.
16312 if (NonParmDecl->getDeclName())
16313 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16314
16315 // Similarly, dive into enums and fish their constants out, making them
16316 // accessible in this scope.
16317 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16318 for (auto *EI : ED->enumerators())
16319 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16320 }
16321 }
16322 }
16323
16324 // Introduce our parameters into the function scope
16325 for (auto *Param : FD->parameters()) {
16326 Param->setOwningFunction(FD);
16327
16328 // If this has an identifier, add it to the scope stack.
16329 if (Param->getIdentifier() && FnBodyScope) {
16330 CheckShadow(S: FnBodyScope, D: Param);
16331
16332 PushOnScopeChains(D: Param, S: FnBodyScope);
16333 }
16334 }
16335
16336 // C++ [module.import/6]
16337 // ...
16338 // A header unit shall not contain a definition of a non-inline function or
16339 // variable whose name has external linkage.
16340 //
16341 // Deleted and Defaulted functions are implicitly inline (but the
16342 // inline state is not set at this point, so check the BodyKind explicitly).
16343 // We choose to allow weak & selectany definitions, as they are common in
16344 // headers, and have semantics similar to inline definitions which are allowed
16345 // in header units.
16346 // FIXME: Consider an alternate location for the test where the inlined()
16347 // state is complete.
16348 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16349 !FD->isInvalidDecl() && !FD->isInlined() &&
16350 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16351 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16352 !FD->isTemplateInstantiation() &&
16353 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16354 assert(FD->isThisDeclarationADefinition());
16355 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16356 FD->setInvalidDecl();
16357 }
16358
16359 // Ensure that the function's exception specification is instantiated.
16360 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16361 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16362
16363 // dllimport cannot be applied to non-inline function definitions.
16364 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16365 !FD->isTemplateInstantiation()) {
16366 assert(!FD->hasAttr<DLLExportAttr>());
16367 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16368 FD->setInvalidDecl();
16369 return D;
16370 }
16371
16372 // Some function attributes (like OptimizeNoneAttr) need actions before
16373 // parsing body started.
16374 applyFunctionAttributesBeforeParsingBody(FD: D);
16375
16376 // We want to attach documentation to original Decl (which might be
16377 // a function template).
16378 ActOnDocumentableDecl(D);
16379 if (getCurLexicalContext()->isObjCContainer() &&
16380 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16381 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16382 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16383
16384 maybeAddDeclWithEffects(D: FD);
16385
16386 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16387 FnBodyScope) {
16388 // An implicit call expression is synthesized for functions declared with
16389 // the sycl_kernel_entry_point attribute. The call may resolve to a
16390 // function template, a member function template, or a call operator
16391 // of a variable template depending on the results of unqualified lookup
16392 // for 'sycl_kernel_launch' from the beginning of the function body.
16393 // Performing that lookup requires the stack of parsing scopes active
16394 // when the definition is parsed and is thus done here; the result is
16395 // cached in FunctionScopeInfo and used to synthesize the (possibly
16396 // unresolved) call expression after the function body has been parsed.
16397 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16398 if (!SKEPAttr->isInvalidAttr()) {
16399 ExprResult LaunchIdExpr =
16400 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16401 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16402 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16403 // treated as an error in the definition of 'FD'; treating it as an error
16404 // of the declaration would affect overload resolution which would
16405 // potentially result in additional errors. If construction of
16406 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16407 // a null pointer value below; that is expected.
16408 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16409 }
16410 }
16411
16412 return D;
16413}
16414
16415void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16416 if (!FD || FD->isInvalidDecl())
16417 return;
16418 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16419 FD = TD->getTemplatedDecl();
16420 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16421 FPOptionsOverride FPO;
16422 FPO.setDisallowOptimizations();
16423 CurFPFeatures.applyChanges(FPO);
16424 FpPragmaStack.CurrentValue =
16425 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16426 }
16427}
16428
16429void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16430 ReturnStmt **Returns = Scope->Returns.data();
16431
16432 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16433 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16434 if (!NRVOCandidate->isNRVOVariable()) {
16435 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16436 DiagID: diag::warn_not_eliding_copy_on_return);
16437 Returns[I]->setNRVOCandidate(nullptr);
16438 }
16439 }
16440 }
16441}
16442
16443bool Sema::canDelayFunctionBody(const Declarator &D) {
16444 // We can't delay parsing the body of a constexpr function template (yet).
16445 if (D.getDeclSpec().hasConstexprSpecifier())
16446 return false;
16447
16448 // We can't delay parsing the body of a function template with a deduced
16449 // return type (yet).
16450 if (D.getDeclSpec().hasAutoTypeSpec()) {
16451 // If the placeholder introduces a non-deduced trailing return type,
16452 // we can still delay parsing it.
16453 if (D.getNumTypeObjects()) {
16454 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16455 if (Outer.Kind == DeclaratorChunk::Function &&
16456 Outer.Fun.hasTrailingReturnType()) {
16457 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16458 return Ty.isNull() || !Ty->isUndeducedType();
16459 }
16460 }
16461 return false;
16462 }
16463
16464 return true;
16465}
16466
16467bool Sema::canSkipFunctionBody(Decl *D) {
16468 // We cannot skip the body of a function (or function template) which is
16469 // constexpr, since we may need to evaluate its body in order to parse the
16470 // rest of the file.
16471 // We cannot skip the body of a function with an undeduced return type,
16472 // because any callers of that function need to know the type.
16473 if (const FunctionDecl *FD = D->getAsFunction()) {
16474 if (FD->isConstexpr())
16475 return false;
16476 // We can't simply call Type::isUndeducedType here, because inside template
16477 // auto can be deduced to a dependent type, which is not considered
16478 // "undeduced".
16479 if (FD->getReturnType()->getContainedDeducedType())
16480 return false;
16481 }
16482 return Consumer.shouldSkipFunctionBody(D);
16483}
16484
16485Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16486 if (!Decl)
16487 return nullptr;
16488 if (FunctionDecl *FD = Decl->getAsFunction())
16489 FD->setHasSkippedBody();
16490 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16491 MD->setHasSkippedBody();
16492 return Decl;
16493}
16494
16495/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16496/// body.
16497class ExitFunctionBodyRAII {
16498public:
16499 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16500 ~ExitFunctionBodyRAII() {
16501 if (!IsLambda)
16502 S.PopExpressionEvaluationContext();
16503 }
16504
16505private:
16506 Sema &S;
16507 bool IsLambda = false;
16508};
16509
16510static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16511 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16512
16513 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16514 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16515 if (!Inserted)
16516 return It->second;
16517
16518 bool R = false;
16519 const BlockDecl *CurBD = BD;
16520
16521 do {
16522 R = !CurBD->doesNotEscape();
16523 if (R)
16524 break;
16525 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16526 } while (CurBD);
16527
16528 return It->second = R;
16529 };
16530
16531 // If the location where 'self' is implicitly retained is inside a escaping
16532 // block, emit a diagnostic.
16533 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16534 S.ImplicitlyRetainedSelfLocs)
16535 if (IsOrNestedInEscapingBlock(P.second))
16536 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16537 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16538}
16539
16540static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16541 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16542 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16543}
16544
16545bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16546 return methodHasName(FD, Name: "get_return_object");
16547}
16548
16549bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16550 return FD->isStatic() &&
16551 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16552}
16553
16554void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16555 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16556 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16557 return;
16558 // Allow some_promise_type::get_return_object().
16559 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16560 return;
16561 if (!FD->hasAttr<CoroWrapperAttr>())
16562 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16563}
16564
16565Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16566 bool RetainFunctionScopeInfo) {
16567 FunctionScopeInfo *FSI = getCurFunction();
16568 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16569
16570 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16571 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16572
16573 SourceLocation AnalysisLoc;
16574 if (Body)
16575 AnalysisLoc = Body->getEndLoc();
16576 else if (FD)
16577 AnalysisLoc = FD->getEndLoc();
16578 sema::AnalysisBasedWarnings::Policy WP =
16579 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16580 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16581
16582 // If we skip function body, we can't tell if a function is a coroutine.
16583 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16584 if (FSI->isCoroutine())
16585 CheckCompletedCoroutineBody(FD, Body);
16586 else
16587 CheckCoroutineWrapper(FD);
16588 }
16589
16590 // Diagnose invalid SYCL kernel entry point function declarations
16591 // and build SYCLKernelCallStmts for valid ones.
16592 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16593 SYCLKernelEntryPointAttr *SKEPAttr =
16594 FD->getAttr<SYCLKernelEntryPointAttr>();
16595 if (FD->isDefaulted()) {
16596 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16597 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16598 SKEPAttr->setInvalidAttr();
16599 } else if (FD->isDeleted()) {
16600 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16601 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16602 SKEPAttr->setInvalidAttr();
16603 } else if (FSI->isCoroutine()) {
16604 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16605 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16606 SKEPAttr->setInvalidAttr();
16607 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16608 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16609 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16610 SKEPAttr->setInvalidAttr();
16611 }
16612
16613 // Build an unresolved SYCL kernel call statement for a function template,
16614 // validate that a SYCL kernel call statement was instantiated for an
16615 // (implicit or explicit) instantiation of a function template, or otherwise
16616 // build a (resolved) SYCL kernel call statement for a non-templated
16617 // function or an explicit specialization.
16618 if (Body && !SKEPAttr->isInvalidAttr()) {
16619 StmtResult SR;
16620 if (FD->isTemplateInstantiation()) {
16621 // The function body should already be a SYCLKernelCallStmt in this
16622 // case, but might not be if there were previous errors.
16623 SR = Body;
16624 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16625 // If name lookup for a template named sycl_kernel_launch failed
16626 // earlier, don't try to build a SYCL kernel call statement as that
16627 // would cause additional errors to be issued; just proceed with the
16628 // original function body.
16629 SR = Body;
16630 } else if (FD->isTemplated()) {
16631 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16632 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16633 } else {
16634 SR = SYCL().BuildSYCLKernelCallStmt(
16635 FD, Body: cast<CompoundStmt>(Val: Body),
16636 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16637 }
16638 // If construction of the replacement body fails, just continue with the
16639 // original function body. An early error return here is not valid; the
16640 // current declaration context and function scopes must be popped before
16641 // returning.
16642 if (SR.isUsable())
16643 Body = SR.get();
16644 }
16645 }
16646
16647 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16648 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16649 if (FD->isDeletedAsWritten())
16650 Diag(Loc: SEAttr->getLocation(),
16651 DiagID: diag::err_sycl_external_invalid_deleted_function)
16652 << SEAttr;
16653 }
16654
16655 {
16656 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16657 // one is already popped when finishing the lambda in BuildLambdaExpr().
16658 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16659 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16660 if (FD) {
16661 // The function body and the DefaultedOrDeletedInfo, if present, use
16662 // the same storage; don't overwrite the latter if the former is null
16663 // (the body is initialised to null anyway, so even if the latter isn't
16664 // present, this would still be a no-op).
16665 if (Body)
16666 FD->setBody(Body);
16667 FD->setWillHaveBody(false);
16668
16669 if (getLangOpts().CPlusPlus14) {
16670 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16671 FD->getReturnType()->isUndeducedType()) {
16672 // For a function with a deduced result type to return void,
16673 // the result type as written must be 'auto' or 'decltype(auto)',
16674 // possibly cv-qualified or constrained, but not ref-qualified.
16675 if (!FD->getReturnType()->getAs<AutoType>()) {
16676 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16677 << FD->getReturnType();
16678 FD->setInvalidDecl();
16679 } else {
16680 // Falling off the end of the function is the same as 'return;'.
16681 Expr *Dummy = nullptr;
16682 if (DeduceFunctionTypeFromReturnExpr(
16683 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16684 AT: FD->getReturnType()->getAs<AutoType>()))
16685 FD->setInvalidDecl();
16686 }
16687 }
16688 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16689 // In C++11, we don't use 'auto' deduction rules for lambda call
16690 // operators because we don't support return type deduction.
16691 auto *LSI = getCurLambda();
16692 if (LSI->HasImplicitReturnType) {
16693 deduceClosureReturnType(CSI&: *LSI);
16694
16695 // C++11 [expr.prim.lambda]p4:
16696 // [...] if there are no return statements in the compound-statement
16697 // [the deduced type is] the type void
16698 QualType RetType =
16699 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16700
16701 // Update the return type to the deduced type.
16702 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16703 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16704 EPI: Proto->getExtProtoInfo()));
16705 }
16706 }
16707
16708 // If the function implicitly returns zero (like 'main') or is naked,
16709 // don't complain about missing return statements.
16710 // Clang implicitly returns 0 in C89 mode, but that's considered an
16711 // extension. The check is necessary to ensure the expected extension
16712 // warning is emitted in C89 mode.
16713 if ((FD->hasImplicitReturnZero() &&
16714 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16715 FD->hasAttr<NakedAttr>())
16716 WP.disableCheckFallThrough();
16717
16718 // MSVC permits the use of pure specifier (=0) on function definition,
16719 // defined at class scope, warn about this non-standard construct.
16720 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16721 !FD->isOutOfLine())
16722 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16723
16724 if (!FD->isInvalidDecl()) {
16725 // Don't diagnose unused parameters of defaulted, deleted or naked
16726 // functions.
16727 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16728 !FD->hasAttr<NakedAttr>())
16729 DiagnoseUnusedParameters(Parameters: FD->parameters());
16730 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16731 ReturnTy: FD->getReturnType(), D: FD);
16732
16733 // If this is a structor, we need a vtable.
16734 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16735 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16736 else if (CXXDestructorDecl *Destructor =
16737 dyn_cast<CXXDestructorDecl>(Val: FD))
16738 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16739
16740 // Try to apply the named return value optimization. We have to check
16741 // if we can do this here because lambdas keep return statements around
16742 // to deduce an implicit return type.
16743 if (FD->getReturnType()->isRecordType() &&
16744 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16745 computeNRVO(Body, Scope: FSI);
16746 }
16747
16748 // GNU warning -Wmissing-prototypes:
16749 // Warn if a global function is defined without a previous
16750 // prototype declaration. This warning is issued even if the
16751 // definition itself provides a prototype. The aim is to detect
16752 // global functions that fail to be declared in header files.
16753 const FunctionDecl *PossiblePrototype = nullptr;
16754 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16755 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16756
16757 if (PossiblePrototype) {
16758 // We found a declaration that is not a prototype,
16759 // but that could be a zero-parameter prototype
16760 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16761 TypeLoc TL = TI->getTypeLoc();
16762 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16763 Diag(Loc: PossiblePrototype->getLocation(),
16764 DiagID: diag::note_declaration_not_a_prototype)
16765 << (FD->getNumParams() != 0)
16766 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16767 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16768 : FixItHint{});
16769 }
16770 } else {
16771 // Returns true if the token beginning at this Loc is `const`.
16772 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16773 const LangOptions &LangOpts) {
16774 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16775 if (LocInfo.first.isInvalid())
16776 return false;
16777
16778 bool Invalid = false;
16779 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16780 if (Invalid)
16781 return false;
16782
16783 if (LocInfo.second > Buffer.size())
16784 return false;
16785
16786 const char *LexStart = Buffer.data() + LocInfo.second;
16787 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16788
16789 return StartTok.consume_front(Prefix: "const") &&
16790 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16791 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16792 };
16793
16794 auto findBeginLoc = [&]() {
16795 // If the return type has `const` qualifier, we want to insert
16796 // `static` before `const` (and not before the typename).
16797 if ((FD->getReturnType()->isAnyPointerType() &&
16798 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16799 FD->getReturnType().isConstQualified()) {
16800 // But only do this if we can determine where the `const` is.
16801
16802 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16803 getLangOpts()))
16804
16805 return FD->getBeginLoc();
16806 }
16807 return FD->getTypeSpecStartLoc();
16808 };
16809 Diag(Loc: FD->getTypeSpecStartLoc(),
16810 DiagID: diag::note_static_for_internal_linkage)
16811 << /* function */ 1
16812 << (FD->getStorageClass() == SC_None
16813 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16814 : FixItHint{});
16815 }
16816 }
16817
16818 // We might not have found a prototype because we didn't wish to warn on
16819 // the lack of a missing prototype. Try again without the checks for
16820 // whether we want to warn on the missing prototype.
16821 if (!PossiblePrototype)
16822 (void)FindPossiblePrototype(FD, PossiblePrototype);
16823
16824 // If the function being defined does not have a prototype, then we may
16825 // need to diagnose it as changing behavior in C23 because we now know
16826 // whether the function accepts arguments or not. This only handles the
16827 // case where the definition has no prototype but does have parameters
16828 // and either there is no previous potential prototype, or the previous
16829 // potential prototype also has no actual prototype. This handles cases
16830 // like:
16831 // void f(); void f(a) int a; {}
16832 // void g(a) int a; {}
16833 // See MergeFunctionDecl() for other cases of the behavior change
16834 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16835 // type without a prototype.
16836 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16837 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16838 !PossiblePrototype->isImplicit()))) {
16839 // The function definition has parameters, so this will change behavior
16840 // in C23. If there is a possible prototype, it comes before the
16841 // function definition.
16842 // FIXME: The declaration may have already been diagnosed as being
16843 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16844 // there's no way to test for the "changes behavior" condition in
16845 // SemaType.cpp when forming the declaration's function type. So, we do
16846 // this awkward dance instead.
16847 //
16848 // If we have a possible prototype and it declares a function with a
16849 // prototype, we don't want to diagnose it; if we have a possible
16850 // prototype and it has no prototype, it may have already been
16851 // diagnosed in SemaType.cpp as deprecated depending on whether
16852 // -Wstrict-prototypes is enabled. If we already warned about it being
16853 // deprecated, add a note that it also changes behavior. If we didn't
16854 // warn about it being deprecated (because the diagnostic is not
16855 // enabled), warn now that it is deprecated and changes behavior.
16856
16857 // This K&R C function definition definitely changes behavior in C23,
16858 // so diagnose it.
16859 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16860 << /*definition*/ 1 << /* not supported in C23 */ 0;
16861
16862 // If we have a possible prototype for the function which is a user-
16863 // visible declaration, we already tested that it has no prototype.
16864 // This will change behavior in C23. This gets a warning rather than a
16865 // note because it's the same behavior-changing problem as with the
16866 // definition.
16867 if (PossiblePrototype)
16868 Diag(Loc: PossiblePrototype->getLocation(),
16869 DiagID: diag::warn_non_prototype_changes_behavior)
16870 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16871 << /*definition*/ 1;
16872 }
16873
16874 // Warn on CPUDispatch with an actual body.
16875 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16876 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16877 if (!CmpndBody->body_empty())
16878 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16879 DiagID: diag::warn_dispatch_body_ignored);
16880
16881 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16882 const CXXMethodDecl *KeyFunction;
16883 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16884 MD->isVirtual() &&
16885 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16886 MD == KeyFunction->getCanonicalDecl()) {
16887 // Update the key-function state if necessary for this ABI.
16888 if (FD->isInlined() &&
16889 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16890 Context.setNonKeyFunction(MD);
16891
16892 // If the newly-chosen key function is already defined, then we
16893 // need to mark the vtable as used retroactively.
16894 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16895 const FunctionDecl *Definition;
16896 if (KeyFunction && KeyFunction->isDefined(Definition))
16897 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16898 } else {
16899 // We just defined they key function; mark the vtable as used.
16900 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16901 }
16902 }
16903 }
16904
16905 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16906 "Function parsing confused");
16907 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16908 assert(MD == getCurMethodDecl() && "Method parsing confused");
16909 MD->setBody(Body);
16910 if (!MD->isInvalidDecl()) {
16911 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
16912 ReturnTy: MD->getReturnType(), D: MD);
16913
16914 if (Body)
16915 computeNRVO(Body, Scope: FSI);
16916 }
16917 if (FSI->ObjCShouldCallSuper) {
16918 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
16919 << MD->getSelector().getAsString();
16920 FSI->ObjCShouldCallSuper = false;
16921 }
16922 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16923 const ObjCMethodDecl *InitMethod = nullptr;
16924 bool isDesignated =
16925 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16926 assert(isDesignated && InitMethod);
16927 (void)isDesignated;
16928
16929 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16930 auto IFace = MD->getClassInterface();
16931 if (!IFace)
16932 return false;
16933 auto SuperD = IFace->getSuperClass();
16934 if (!SuperD)
16935 return false;
16936 return SuperD->getIdentifier() ==
16937 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
16938 };
16939 // Don't issue this warning for unavailable inits or direct subclasses
16940 // of NSObject.
16941 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16942 Diag(Loc: MD->getLocation(),
16943 DiagID: diag::warn_objc_designated_init_missing_super_call);
16944 Diag(Loc: InitMethod->getLocation(),
16945 DiagID: diag::note_objc_designated_init_marked_here);
16946 }
16947 FSI->ObjCWarnForNoDesignatedInitChain = false;
16948 }
16949 if (FSI->ObjCWarnForNoInitDelegation) {
16950 // Don't issue this warning for unavailable inits.
16951 if (!MD->isUnavailable())
16952 Diag(Loc: MD->getLocation(),
16953 DiagID: diag::warn_objc_secondary_init_missing_init_call);
16954 FSI->ObjCWarnForNoInitDelegation = false;
16955 }
16956
16957 diagnoseImplicitlyRetainedSelf(S&: *this);
16958 } else {
16959 // Parsing the function declaration failed in some way. Pop the fake scope
16960 // we pushed on.
16961 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16962 return nullptr;
16963 }
16964
16965 if (Body && FSI->HasPotentialAvailabilityViolations)
16966 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16967
16968 assert(!FSI->ObjCShouldCallSuper &&
16969 "This should only be set for ObjC methods, which should have been "
16970 "handled in the block above.");
16971
16972 // Verify and clean out per-function state.
16973 if (Body && (!FD || !FD->isDefaulted())) {
16974 // C++ constructors that have function-try-blocks can't have return
16975 // statements in the handlers of that block. (C++ [except.handle]p14)
16976 // Verify this.
16977 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16978 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16979
16980 // Verify that gotos and switch cases don't jump into scopes illegally.
16981 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16982 DiagnoseInvalidJumps(Body);
16983
16984 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16985 if (!Destructor->getParent()->isDependentType())
16986 CheckDestructor(Destructor);
16987
16988 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16989 Record: Destructor->getParent());
16990 }
16991
16992 // If any errors have occurred, clear out any temporaries that may have
16993 // been leftover. This ensures that these temporaries won't be picked up
16994 // for deletion in some later function.
16995 if (hasUncompilableErrorOccurred() ||
16996 hasAnyUnrecoverableErrorsInThisFunction() ||
16997 getDiagnostics().getSuppressAllDiagnostics()) {
16998 DiscardCleanupsInEvaluationContext();
16999 }
17000 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17001 // Since the body is valid, issue any analysis-based warnings that are
17002 // enabled.
17003 ActivePolicy = &WP;
17004 }
17005
17006 if (!IsInstantiation && FD &&
17007 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17008 !FD->isInvalidDecl() &&
17009 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17010 FD->setInvalidDecl();
17011
17012 if (FD && FD->hasAttr<NakedAttr>()) {
17013 for (const Stmt *S : Body->children()) {
17014 // Allow local register variables without initializer as they don't
17015 // require prologue.
17016 bool RegisterVariables = false;
17017 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17018 for (const auto *Decl : DS->decls()) {
17019 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17020 RegisterVariables =
17021 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17022 if (!RegisterVariables)
17023 break;
17024 }
17025 }
17026 }
17027 if (RegisterVariables)
17028 continue;
17029 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17030 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17031 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17032 FD->setInvalidDecl();
17033 break;
17034 }
17035 }
17036 }
17037
17038 assert(ExprCleanupObjects.size() ==
17039 ExprEvalContexts.back().NumCleanupObjects &&
17040 "Leftover temporaries in function");
17041 assert(!Cleanup.exprNeedsCleanups() &&
17042 "Unaccounted cleanups in function");
17043 assert(MaybeODRUseExprs.empty() &&
17044 "Leftover expressions for odr-use checking");
17045 }
17046 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17047 // the declaration context below. Otherwise, we're unable to transform
17048 // 'this' expressions when transforming immediate context functions.
17049
17050 if (FD)
17051 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17052
17053 if (!IsInstantiation)
17054 PopDeclContext();
17055
17056 if (!RetainFunctionScopeInfo)
17057 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17058 // If any errors have occurred, clear out any temporaries that may have
17059 // been leftover. This ensures that these temporaries won't be picked up for
17060 // deletion in some later function.
17061 if (hasUncompilableErrorOccurred()) {
17062 DiscardCleanupsInEvaluationContext();
17063 }
17064
17065 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17066 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17067 auto ES = getEmissionStatus(Decl: FD);
17068 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17069 ES == Sema::FunctionEmissionStatus::Unknown)
17070 DeclsToCheckForDeferredDiags.insert(X: FD);
17071 }
17072
17073 if (FD && !FD->isDeleted())
17074 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17075
17076 return dcl;
17077}
17078
17079/// When we finish delayed parsing of an attribute, we must attach it to the
17080/// relevant Decl.
17081void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17082 ParsedAttributes &Attrs) {
17083 // Always attach attributes to the underlying decl.
17084 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17085 D = TD->getTemplatedDecl();
17086 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17087 ProcessAPINotes(D);
17088
17089 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17090 if (Method->isStatic())
17091 checkThisInStaticMemberFunctionAttributes(Method);
17092}
17093
17094NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17095 IdentifierInfo &II, Scope *S) {
17096 // It is not valid to implicitly define a function in C23.
17097 assert(LangOpts.implicitFunctionsAllowed() &&
17098 "Implicit function declarations aren't allowed in this language mode");
17099
17100 // Find the scope in which the identifier is injected and the corresponding
17101 // DeclContext.
17102 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17103 // In that case, we inject the declaration into the translation unit scope
17104 // instead.
17105 Scope *BlockScope = S;
17106 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17107 BlockScope = BlockScope->getParent();
17108
17109 // Loop until we find a DeclContext that is either a function/method or the
17110 // translation unit, which are the only two valid places to implicitly define
17111 // a function. This avoids accidentally defining the function within a tag
17112 // declaration, for example.
17113 Scope *ContextScope = BlockScope;
17114 while (!ContextScope->getEntity() ||
17115 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17116 !ContextScope->getEntity()->isTranslationUnit()))
17117 ContextScope = ContextScope->getParent();
17118 ContextRAII SavedContext(*this, ContextScope->getEntity());
17119
17120 // Before we produce a declaration for an implicitly defined
17121 // function, see whether there was a locally-scoped declaration of
17122 // this name as a function or variable. If so, use that
17123 // (non-visible) declaration, and complain about it.
17124 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17125 if (ExternCPrev) {
17126 // We still need to inject the function into the enclosing block scope so
17127 // that later (non-call) uses can see it.
17128 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17129
17130 // C89 footnote 38:
17131 // If in fact it is not defined as having type "function returning int",
17132 // the behavior is undefined.
17133 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17134 !Context.typesAreCompatible(
17135 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17136 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17137 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17138 << ExternCPrev << !getLangOpts().C99;
17139 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17140 return ExternCPrev;
17141 }
17142 }
17143
17144 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17145 unsigned diag_id;
17146 if (II.getName().starts_with(Prefix: "__builtin_"))
17147 diag_id = diag::warn_builtin_unknown;
17148 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17149 else if (getLangOpts().C99)
17150 diag_id = diag::ext_implicit_function_decl_c99;
17151 else
17152 diag_id = diag::warn_implicit_function_decl;
17153
17154 TypoCorrection Corrected;
17155 // Because typo correction is expensive, only do it if the implicit
17156 // function declaration is going to be treated as an error.
17157 //
17158 // Perform the correction before issuing the main diagnostic, as some
17159 // consumers use typo-correction callbacks to enhance the main diagnostic.
17160 if (S && !ExternCPrev &&
17161 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17162 DeclFilterCCC<FunctionDecl> CCC{};
17163 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17164 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17165 }
17166
17167 Diag(Loc, DiagID: diag_id) << &II;
17168 if (Corrected) {
17169 // If the correction is going to suggest an implicitly defined function,
17170 // skip the correction as not being a particularly good idea.
17171 bool Diagnose = true;
17172 if (const auto *D = Corrected.getCorrectionDecl())
17173 Diagnose = !D->isImplicit();
17174 if (Diagnose)
17175 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17176 /*ErrorRecovery*/ false);
17177 }
17178
17179 // If we found a prior declaration of this function, don't bother building
17180 // another one. We've already pushed that one into scope, so there's nothing
17181 // more to do.
17182 if (ExternCPrev)
17183 return ExternCPrev;
17184
17185 // Set a Declarator for the implicit definition: int foo();
17186 const char *Dummy;
17187 AttributeFactory attrFactory;
17188 DeclSpec DS(attrFactory);
17189 unsigned DiagID;
17190 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17191 Policy: Context.getPrintingPolicy());
17192 (void)Error; // Silence warning.
17193 assert(!Error && "Error setting up implicit decl!");
17194 SourceLocation NoLoc;
17195 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17196 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17197 /*IsAmbiguous=*/false,
17198 /*LParenLoc=*/NoLoc,
17199 /*Params=*/nullptr,
17200 /*NumParams=*/0,
17201 /*EllipsisLoc=*/NoLoc,
17202 /*RParenLoc=*/NoLoc,
17203 /*RefQualifierIsLvalueRef=*/true,
17204 /*RefQualifierLoc=*/NoLoc,
17205 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17206 /*ESpecRange=*/SourceRange(),
17207 /*Exceptions=*/nullptr,
17208 /*ExceptionRanges=*/nullptr,
17209 /*NumExceptions=*/0,
17210 /*NoexceptExpr=*/nullptr,
17211 /*ExceptionSpecTokens=*/nullptr,
17212 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17213 TheDeclarator&: D),
17214 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17215 D.SetIdentifier(Id: &II, IdLoc: Loc);
17216
17217 // Insert this function into the enclosing block scope.
17218 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17219 FD->setImplicit();
17220
17221 AddKnownFunctionAttributes(FD);
17222
17223 return FD;
17224}
17225
17226void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17227 FunctionDecl *FD) {
17228 if (FD->isInvalidDecl())
17229 return;
17230
17231 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17232 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17233 return;
17234
17235 UnsignedOrNone AlignmentParam = std::nullopt;
17236 bool IsNothrow = false;
17237 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17238 return;
17239
17240 // C++2a [basic.stc.dynamic.allocation]p4:
17241 // An allocation function that has a non-throwing exception specification
17242 // indicates failure by returning a null pointer value. Any other allocation
17243 // function never returns a null pointer value and indicates failure only by
17244 // throwing an exception [...]
17245 //
17246 // However, -fcheck-new invalidates this possible assumption, so don't add
17247 // NonNull when that is enabled.
17248 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17249 !getLangOpts().CheckNew)
17250 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17251
17252 // C++2a [basic.stc.dynamic.allocation]p2:
17253 // An allocation function attempts to allocate the requested amount of
17254 // storage. [...] If the request succeeds, the value returned by a
17255 // replaceable allocation function is a [...] pointer value p0 different
17256 // from any previously returned value p1 [...]
17257 //
17258 // However, this particular information is being added in codegen,
17259 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17260
17261 // C++2a [basic.stc.dynamic.allocation]p2:
17262 // An allocation function attempts to allocate the requested amount of
17263 // storage. If it is successful, it returns the address of the start of a
17264 // block of storage whose length in bytes is at least as large as the
17265 // requested size.
17266 if (!FD->hasAttr<AllocSizeAttr>()) {
17267 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17268 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17269 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17270 }
17271
17272 // C++2a [basic.stc.dynamic.allocation]p3:
17273 // For an allocation function [...], the pointer returned on a successful
17274 // call shall represent the address of storage that is aligned as follows:
17275 // (3.1) If the allocation function takes an argument of type
17276 // std​::​align_­val_­t, the storage will have the alignment
17277 // specified by the value of this argument.
17278 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17279 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17280 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17281 }
17282
17283 // FIXME:
17284 // C++2a [basic.stc.dynamic.allocation]p3:
17285 // For an allocation function [...], the pointer returned on a successful
17286 // call shall represent the address of storage that is aligned as follows:
17287 // (3.2) Otherwise, if the allocation function is named operator new[],
17288 // the storage is aligned for any object that does not have
17289 // new-extended alignment ([basic.align]) and is no larger than the
17290 // requested size.
17291 // (3.3) Otherwise, the storage is aligned for any object that does not
17292 // have new-extended alignment and is of the requested size.
17293}
17294
17295void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17296 if (FD->isInvalidDecl())
17297 return;
17298
17299 // If this is a built-in function, map its builtin attributes to
17300 // actual attributes.
17301 if (unsigned BuiltinID = FD->getBuiltinID()) {
17302 // Handle printf-formatting attributes.
17303 unsigned FormatIdx;
17304 bool HasVAListArg;
17305 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17306 if (!FD->hasAttr<FormatAttr>()) {
17307 const char *fmt = "printf";
17308 unsigned int NumParams = FD->getNumParams();
17309 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17310 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17311 fmt = "NSString";
17312 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17313 Type: &Context.Idents.get(Name: fmt),
17314 FormatIdx: FormatIdx+1,
17315 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17316 Range: FD->getLocation()));
17317 }
17318 }
17319 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17320 HasVAListArg)) {
17321 if (!FD->hasAttr<FormatAttr>())
17322 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17323 Type: &Context.Idents.get(Name: "scanf"),
17324 FormatIdx: FormatIdx+1,
17325 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17326 Range: FD->getLocation()));
17327 }
17328
17329 // Handle automatically recognized callbacks.
17330 SmallVector<int, 4> Encoding;
17331 if (!FD->hasAttr<CallbackAttr>() &&
17332 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17333 FD->addAttr(A: CallbackAttr::CreateImplicit(
17334 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17335
17336 // Mark const if we don't care about errno and/or floating point exceptions
17337 // that are the only thing preventing the function from being const. This
17338 // allows IRgen to use LLVM intrinsics for such functions.
17339 bool NoExceptions =
17340 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17341 bool ConstWithoutErrnoAndExceptions =
17342 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17343 bool ConstWithoutExceptions =
17344 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17345 if (!FD->hasAttr<ConstAttr>() &&
17346 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17347 (!ConstWithoutErrnoAndExceptions ||
17348 (!getLangOpts().MathErrno && NoExceptions)) &&
17349 (!ConstWithoutExceptions || NoExceptions))
17350 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17351
17352 // We make "fma" on GNU or Windows const because we know it does not set
17353 // errno in those environments even though it could set errno based on the
17354 // C standard.
17355 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17356 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17357 !FD->hasAttr<ConstAttr>()) {
17358 switch (BuiltinID) {
17359 case Builtin::BI__builtin_fma:
17360 case Builtin::BI__builtin_fmaf:
17361 case Builtin::BI__builtin_fmal:
17362 case Builtin::BIfma:
17363 case Builtin::BIfmaf:
17364 case Builtin::BIfmal:
17365 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17366 break;
17367 default:
17368 break;
17369 }
17370 }
17371
17372 SmallVector<int, 4> Indxs;
17373 Builtin::Info::NonNullMode OptMode;
17374 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17375 !FD->hasAttr<NonNullAttr>()) {
17376 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17377 for (int I : Indxs) {
17378 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17379 QualType T = PVD->getType();
17380 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17381 PVD->setType(T);
17382 }
17383 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17384 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17385 for (int I : Indxs)
17386 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17387 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17388 ArgsSize: ParamIndxs.size()));
17389 }
17390 }
17391 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17392 !FD->hasAttr<ReturnsTwiceAttr>())
17393 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17394 Range: FD->getLocation()));
17395 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17396 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17397 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17398 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17399 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17400 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17401 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17402 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17403 // Add the appropriate attribute, depending on the CUDA compilation mode
17404 // and which target the builtin belongs to. For example, during host
17405 // compilation, aux builtins are __device__, while the rest are __host__.
17406 if (getLangOpts().CUDAIsDevice !=
17407 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17408 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17409 else
17410 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17411 }
17412
17413 // Add known guaranteed alignment for allocation functions.
17414 switch (BuiltinID) {
17415 case Builtin::BImemalign:
17416 case Builtin::BIaligned_alloc:
17417 if (!FD->hasAttr<AllocAlignAttr>())
17418 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17419 Range: FD->getLocation()));
17420 break;
17421 default:
17422 break;
17423 }
17424
17425 // Add allocsize attribute for allocation functions.
17426 switch (BuiltinID) {
17427 case Builtin::BIcalloc:
17428 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17429 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17430 break;
17431 case Builtin::BImemalign:
17432 case Builtin::BIaligned_alloc:
17433 case Builtin::BIrealloc:
17434 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17435 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17436 break;
17437 case Builtin::BImalloc:
17438 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17439 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17440 break;
17441 default:
17442 break;
17443 }
17444 }
17445
17446 LazyProcessLifetimeCaptureByParams(FD);
17447 inferLifetimeBoundAttribute(FD);
17448 inferLifetimeCaptureByAttribute(FD);
17449 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17450
17451 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17452 // throw, add an implicit nothrow attribute to any extern "C" function we come
17453 // across.
17454 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17455 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17456 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17457 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17458 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17459 }
17460
17461 IdentifierInfo *Name = FD->getIdentifier();
17462 if (!Name)
17463 return;
17464 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17465 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17466 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17467 LinkageSpecLanguageIDs::C)) {
17468 // Okay: this could be a libc/libm/Objective-C function we know
17469 // about.
17470 } else
17471 return;
17472
17473 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17474 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17475 // target-specific builtins, perhaps?
17476 if (!FD->hasAttr<FormatAttr>())
17477 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17478 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17479 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17480 Range: FD->getLocation()));
17481 }
17482
17483 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17484 // We already have a __builtin___CFStringMakeConstantString,
17485 // but builds that use -fno-constant-cfstrings don't go through that.
17486 if (!FD->hasAttr<FormatArgAttr>())
17487 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17488 Range: FD->getLocation()));
17489 }
17490}
17491
17492TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17493 TypeSourceInfo *TInfo) {
17494 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17495 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17496
17497 if (!TInfo) {
17498 assert(D.isInvalidType() && "no declarator info for valid type");
17499 TInfo = Context.getTrivialTypeSourceInfo(T);
17500 }
17501
17502 // Scope manipulation handled by caller.
17503 TypedefDecl *NewTD =
17504 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17505 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17506
17507 // Bail out immediately if we have an invalid declaration.
17508 if (D.isInvalidType()) {
17509 NewTD->setInvalidDecl();
17510 return NewTD;
17511 }
17512
17513 if (D.getDeclSpec().isModulePrivateSpecified()) {
17514 if (CurContext->isFunctionOrMethod())
17515 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17516 << 2 << NewTD
17517 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17518 << FixItHint::CreateRemoval(
17519 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17520 else
17521 NewTD->setModulePrivate();
17522 }
17523
17524 // C++ [dcl.typedef]p8:
17525 // If the typedef declaration defines an unnamed class (or
17526 // enum), the first typedef-name declared by the declaration
17527 // to be that class type (or enum type) is used to denote the
17528 // class type (or enum type) for linkage purposes only.
17529 // We need to check whether the type was declared in the declaration.
17530 switch (D.getDeclSpec().getTypeSpecType()) {
17531 case TST_enum:
17532 case TST_struct:
17533 case TST_interface:
17534 case TST_union:
17535 case TST_class: {
17536 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17537 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17538 break;
17539 }
17540
17541 default:
17542 break;
17543 }
17544
17545 return NewTD;
17546}
17547
17548bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17549 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17550 QualType T = TI->getType();
17551
17552 if (T->isDependentType())
17553 return false;
17554
17555 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17556 // integral type; any cv-qualification is ignored.
17557 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17558 // non-atomic version of the type specified by the type specifiers in the
17559 // specifier qualifier list.
17560 // Because of how odd C's rule is, we'll let the user know that operations
17561 // involving the enumeration type will be non-atomic.
17562 if (T->isAtomicType())
17563 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17564
17565 Qualifiers Q = T.getQualifiers();
17566 std::optional<unsigned> QualSelect;
17567 if (Q.hasConst() && Q.hasVolatile())
17568 QualSelect = diag::CVQualList::Both;
17569 else if (Q.hasConst())
17570 QualSelect = diag::CVQualList::Const;
17571 else if (Q.hasVolatile())
17572 QualSelect = diag::CVQualList::Volatile;
17573
17574 if (QualSelect)
17575 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17576
17577 T = T.getAtomicUnqualifiedType();
17578
17579 // This doesn't use 'isIntegralType' despite the error message mentioning
17580 // integral type because isIntegralType would also allow enum types in C.
17581 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17582 if (BT->isInteger())
17583 return false;
17584
17585 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17586 << T << T->isBitIntType();
17587}
17588
17589bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17590 QualType EnumUnderlyingTy, bool IsFixed,
17591 const EnumDecl *Prev) {
17592 if (IsScoped != Prev->isScoped()) {
17593 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17594 << Prev->isScoped();
17595 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17596 return true;
17597 }
17598
17599 if (IsFixed && Prev->isFixed()) {
17600 if (!EnumUnderlyingTy->isDependentType() &&
17601 !Prev->getIntegerType()->isDependentType() &&
17602 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17603 T2: Prev->getIntegerType())) {
17604 // TODO: Highlight the underlying type of the redeclaration.
17605 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17606 << EnumUnderlyingTy << Prev->getIntegerType();
17607 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17608 << Prev->getIntegerTypeRange();
17609 return true;
17610 }
17611 } else if (IsFixed != Prev->isFixed()) {
17612 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17613 << Prev->isFixed();
17614 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17615 return true;
17616 }
17617
17618 return false;
17619}
17620
17621/// Get diagnostic %select index for tag kind for
17622/// redeclaration diagnostic message.
17623/// WARNING: Indexes apply to particular diagnostics only!
17624///
17625/// \returns diagnostic %select index.
17626static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17627 switch (Tag) {
17628 case TagTypeKind::Struct:
17629 return 0;
17630 case TagTypeKind::Interface:
17631 return 1;
17632 case TagTypeKind::Class:
17633 return 2;
17634 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17635 }
17636}
17637
17638/// Determine if tag kind is a class-key compatible with
17639/// class for redeclaration (class, struct, or __interface).
17640///
17641/// \returns true iff the tag kind is compatible.
17642static bool isClassCompatTagKind(TagTypeKind Tag)
17643{
17644 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17645 Tag == TagTypeKind::Interface;
17646}
17647
17648NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17649 if (isa<TypedefDecl>(Val: PrevDecl))
17650 return NonTagKind::Typedef;
17651 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17652 return NonTagKind::TypeAlias;
17653 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17654 return NonTagKind::Template;
17655 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17656 return NonTagKind::TypeAliasTemplate;
17657 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17658 return NonTagKind::TemplateTemplateArgument;
17659 switch (TTK) {
17660 case TagTypeKind::Struct:
17661 case TagTypeKind::Interface:
17662 case TagTypeKind::Class:
17663 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17664 : NonTagKind::NonStruct;
17665 case TagTypeKind::Union:
17666 return NonTagKind::NonUnion;
17667 case TagTypeKind::Enum:
17668 return NonTagKind::NonEnum;
17669 }
17670 llvm_unreachable("invalid TTK");
17671}
17672
17673bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17674 TagTypeKind NewTag, bool isDefinition,
17675 SourceLocation NewTagLoc,
17676 const IdentifierInfo *Name) {
17677 // C++ [dcl.type.elab]p3:
17678 // The class-key or enum keyword present in the
17679 // elaborated-type-specifier shall agree in kind with the
17680 // declaration to which the name in the elaborated-type-specifier
17681 // refers. This rule also applies to the form of
17682 // elaborated-type-specifier that declares a class-name or
17683 // friend class since it can be construed as referring to the
17684 // definition of the class. Thus, in any
17685 // elaborated-type-specifier, the enum keyword shall be used to
17686 // refer to an enumeration (7.2), the union class-key shall be
17687 // used to refer to a union (clause 9), and either the class or
17688 // struct class-key shall be used to refer to a class (clause 9)
17689 // declared using the class or struct class-key.
17690 TagTypeKind OldTag = Previous->getTagKind();
17691 if (OldTag != NewTag &&
17692 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17693 return false;
17694
17695 // Tags are compatible, but we might still want to warn on mismatched tags.
17696 // Non-class tags can't be mismatched at this point.
17697 if (!isClassCompatTagKind(Tag: NewTag))
17698 return true;
17699
17700 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17701 // by our warning analysis. We don't want to warn about mismatches with (eg)
17702 // declarations in system headers that are designed to be specialized, but if
17703 // a user asks us to warn, we should warn if their code contains mismatched
17704 // declarations.
17705 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17706 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17707 Loc);
17708 };
17709 if (IsIgnoredLoc(NewTagLoc))
17710 return true;
17711
17712 auto IsIgnored = [&](const TagDecl *Tag) {
17713 return IsIgnoredLoc(Tag->getLocation());
17714 };
17715 while (IsIgnored(Previous)) {
17716 Previous = Previous->getPreviousDecl();
17717 if (!Previous)
17718 return true;
17719 OldTag = Previous->getTagKind();
17720 }
17721
17722 bool isTemplate = false;
17723 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17724 isTemplate = Record->getDescribedClassTemplate();
17725
17726 if (inTemplateInstantiation()) {
17727 if (OldTag != NewTag) {
17728 // In a template instantiation, do not offer fix-its for tag mismatches
17729 // since they usually mess up the template instead of fixing the problem.
17730 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17731 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17732 << getRedeclDiagFromTagKind(Tag: OldTag);
17733 // FIXME: Note previous location?
17734 }
17735 return true;
17736 }
17737
17738 if (isDefinition) {
17739 // On definitions, check all previous tags and issue a fix-it for each
17740 // one that doesn't match the current tag.
17741 if (Previous->getDefinition()) {
17742 // Don't suggest fix-its for redefinitions.
17743 return true;
17744 }
17745
17746 bool previousMismatch = false;
17747 for (const TagDecl *I : Previous->redecls()) {
17748 if (I->getTagKind() != NewTag) {
17749 // Ignore previous declarations for which the warning was disabled.
17750 if (IsIgnored(I))
17751 continue;
17752
17753 if (!previousMismatch) {
17754 previousMismatch = true;
17755 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17756 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17757 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17758 }
17759 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17760 << getRedeclDiagFromTagKind(Tag: NewTag)
17761 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17762 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17763 }
17764 }
17765 return true;
17766 }
17767
17768 // Identify the prevailing tag kind: this is the kind of the definition (if
17769 // there is a non-ignored definition), or otherwise the kind of the prior
17770 // (non-ignored) declaration.
17771 const TagDecl *PrevDef = Previous->getDefinition();
17772 if (PrevDef && IsIgnored(PrevDef))
17773 PrevDef = nullptr;
17774 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17775 if (Redecl->getTagKind() != NewTag) {
17776 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17777 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17778 << getRedeclDiagFromTagKind(Tag: OldTag);
17779 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17780
17781 // If there is a previous definition, suggest a fix-it.
17782 if (PrevDef) {
17783 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17784 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17785 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17786 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17787 }
17788 }
17789
17790 return true;
17791}
17792
17793/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17794/// from an outer enclosing namespace or file scope inside a friend declaration.
17795/// This should provide the commented out code in the following snippet:
17796/// namespace N {
17797/// struct X;
17798/// namespace M {
17799/// struct Y { friend struct /*N::*/ X; };
17800/// }
17801/// }
17802static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17803 SourceLocation NameLoc) {
17804 // While the decl is in a namespace, do repeated lookup of that name and see
17805 // if we get the same namespace back. If we do not, continue until
17806 // translation unit scope, at which point we have a fully qualified NNS.
17807 SmallVector<IdentifierInfo *, 4> Namespaces;
17808 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17809 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17810 // This tag should be declared in a namespace, which can only be enclosed by
17811 // other namespaces. Bail if there's an anonymous namespace in the chain.
17812 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17813 if (!Namespace || Namespace->isAnonymousNamespace())
17814 return FixItHint();
17815 IdentifierInfo *II = Namespace->getIdentifier();
17816 Namespaces.push_back(Elt: II);
17817 NamedDecl *Lookup = SemaRef.LookupSingleName(
17818 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17819 if (Lookup == Namespace)
17820 break;
17821 }
17822
17823 // Once we have all the namespaces, reverse them to go outermost first, and
17824 // build an NNS.
17825 SmallString<64> Insertion;
17826 llvm::raw_svector_ostream OS(Insertion);
17827 if (DC->isTranslationUnit())
17828 OS << "::";
17829 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17830 for (auto *II : Namespaces)
17831 OS << II->getName() << "::";
17832 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17833}
17834
17835/// Determine whether a tag originally declared in context \p OldDC can
17836/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17837/// found a declaration in \p OldDC as a previous decl, perhaps through a
17838/// using-declaration).
17839static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17840 DeclContext *NewDC) {
17841 OldDC = OldDC->getRedeclContext();
17842 NewDC = NewDC->getRedeclContext();
17843
17844 if (OldDC->Equals(DC: NewDC))
17845 return true;
17846
17847 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17848 // encloses the other).
17849 if (S.getLangOpts().MSVCCompat &&
17850 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17851 return true;
17852
17853 return false;
17854}
17855
17856DeclResult
17857Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17858 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17859 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17860 SourceLocation ModulePrivateLoc,
17861 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17862 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17863 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17864 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17865 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17866 // If this is not a definition, it must have a name.
17867 IdentifierInfo *OrigName = Name;
17868 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17869 "Nameless record must be a definition!");
17870 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17871
17872 OwnedDecl = false;
17873 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17874 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17875
17876 // FIXME: Check member specializations more carefully.
17877 bool isMemberSpecialization = false;
17878 bool IsInjectedClassName = false;
17879 bool Invalid = false;
17880
17881 // We only need to do this matching if we have template parameters
17882 // or a scope specifier, which also conveniently avoids this work
17883 // for non-C++ cases.
17884 if (TemplateParameterLists.size() > 0 ||
17885 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17886 TemplateParameterList *TemplateParams =
17887 MatchTemplateParametersToScopeSpecifier(
17888 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17889 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17890
17891 // C++23 [dcl.type.elab] p2:
17892 // If an elaborated-type-specifier is the sole constituent of a
17893 // declaration, the declaration is ill-formed unless it is an explicit
17894 // specialization, an explicit instantiation or it has one of the
17895 // following forms: [...]
17896 // C++23 [dcl.enum] p1:
17897 // If the enum-head-name of an opaque-enum-declaration contains a
17898 // nested-name-specifier, the declaration shall be an explicit
17899 // specialization.
17900 //
17901 // FIXME: Class template partial specializations can be forward declared
17902 // per CWG2213, but the resolution failed to allow qualified forward
17903 // declarations. This is almost certainly unintentional, so we allow them.
17904 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17905 !isMemberSpecialization)
17906 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
17907 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17908
17909 if (TemplateParams) {
17910 if (Kind == TagTypeKind::Enum) {
17911 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
17912 return true;
17913 }
17914
17915 if (TemplateParams->size() > 0) {
17916 // This is a declaration or definition of a class template (which may
17917 // be a member of another template).
17918
17919 if (Invalid)
17920 return true;
17921
17922 OwnedDecl = false;
17923 DeclResult Result = CheckClassTemplate(
17924 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17925 AS, ModulePrivateLoc,
17926 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17927 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17928 return Result.get();
17929 } else {
17930 // The "template<>" header is extraneous.
17931 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
17932 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17933 isMemberSpecialization = true;
17934 }
17935 }
17936
17937 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17938 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17939 return true;
17940 }
17941
17942 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17943 // C++23 [dcl.type.elab]p4:
17944 // If an elaborated-type-specifier appears with the friend specifier as
17945 // an entire member-declaration, the member-declaration shall have one
17946 // of the following forms:
17947 // friend class-key nested-name-specifier(opt) identifier ;
17948 // friend class-key simple-template-id ;
17949 // friend class-key nested-name-specifier template(opt)
17950 // simple-template-id ;
17951 //
17952 // Since enum is not a class-key, so declarations like "friend enum E;"
17953 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17954 // invalid, most implementations accept so we issue a pedantic warning.
17955 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
17956 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17957 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17958 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
17959 << (ScopedEnum + ScopedEnumUsesClassTag);
17960 }
17961
17962 // Figure out the underlying type if this a enum declaration. We need to do
17963 // this early, because it's needed to detect if this is an incompatible
17964 // redeclaration.
17965 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17966 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17967
17968 if (Kind == TagTypeKind::Enum) {
17969 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17970 // No underlying type explicitly specified, or we failed to parse the
17971 // type, default to int.
17972 EnumUnderlying = Context.IntTy.getTypePtr();
17973 } else if (UnderlyingType.get()) {
17974 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17975 // integral type; any cv-qualification is ignored.
17976 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17977 // unqualified, non-atomic version of the type specified by the type
17978 // specifiers in the specifier qualifier list.
17979 TypeSourceInfo *TI = nullptr;
17980 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17981 EnumUnderlying = TI;
17982
17983 if (CheckEnumUnderlyingType(TI))
17984 // Recover by falling back to int.
17985 EnumUnderlying = Context.IntTy.getTypePtr();
17986
17987 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17988 UPPC: UPPC_FixedUnderlyingType))
17989 EnumUnderlying = Context.IntTy.getTypePtr();
17990
17991 // If the underlying type is atomic, we need to adjust the type before
17992 // continuing. This only happens in the case we stored a TypeSourceInfo
17993 // into EnumUnderlying because the other cases are error recovery up to
17994 // this point. But because it's not possible to gin up a TypeSourceInfo
17995 // for a non-atomic type from an atomic one, we'll store into the Type
17996 // field instead. FIXME: it would be nice to have an easy way to get a
17997 // derived TypeSourceInfo which strips qualifiers including the weird
17998 // ones like _Atomic where it forms a different type.
17999 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18000 TI && TI->getType()->isAtomicType())
18001 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18002
18003 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18004 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18005 // of 'int'. However, if this is an unfixed forward declaration, don't set
18006 // the underlying type unless the user enables -fms-compatibility. This
18007 // makes unfixed forward declared enums incomplete and is more conforming.
18008 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18009 EnumUnderlying = Context.IntTy.getTypePtr();
18010 }
18011 }
18012
18013 DeclContext *SearchDC = CurContext;
18014 DeclContext *DC = CurContext;
18015 bool isStdBadAlloc = false;
18016 bool isStdAlignValT = false;
18017
18018 RedeclarationKind Redecl = forRedeclarationInCurContext();
18019 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18020 Redecl = RedeclarationKind::NotForRedeclaration;
18021
18022 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18023 /// implemented asks for structural equivalence checking, the returned decl
18024 /// here is passed back to the parser, allowing the tag body to be parsed.
18025 auto createTagFromNewDecl = [&]() -> TagDecl * {
18026 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18027 // If there is an identifier, use the location of the identifier as the
18028 // location of the decl, otherwise use the location of the struct/union
18029 // keyword.
18030 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18031 TagDecl *New = nullptr;
18032
18033 if (Kind == TagTypeKind::Enum) {
18034 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18035 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18036 // If this is an undefined enum, bail.
18037 if (TUK != TagUseKind::Definition && !Invalid)
18038 return nullptr;
18039 if (EnumUnderlying) {
18040 EnumDecl *ED = cast<EnumDecl>(Val: New);
18041 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18042 ED->setIntegerTypeSourceInfo(TI);
18043 else
18044 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18045 QualType EnumTy = ED->getIntegerType();
18046 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18047 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18048 : EnumTy);
18049 }
18050 } else { // struct/union
18051 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18052 PrevDecl: nullptr);
18053 }
18054
18055 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18056 // Add alignment attributes if necessary; these attributes are checked
18057 // when the ASTContext lays out the structure.
18058 //
18059 // It is important for implementing the correct semantics that this
18060 // happen here (in ActOnTag). The #pragma pack stack is
18061 // maintained as a result of parser callbacks which can occur at
18062 // many points during the parsing of a struct declaration (because
18063 // the #pragma tokens are effectively skipped over during the
18064 // parsing of the struct).
18065 if (TUK == TagUseKind::Definition &&
18066 (!SkipBody || !SkipBody->ShouldSkip)) {
18067 if (LangOpts.HLSL)
18068 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18069 AddAlignmentAttributesForRecord(RD);
18070 AddMsStructLayoutForRecord(RD);
18071 }
18072 }
18073 New->setLexicalDeclContext(CurContext);
18074 return New;
18075 };
18076
18077 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18078 if (Name && SS.isNotEmpty()) {
18079 // We have a nested-name tag ('struct foo::bar').
18080
18081 // Check for invalid 'foo::'.
18082 if (SS.isInvalid()) {
18083 Name = nullptr;
18084 goto CreateNewDecl;
18085 }
18086
18087 // If this is a friend or a reference to a class in a dependent
18088 // context, don't try to make a decl for it.
18089 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18090 DC = computeDeclContext(SS, EnteringContext: false);
18091 if (!DC) {
18092 IsDependent = true;
18093 return true;
18094 }
18095 } else {
18096 DC = computeDeclContext(SS, EnteringContext: true);
18097 if (!DC) {
18098 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18099 << SS.getRange();
18100 return true;
18101 }
18102 }
18103
18104 if (RequireCompleteDeclContext(SS, DC))
18105 return true;
18106
18107 SearchDC = DC;
18108 // Look-up name inside 'foo::'.
18109 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18110
18111 if (Previous.isAmbiguous())
18112 return true;
18113
18114 if (Previous.empty()) {
18115 // Name lookup did not find anything. However, if the
18116 // nested-name-specifier refers to the current instantiation,
18117 // and that current instantiation has any dependent base
18118 // classes, we might find something at instantiation time: treat
18119 // this as a dependent elaborated-type-specifier.
18120 // But this only makes any sense for reference-like lookups.
18121 if (Previous.wasNotFoundInCurrentInstantiation() &&
18122 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18123 IsDependent = true;
18124 return true;
18125 }
18126
18127 // A tag 'foo::bar' must already exist.
18128 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18129 << Kind << Name << DC << SS.getRange();
18130 Name = nullptr;
18131 Invalid = true;
18132 goto CreateNewDecl;
18133 }
18134 } else if (Name) {
18135 // C++14 [class.mem]p14:
18136 // If T is the name of a class, then each of the following shall have a
18137 // name different from T:
18138 // -- every member of class T that is itself a type
18139 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18140 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18141 return true;
18142
18143 // If this is a named struct, check to see if there was a previous forward
18144 // declaration or definition.
18145 // FIXME: We're looking into outer scopes here, even when we
18146 // shouldn't be. Doing so can result in ambiguities that we
18147 // shouldn't be diagnosing.
18148 LookupName(R&: Previous, S);
18149
18150 // When declaring or defining a tag, ignore ambiguities introduced
18151 // by types using'ed into this scope.
18152 if (Previous.isAmbiguous() &&
18153 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18154 LookupResult::Filter F = Previous.makeFilter();
18155 while (F.hasNext()) {
18156 NamedDecl *ND = F.next();
18157 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18158 DC: SearchDC->getRedeclContext()))
18159 F.erase();
18160 }
18161 F.done();
18162 }
18163
18164 // C++11 [namespace.memdef]p3:
18165 // If the name in a friend declaration is neither qualified nor
18166 // a template-id and the declaration is a function or an
18167 // elaborated-type-specifier, the lookup to determine whether
18168 // the entity has been previously declared shall not consider
18169 // any scopes outside the innermost enclosing namespace.
18170 //
18171 // MSVC doesn't implement the above rule for types, so a friend tag
18172 // declaration may be a redeclaration of a type declared in an enclosing
18173 // scope. They do implement this rule for friend functions.
18174 //
18175 // Does it matter that this should be by scope instead of by
18176 // semantic context?
18177 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18178 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18179 LookupResult::Filter F = Previous.makeFilter();
18180 bool FriendSawTagOutsideEnclosingNamespace = false;
18181 while (F.hasNext()) {
18182 NamedDecl *ND = F.next();
18183 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18184 if (DC->isFileContext() &&
18185 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18186 if (getLangOpts().MSVCCompat)
18187 FriendSawTagOutsideEnclosingNamespace = true;
18188 else
18189 F.erase();
18190 }
18191 }
18192 F.done();
18193
18194 // Diagnose this MSVC extension in the easy case where lookup would have
18195 // unambiguously found something outside the enclosing namespace.
18196 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18197 NamedDecl *ND = Previous.getFoundDecl();
18198 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18199 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18200 }
18201 }
18202
18203 // Note: there used to be some attempt at recovery here.
18204 if (Previous.isAmbiguous())
18205 return true;
18206
18207 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18208 // FIXME: This makes sure that we ignore the contexts associated
18209 // with C structs, unions, and enums when looking for a matching
18210 // tag declaration or definition. See the similar lookup tweak
18211 // in Sema::LookupName; is there a better way to deal with this?
18212 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18213 SearchDC = SearchDC->getParent();
18214 } else if (getLangOpts().CPlusPlus) {
18215 // Inside ObjCContainer want to keep it as a lexical decl context but go
18216 // past it (most often to TranslationUnit) to find the semantic decl
18217 // context.
18218 while (isa<ObjCContainerDecl>(Val: SearchDC))
18219 SearchDC = SearchDC->getParent();
18220 }
18221 } else if (getLangOpts().CPlusPlus) {
18222 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18223 // TagDecl the same way as we skip it for named TagDecl.
18224 while (isa<ObjCContainerDecl>(Val: SearchDC))
18225 SearchDC = SearchDC->getParent();
18226 }
18227
18228 if (Previous.isSingleResult() &&
18229 Previous.getFoundDecl()->isTemplateParameter()) {
18230 // Maybe we will complain about the shadowed template parameter.
18231 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18232 // Just pretend that we didn't see the previous declaration.
18233 Previous.clear();
18234 }
18235
18236 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18237 DC->Equals(DC: getStdNamespace())) {
18238 if (Name->isStr(Str: "bad_alloc")) {
18239 // This is a declaration of or a reference to "std::bad_alloc".
18240 isStdBadAlloc = true;
18241
18242 // If std::bad_alloc has been implicitly declared (but made invisible to
18243 // name lookup), fill in this implicit declaration as the previous
18244 // declaration, so that the declarations get chained appropriately.
18245 if (Previous.empty() && StdBadAlloc)
18246 Previous.addDecl(D: getStdBadAlloc());
18247 } else if (Name->isStr(Str: "align_val_t")) {
18248 isStdAlignValT = true;
18249 if (Previous.empty() && StdAlignValT)
18250 Previous.addDecl(D: getStdAlignValT());
18251 }
18252 }
18253
18254 // If we didn't find a previous declaration, and this is a reference
18255 // (or friend reference), move to the correct scope. In C++, we
18256 // also need to do a redeclaration lookup there, just in case
18257 // there's a shadow friend decl.
18258 if (Name && Previous.empty() &&
18259 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18260 IsTemplateParamOrArg)) {
18261 if (Invalid) goto CreateNewDecl;
18262 assert(SS.isEmpty());
18263
18264 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18265 // C++ [basic.scope.pdecl]p5:
18266 // -- for an elaborated-type-specifier of the form
18267 //
18268 // class-key identifier
18269 //
18270 // if the elaborated-type-specifier is used in the
18271 // decl-specifier-seq or parameter-declaration-clause of a
18272 // function defined in namespace scope, the identifier is
18273 // declared as a class-name in the namespace that contains
18274 // the declaration; otherwise, except as a friend
18275 // declaration, the identifier is declared in the smallest
18276 // non-class, non-function-prototype scope that contains the
18277 // declaration.
18278 //
18279 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18280 // C structs and unions.
18281 //
18282 // It is an error in C++ to declare (rather than define) an enum
18283 // type, including via an elaborated type specifier. We'll
18284 // diagnose that later; for now, declare the enum in the same
18285 // scope as we would have picked for any other tag type.
18286 //
18287 // GNU C also supports this behavior as part of its incomplete
18288 // enum types extension, while GNU C++ does not.
18289 //
18290 // Find the context where we'll be declaring the tag.
18291 // FIXME: We would like to maintain the current DeclContext as the
18292 // lexical context,
18293 SearchDC = getTagInjectionContext(DC: SearchDC);
18294
18295 // Find the scope where we'll be declaring the tag.
18296 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18297 } else {
18298 assert(TUK == TagUseKind::Friend);
18299 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18300
18301 // C++ [namespace.memdef]p3:
18302 // If a friend declaration in a non-local class first declares a
18303 // class or function, the friend class or function is a member of
18304 // the innermost enclosing namespace.
18305 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18306 : SearchDC->getEnclosingNamespaceContext();
18307 }
18308
18309 // In C++, we need to do a redeclaration lookup to properly
18310 // diagnose some problems.
18311 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18312 // hidden declaration so that we don't get ambiguity errors when using a
18313 // type declared by an elaborated-type-specifier. In C that is not correct
18314 // and we should instead merge compatible types found by lookup.
18315 if (getLangOpts().CPlusPlus) {
18316 // FIXME: This can perform qualified lookups into function contexts,
18317 // which are meaningless.
18318 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18319 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18320 } else {
18321 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18322 LookupName(R&: Previous, S);
18323 }
18324 }
18325
18326 // If we have a known previous declaration to use, then use it.
18327 if (Previous.empty() && SkipBody && SkipBody->Previous)
18328 Previous.addDecl(D: SkipBody->Previous);
18329
18330 if (!Previous.empty()) {
18331 NamedDecl *PrevDecl = Previous.getFoundDecl();
18332 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18333
18334 // It's okay to have a tag decl in the same scope as a typedef
18335 // which hides a tag decl in the same scope. Finding this
18336 // with a redeclaration lookup can only actually happen in C++.
18337 //
18338 // This is also okay for elaborated-type-specifiers, which is
18339 // technically forbidden by the current standard but which is
18340 // okay according to the likely resolution of an open issue;
18341 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18342 if (getLangOpts().CPlusPlus) {
18343 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18344 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18345 if (Tag->getDeclName() == Name &&
18346 Tag->getDeclContext()->getRedeclContext()
18347 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18348 PrevDecl = Tag;
18349 Previous.clear();
18350 Previous.addDecl(D: Tag);
18351 Previous.resolveKind();
18352 }
18353 }
18354 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18355 TUK == TagUseKind::Reference && RD &&
18356 RD->isInjectedClassName()) {
18357 // If lookup found the injected class name, the previous declaration is
18358 // the class being injected into.
18359 PrevDecl = cast<TagDecl>(Val: RD->getDeclContext());
18360 Previous.clear();
18361 Previous.addDecl(D: PrevDecl);
18362 Previous.resolveKind();
18363 IsInjectedClassName = true;
18364 }
18365 }
18366
18367 // If this is a redeclaration of a using shadow declaration, it must
18368 // declare a tag in the same context. In MSVC mode, we allow a
18369 // redefinition if either context is within the other.
18370 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18371 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18372 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18373 TUK != TagUseKind::Friend &&
18374 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18375 !(OldTag && isAcceptableTagRedeclContext(
18376 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18377 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18378 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18379 DiagID: diag::note_using_decl_target);
18380 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18381 << 0;
18382 // Recover by ignoring the old declaration.
18383 Previous.clear();
18384 goto CreateNewDecl;
18385 }
18386 }
18387
18388 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18389 // If this is a use of a previous tag, or if the tag is already declared
18390 // in the same scope (so that the definition/declaration completes or
18391 // rementions the tag), reuse the decl.
18392 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18393 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18394 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18395 // Make sure that this wasn't declared as an enum and now used as a
18396 // struct or something similar.
18397 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18398 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18399 Name)) {
18400 bool SafeToContinue =
18401 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18402 Kind != TagTypeKind::Enum);
18403 if (SafeToContinue)
18404 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18405 << Name
18406 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18407 Code: PrevTagDecl->getKindName());
18408 else
18409 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18410 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18411
18412 if (SafeToContinue)
18413 Kind = PrevTagDecl->getTagKind();
18414 else {
18415 // Recover by making this an anonymous redefinition.
18416 Name = nullptr;
18417 Previous.clear();
18418 Invalid = true;
18419 }
18420 }
18421
18422 if (Kind == TagTypeKind::Enum &&
18423 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18424 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18425 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18426 return PrevTagDecl;
18427
18428 QualType EnumUnderlyingTy;
18429 if (TypeSourceInfo *TI =
18430 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18431 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18432 else if (const Type *T =
18433 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18434 EnumUnderlyingTy = QualType(T, 0);
18435
18436 // All conflicts with previous declarations are recovered by
18437 // returning the previous declaration, unless this is a definition,
18438 // in which case we want the caller to bail out.
18439 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18440 IsScoped: ScopedEnum, EnumUnderlyingTy,
18441 IsFixed, Prev: PrevEnum))
18442 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18443 }
18444
18445 // C++11 [class.mem]p1:
18446 // A member shall not be declared twice in the member-specification,
18447 // except that a nested class or member class template can be declared
18448 // and then later defined.
18449 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18450 S->isDeclScope(D: PrevDecl)) {
18451 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18452 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18453 }
18454
18455 if (!Invalid) {
18456 // If this is a use, just return the declaration we found, unless
18457 // we have attributes.
18458 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18459 if (!Attrs.empty()) {
18460 // FIXME: Diagnose these attributes. For now, we create a new
18461 // declaration to hold them.
18462 } else if (TUK == TagUseKind::Reference &&
18463 (PrevTagDecl->getFriendObjectKind() ==
18464 Decl::FOK_Undeclared ||
18465 PrevDecl->getOwningModule() != getCurrentModule()) &&
18466 SS.isEmpty()) {
18467 // This declaration is a reference to an existing entity, but
18468 // has different visibility from that entity: it either makes
18469 // a friend visible or it makes a type visible in a new module.
18470 // In either case, create a new declaration. We only do this if
18471 // the declaration would have meant the same thing if no prior
18472 // declaration were found, that is, if it was found in the same
18473 // scope where we would have injected a declaration.
18474 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18475 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18476 return PrevTagDecl;
18477 // This is in the injected scope, create a new declaration in
18478 // that scope.
18479 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18480 } else {
18481 return PrevTagDecl;
18482 }
18483 }
18484
18485 // Diagnose attempts to redefine a tag.
18486 if (TUK == TagUseKind::Definition) {
18487 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18488 // If the type is currently being defined, complain
18489 // about a nested redefinition.
18490 if (Def->isBeingDefined()) {
18491 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18492 Diag(Loc: PrevTagDecl->getLocation(),
18493 DiagID: diag::note_previous_definition);
18494 Name = nullptr;
18495 Previous.clear();
18496 Invalid = true;
18497 } else {
18498 // If we're defining a specialization and the previous
18499 // definition is from an implicit instantiation, don't emit an
18500 // error here; we'll catch this in the general case below.
18501 bool IsExplicitSpecializationAfterInstantiation = false;
18502 if (isMemberSpecialization) {
18503 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18504 IsExplicitSpecializationAfterInstantiation =
18505 RD->getTemplateSpecializationKind() !=
18506 TSK_ExplicitSpecialization;
18507 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18508 IsExplicitSpecializationAfterInstantiation =
18509 ED->getTemplateSpecializationKind() !=
18510 TSK_ExplicitSpecialization;
18511 }
18512
18513 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18514 // do not keep more that one definition around (merge them).
18515 // However, ensure the decl passes the structural compatibility
18516 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18517 NamedDecl *Hidden = nullptr;
18518 bool HiddenDefVisible = false;
18519 if (SkipBody &&
18520 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18521 getLangOpts().C23)) {
18522 // There is a definition of this tag, but it is not visible.
18523 // We explicitly make use of C++'s one definition rule here,
18524 // and assume that this definition is identical to the hidden
18525 // one we already have. Make the existing definition visible
18526 // and use it in place of this one.
18527 if (!getLangOpts().CPlusPlus) {
18528 // Postpone making the old definition visible until after we
18529 // complete parsing the new one and do the structural
18530 // comparison.
18531 SkipBody->CheckSameAsPrevious = true;
18532 SkipBody->New = createTagFromNewDecl();
18533 SkipBody->Previous = Def;
18534
18535 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18536 return Def;
18537 }
18538
18539 SkipBody->ShouldSkip = true;
18540 SkipBody->Previous = Def;
18541 if (!HiddenDefVisible && Hidden)
18542 makeMergedDefinitionVisible(ND: Hidden);
18543 // Carry on and handle it like a normal definition. We'll
18544 // skip starting the definition later.
18545
18546 } else if (!IsExplicitSpecializationAfterInstantiation) {
18547 // A redeclaration in function prototype scope in C isn't
18548 // visible elsewhere, so merely issue a warning.
18549 if (!getLangOpts().CPlusPlus &&
18550 S->containedInPrototypeScope())
18551 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18552 << Name;
18553 else
18554 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18555 notePreviousDefinition(Old: Def,
18556 New: NameLoc.isValid() ? NameLoc : KWLoc);
18557 // If this is a redefinition, recover by making this
18558 // struct be anonymous, which will make any later
18559 // references get the previous definition.
18560 Name = nullptr;
18561 Previous.clear();
18562 Invalid = true;
18563 }
18564 }
18565 }
18566
18567 // Okay, this is definition of a previously declared or referenced
18568 // tag. We're going to create a new Decl for it.
18569 }
18570
18571 // Okay, we're going to make a redeclaration. If this is some kind
18572 // of reference, make sure we build the redeclaration in the same DC
18573 // as the original, and ignore the current access specifier.
18574 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18575 SearchDC = PrevTagDecl->getDeclContext();
18576 AS = AS_none;
18577 }
18578 }
18579 // If we get here we have (another) forward declaration or we
18580 // have a definition. Just create a new decl.
18581
18582 } else {
18583 // If we get here, this is a definition of a new tag type in a nested
18584 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18585 // new decl/type. We set PrevDecl to NULL so that the entities
18586 // have distinct types.
18587 Previous.clear();
18588 }
18589 // If we get here, we're going to create a new Decl. If PrevDecl
18590 // is non-NULL, it's a definition of the tag declared by
18591 // PrevDecl. If it's NULL, we have a new definition.
18592
18593 // Otherwise, PrevDecl is not a tag, but was found with tag
18594 // lookup. This is only actually possible in C++, where a few
18595 // things like templates still live in the tag namespace.
18596 } else {
18597 // Use a better diagnostic if an elaborated-type-specifier
18598 // found the wrong kind of type on the first
18599 // (non-redeclaration) lookup.
18600 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18601 !Previous.isForRedeclaration()) {
18602 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18603 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18604 << PrevDecl << NTK << Kind;
18605 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18606 Invalid = true;
18607
18608 // Otherwise, only diagnose if the declaration is in scope.
18609 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18610 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18611 // do nothing
18612
18613 // Diagnose implicit declarations introduced by elaborated types.
18614 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18615 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18616 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18617 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18618 Invalid = true;
18619
18620 // Otherwise it's a declaration. Call out a particularly common
18621 // case here.
18622 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18623 unsigned Kind = 0;
18624 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18625 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18626 << Name << Kind << TND->getUnderlyingType();
18627 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18628 Invalid = true;
18629
18630 // Otherwise, diagnose.
18631 } else {
18632 // The tag name clashes with something else in the target scope,
18633 // issue an error and recover by making this tag be anonymous.
18634 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18635 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18636 Name = nullptr;
18637 Invalid = true;
18638 }
18639
18640 // The existing declaration isn't relevant to us; we're in a
18641 // new scope, so clear out the previous declaration.
18642 Previous.clear();
18643 }
18644 }
18645
18646CreateNewDecl:
18647
18648 TagDecl *PrevDecl = nullptr;
18649 if (Previous.isSingleResult())
18650 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18651
18652 // If there is an identifier, use the location of the identifier as the
18653 // location of the decl, otherwise use the location of the struct/union
18654 // keyword.
18655 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18656
18657 // Otherwise, create a new declaration. If there is a previous
18658 // declaration of the same entity, the two will be linked via
18659 // PrevDecl.
18660 TagDecl *New;
18661
18662 if (Kind == TagTypeKind::Enum) {
18663 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18664 // enum X { A, B, C } D; D should chain to X.
18665 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18666 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18667 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18668
18669 EnumDecl *ED = cast<EnumDecl>(Val: New);
18670 ED->setEnumKeyRange(SourceRange(
18671 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18672
18673 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18674 StdAlignValT = cast<EnumDecl>(Val: New);
18675
18676 // If this is an undefined enum, warn.
18677 if (TUK != TagUseKind::Definition && !Invalid) {
18678 TagDecl *Def;
18679 if (IsFixed && ED->isFixed()) {
18680 // C++0x: 7.2p2: opaque-enum-declaration.
18681 // Conflicts are diagnosed above. Do nothing.
18682 } else if (PrevDecl &&
18683 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18684 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18685 << New;
18686 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18687 } else {
18688 unsigned DiagID = diag::ext_forward_ref_enum;
18689 if (getLangOpts().MSVCCompat)
18690 DiagID = diag::ext_ms_forward_ref_enum;
18691 else if (getLangOpts().CPlusPlus)
18692 DiagID = diag::err_forward_ref_enum;
18693 Diag(Loc, DiagID);
18694 }
18695 }
18696
18697 if (EnumUnderlying) {
18698 EnumDecl *ED = cast<EnumDecl>(Val: New);
18699 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18700 ED->setIntegerTypeSourceInfo(TI);
18701 else
18702 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18703 QualType EnumTy = ED->getIntegerType();
18704 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18705 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18706 : EnumTy);
18707 assert(ED->isComplete() && "enum with type should be complete");
18708 }
18709 } else {
18710 // struct/union/class
18711
18712 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18713 // struct X { int A; } D; D should chain to X.
18714 if (getLangOpts().CPlusPlus) {
18715 // FIXME: Look for a way to use RecordDecl for simple structs.
18716 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18717 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18718
18719 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18720 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18721 } else
18722 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18723 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18724 }
18725
18726 // Only C23 and later allow defining new types in 'offsetof()'.
18727 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18728 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18729 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18730 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18731
18732 // C++11 [dcl.type]p3:
18733 // A type-specifier-seq shall not define a class or enumeration [...].
18734 if (!Invalid && getLangOpts().CPlusPlus &&
18735 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18736 TUK == TagUseKind::Definition) {
18737 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18738 << Context.getCanonicalTagType(TD: New);
18739 Invalid = true;
18740 }
18741
18742 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18743 DC->getDeclKind() == Decl::Enum) {
18744 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18745 << Context.getCanonicalTagType(TD: New);
18746 Invalid = true;
18747 }
18748
18749 // Maybe add qualifier info.
18750 if (SS.isNotEmpty()) {
18751 if (SS.isSet()) {
18752 // If this is either a declaration or a definition, check the
18753 // nested-name-specifier against the current context.
18754 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18755 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18756 /*TemplateId=*/nullptr,
18757 IsMemberSpecialization: isMemberSpecialization))
18758 Invalid = true;
18759
18760 New->setQualifierInfo(SS.getWithLocInContext(Context));
18761 if (TemplateParameterLists.size() > 0) {
18762 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18763 }
18764 }
18765 else
18766 Invalid = true;
18767 }
18768
18769 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18770 // Add alignment attributes if necessary; these attributes are checked when
18771 // the ASTContext lays out the structure.
18772 //
18773 // It is important for implementing the correct semantics that this
18774 // happen here (in ActOnTag). The #pragma pack stack is
18775 // maintained as a result of parser callbacks which can occur at
18776 // many points during the parsing of a struct declaration (because
18777 // the #pragma tokens are effectively skipped over during the
18778 // parsing of the struct).
18779 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18780 if (LangOpts.HLSL)
18781 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18782 AddAlignmentAttributesForRecord(RD);
18783 AddMsStructLayoutForRecord(RD);
18784 }
18785 }
18786
18787 if (ModulePrivateLoc.isValid()) {
18788 if (isMemberSpecialization)
18789 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18790 << 2
18791 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18792 // __module_private__ does not apply to local classes. However, we only
18793 // diagnose this as an error when the declaration specifiers are
18794 // freestanding. Here, we just ignore the __module_private__.
18795 else if (!SearchDC->isFunctionOrMethod())
18796 New->setModulePrivate();
18797 }
18798
18799 // If this is a specialization of a member class (of a class template),
18800 // check the specialization.
18801 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18802 Invalid = true;
18803
18804 // If we're declaring or defining a tag in function prototype scope in C,
18805 // note that this type can only be used within the function and add it to
18806 // the list of decls to inject into the function definition scope. However,
18807 // in C23 and later, while the type is only visible within the function, the
18808 // function can be called with a compatible type defined in the same TU, so
18809 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18810 if ((Name || Kind == TagTypeKind::Enum) &&
18811 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18812 if (getLangOpts().CPlusPlus) {
18813 // C++ [dcl.fct]p6:
18814 // Types shall not be defined in return or parameter types.
18815 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18816 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18817 << Name;
18818 Invalid = true;
18819 }
18820 if (TUK == TagUseKind::Declaration)
18821 Invalid = true;
18822 } else if (!PrevDecl) {
18823 // In C23 mode, if the declaration is complete, we do not want to
18824 // diagnose.
18825 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18826 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
18827 << Context.getCanonicalTagType(TD: New);
18828 }
18829 }
18830
18831 if (Invalid)
18832 New->setInvalidDecl();
18833
18834 // Set the lexical context. If the tag has a C++ scope specifier, the
18835 // lexical context will be different from the semantic context.
18836 New->setLexicalDeclContext(CurContext);
18837
18838 // Mark this as a friend decl if applicable.
18839 // In Microsoft mode, a friend declaration also acts as a forward
18840 // declaration so we always pass true to setObjectOfFriendDecl to make
18841 // the tag name visible.
18842 if (TUK == TagUseKind::Friend)
18843 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18844
18845 // Set the access specifier.
18846 if (!Invalid && SearchDC->isRecord())
18847 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18848
18849 if (PrevDecl)
18850 CheckRedeclarationInModule(New, Old: PrevDecl);
18851
18852 if (TUK == TagUseKind::Definition) {
18853 if (!SkipBody || !SkipBody->ShouldSkip) {
18854 New->startDefinition();
18855 } else {
18856 New->setCompleteDefinition();
18857 New->demoteThisDefinitionToDeclaration();
18858 }
18859 }
18860
18861 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18862 AddPragmaAttributes(S, D: New);
18863
18864 // If this has an identifier, add it to the scope stack.
18865 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18866 // We might be replacing an existing declaration in the lookup tables;
18867 // if so, borrow its access specifier.
18868 if (PrevDecl)
18869 New->setAccess(PrevDecl->getAccess());
18870
18871 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18872 DC->makeDeclVisibleInContext(D: New);
18873 if (Name) // can be null along some error paths
18874 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18875 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18876 } else if (Name) {
18877 S = getNonFieldDeclScope(S);
18878 PushOnScopeChains(D: New, S, AddToContext: true);
18879 } else {
18880 CurContext->addDecl(D: New);
18881 }
18882
18883 // If this is the C FILE type, notify the AST context.
18884 if (IdentifierInfo *II = New->getIdentifier())
18885 if (!New->isInvalidDecl() &&
18886 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18887 II->isStr(Str: "FILE"))
18888 Context.setFILEDecl(New);
18889
18890 if (PrevDecl)
18891 mergeDeclAttributes(New, Old: PrevDecl);
18892
18893 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18894 inferGslOwnerPointerAttribute(Record: CXXRD);
18895 inferNullableClassAttribute(CRD: CXXRD);
18896 }
18897
18898 // If there's a #pragma GCC visibility in scope, set the visibility of this
18899 // record.
18900 AddPushedVisibilityAttribute(RD: New);
18901
18902 // If this is not a definition, process API notes for it now.
18903 if (TUK != TagUseKind::Definition)
18904 ProcessAPINotes(D: New);
18905
18906 if (isMemberSpecialization && !New->isInvalidDecl())
18907 CompleteMemberSpecialization(Member: New, Previous);
18908
18909 OwnedDecl = true;
18910 // In C++, don't return an invalid declaration. We can't recover well from
18911 // the cases where we make the type anonymous.
18912 if (Invalid && getLangOpts().CPlusPlus) {
18913 if (New->isBeingDefined())
18914 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18915 RD->completeDefinition();
18916 return true;
18917 } else if (SkipBody && SkipBody->ShouldSkip) {
18918 return SkipBody->Previous;
18919 } else {
18920 return New;
18921 }
18922}
18923
18924void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18925 AdjustDeclIfTemplate(Decl&: TagD);
18926 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18927
18928 // Enter the tag context.
18929 PushDeclContext(S, DC: Tag);
18930
18931 ActOnDocumentableDecl(D: TagD);
18932
18933 // If there's a #pragma GCC visibility in scope, set the visibility of this
18934 // record.
18935 AddPushedVisibilityAttribute(RD: Tag);
18936}
18937
18938bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18939 SkipBodyInfo &SkipBody) {
18940 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
18941 return false;
18942
18943 // Make the previous decl visible.
18944 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18945 CleanupMergedEnum(S, New: SkipBody.New);
18946 return true;
18947}
18948
18949void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18950 SourceLocation FinalLoc,
18951 bool IsFinalSpelledSealed,
18952 bool IsAbstract,
18953 SourceLocation LBraceLoc) {
18954 AdjustDeclIfTemplate(Decl&: TagD);
18955 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18956
18957 FieldCollector->StartClass();
18958
18959 if (!Record->getIdentifier())
18960 return;
18961
18962 if (IsAbstract)
18963 Record->markAbstract();
18964
18965 if (FinalLoc.isValid()) {
18966 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
18967 S: IsFinalSpelledSealed
18968 ? FinalAttr::Keyword_sealed
18969 : FinalAttr::Keyword_final));
18970 }
18971
18972 // C++ [class]p2:
18973 // [...] The class-name is also inserted into the scope of the
18974 // class itself; this is known as the injected-class-name. For
18975 // purposes of access checking, the injected-class-name is treated
18976 // as if it were a public member name.
18977 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18978 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18979 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
18980 InjectedClassName->setImplicit();
18981 InjectedClassName->setAccess(AS_public);
18982 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18983 InjectedClassName->setDescribedClassTemplate(Template);
18984
18985 PushOnScopeChains(D: InjectedClassName, S);
18986 assert(InjectedClassName->isInjectedClassName() &&
18987 "Broken injected-class-name");
18988}
18989
18990void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18991 SourceRange BraceRange) {
18992 AdjustDeclIfTemplate(Decl&: TagD);
18993 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18994 Tag->setBraceRange(BraceRange);
18995
18996 // Make sure we "complete" the definition even it is invalid.
18997 if (Tag->isBeingDefined()) {
18998 assert(Tag->isInvalidDecl() && "We should already have completed it");
18999 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19000 RD->completeDefinition();
19001 }
19002
19003 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19004 FieldCollector->FinishClass();
19005 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19006 auto *Def = RD->getDefinition();
19007 assert(Def && "The record is expected to have a completed definition");
19008 unsigned NumInitMethods = 0;
19009 for (auto *Method : Def->methods()) {
19010 if (!Method->getIdentifier())
19011 continue;
19012 if (Method->getName() == "__init")
19013 NumInitMethods++;
19014 }
19015 if (NumInitMethods > 1 || !Def->hasInitMethod())
19016 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19017 }
19018
19019 // If we're defining a dynamic class in a module interface unit, we always
19020 // need to produce the vtable for it, even if the vtable is not used in the
19021 // current TU.
19022 //
19023 // The case where the current class is not dynamic is handled in
19024 // MarkVTableUsed.
19025 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19026 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19027 }
19028
19029 // Exit this scope of this tag's definition.
19030 PopDeclContext();
19031
19032 if (getCurLexicalContext()->isObjCContainer() &&
19033 Tag->getDeclContext()->isFileContext())
19034 Tag->setTopLevelDeclInObjCContainer();
19035
19036 // Notify the consumer that we've defined a tag.
19037 if (!Tag->isInvalidDecl())
19038 Consumer.HandleTagDeclDefinition(D: Tag);
19039
19040 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19041 // from XLs and instead matches the XL #pragma pack(1) behavior.
19042 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19043 AlignPackStack.hasValue()) {
19044 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19045 // Only diagnose #pragma align(packed).
19046 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19047 return;
19048 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19049 if (!RD)
19050 return;
19051 // Only warn if there is at least 1 bitfield member.
19052 if (llvm::any_of(Range: RD->fields(),
19053 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19054 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19055 }
19056}
19057
19058void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19059 AdjustDeclIfTemplate(Decl&: TagD);
19060 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19061 Tag->setInvalidDecl();
19062
19063 // Make sure we "complete" the definition even it is invalid.
19064 if (Tag->isBeingDefined()) {
19065 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19066 RD->completeDefinition();
19067 }
19068
19069 // We're undoing ActOnTagStartDefinition here, not
19070 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19071 // the FieldCollector.
19072
19073 PopDeclContext();
19074}
19075
19076// Note that FieldName may be null for anonymous bitfields.
19077ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19078 const IdentifierInfo *FieldName,
19079 QualType FieldTy, bool IsMsStruct,
19080 Expr *BitWidth) {
19081 assert(BitWidth);
19082 if (BitWidth->containsErrors())
19083 return ExprError();
19084
19085 // C99 6.7.2.1p4 - verify the field type.
19086 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19087 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19088 // Handle incomplete and sizeless types with a specific error.
19089 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19090 DiagID: diag::err_field_incomplete_or_sizeless))
19091 return ExprError();
19092 if (FieldName)
19093 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19094 << FieldName << FieldTy << BitWidth->getSourceRange();
19095 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19096 << FieldTy << BitWidth->getSourceRange();
19097 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19098 return ExprError();
19099
19100 // If the bit-width is type- or value-dependent, don't try to check
19101 // it now.
19102 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19103 return BitWidth;
19104
19105 llvm::APSInt Value;
19106 ExprResult ICE =
19107 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19108 if (ICE.isInvalid())
19109 return ICE;
19110 BitWidth = ICE.get();
19111
19112 // Zero-width bitfield is ok for anonymous field.
19113 if (Value == 0 && FieldName)
19114 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19115 << FieldName << BitWidth->getSourceRange();
19116
19117 if (Value.isSigned() && Value.isNegative()) {
19118 if (FieldName)
19119 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19120 << FieldName << toString(I: Value, Radix: 10);
19121 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19122 << toString(I: Value, Radix: 10);
19123 }
19124
19125 // The size of the bit-field must not exceed our maximum permitted object
19126 // size.
19127 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19128 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19129 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19130 }
19131
19132 if (!FieldTy->isDependentType()) {
19133 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19134 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19135 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19136
19137 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19138 // ABI.
19139 bool CStdConstraintViolation =
19140 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19141 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19142 if (CStdConstraintViolation || MSBitfieldViolation) {
19143 unsigned DiagWidth =
19144 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19145 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19146 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19147 << !CStdConstraintViolation << DiagWidth;
19148 }
19149
19150 // Warn on types where the user might conceivably expect to get all
19151 // specified bits as value bits: that's all integral types other than
19152 // 'bool'.
19153 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19154 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19155 << FieldName << Value << (unsigned)TypeWidth;
19156 }
19157 }
19158
19159 if (isa<ConstantExpr>(Val: BitWidth))
19160 return BitWidth;
19161 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19162}
19163
19164Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19165 Declarator &D, Expr *BitfieldWidth) {
19166 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19167 D, BitfieldWidth,
19168 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19169 return Res;
19170}
19171
19172FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19173 SourceLocation DeclStart,
19174 Declarator &D, Expr *BitWidth,
19175 InClassInitStyle InitStyle,
19176 AccessSpecifier AS) {
19177 if (D.isDecompositionDeclarator()) {
19178 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19179 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19180 << Decomp.getSourceRange();
19181 return nullptr;
19182 }
19183
19184 const IdentifierInfo *II = D.getIdentifier();
19185 SourceLocation Loc = DeclStart;
19186 if (II) Loc = D.getIdentifierLoc();
19187
19188 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19189 QualType T = TInfo->getType();
19190 if (getLangOpts().CPlusPlus) {
19191 CheckExtraCXXDefaultArguments(D);
19192
19193 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19194 UPPC: UPPC_DataMemberType)) {
19195 D.setInvalidType();
19196 T = Context.IntTy;
19197 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19198 }
19199 }
19200
19201 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19202
19203 if (D.getDeclSpec().isInlineSpecified())
19204 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19205 << getLangOpts().CPlusPlus17;
19206 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19207 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19208 DiagID: diag::err_invalid_thread)
19209 << DeclSpec::getSpecifierName(S: TSCS);
19210
19211 // Check to see if this name was declared as a member previously
19212 NamedDecl *PrevDecl = nullptr;
19213 LookupResult Previous(*this, II, Loc, LookupMemberName,
19214 RedeclarationKind::ForVisibleRedeclaration);
19215 LookupName(R&: Previous, S);
19216 switch (Previous.getResultKind()) {
19217 case LookupResultKind::Found:
19218 case LookupResultKind::FoundUnresolvedValue:
19219 PrevDecl = Previous.getAsSingle<NamedDecl>();
19220 break;
19221
19222 case LookupResultKind::FoundOverloaded:
19223 PrevDecl = Previous.getRepresentativeDecl();
19224 break;
19225
19226 case LookupResultKind::NotFound:
19227 case LookupResultKind::NotFoundInCurrentInstantiation:
19228 case LookupResultKind::Ambiguous:
19229 break;
19230 }
19231 Previous.suppressDiagnostics();
19232
19233 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19234 // Maybe we will complain about the shadowed template parameter.
19235 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19236 // Just pretend that we didn't see the previous declaration.
19237 PrevDecl = nullptr;
19238 }
19239
19240 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19241 PrevDecl = nullptr;
19242
19243 bool Mutable
19244 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19245 SourceLocation TSSL = D.getBeginLoc();
19246 FieldDecl *NewFD
19247 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19248 TSSL, AS, PrevDecl, D: &D);
19249
19250 if (NewFD->isInvalidDecl())
19251 Record->setInvalidDecl();
19252
19253 if (D.getDeclSpec().isModulePrivateSpecified())
19254 NewFD->setModulePrivate();
19255
19256 if (NewFD->isInvalidDecl() && PrevDecl) {
19257 // Don't introduce NewFD into scope; there's already something
19258 // with the same name in the same scope.
19259 } else if (II) {
19260 PushOnScopeChains(D: NewFD, S);
19261 } else
19262 Record->addDecl(D: NewFD);
19263
19264 return NewFD;
19265}
19266
19267FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19268 TypeSourceInfo *TInfo,
19269 RecordDecl *Record, SourceLocation Loc,
19270 bool Mutable, Expr *BitWidth,
19271 InClassInitStyle InitStyle,
19272 SourceLocation TSSL,
19273 AccessSpecifier AS, NamedDecl *PrevDecl,
19274 Declarator *D) {
19275 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19276 bool InvalidDecl = false;
19277 if (D) InvalidDecl = D->isInvalidType();
19278
19279 // If we receive a broken type, recover by assuming 'int' and
19280 // marking this declaration as invalid.
19281 if (T.isNull() || T->containsErrors()) {
19282 InvalidDecl = true;
19283 T = Context.IntTy;
19284 }
19285
19286 QualType EltTy = Context.getBaseElementType(QT: T);
19287 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19288 bool isIncomplete =
19289 LangOpts.HLSL // HLSL allows sizeless builtin types
19290 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19291 : RequireCompleteSizedType(Loc, T: EltTy,
19292 DiagID: diag::err_field_incomplete_or_sizeless);
19293 if (isIncomplete) {
19294 // Fields of incomplete type force their record to be invalid.
19295 Record->setInvalidDecl();
19296 InvalidDecl = true;
19297 } else {
19298 NamedDecl *Def;
19299 EltTy->isIncompleteType(Def: &Def);
19300 if (Def && Def->isInvalidDecl()) {
19301 Record->setInvalidDecl();
19302 InvalidDecl = true;
19303 }
19304 }
19305 }
19306
19307 // TR 18037 does not allow fields to be declared with address space
19308 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19309 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19310 Diag(Loc, DiagID: diag::err_field_with_address_space);
19311 Record->setInvalidDecl();
19312 InvalidDecl = true;
19313 }
19314
19315 if (LangOpts.OpenCL) {
19316 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19317 // used as structure or union field: image, sampler, event or block types.
19318 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19319 T->isBlockPointerType()) {
19320 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19321 Record->setInvalidDecl();
19322 InvalidDecl = true;
19323 }
19324 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19325 // is enabled.
19326 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19327 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19328 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19329 InvalidDecl = true;
19330 }
19331 }
19332
19333 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19334 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19335 T.hasQualifiers()) {
19336 InvalidDecl = true;
19337 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19338 }
19339
19340 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19341 // than a variably modified type.
19342 if (!InvalidDecl && T->isVariablyModifiedType()) {
19343 if (!tryToFixVariablyModifiedVarType(
19344 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19345 InvalidDecl = true;
19346 }
19347
19348 // Fields can not have abstract class types
19349 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19350 DiagID: diag::err_abstract_type_in_decl,
19351 Args: AbstractFieldType))
19352 InvalidDecl = true;
19353
19354 if (InvalidDecl)
19355 BitWidth = nullptr;
19356 // If this is declared as a bit-field, check the bit-field.
19357 if (BitWidth) {
19358 BitWidth =
19359 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19360 if (!BitWidth) {
19361 InvalidDecl = true;
19362 BitWidth = nullptr;
19363 }
19364 }
19365
19366 // Check that 'mutable' is consistent with the type of the declaration.
19367 if (!InvalidDecl && Mutable) {
19368 unsigned DiagID = 0;
19369 if (T->isReferenceType())
19370 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19371 : diag::err_mutable_reference;
19372 else if (T.isConstQualified())
19373 DiagID = diag::err_mutable_const;
19374
19375 if (DiagID) {
19376 SourceLocation ErrLoc = Loc;
19377 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19378 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19379 Diag(Loc: ErrLoc, DiagID);
19380 if (DiagID != diag::ext_mutable_reference) {
19381 Mutable = false;
19382 InvalidDecl = true;
19383 }
19384 }
19385 }
19386
19387 // C++11 [class.union]p8 (DR1460):
19388 // At most one variant member of a union may have a
19389 // brace-or-equal-initializer.
19390 if (InitStyle != ICIS_NoInit)
19391 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19392
19393 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19394 BW: BitWidth, Mutable, InitStyle);
19395 if (InvalidDecl)
19396 NewFD->setInvalidDecl();
19397
19398 if (!InvalidDecl)
19399 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19400
19401 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19402 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19403 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19404 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19405 NewFD->setInvalidDecl();
19406 }
19407
19408 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19409 if (Record->isUnion()) {
19410 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19411 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19412
19413 // C++ [class.union]p1: An object of a class with a non-trivial
19414 // constructor, a non-trivial copy constructor, a non-trivial
19415 // destructor, or a non-trivial copy assignment operator
19416 // cannot be a member of a union, nor can an array of such
19417 // objects.
19418 if (CheckNontrivialField(FD: NewFD))
19419 NewFD->setInvalidDecl();
19420 }
19421
19422 // C++ [class.union]p1: If a union contains a member of reference type,
19423 // the program is ill-formed, except when compiling with MSVC extensions
19424 // enabled.
19425 if (EltTy->isReferenceType()) {
19426 const bool HaveMSExt =
19427 getLangOpts().MicrosoftExt &&
19428 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19429
19430 Diag(Loc: NewFD->getLocation(),
19431 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19432 : diag::err_union_member_of_reference_type)
19433 << NewFD->getDeclName() << EltTy;
19434 if (!HaveMSExt)
19435 NewFD->setInvalidDecl();
19436 }
19437 }
19438 }
19439
19440 // FIXME: We need to pass in the attributes given an AST
19441 // representation, not a parser representation.
19442 if (D) {
19443 // FIXME: The current scope is almost... but not entirely... correct here.
19444 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19445
19446 if (NewFD->hasAttrs())
19447 CheckAlignasUnderalignment(D: NewFD);
19448 }
19449
19450 // In auto-retain/release, infer strong retension for fields of
19451 // retainable type.
19452 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19453 NewFD->setInvalidDecl();
19454
19455 if (T.isObjCGCWeak())
19456 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19457
19458 // PPC MMA non-pointer types are not allowed as field types.
19459 if (Context.getTargetInfo().getTriple().isPPC64() &&
19460 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19461 NewFD->setInvalidDecl();
19462
19463 NewFD->setAccess(AS);
19464 return NewFD;
19465}
19466
19467bool Sema::CheckNontrivialField(FieldDecl *FD) {
19468 assert(FD);
19469 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19470
19471 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19472 return false;
19473
19474 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19475 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19476 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19477 // We check for copy constructors before constructors
19478 // because otherwise we'll never get complaints about
19479 // copy constructors.
19480
19481 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19482 // We're required to check for any non-trivial constructors. Since the
19483 // implicit default constructor is suppressed if there are any
19484 // user-declared constructors, we just need to check that there is a
19485 // trivial default constructor and a trivial copy constructor. (We don't
19486 // worry about move constructors here, since this is a C++98 check.)
19487 if (RDecl->hasNonTrivialCopyConstructor())
19488 member = CXXSpecialMemberKind::CopyConstructor;
19489 else if (!RDecl->hasTrivialDefaultConstructor())
19490 member = CXXSpecialMemberKind::DefaultConstructor;
19491 else if (RDecl->hasNonTrivialCopyAssignment())
19492 member = CXXSpecialMemberKind::CopyAssignment;
19493 else if (RDecl->hasNonTrivialDestructor())
19494 member = CXXSpecialMemberKind::Destructor;
19495
19496 if (member != CXXSpecialMemberKind::Invalid) {
19497 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19498 RDecl->hasObjectMember()) {
19499 // Objective-C++ ARC: it is an error to have a non-trivial field of
19500 // a union. However, system headers in Objective-C programs
19501 // occasionally have Objective-C lifetime objects within unions,
19502 // and rather than cause the program to fail, we make those
19503 // members unavailable.
19504 SourceLocation Loc = FD->getLocation();
19505 if (getSourceManager().isInSystemHeader(Loc)) {
19506 if (!FD->hasAttr<UnavailableAttr>())
19507 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19508 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19509 return false;
19510 }
19511 }
19512
19513 Diag(Loc: FD->getLocation(),
19514 DiagID: getLangOpts().CPlusPlus11
19515 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19516 : diag::err_illegal_union_or_anon_struct_member)
19517 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19518 DiagnoseNontrivial(Record: RDecl, CSM: member);
19519 return !getLangOpts().CPlusPlus11;
19520 }
19521 }
19522
19523 return false;
19524}
19525
19526void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19527 SmallVectorImpl<Decl *> &AllIvarDecls) {
19528 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19529 return;
19530
19531 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19532 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19533
19534 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19535 return;
19536 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19537 if (!ID) {
19538 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19539 if (!CD->IsClassExtension())
19540 return;
19541 }
19542 // No need to add this to end of @implementation.
19543 else
19544 return;
19545 }
19546 // All conditions are met. Add a new bitfield to the tail end of ivars.
19547 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19548 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19549 Expr *BitWidth =
19550 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19551
19552 Ivar = ObjCIvarDecl::Create(
19553 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19554 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19555 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19556 AllIvarDecls.push_back(Elt: Ivar);
19557}
19558
19559/// [class.dtor]p4:
19560/// At the end of the definition of a class, overload resolution is
19561/// performed among the prospective destructors declared in that class with
19562/// an empty argument list to select the destructor for the class, also
19563/// known as the selected destructor.
19564///
19565/// We do the overload resolution here, then mark the selected constructor in the AST.
19566/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19567static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19568 if (!Record->hasUserDeclaredDestructor()) {
19569 return;
19570 }
19571
19572 SourceLocation Loc = Record->getLocation();
19573 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19574
19575 for (auto *Decl : Record->decls()) {
19576 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19577 if (DD->isInvalidDecl())
19578 continue;
19579 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19580 CandidateSet&: OCS);
19581 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19582 }
19583 }
19584
19585 if (OCS.empty()) {
19586 return;
19587 }
19588 OverloadCandidateSet::iterator Best;
19589 unsigned Msg = 0;
19590 OverloadCandidateDisplayKind DisplayKind;
19591
19592 switch (OCS.BestViableFunction(S, Loc, Best)) {
19593 case OR_Success:
19594 case OR_Deleted:
19595 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19596 break;
19597
19598 case OR_Ambiguous:
19599 Msg = diag::err_ambiguous_destructor;
19600 DisplayKind = OCD_AmbiguousCandidates;
19601 break;
19602
19603 case OR_No_Viable_Function:
19604 Msg = diag::err_no_viable_destructor;
19605 DisplayKind = OCD_AllCandidates;
19606 break;
19607 }
19608
19609 if (Msg) {
19610 // OpenCL have got their own thing going with destructors. It's slightly broken,
19611 // but we allow it.
19612 if (!S.LangOpts.OpenCL) {
19613 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19614 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19615 Record->setInvalidDecl();
19616 }
19617 // It's a bit hacky: At this point we've raised an error but we want the
19618 // rest of the compiler to continue somehow working. However almost
19619 // everything we'll try to do with the class will depend on there being a
19620 // destructor. So let's pretend the first one is selected and hope for the
19621 // best.
19622 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19623 }
19624}
19625
19626/// [class.mem.special]p5
19627/// Two special member functions are of the same kind if:
19628/// - they are both default constructors,
19629/// - they are both copy or move constructors with the same first parameter
19630/// type, or
19631/// - they are both copy or move assignment operators with the same first
19632/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19633static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19634 CXXMethodDecl *M1,
19635 CXXMethodDecl *M2,
19636 CXXSpecialMemberKind CSM) {
19637 // We don't want to compare templates to non-templates: See
19638 // https://github.com/llvm/llvm-project/issues/59206
19639 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19640 return bool(M1->getDescribedFunctionTemplate()) ==
19641 bool(M2->getDescribedFunctionTemplate());
19642 // FIXME: better resolve CWG
19643 // https://cplusplus.github.io/CWG/issues/2787.html
19644 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19645 T2: M2->getNonObjectParameter(I: 0)->getType()))
19646 return false;
19647 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19648 T2: M2->getFunctionObjectParameterReferenceType()))
19649 return false;
19650
19651 return true;
19652}
19653
19654/// [class.mem.special]p6:
19655/// An eligible special member function is a special member function for which:
19656/// - the function is not deleted,
19657/// - the associated constraints, if any, are satisfied, and
19658/// - no special member function of the same kind whose associated constraints
19659/// [CWG2595], if any, are satisfied is more constrained.
19660static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19661 ArrayRef<CXXMethodDecl *> Methods,
19662 CXXSpecialMemberKind CSM) {
19663 SmallVector<bool, 4> SatisfactionStatus;
19664
19665 for (CXXMethodDecl *Method : Methods) {
19666 if (!Method->getTrailingRequiresClause())
19667 SatisfactionStatus.push_back(Elt: true);
19668 else {
19669 ConstraintSatisfaction Satisfaction;
19670 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19671 SatisfactionStatus.push_back(Elt: false);
19672 else
19673 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19674 }
19675 }
19676
19677 for (size_t i = 0; i < Methods.size(); i++) {
19678 if (!SatisfactionStatus[i])
19679 continue;
19680 CXXMethodDecl *Method = Methods[i];
19681 CXXMethodDecl *OrigMethod = Method;
19682 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19683 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19684
19685 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19686 bool AnotherMethodIsMoreConstrained = false;
19687 for (size_t j = 0; j < Methods.size(); j++) {
19688 if (i == j || !SatisfactionStatus[j])
19689 continue;
19690 CXXMethodDecl *OtherMethod = Methods[j];
19691 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19692 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19693
19694 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19695 CSM))
19696 continue;
19697
19698 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19699 if (!Other)
19700 continue;
19701 if (!Orig) {
19702 AnotherMethodIsMoreConstrained = true;
19703 break;
19704 }
19705 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19706 Result&: AnotherMethodIsMoreConstrained)) {
19707 // There was an error with the constraints comparison. Exit the loop
19708 // and don't consider this function eligible.
19709 AnotherMethodIsMoreConstrained = true;
19710 }
19711 if (AnotherMethodIsMoreConstrained)
19712 break;
19713 }
19714 // FIXME: Do not consider deleted methods as eligible after implementing
19715 // DR1734 and DR1496.
19716 if (!AnotherMethodIsMoreConstrained) {
19717 Method->setIneligibleOrNotSelected(false);
19718 Record->addedEligibleSpecialMemberFunction(MD: Method,
19719 SMKind: 1 << llvm::to_underlying(E: CSM));
19720 }
19721 }
19722}
19723
19724static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19725 CXXRecordDecl *Record) {
19726 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19727 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19728 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19729 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19730 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19731
19732 for (auto *Decl : Record->decls()) {
19733 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19734 if (!MD) {
19735 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19736 if (FTD)
19737 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19738 }
19739 if (!MD)
19740 continue;
19741 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19742 if (CD->isInvalidDecl())
19743 continue;
19744 if (CD->isDefaultConstructor())
19745 DefaultConstructors.push_back(Elt: MD);
19746 else if (CD->isCopyConstructor())
19747 CopyConstructors.push_back(Elt: MD);
19748 else if (CD->isMoveConstructor())
19749 MoveConstructors.push_back(Elt: MD);
19750 } else if (MD->isCopyAssignmentOperator()) {
19751 CopyAssignmentOperators.push_back(Elt: MD);
19752 } else if (MD->isMoveAssignmentOperator()) {
19753 MoveAssignmentOperators.push_back(Elt: MD);
19754 }
19755 }
19756
19757 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19758 CSM: CXXSpecialMemberKind::DefaultConstructor);
19759 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19760 CSM: CXXSpecialMemberKind::CopyConstructor);
19761 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19762 CSM: CXXSpecialMemberKind::MoveConstructor);
19763 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19764 CSM: CXXSpecialMemberKind::CopyAssignment);
19765 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19766 CSM: CXXSpecialMemberKind::MoveAssignment);
19767}
19768
19769bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19770 // Check to see if a FieldDecl is a pointer to a function.
19771 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19772 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19773 if (!FD) {
19774 // Check whether this is a forward declaration that was inserted by
19775 // Clang. This happens when a non-forward declared / defined type is
19776 // used, e.g.:
19777 //
19778 // struct foo {
19779 // struct bar *(*f)();
19780 // struct bar *(*g)();
19781 // };
19782 //
19783 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19784 // incomplete definition.
19785 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19786 return !TD->isCompleteDefinition();
19787 return false;
19788 }
19789 QualType FieldType = FD->getType().getDesugaredType(Context);
19790 if (isa<PointerType>(Val: FieldType)) {
19791 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19792 return PointeeType.getDesugaredType(Context)->isFunctionType();
19793 }
19794 // If a member is a struct entirely of function pointers, that counts too.
19795 if (const auto *Record = FieldType->getAsRecordDecl();
19796 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19797 return true;
19798 return false;
19799 };
19800
19801 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19802}
19803
19804void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19805 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19806 SourceLocation RBrac,
19807 const ParsedAttributesView &Attrs) {
19808 assert(EnclosingDecl && "missing record or interface decl");
19809
19810 // If this is an Objective-C @implementation or category and we have
19811 // new fields here we should reset the layout of the interface since
19812 // it will now change.
19813 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19814 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19815 switch (DC->getKind()) {
19816 default: break;
19817 case Decl::ObjCCategory:
19818 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19819 break;
19820 case Decl::ObjCImplementation:
19821 Context.
19822 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19823 break;
19824 }
19825 }
19826
19827 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19828 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19829
19830 // Start counting up the number of named members; make sure to include
19831 // members of anonymous structs and unions in the total.
19832 unsigned NumNamedMembers = 0;
19833 if (Record) {
19834 for (const auto *I : Record->decls()) {
19835 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19836 if (IFD->getDeclName())
19837 ++NumNamedMembers;
19838 }
19839 }
19840
19841 // Verify that all the fields are okay.
19842 SmallVector<FieldDecl*, 32> RecFields;
19843 const FieldDecl *PreviousField = nullptr;
19844 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19845 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19846 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19847
19848 // Get the type for the field.
19849 const Type *FDTy = FD->getType().getTypePtr();
19850
19851 if (!FD->isAnonymousStructOrUnion()) {
19852 // Remember all fields written by the user.
19853 RecFields.push_back(Elt: FD);
19854 }
19855
19856 // If the field is already invalid for some reason, don't emit more
19857 // diagnostics about it.
19858 if (FD->isInvalidDecl()) {
19859 EnclosingDecl->setInvalidDecl();
19860 continue;
19861 }
19862
19863 // C99 6.7.2.1p2:
19864 // A structure or union shall not contain a member with
19865 // incomplete or function type (hence, a structure shall not
19866 // contain an instance of itself, but may contain a pointer to
19867 // an instance of itself), except that the last member of a
19868 // structure with more than one named member may have incomplete
19869 // array type; such a structure (and any union containing,
19870 // possibly recursively, a member that is such a structure)
19871 // shall not be a member of a structure or an element of an
19872 // array.
19873 bool IsLastField = (i + 1 == Fields.end());
19874 if (FDTy->isFunctionType()) {
19875 // Field declared as a function.
19876 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19877 << FD->getDeclName();
19878 FD->setInvalidDecl();
19879 EnclosingDecl->setInvalidDecl();
19880 continue;
19881 } else if (FDTy->isIncompleteArrayType() &&
19882 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19883 if (Record) {
19884 // Flexible array member.
19885 // Microsoft and g++ is more permissive regarding flexible array.
19886 // It will accept flexible array in union and also
19887 // as the sole element of a struct/class.
19888 unsigned DiagID = 0;
19889 if (!Record->isUnion() && !IsLastField) {
19890 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
19891 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19892 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
19893 FD->setInvalidDecl();
19894 EnclosingDecl->setInvalidDecl();
19895 continue;
19896 } else if (Record->isUnion())
19897 DiagID = getLangOpts().MicrosoftExt
19898 ? diag::ext_flexible_array_union_ms
19899 : diag::ext_flexible_array_union_gnu;
19900 else if (NumNamedMembers < 1)
19901 DiagID = getLangOpts().MicrosoftExt
19902 ? diag::ext_flexible_array_empty_aggregate_ms
19903 : diag::ext_flexible_array_empty_aggregate_gnu;
19904
19905 if (DiagID)
19906 Diag(Loc: FD->getLocation(), DiagID)
19907 << FD->getDeclName() << Record->getTagKind();
19908 // While the layout of types that contain virtual bases is not specified
19909 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19910 // virtual bases after the derived members. This would make a flexible
19911 // array member declared at the end of an object not adjacent to the end
19912 // of the type.
19913 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19914 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
19915 << FD->getDeclName() << Record->getTagKind();
19916 if (!getLangOpts().C99)
19917 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
19918 << FD->getDeclName() << Record->getTagKind();
19919
19920 // If the element type has a non-trivial destructor, we would not
19921 // implicitly destroy the elements, so disallow it for now.
19922 //
19923 // FIXME: GCC allows this. We should probably either implicitly delete
19924 // the destructor of the containing class, or just allow this.
19925 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
19926 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19927 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
19928 << FD->getDeclName() << FD->getType();
19929 FD->setInvalidDecl();
19930 EnclosingDecl->setInvalidDecl();
19931 continue;
19932 }
19933 // Okay, we have a legal flexible array member at the end of the struct.
19934 Record->setHasFlexibleArrayMember(true);
19935 } else {
19936 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19937 // unless they are followed by another ivar. That check is done
19938 // elsewhere, after synthesized ivars are known.
19939 }
19940 } else if (!FDTy->isDependentType() &&
19941 (LangOpts.HLSL // HLSL allows sizeless builtin types
19942 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
19943 DiagID: diag::err_incomplete_type)
19944 : RequireCompleteSizedType(
19945 Loc: FD->getLocation(), T: FD->getType(),
19946 DiagID: diag::err_field_incomplete_or_sizeless))) {
19947 // Incomplete type
19948 FD->setInvalidDecl();
19949 EnclosingDecl->setInvalidDecl();
19950 continue;
19951 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19952 if (Record && RD->hasFlexibleArrayMember()) {
19953 // A type which contains a flexible array member is considered to be a
19954 // flexible array member.
19955 Record->setHasFlexibleArrayMember(true);
19956 if (!Record->isUnion()) {
19957 // If this is a struct/class and this is not the last element, reject
19958 // it. Note that GCC supports variable sized arrays in the middle of
19959 // structures.
19960 if (!IsLastField)
19961 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
19962 << FD->getDeclName() << FD->getType();
19963 else {
19964 // We support flexible arrays at the end of structs in
19965 // other structs as an extension.
19966 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
19967 << FD->getDeclName();
19968 }
19969 }
19970 }
19971 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
19972 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
19973 DiagID: diag::err_abstract_type_in_decl,
19974 Args: AbstractIvarType)) {
19975 // Ivars can not have abstract class types
19976 FD->setInvalidDecl();
19977 }
19978 if (Record && RD->hasObjectMember())
19979 Record->setHasObjectMember(true);
19980 if (Record && RD->hasVolatileMember())
19981 Record->setHasVolatileMember(true);
19982 } else if (FDTy->isObjCObjectType()) {
19983 /// A field cannot be an Objective-c object
19984 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
19985 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
19986 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19987 FD->setType(T);
19988 } else if (Record && Record->isUnion() &&
19989 FD->getType().hasNonTrivialObjCLifetime() &&
19990 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
19991 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19992 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19993 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
19994 // For backward compatibility, fields of C unions declared in system
19995 // headers that have non-trivial ObjC ownership qualifications are marked
19996 // as unavailable unless the qualifier is explicit and __strong. This can
19997 // break ABI compatibility between programs compiled with ARC and MRR, but
19998 // is a better option than rejecting programs using those unions under
19999 // ARC.
20000 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20001 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20002 Range: FD->getLocation()));
20003 } else if (getLangOpts().ObjC &&
20004 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20005 !Record->hasObjectMember()) {
20006 if (FD->getType()->isObjCObjectPointerType() ||
20007 FD->getType().isObjCGCStrong())
20008 Record->setHasObjectMember(true);
20009 else if (Context.getAsArrayType(T: FD->getType())) {
20010 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20011 if (const auto *RD = BaseType->getAsRecordDecl();
20012 RD && RD->hasObjectMember())
20013 Record->setHasObjectMember(true);
20014 else if (BaseType->isObjCObjectPointerType() ||
20015 BaseType.isObjCGCStrong())
20016 Record->setHasObjectMember(true);
20017 }
20018 }
20019
20020 if (Record && !getLangOpts().CPlusPlus &&
20021 !shouldIgnoreForRecordTriviality(FD)) {
20022 QualType FT = FD->getType();
20023 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20024 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20025 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20026 Record->isUnion())
20027 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20028 }
20029 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20030 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20031 Record->setNonTrivialToPrimitiveCopy(true);
20032 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20033 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20034 }
20035 if (FD->hasAttr<ExplicitInitAttr>())
20036 Record->setHasUninitializedExplicitInitFields(true);
20037 if (FT.isDestructedType()) {
20038 Record->setNonTrivialToPrimitiveDestroy(true);
20039 Record->setParamDestroyedInCallee(true);
20040 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20041 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20042 }
20043
20044 if (const auto *RD = FT->getAsRecordDecl()) {
20045 if (RD->getArgPassingRestrictions() ==
20046 RecordArgPassingKind::CanNeverPassInRegs)
20047 Record->setArgPassingRestrictions(
20048 RecordArgPassingKind::CanNeverPassInRegs);
20049 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20050 Record->setArgPassingRestrictions(
20051 RecordArgPassingKind::CanNeverPassInRegs);
20052 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20053 Q && Q.isAddressDiscriminated()) {
20054 Record->setArgPassingRestrictions(
20055 RecordArgPassingKind::CanNeverPassInRegs);
20056 Record->setNonTrivialToPrimitiveCopy(true);
20057 }
20058 }
20059
20060 if (Record && FD->getType().isVolatileQualified())
20061 Record->setHasVolatileMember(true);
20062 bool ReportMSBitfieldStoragePacking =
20063 Record && PreviousField &&
20064 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20065 Loc: Record->getLocation());
20066 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20067 return FD->isBitField() && !FD->getType()->isDependentType();
20068 };
20069
20070 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20071 IsNonDependentBitField(PreviousField)) {
20072 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20073 CharUnits PreviousFieldStorageSize =
20074 Context.getTypeSizeInChars(T: PreviousField->getType());
20075 if (FDStorageSize != PreviousFieldStorageSize) {
20076 Diag(Loc: FD->getLocation(),
20077 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20078 << FD << FD->getType() << FDStorageSize.getQuantity()
20079 << PreviousFieldStorageSize.getQuantity();
20080 Diag(Loc: PreviousField->getLocation(),
20081 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20082 << PreviousField << PreviousField->getType();
20083 }
20084 }
20085 // Keep track of the number of named members.
20086 if (FD->getIdentifier())
20087 ++NumNamedMembers;
20088 }
20089
20090 // Okay, we successfully defined 'Record'.
20091 if (Record) {
20092 bool Completed = false;
20093 if (S) {
20094 Scope *Parent = S->getParent();
20095 if (Parent && Parent->isTypeAliasScope() &&
20096 Parent->isTemplateParamScope())
20097 Record->setInvalidDecl();
20098 }
20099
20100 if (CXXRecord) {
20101 if (!CXXRecord->isInvalidDecl()) {
20102 // Set access bits correctly on the directly-declared conversions.
20103 for (CXXRecordDecl::conversion_iterator
20104 I = CXXRecord->conversion_begin(),
20105 E = CXXRecord->conversion_end(); I != E; ++I)
20106 I.setAccess((*I)->getAccess());
20107 }
20108
20109 // Add any implicitly-declared members to this class.
20110 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20111
20112 if (!CXXRecord->isDependentType()) {
20113 if (!CXXRecord->isInvalidDecl()) {
20114 // If we have virtual base classes, we may end up finding multiple
20115 // final overriders for a given virtual function. Check for this
20116 // problem now.
20117 if (CXXRecord->getNumVBases()) {
20118 CXXFinalOverriderMap FinalOverriders;
20119 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20120
20121 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20122 MEnd = FinalOverriders.end();
20123 M != MEnd; ++M) {
20124 for (OverridingMethods::iterator SO = M->second.begin(),
20125 SOEnd = M->second.end();
20126 SO != SOEnd; ++SO) {
20127 assert(SO->second.size() > 0 &&
20128 "Virtual function without overriding functions?");
20129 if (SO->second.size() == 1)
20130 continue;
20131
20132 // C++ [class.virtual]p2:
20133 // In a derived class, if a virtual member function of a base
20134 // class subobject has more than one final overrider the
20135 // program is ill-formed.
20136 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20137 << (const NamedDecl *)M->first << Record;
20138 Diag(Loc: M->first->getLocation(),
20139 DiagID: diag::note_overridden_virtual_function);
20140 for (OverridingMethods::overriding_iterator
20141 OM = SO->second.begin(),
20142 OMEnd = SO->second.end();
20143 OM != OMEnd; ++OM)
20144 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20145 << (const NamedDecl *)M->first << OM->Method->getParent();
20146
20147 Record->setInvalidDecl();
20148 }
20149 }
20150 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20151 Completed = true;
20152 }
20153 }
20154 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20155 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20156 }
20157 }
20158
20159 if (!Completed)
20160 Record->completeDefinition();
20161
20162 // Handle attributes before checking the layout.
20163 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20164
20165 // Maybe randomize the record's decls. We automatically randomize a record
20166 // of function pointers, unless it has the "no_randomize_layout" attribute.
20167 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20168 !Record->isRandomized() && !Record->isUnion() &&
20169 (Record->hasAttr<RandomizeLayoutAttr>() ||
20170 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20171 EntirelyFunctionPointers(Record)))) {
20172 SmallVector<Decl *, 32> NewDeclOrdering;
20173 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20174 FinalOrdering&: NewDeclOrdering))
20175 Record->reorderDecls(Decls: NewDeclOrdering);
20176 }
20177
20178 // We may have deferred checking for a deleted destructor. Check now.
20179 if (CXXRecord) {
20180 auto *Dtor = CXXRecord->getDestructor();
20181 if (Dtor && Dtor->isImplicit() &&
20182 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20183 CXXRecord->setImplicitDestructorIsDeleted();
20184 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20185 }
20186 }
20187
20188 if (Record->hasAttrs()) {
20189 CheckAlignasUnderalignment(D: Record);
20190
20191 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20192 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20193 Range: IA->getRange(), BestCase: IA->getBestCase(),
20194 SemanticSpelling: IA->getInheritanceModel());
20195 }
20196
20197 // Check if the structure/union declaration is a type that can have zero
20198 // size in C. For C this is a language extension, for C++ it may cause
20199 // compatibility problems.
20200 bool CheckForZeroSize;
20201 if (!getLangOpts().CPlusPlus) {
20202 CheckForZeroSize = true;
20203 } else {
20204 // For C++ filter out types that cannot be referenced in C code.
20205 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20206 CheckForZeroSize =
20207 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20208 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20209 CXXRecord->isCLike();
20210 }
20211 if (CheckForZeroSize) {
20212 bool ZeroSize = true;
20213 bool IsEmpty = true;
20214 unsigned NonBitFields = 0;
20215 for (RecordDecl::field_iterator I = Record->field_begin(),
20216 E = Record->field_end();
20217 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20218 IsEmpty = false;
20219 if (I->isUnnamedBitField()) {
20220 if (!I->isZeroLengthBitField())
20221 ZeroSize = false;
20222 } else {
20223 ++NonBitFields;
20224 QualType FieldType = I->getType();
20225 if (FieldType->isIncompleteType() ||
20226 !Context.getTypeSizeInChars(T: FieldType).isZero())
20227 ZeroSize = false;
20228 }
20229 }
20230
20231 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20232 // allowed in C++, but warn if its declaration is inside
20233 // extern "C" block.
20234 if (ZeroSize) {
20235 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20236 diag::warn_zero_size_struct_union_in_extern_c :
20237 diag::warn_zero_size_struct_union_compat)
20238 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20239 }
20240
20241 // Structs without named members are extension in C (C99 6.7.2.1p7),
20242 // but are accepted by GCC. In C2y, this became implementation-defined
20243 // (C2y 6.7.3.2p10).
20244 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20245 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20246 : diag::ext_no_named_members_in_struct_union)
20247 << Record->isUnion();
20248 }
20249 }
20250 } else {
20251 ObjCIvarDecl **ClsFields =
20252 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20253 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20254 ID->setEndOfDefinitionLoc(RBrac);
20255 // Add ivar's to class's DeclContext.
20256 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20257 ClsFields[i]->setLexicalDeclContext(ID);
20258 ID->addDecl(D: ClsFields[i]);
20259 }
20260 // Must enforce the rule that ivars in the base classes may not be
20261 // duplicates.
20262 if (ID->getSuperClass())
20263 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20264 } else if (ObjCImplementationDecl *IMPDecl =
20265 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20266 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20267 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20268 // Ivar declared in @implementation never belongs to the implementation.
20269 // Only it is in implementation's lexical context.
20270 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20271 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20272 Loc: RBrac);
20273 IMPDecl->setIvarLBraceLoc(LBrac);
20274 IMPDecl->setIvarRBraceLoc(RBrac);
20275 } else if (ObjCCategoryDecl *CDecl =
20276 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20277 // case of ivars in class extension; all other cases have been
20278 // reported as errors elsewhere.
20279 // FIXME. Class extension does not have a LocEnd field.
20280 // CDecl->setLocEnd(RBrac);
20281 // Add ivar's to class extension's DeclContext.
20282 // Diagnose redeclaration of private ivars.
20283 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20284 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20285 if (IDecl) {
20286 if (const ObjCIvarDecl *ClsIvar =
20287 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20288 Diag(Loc: ClsFields[i]->getLocation(),
20289 DiagID: diag::err_duplicate_ivar_declaration);
20290 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20291 continue;
20292 }
20293 for (const auto *Ext : IDecl->known_extensions()) {
20294 if (const ObjCIvarDecl *ClsExtIvar
20295 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20296 Diag(Loc: ClsFields[i]->getLocation(),
20297 DiagID: diag::err_duplicate_ivar_declaration);
20298 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20299 continue;
20300 }
20301 }
20302 }
20303 ClsFields[i]->setLexicalDeclContext(CDecl);
20304 CDecl->addDecl(D: ClsFields[i]);
20305 }
20306 CDecl->setIvarLBraceLoc(LBrac);
20307 CDecl->setIvarRBraceLoc(RBrac);
20308 }
20309 }
20310 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20311 ProcessAPINotes(D: Record);
20312}
20313
20314// Given an integral type, return the next larger integral type
20315// (or a NULL type of no such type exists).
20316static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20317 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20318 // enum checking below.
20319 assert((T->isIntegralType(Context) ||
20320 T->isEnumeralType()) && "Integral type required!");
20321 const unsigned NumTypes = 4;
20322 QualType SignedIntegralTypes[NumTypes] = {
20323 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20324 };
20325 QualType UnsignedIntegralTypes[NumTypes] = {
20326 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20327 Context.UnsignedLongLongTy
20328 };
20329
20330 unsigned BitWidth = Context.getTypeSize(T);
20331 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20332 : UnsignedIntegralTypes;
20333 for (unsigned I = 0; I != NumTypes; ++I)
20334 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20335 return Types[I];
20336
20337 return QualType();
20338}
20339
20340EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20341 EnumConstantDecl *LastEnumConst,
20342 SourceLocation IdLoc,
20343 IdentifierInfo *Id,
20344 Expr *Val) {
20345 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20346 llvm::APSInt EnumVal(IntWidth);
20347 QualType EltTy;
20348
20349 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20350 Val = nullptr;
20351
20352 if (Val)
20353 Val = DefaultLvalueConversion(E: Val).get();
20354
20355 if (Val) {
20356 if (Enum->isDependentType() || Val->isTypeDependent() ||
20357 Val->containsErrors())
20358 EltTy = Context.DependentTy;
20359 else {
20360 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20361 // underlying type, but do allow it in all other contexts.
20362 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20363 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20364 // constant-expression in the enumerator-definition shall be a converted
20365 // constant expression of the underlying type.
20366 EltTy = Enum->getIntegerType();
20367 ExprResult Converted = CheckConvertedConstantExpression(
20368 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20369 if (Converted.isInvalid())
20370 Val = nullptr;
20371 else
20372 Val = Converted.get();
20373 } else if (!Val->isValueDependent() &&
20374 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20375 CanFold: AllowFoldKind::Allow)
20376 .get())) {
20377 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20378 } else {
20379 if (Enum->isComplete()) {
20380 EltTy = Enum->getIntegerType();
20381
20382 // In Obj-C and Microsoft mode, require the enumeration value to be
20383 // representable in the underlying type of the enumeration. In C++11,
20384 // we perform a non-narrowing conversion as part of converted constant
20385 // expression checking.
20386 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20387 if (Context.getTargetInfo()
20388 .getTriple()
20389 .isWindowsMSVCEnvironment()) {
20390 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20391 } else {
20392 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20393 }
20394 }
20395
20396 // Cast to the underlying type.
20397 Val = ImpCastExprToType(E: Val, Type: EltTy,
20398 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20399 : CK_IntegralCast)
20400 .get();
20401 } else if (getLangOpts().CPlusPlus) {
20402 // C++11 [dcl.enum]p5:
20403 // If the underlying type is not fixed, the type of each enumerator
20404 // is the type of its initializing value:
20405 // - If an initializer is specified for an enumerator, the
20406 // initializing value has the same type as the expression.
20407 EltTy = Val->getType();
20408 } else {
20409 // C99 6.7.2.2p2:
20410 // The expression that defines the value of an enumeration constant
20411 // shall be an integer constant expression that has a value
20412 // representable as an int.
20413
20414 // Complain if the value is not representable in an int.
20415 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20416 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20417 ? diag::warn_c17_compat_enum_value_not_int
20418 : diag::ext_c23_enum_value_not_int)
20419 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20420 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20421 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20422 // Force the type of the expression to 'int'.
20423 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20424 }
20425 EltTy = Val->getType();
20426 }
20427 }
20428 }
20429 }
20430
20431 if (!Val) {
20432 if (Enum->isDependentType())
20433 EltTy = Context.DependentTy;
20434 else if (!LastEnumConst) {
20435 // C++0x [dcl.enum]p5:
20436 // If the underlying type is not fixed, the type of each enumerator
20437 // is the type of its initializing value:
20438 // - If no initializer is specified for the first enumerator, the
20439 // initializing value has an unspecified integral type.
20440 //
20441 // GCC uses 'int' for its unspecified integral type, as does
20442 // C99 6.7.2.2p3.
20443 if (Enum->isFixed()) {
20444 EltTy = Enum->getIntegerType();
20445 }
20446 else {
20447 EltTy = Context.IntTy;
20448 }
20449 } else {
20450 // Assign the last value + 1.
20451 EnumVal = LastEnumConst->getInitVal();
20452 ++EnumVal;
20453 EltTy = LastEnumConst->getType();
20454
20455 // Check for overflow on increment.
20456 if (EnumVal < LastEnumConst->getInitVal()) {
20457 // C++0x [dcl.enum]p5:
20458 // If the underlying type is not fixed, the type of each enumerator
20459 // is the type of its initializing value:
20460 //
20461 // - Otherwise the type of the initializing value is the same as
20462 // the type of the initializing value of the preceding enumerator
20463 // unless the incremented value is not representable in that type,
20464 // in which case the type is an unspecified integral type
20465 // sufficient to contain the incremented value. If no such type
20466 // exists, the program is ill-formed.
20467 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20468 if (T.isNull() || Enum->isFixed()) {
20469 // There is no integral type larger enough to represent this
20470 // value. Complain, then allow the value to wrap around.
20471 EnumVal = LastEnumConst->getInitVal();
20472 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20473 ++EnumVal;
20474 if (Enum->isFixed())
20475 // When the underlying type is fixed, this is ill-formed.
20476 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20477 << toString(I: EnumVal, Radix: 10)
20478 << EltTy;
20479 else
20480 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20481 << toString(I: EnumVal, Radix: 10);
20482 } else {
20483 EltTy = T;
20484 }
20485
20486 // Retrieve the last enumerator's value, extent that type to the
20487 // type that is supposed to be large enough to represent the incremented
20488 // value, then increment.
20489 EnumVal = LastEnumConst->getInitVal();
20490 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20491 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20492 ++EnumVal;
20493
20494 // If we're not in C++, diagnose the overflow of enumerator values,
20495 // which in C99 means that the enumerator value is not representable in
20496 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20497 // are representable in some larger integral type and we allow it in
20498 // older language modes as an extension.
20499 // Exclude fixed enumerators since they are diagnosed with an error for
20500 // this case.
20501 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20502 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20503 ? diag::warn_c17_compat_enum_value_not_int
20504 : diag::ext_c23_enum_value_not_int)
20505 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20506 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20507 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20508 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20509 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20510 : diag::ext_c23_enum_value_not_int)
20511 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20512 }
20513 }
20514 }
20515
20516 if (!EltTy->isDependentType()) {
20517 // Make the enumerator value match the signedness and size of the
20518 // enumerator's type.
20519 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20520 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20521 }
20522
20523 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20524 E: Val, V: EnumVal);
20525}
20526
20527SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20528 SourceLocation IILoc) {
20529 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20530 !getLangOpts().CPlusPlus)
20531 return SkipBodyInfo();
20532
20533 // We have an anonymous enum definition. Look up the first enumerator to
20534 // determine if we should merge the definition with an existing one and
20535 // skip the body.
20536 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20537 Redecl: forRedeclarationInCurContext());
20538 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20539 if (!PrevECD)
20540 return SkipBodyInfo();
20541
20542 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20543 NamedDecl *Hidden;
20544 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20545 SkipBodyInfo Skip;
20546 Skip.Previous = Hidden;
20547 return Skip;
20548 }
20549
20550 return SkipBodyInfo();
20551}
20552
20553Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20554 SourceLocation IdLoc, IdentifierInfo *Id,
20555 const ParsedAttributesView &Attrs,
20556 SourceLocation EqualLoc, Expr *Val,
20557 SkipBodyInfo *SkipBody) {
20558 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20559 EnumConstantDecl *LastEnumConst =
20560 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20561
20562 // The scope passed in may not be a decl scope. Zip up the scope tree until
20563 // we find one that is.
20564 S = getNonFieldDeclScope(S);
20565
20566 // Verify that there isn't already something declared with this name in this
20567 // scope.
20568 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20569 RedeclarationKind::ForVisibleRedeclaration);
20570 LookupName(R, S);
20571 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20572
20573 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20574 // Maybe we will complain about the shadowed template parameter.
20575 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20576 // Just pretend that we didn't see the previous declaration.
20577 PrevDecl = nullptr;
20578 }
20579
20580 // C++ [class.mem]p15:
20581 // If T is the name of a class, then each of the following shall have a name
20582 // different from T:
20583 // - every enumerator of every member of class T that is an unscoped
20584 // enumerated type
20585 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20586 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20587 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20588 return nullptr;
20589
20590 EnumConstantDecl *New =
20591 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20592 if (!New)
20593 return nullptr;
20594
20595 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20596 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20597 // Check for other kinds of shadowing not already handled.
20598 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20599 }
20600
20601 // When in C++, we may get a TagDecl with the same name; in this case the
20602 // enum constant will 'hide' the tag.
20603 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20604 "Received TagDecl when not in C++!");
20605 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20606 if (isa<EnumConstantDecl>(Val: PrevDecl))
20607 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20608 else
20609 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20610 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20611 return nullptr;
20612 }
20613 }
20614
20615 // Process attributes.
20616 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20617 AddPragmaAttributes(S, D: New);
20618 ProcessAPINotes(D: New);
20619
20620 // Register this decl in the current scope stack.
20621 New->setAccess(TheEnumDecl->getAccess());
20622 PushOnScopeChains(D: New, S);
20623
20624 ActOnDocumentableDecl(D: New);
20625
20626 return New;
20627}
20628
20629// Returns true when the enum initial expression does not trigger the
20630// duplicate enum warning. A few common cases are exempted as follows:
20631// Element2 = Element1
20632// Element2 = Element1 + 1
20633// Element2 = Element1 - 1
20634// Where Element2 and Element1 are from the same enum.
20635static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20636 Expr *InitExpr = ECD->getInitExpr();
20637 if (!InitExpr)
20638 return true;
20639 InitExpr = InitExpr->IgnoreImpCasts();
20640
20641 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20642 if (!BO->isAdditiveOp())
20643 return true;
20644 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20645 if (!IL)
20646 return true;
20647 if (IL->getValue() != 1)
20648 return true;
20649
20650 InitExpr = BO->getLHS();
20651 }
20652
20653 // This checks if the elements are from the same enum.
20654 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20655 if (!DRE)
20656 return true;
20657
20658 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20659 if (!EnumConstant)
20660 return true;
20661
20662 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20663 Enum)
20664 return true;
20665
20666 return false;
20667}
20668
20669// Emits a warning when an element is implicitly set a value that
20670// a previous element has already been set to.
20671static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20672 EnumDecl *Enum, QualType EnumType) {
20673 // Avoid anonymous enums
20674 if (!Enum->getIdentifier())
20675 return;
20676
20677 // Only check for small enums.
20678 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20679 return;
20680
20681 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20682 return;
20683
20684 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20685 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20686
20687 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20688
20689 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20690 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20691
20692 // Use int64_t as a key to avoid needing special handling for map keys.
20693 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20694 llvm::APSInt Val = D->getInitVal();
20695 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20696 };
20697
20698 DuplicatesVector DupVector;
20699 ValueToVectorMap EnumMap;
20700
20701 // Populate the EnumMap with all values represented by enum constants without
20702 // an initializer.
20703 for (auto *Element : Elements) {
20704 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20705
20706 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20707 // this constant. Skip this enum since it may be ill-formed.
20708 if (!ECD) {
20709 return;
20710 }
20711
20712 // Constants with initializers are handled in the next loop.
20713 if (ECD->getInitExpr())
20714 continue;
20715
20716 // Duplicate values are handled in the next loop.
20717 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20718 }
20719
20720 if (EnumMap.size() == 0)
20721 return;
20722
20723 // Create vectors for any values that has duplicates.
20724 for (auto *Element : Elements) {
20725 // The last loop returned if any constant was null.
20726 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20727 if (!ValidDuplicateEnum(ECD, Enum))
20728 continue;
20729
20730 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20731 if (Iter == EnumMap.end())
20732 continue;
20733
20734 DeclOrVector& Entry = Iter->second;
20735 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20736 // Ensure constants are different.
20737 if (D == ECD)
20738 continue;
20739
20740 // Create new vector and push values onto it.
20741 auto Vec = std::make_unique<ECDVector>();
20742 Vec->push_back(Elt: D);
20743 Vec->push_back(Elt: ECD);
20744
20745 // Update entry to point to the duplicates vector.
20746 Entry = Vec.get();
20747
20748 // Store the vector somewhere we can consult later for quick emission of
20749 // diagnostics.
20750 DupVector.emplace_back(Args: std::move(Vec));
20751 continue;
20752 }
20753
20754 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20755 // Make sure constants are not added more than once.
20756 if (*Vec->begin() == ECD)
20757 continue;
20758
20759 Vec->push_back(Elt: ECD);
20760 }
20761
20762 // Emit diagnostics.
20763 for (const auto &Vec : DupVector) {
20764 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20765
20766 // Emit warning for one enum constant.
20767 auto *FirstECD = Vec->front();
20768 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20769 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20770 << FirstECD->getSourceRange();
20771
20772 // Emit one note for each of the remaining enum constants with
20773 // the same value.
20774 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20775 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20776 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20777 << ECD->getSourceRange();
20778 }
20779}
20780
20781bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20782 bool AllowMask) const {
20783 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20784 assert(ED->isCompleteDefinition() && "expected enum definition");
20785
20786 auto R = FlagBitsCache.try_emplace(Key: ED);
20787 llvm::APInt &FlagBits = R.first->second;
20788
20789 if (R.second) {
20790 for (auto *E : ED->enumerators()) {
20791 const auto &EVal = E->getInitVal();
20792 // Only single-bit enumerators introduce new flag values.
20793 if (EVal.isPowerOf2())
20794 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20795 }
20796 }
20797
20798 // A value is in a flag enum if either its bits are a subset of the enum's
20799 // flag bits (the first condition) or we are allowing masks and the same is
20800 // true of its complement (the second condition). When masks are allowed, we
20801 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20802 //
20803 // While it's true that any value could be used as a mask, the assumption is
20804 // that a mask will have all of the insignificant bits set. Anything else is
20805 // likely a logic error.
20806 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20807 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20808}
20809
20810// Emits a warning when a suspicious comparison operator is used along side
20811// binary operators in enum initializers.
20812static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20813 const EnumDecl *Enum) {
20814 bool HasBitwiseOp = false;
20815 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20816
20817 // Iterate over all the enum values, gather suspisious comparison ops and
20818 // whether any enum initialisers contain a binary operator.
20819 for (const auto *ECD : Enum->enumerators()) {
20820 const Expr *InitExpr = ECD->getInitExpr();
20821 if (!InitExpr)
20822 continue;
20823
20824 const Expr *E = InitExpr->IgnoreParenImpCasts();
20825
20826 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
20827 BinaryOperatorKind Op = BinOp->getOpcode();
20828
20829 // Check for bitwise ops (<<, >>, &, |)
20830 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20831 HasBitwiseOp = true;
20832 } else if (Op == BO_LT || Op == BO_GT) {
20833 // Check for the typo pattern (Comparison < or >)
20834 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20835 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
20836 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20837 if (IntLiteral->getValue() == 1)
20838 SuspiciousCompares.push_back(Elt: BinOp);
20839 }
20840 }
20841 }
20842 }
20843
20844 // If we found a bitwise op and some sus compares, iterate over the compares
20845 // and warn.
20846 if (HasBitwiseOp) {
20847 for (const auto *BinOp : SuspiciousCompares) {
20848 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20849 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
20850 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
20851 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20852
20853 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
20854 << BinOp->getOpcodeStr() << SuggestedOp;
20855
20856 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
20857 << SuggestedOp
20858 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
20859 }
20860 }
20861}
20862
20863void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20864 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20865 const ParsedAttributesView &Attrs) {
20866 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20867 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
20868
20869 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20870 ProcessAPINotes(D: Enum);
20871
20872 if (Enum->isDependentType()) {
20873 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20874 EnumConstantDecl *ECD =
20875 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20876 if (!ECD) continue;
20877
20878 ECD->setType(EnumType);
20879 }
20880
20881 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20882 return;
20883 }
20884
20885 // Verify that all the values are okay, compute the size of the values, and
20886 // reverse the list.
20887 unsigned NumNegativeBits = 0;
20888 unsigned NumPositiveBits = 0;
20889 bool MembersRepresentableByInt =
20890 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20891
20892 // Figure out the type that should be used for this enum.
20893 QualType BestType;
20894 unsigned BestWidth;
20895
20896 // C++0x N3000 [conv.prom]p3:
20897 // An rvalue of an unscoped enumeration type whose underlying
20898 // type is not fixed can be converted to an rvalue of the first
20899 // of the following types that can represent all the values of
20900 // the enumeration: int, unsigned int, long int, unsigned long
20901 // int, long long int, or unsigned long long int.
20902 // C99 6.4.4.3p2:
20903 // An identifier declared as an enumeration constant has type int.
20904 // The C99 rule is modified by C23.
20905 QualType BestPromotionType;
20906
20907 bool Packed = Enum->hasAttr<PackedAttr>();
20908 // -fshort-enums is the equivalent to specifying the packed attribute on all
20909 // enum definitions.
20910 if (LangOpts.ShortEnums)
20911 Packed = true;
20912
20913 // If the enum already has a type because it is fixed or dictated by the
20914 // target, promote that type instead of analyzing the enumerators.
20915 if (Enum->isComplete()) {
20916 BestType = Enum->getIntegerType();
20917 if (Context.isPromotableIntegerType(T: BestType))
20918 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20919 else
20920 BestPromotionType = BestType;
20921
20922 BestWidth = Context.getIntWidth(T: BestType);
20923 } else {
20924 bool EnumTooLarge = Context.computeBestEnumTypes(
20925 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20926 BestWidth = Context.getIntWidth(T: BestType);
20927 if (EnumTooLarge)
20928 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
20929 }
20930
20931 // Loop over all of the enumerator constants, changing their types to match
20932 // the type of the enum if needed.
20933 for (auto *D : Elements) {
20934 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20935 if (!ECD) continue; // Already issued a diagnostic.
20936
20937 // C99 says the enumerators have int type, but we allow, as an
20938 // extension, the enumerators to be larger than int size. If each
20939 // enumerator value fits in an int, type it as an int, otherwise type it the
20940 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20941 // that X has type 'int', not 'unsigned'.
20942
20943 // Determine whether the value fits into an int.
20944 llvm::APSInt InitVal = ECD->getInitVal();
20945
20946 // If it fits into an integer type, force it. Otherwise force it to match
20947 // the enum decl type.
20948 QualType NewTy;
20949 unsigned NewWidth;
20950 bool NewSign;
20951 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20952 MembersRepresentableByInt) {
20953 // C23 6.7.3.3.3p15:
20954 // The enumeration member type for an enumerated type without fixed
20955 // underlying type upon completion is:
20956 // - int if all the values of the enumeration are representable as an
20957 // int; or,
20958 // - the enumerated type
20959 NewTy = Context.IntTy;
20960 NewWidth = Context.getTargetInfo().getIntWidth();
20961 NewSign = true;
20962 } else if (ECD->getType() == BestType) {
20963 // Already the right type!
20964 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
20965 // C++ [dcl.enum]p4: Following the closing brace of an
20966 // enum-specifier, each enumerator has the type of its
20967 // enumeration.
20968 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20969 // with fixed underlying type is the enumerated type.
20970 ECD->setType(EnumType);
20971 continue;
20972 } else {
20973 NewTy = BestType;
20974 NewWidth = BestWidth;
20975 NewSign = BestType->isSignedIntegerOrEnumerationType();
20976 }
20977
20978 // Adjust the APSInt value.
20979 InitVal = InitVal.extOrTrunc(width: NewWidth);
20980 InitVal.setIsSigned(NewSign);
20981 ECD->setInitVal(C: Context, V: InitVal);
20982
20983 // Adjust the Expr initializer and type.
20984 if (ECD->getInitExpr() &&
20985 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20986 ECD->setInitExpr(ImplicitCastExpr::Create(
20987 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20988 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20989 if (getLangOpts().CPlusPlus ||
20990 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
20991 // C++ [dcl.enum]p4: Following the closing brace of an
20992 // enum-specifier, each enumerator has the type of its
20993 // enumeration.
20994 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20995 // with fixed underlying type is the enumerated type.
20996 ECD->setType(EnumType);
20997 else
20998 ECD->setType(NewTy);
20999 }
21000
21001 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21002 NumPositiveBits, NumNegativeBits);
21003
21004 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21005 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21006
21007 if (Enum->isClosedFlag()) {
21008 for (Decl *D : Elements) {
21009 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21010 if (!ECD) continue; // Already issued a diagnostic.
21011
21012 llvm::APSInt InitVal = ECD->getInitVal();
21013 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21014 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21015 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21016 << ECD << Enum;
21017 }
21018 }
21019
21020 // Now that the enum type is defined, ensure it's not been underaligned.
21021 if (Enum->hasAttrs())
21022 CheckAlignasUnderalignment(D: Enum);
21023}
21024
21025Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21026 SourceLocation EndLoc) {
21027
21028 FileScopeAsmDecl *New =
21029 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21030 CurContext->addDecl(D: New);
21031 return New;
21032}
21033
21034TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21035 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21036 CurContext->addDecl(D: New);
21037 PushDeclContext(S, DC: New);
21038 PushFunctionScope();
21039 PushCompoundScope(IsStmtExpr: false);
21040 return New;
21041}
21042
21043void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21044 if (Statement)
21045 D->setStmt(Statement);
21046 PopCompoundScope();
21047 PopFunctionScopeInfo();
21048 PopDeclContext();
21049}
21050
21051void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21052 IdentifierInfo* AliasName,
21053 SourceLocation PragmaLoc,
21054 SourceLocation NameLoc,
21055 SourceLocation AliasNameLoc) {
21056 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21057 NameKind: LookupOrdinaryName);
21058 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21059 AttributeCommonInfo::Form::Pragma());
21060 AsmLabelAttr *Attr =
21061 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21062
21063 // If a declaration that:
21064 // 1) declares a function or a variable
21065 // 2) has external linkage
21066 // already exists, add a label attribute to it.
21067 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21068 if (isDeclExternC(D: PrevDecl))
21069 PrevDecl->addAttr(A: Attr);
21070 else
21071 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21072 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21073 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21074 } else
21075 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21076}
21077
21078void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21079 SourceLocation PragmaLoc,
21080 SourceLocation NameLoc) {
21081 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21082
21083 if (PrevDecl) {
21084 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21085 } else {
21086 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21087 }
21088}
21089
21090void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21091 IdentifierInfo* AliasName,
21092 SourceLocation PragmaLoc,
21093 SourceLocation NameLoc,
21094 SourceLocation AliasNameLoc) {
21095 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21096 NameKind: LookupOrdinaryName);
21097 WeakInfo W = WeakInfo(Name, NameLoc);
21098
21099 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21100 if (!PrevDecl->hasAttr<AliasAttr>())
21101 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21102 DeclApplyPragmaWeak(S: TUScope, ND, W);
21103 } else {
21104 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21105 }
21106}
21107
21108Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21109 bool Final) {
21110 assert(FD && "Expected non-null FunctionDecl");
21111
21112 // Templates are emitted when they're instantiated.
21113 if (FD->isDependentContext())
21114 return FunctionEmissionStatus::TemplateDiscarded;
21115
21116 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21117 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21118 FD->hasAttr<SYCLExternalAttr>()))
21119 return FunctionEmissionStatus::Emitted;
21120
21121 // Check whether this function is an externally visible definition.
21122 auto IsEmittedForExternalSymbol = [this, FD]() {
21123 // We have to check the GVA linkage of the function's *definition* -- if we
21124 // only have a declaration, we don't know whether or not the function will
21125 // be emitted, because (say) the definition could include "inline".
21126 const FunctionDecl *Def = FD->getDefinition();
21127
21128 // We can't compute linkage when we skip function bodies.
21129 return Def && !Def->hasSkippedBody() &&
21130 !isDiscardableGVALinkage(
21131 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21132 };
21133
21134 if (LangOpts.OpenMPIsTargetDevice) {
21135 // In OpenMP device mode we will not emit host only functions, or functions
21136 // we don't need due to their linkage.
21137 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21138 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21139 // DevTy may be changed later by
21140 // #pragma omp declare target to(*) device_type(*).
21141 // Therefore DevTy having no value does not imply host. The emission status
21142 // will be checked again at the end of compilation unit with Final = true.
21143 if (DevTy)
21144 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21145 return FunctionEmissionStatus::OMPDiscarded;
21146 // If we have an explicit value for the device type, or we are in a target
21147 // declare context, we need to emit all extern and used symbols.
21148 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21149 if (IsEmittedForExternalSymbol())
21150 return FunctionEmissionStatus::Emitted;
21151 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21152 // we'll omit it.
21153 if (Final)
21154 return FunctionEmissionStatus::OMPDiscarded;
21155 } else if (LangOpts.OpenMP > 45) {
21156 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21157 // function. In 5.0, no_host was introduced which might cause a function to
21158 // be omitted.
21159 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21160 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21161 if (DevTy)
21162 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21163 return FunctionEmissionStatus::OMPDiscarded;
21164 }
21165
21166 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21167 return FunctionEmissionStatus::Emitted;
21168
21169 if (LangOpts.CUDA) {
21170 // When compiling for device, host functions are never emitted. Similarly,
21171 // when compiling for host, device and global functions are never emitted.
21172 // (Technically, we do emit a host-side stub for global functions, but this
21173 // doesn't count for our purposes here.)
21174 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21175 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21176 return FunctionEmissionStatus::CUDADiscarded;
21177 if (!LangOpts.CUDAIsDevice &&
21178 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21179 return FunctionEmissionStatus::CUDADiscarded;
21180
21181 if (IsEmittedForExternalSymbol())
21182 return FunctionEmissionStatus::Emitted;
21183
21184 // If FD is a virtual destructor of an explicit instantiation
21185 // of a template class, return Emitted.
21186 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
21187 if (Destructor->isVirtual()) {
21188 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21189 Val: Destructor->getParent())) {
21190 TemplateSpecializationKind TSK =
21191 Spec->getTemplateSpecializationKind();
21192 if (TSK == TSK_ExplicitInstantiationDeclaration ||
21193 TSK == TSK_ExplicitInstantiationDefinition)
21194 return FunctionEmissionStatus::Emitted;
21195 }
21196 }
21197 }
21198 }
21199
21200 // Otherwise, the function is known-emitted if it's in our set of
21201 // known-emitted functions.
21202 return FunctionEmissionStatus::Unknown;
21203}
21204
21205bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21206 // Host-side references to a __global__ function refer to the stub, so the
21207 // function itself is never emitted and therefore should not be marked.
21208 // If we have host fn calls kernel fn calls host+device, the HD function
21209 // does not get instantiated on the host. We model this by omitting at the
21210 // call to the kernel from the callgraph. This ensures that, when compiling
21211 // for host, only HD functions actually called from the host get marked as
21212 // known-emitted.
21213 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21214 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21215}
21216
21217bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21218 bool &Visible) {
21219 Visible = hasVisibleDefinition(D, Suggested);
21220 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21221 // for declaratins which is attached to named modules.
21222 // We only did this if the current module is named module as we have better
21223 // diagnostics for declarations in global module and named modules.
21224 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21225 D->isInNamedModule())
21226 return false;
21227 // The redefinition of D in the **current** TU is allowed if D is invisible or
21228 // D is defined in the global module of other module units.
21229 return D->isInAnotherModuleUnit() || !Visible;
21230}
21231